text
stringlengths 54
60.6k
|
|---|
<commit_before>//RUN: make -C %testexecdir/../../clang/ test TESTSUITE=Sema CLANG=%p/clangTestUnloader.sh
<commit_msg>XFAIL clang's testsuite for now.<commit_after>//RUN: make -C %testexecdir/../../clang/ test TESTSUITE=Sema CLANG=%p/clangTestUnloader.sh
//XFAIL: *
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: tdcomp.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: obo $ $Date: 2004-06-04 02:33:08 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _STOC_RDBTDP_BASE_HXX
#include "base.hxx"
#endif
#include "registry/reader.hxx"
#include "registry/version.h"
namespace stoc_rdbtdp
{
//__________________________________________________________________________________________________
CompoundTypeDescriptionImpl::~CompoundTypeDescriptionImpl()
{
delete _pMembers;
delete _pMemberNames;
g_moduleCount.modCnt.release( &g_moduleCount.modCnt );
}
// XTypeDescription
//__________________________________________________________________________________________________
TypeClass CompoundTypeDescriptionImpl::getTypeClass()
throw(::com::sun::star::uno::RuntimeException)
{
return _eTypeClass;
}
//__________________________________________________________________________________________________
OUString CompoundTypeDescriptionImpl::getName()
throw(::com::sun::star::uno::RuntimeException)
{
return _aName;
}
// XCompoundTypeDescription
//__________________________________________________________________________________________________
Reference< XTypeDescription > CompoundTypeDescriptionImpl::getBaseType()
throw(::com::sun::star::uno::RuntimeException)
{
if (!_xBaseTD.is() && _aBaseType.getLength())
{
try
{
Reference< XTypeDescription > xBaseTD;
if (_xTDMgr->getByHierarchicalName( _aBaseType ) >>= xBaseTD)
{
MutexGuard aGuard( getMutex() );
if (! _xBaseTD.is())
_xBaseTD = xBaseTD;
return _xBaseTD;
}
}
catch (NoSuchElementException &)
{
}
// never try again, if no base td was found
_aBaseType = OUString();
}
return _xBaseTD;
}
//__________________________________________________________________________________________________
namespace {
class TypeParameter: public WeakImplHelper1< XTypeDescription > {
public:
explicit TypeParameter(OUString const & name): m_name(name) {}
virtual TypeClass SAL_CALL getTypeClass() throw (RuntimeException)
{ return TypeClass_UNKNOWN; }
virtual OUString SAL_CALL getName() throw (RuntimeException)
{ return m_name; }
private:
OUString m_name;
};
}
Sequence< Reference< XTypeDescription > > CompoundTypeDescriptionImpl::getMemberTypes()
throw(::com::sun::star::uno::RuntimeException)
{
if (! _pMembers)
{
typereg::Reader aReader(
_aBytes.getConstArray(), _aBytes.getLength(), false,
TYPEREG_VERSION_1);
sal_uInt16 nFields = aReader.getFieldCount();
Sequence< Reference< XTypeDescription > > * pTempMembers =
new Sequence< Reference< XTypeDescription > >( nFields );
Reference< XTypeDescription > * pMembers = pTempMembers->getArray();
while (nFields--)
{
if ((aReader.getFieldFlags(nFields) & RT_ACCESS_PARAMETERIZED_TYPE)
!= 0)
{
pMembers[nFields] = new TypeParameter(
aReader.getFieldTypeName(nFields));
} else {
try {
_xTDMgr->getByHierarchicalName(
aReader.getFieldTypeName(nFields).replace('/', '.'))
>>= pMembers[nFields];
} catch (NoSuchElementException &) {}
OSL_ENSURE(
pMembers[nFields].is(), "### compound member unknown!");
}
}
ClearableMutexGuard aGuard( getMutex() );
if (_pMembers)
{
aGuard.clear();
delete pTempMembers;
}
else
{
_pMembers = pTempMembers;
}
}
return *_pMembers;
}
//__________________________________________________________________________________________________
Sequence< OUString > CompoundTypeDescriptionImpl::getMemberNames()
throw(::com::sun::star::uno::RuntimeException)
{
if (! _pMemberNames)
{
typereg::Reader aReader(
_aBytes.getConstArray(), _aBytes.getLength(), false,
TYPEREG_VERSION_1);
sal_uInt16 nFields = aReader.getFieldCount();
Sequence< OUString > * pTempMemberNames = new Sequence< OUString >( nFields );
OUString * pMemberNames = pTempMemberNames->getArray();
while (nFields--)
{
pMemberNames[nFields] = aReader.getFieldName( nFields );
}
ClearableMutexGuard aGuard( getMutex() );
if (_pMemberNames)
{
aGuard.clear();
delete pTempMemberNames;
}
else
{
_pMemberNames = pTempMemberNames;
}
}
return *_pMemberNames;
}
}
<commit_msg>INTEGRATION: CWS ooo19126 (1.9.58); FILE MERGED 2005/09/05 17:11:05 rt 1.9.58.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: tdcomp.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: rt $ $Date: 2005-09-08 08:05:57 $
*
* 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 _STOC_RDBTDP_BASE_HXX
#include "base.hxx"
#endif
#include "registry/reader.hxx"
#include "registry/version.h"
namespace stoc_rdbtdp
{
//__________________________________________________________________________________________________
CompoundTypeDescriptionImpl::~CompoundTypeDescriptionImpl()
{
delete _pMembers;
delete _pMemberNames;
g_moduleCount.modCnt.release( &g_moduleCount.modCnt );
}
// XTypeDescription
//__________________________________________________________________________________________________
TypeClass CompoundTypeDescriptionImpl::getTypeClass()
throw(::com::sun::star::uno::RuntimeException)
{
return _eTypeClass;
}
//__________________________________________________________________________________________________
OUString CompoundTypeDescriptionImpl::getName()
throw(::com::sun::star::uno::RuntimeException)
{
return _aName;
}
// XCompoundTypeDescription
//__________________________________________________________________________________________________
Reference< XTypeDescription > CompoundTypeDescriptionImpl::getBaseType()
throw(::com::sun::star::uno::RuntimeException)
{
if (!_xBaseTD.is() && _aBaseType.getLength())
{
try
{
Reference< XTypeDescription > xBaseTD;
if (_xTDMgr->getByHierarchicalName( _aBaseType ) >>= xBaseTD)
{
MutexGuard aGuard( getMutex() );
if (! _xBaseTD.is())
_xBaseTD = xBaseTD;
return _xBaseTD;
}
}
catch (NoSuchElementException &)
{
}
// never try again, if no base td was found
_aBaseType = OUString();
}
return _xBaseTD;
}
//__________________________________________________________________________________________________
namespace {
class TypeParameter: public WeakImplHelper1< XTypeDescription > {
public:
explicit TypeParameter(OUString const & name): m_name(name) {}
virtual TypeClass SAL_CALL getTypeClass() throw (RuntimeException)
{ return TypeClass_UNKNOWN; }
virtual OUString SAL_CALL getName() throw (RuntimeException)
{ return m_name; }
private:
OUString m_name;
};
}
Sequence< Reference< XTypeDescription > > CompoundTypeDescriptionImpl::getMemberTypes()
throw(::com::sun::star::uno::RuntimeException)
{
if (! _pMembers)
{
typereg::Reader aReader(
_aBytes.getConstArray(), _aBytes.getLength(), false,
TYPEREG_VERSION_1);
sal_uInt16 nFields = aReader.getFieldCount();
Sequence< Reference< XTypeDescription > > * pTempMembers =
new Sequence< Reference< XTypeDescription > >( nFields );
Reference< XTypeDescription > * pMembers = pTempMembers->getArray();
while (nFields--)
{
if ((aReader.getFieldFlags(nFields) & RT_ACCESS_PARAMETERIZED_TYPE)
!= 0)
{
pMembers[nFields] = new TypeParameter(
aReader.getFieldTypeName(nFields));
} else {
try {
_xTDMgr->getByHierarchicalName(
aReader.getFieldTypeName(nFields).replace('/', '.'))
>>= pMembers[nFields];
} catch (NoSuchElementException &) {}
OSL_ENSURE(
pMembers[nFields].is(), "### compound member unknown!");
}
}
ClearableMutexGuard aGuard( getMutex() );
if (_pMembers)
{
aGuard.clear();
delete pTempMembers;
}
else
{
_pMembers = pTempMembers;
}
}
return *_pMembers;
}
//__________________________________________________________________________________________________
Sequence< OUString > CompoundTypeDescriptionImpl::getMemberNames()
throw(::com::sun::star::uno::RuntimeException)
{
if (! _pMemberNames)
{
typereg::Reader aReader(
_aBytes.getConstArray(), _aBytes.getLength(), false,
TYPEREG_VERSION_1);
sal_uInt16 nFields = aReader.getFieldCount();
Sequence< OUString > * pTempMemberNames = new Sequence< OUString >( nFields );
OUString * pMemberNames = pTempMemberNames->getArray();
while (nFields--)
{
pMemberNames[nFields] = aReader.getFieldName( nFields );
}
ClearableMutexGuard aGuard( getMutex() );
if (_pMemberNames)
{
aGuard.clear();
delete pTempMemberNames;
}
else
{
_pMemberNames = pTempMemberNames;
}
}
return *_pMemberNames;
}
}
<|endoftext|>
|
<commit_before>#include <phypp.hpp>
int phypp_main(int argc, char* argv[]) {
if (argc < 2) {
print("usage: median_sub <directory> <mask_catalog>");
return 0;
}
std::string dir = file::directorize(argv[1]);
vec1s files = dir+file::list_files(dir+"sci_reconstructed*-sci.fits");
if (files.empty()) {
files = dir+file::list_files(dir+"SCI_RECONSTRUCTED*-sci.fits");
}
vec1d ra, dec, size;
if (argc > 2) {
vec1s id;
ascii::read_table(argv[2], ascii::find_skip(argv[2]), id, ra, dec, size);
}
auto ksigma = [](vec1d data) {
double v = median(data);
double m = 1.48*median(abs(data - v));
vec1u idg = where(abs(data - v) < 7*m);
return mean(data[idg]);
};
for (auto oname : files) {
std::string newfile = file::get_basename(oname);
file::copy(oname, newfile);
fits::image fimg(newfile);
for (uint_t i : range(1, fimg.hdu_count())) {
fimg.reach_hdu(i);
if (fimg.axis_count() != 3) continue;
vec3d cube;
fimg.read(cube);
uint_t ny = cube.dims[1];
uint_t nx = cube.dims[2];
vec2b mask = replicate(true, ny, nx);
// Mask nearby sources from the provided catalog (if any)
if (!ra.empty()) {
astro::wcs w(fimg.read_header());
vec1d x, y;
astro::ad2xy(w, ra, dec, x, y);
x -= 1.0; y -= 1.0;
double aspix;
astro::get_pixel_size(w, aspix);
vec1d r = size/aspix;
vec2d ix = generate_img(mask.dims, [](int_t, int_t tx) { return tx; });
vec2d iy = generate_img(mask.dims, [](int_t ty, int_t) { return ty; });
for (uint_t s : range(ra)) {
mask = mask && sqr(x[s] - ix) + sqr(y[s] - iy) > sqr(r[s]);
}
}
// Mask borders
mask(0,_) = mask(ny-1,_) = mask(_,0) = mask(_,nx-1) = false;
// Subtract whole IFU
vec1u idg = where(mask);
for (uint_t l : range(cube.dims[0])) {
cube(l,_,_) -= ksigma(cube(l,_,_)[idg]);
}
fimg.update(cube);
}
}
return 0;
}
<commit_msg>median_sub can now simply mask the center of the IFU<commit_after>#include <phypp.hpp>
int phypp_main(int argc, char* argv[]) {
if (argc < 2) {
print("usage: median_sub <directory> [options]");
return 0;
}
std::string dir = file::directorize(argv[1]);
vec1s files = dir+file::list_files(dir+"sci_reconstructed*-sci.fits");
if (files.empty()) {
files = dir+file::list_files(dir+"SCI_RECONSTRUCTED*-sci.fits");
}
bool mask_center = false;
double mask_radius = 0.5; // arcsec
std::string masks;
read_args(argc-1, argv+1, arg_list(mask_center, masks, mask_radius));
vec1d ra, dec, size;
if (!masks.empty()) {
ascii::read_table(masks, ascii::find_skip(masks), _, ra, dec, size);
}
auto ksigma = [](vec1d data) {
double v = median(data);
double m = 1.48*median(abs(data - v));
vec1u idg = where(abs(data - v) < 7*m);
return mean(data[idg]);
};
for (auto oname : files) {
std::string newfile = file::get_basename(oname);
file::copy(oname, newfile);
fits::image fimg(newfile);
for (uint_t i : range(1, fimg.hdu_count())) {
fimg.reach_hdu(i);
if (fimg.axis_count() != 3) continue;
vec3d cube;
fimg.read(cube);
uint_t ny = cube.dims[1];
uint_t nx = cube.dims[2];
vec2b mask = replicate(true, ny, nx);
// Mask nearby sources from the provided catalog (if any)
if (!ra.empty()) {
astro::wcs w(fimg.read_header());
vec1d x, y;
astro::ad2xy(w, ra, dec, x, y);
x -= 1.0; y -= 1.0;
double aspix = 1.0;
if (!astro::get_pixel_size(w, aspix)) {
error("could not read pixel size from cube");
return 1;
}
vec1d r = size/aspix;
vec2d ix = generate_img(mask.dims, [](int_t, int_t tx) { return tx; });
vec2d iy = generate_img(mask.dims, [](int_t ty, int_t) { return ty; });
for (uint_t s : range(ra)) {
mask = mask && sqr(x[s] - ix) + sqr(y[s] - iy) > sqr(r[s]);
}
} else if (mask_center) {
astro::wcs w(fimg.read_header());
double aspix = 1.0;
if (!astro::get_pixel_size(w, aspix)) {
error("could not read pixel size from cube");
return 1;
}
vec2d ix = generate_img(mask.dims, [](int_t, int_t tx) { return tx; });
vec2d iy = generate_img(mask.dims, [](int_t ty, int_t) { return ty; });
mask = mask && sqr(nx/2 - ix) + sqr(ny/2 - iy) > sqr(mask_radius/aspix);
}
// Mask borders
mask(0,_) = mask(ny-1,_) = mask(_,0) = mask(_,nx-1) = false;
// Subtract whole IFU
vec1u idg = where(mask);
for (uint_t l : range(cube.dims[0])) {
cube(l,_,_) -= ksigma(cube(l,_,_)[idg]);
}
fimg.update(cube);
}
}
return 0;
}
<|endoftext|>
|
<commit_before>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 2000-2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
#include "ICUBridgeCollationCompareFunctorImpl.hpp"
#include "ICUBridge.hpp"
#include <algorithm>
#include <cstdlib>
#include <Include/XalanAutoPtr.hpp>
#include <PlatformSupport/DOMStringHelper.hpp>
#include <PlatformSupport/XalanUnicode.hpp>
XALAN_CPP_NAMESPACE_BEGIN
const StylesheetExecutionContextDefault::DefaultCollationCompareFunctor ICUBridgeCollationCompareFunctorImpl::s_defaultFunctor;
inline ICUBridgeCollationCompareFunctorImpl::CollatorType*
createCollator(
UErrorCode& theStatus,
const Locale& theLocale,
XalanDOMString* theLocaleName = 0)
{
typedef ICUBridgeCollationCompareFunctorImpl::CollatorType CollatorType;
if (theLocaleName != 0)
{
*theLocaleName = theLocale.getName();
// Replace _ with -, since that's what xml:lang specifies...
XalanDOMString::size_type theIndex;
while((theIndex = indexOf(*theLocaleName, XalanUnicode::charLowLine)) != theLocaleName->length())
{
(*theLocaleName)[theIndex] = XalanUnicode::charHyphenMinus;
}
}
return CollatorType::createInstance(theLocale, theStatus);
}
inline ICUBridgeCollationCompareFunctorImpl::CollatorType*
createCollator(
UErrorCode& theStatus,
XalanDOMString* theLocaleName = 0)
{
const char* theLang =
#if defined(XALAN_STRICT_ANSI_HEADERS)
std::getenv("LANG");
#else
getenv("LANG");
#endif
if (theLang == 0)
{
#if defined(XALAN_ICU_DEFAULT_LOCALE_PROBLEM)
return createCollator(theStatus, Locale::US, theLocaleName);
#else
return createCollator(theStatus, Locale::getDefault(), theLocaleName);
#endif
}
else
{
return createCollator(theStatus, Locale(theLang), theLocaleName);
}
}
ICUBridgeCollationCompareFunctorImpl::ICUBridgeCollationCompareFunctorImpl(bool fCacheCollators) :
m_isValid(false),
m_defaultCollator(0),
m_defaultCollatorLocaleName(),
m_cacheCollators(fCacheCollators),
m_collatorCache()
{
UErrorCode theStatus = U_ZERO_ERROR;
m_defaultCollator = createCollator(theStatus, &m_defaultCollatorLocaleName);
if (U_SUCCESS(theStatus))
{
m_isValid = true;
}
}
ICUBridgeCollationCompareFunctorImpl::~ICUBridgeCollationCompareFunctorImpl()
{
#if !defined(XALAN_NO_NAMESPACES)
using std::for_each;
#endif
delete m_defaultCollator;
for_each(
m_collatorCache.begin(),
m_collatorCache.end(),
CollationCacheStruct::CollatorDeleteFunctor());
}
int
ICUBridgeCollationCompareFunctorImpl::doCompare(
const CollatorType& theCollator,
const XalanDOMChar* theLHS,
const XalanDOMChar* theRHS) const
{
#if defined(XALAN_USE_WCHAR_CAST_HACK)
return theCollator.compare(
(const wchar_t*)theLHS,
length(theLHS),
(const wchar_t*)theRHS,
length(theRHS));
#else
return theCollator.compare(
theLHS,
length(theLHS),
theRHS,
length(theRHS));
#endif
}
inline UColAttributeValue
caseOrderConvert(ICUBridgeCollationCompareFunctorImpl::eCaseOrder theCaseOrder)
{
switch(theCaseOrder)
{
case StylesheetExecutionContext::eLowerFirst:
return UCOL_LOWER_FIRST;
break;
case StylesheetExecutionContext::eUpperFirst:
return UCOL_UPPER_FIRST;
break;
case StylesheetExecutionContext::eDefault:
break;
default:
assert(false);
break;
}
return UCOL_DEFAULT;
}
int
ICUBridgeCollationCompareFunctorImpl::doDefaultCompare(
const XalanDOMChar* theLHS,
const XalanDOMChar* theRHS) const
{
if (isValid() == false)
{
return s_defaultFunctor(theLHS, theRHS, StylesheetExecutionContext::eDefault);
}
else
{
assert(m_defaultCollator != 0);
return doCompare(*m_defaultCollator, theLHS, theRHS);
}
}
inline ICUBridgeCollationCompareFunctorImpl::CollatorType*
createCollator(
const XalanDOMChar* theLocale,
UErrorCode& theStatus)
{
assert(theLocale != 0);
const XalanDOMString::size_type theLength = length(theLocale);
if (theLength >= ULOC_FULLNAME_CAPACITY)
{
theStatus = U_ILLEGAL_ARGUMENT_ERROR;
return 0;
}
else
{
#if defined(XALAN_NON_ASCII_PLATFORM)
CharVectorType theVector;
TranscodeToLocalCodePage(theLocale, theVector, true);
const char* const theBuffer = c_str(theVector);
#else
char theBuffer[ULOC_FULLNAME_CAPACITY];
// Since language names must be ASCII, this
// is the cheapest way to "transcode"...
for (unsigned int i = 0; i <= theLength; ++i)
{
theBuffer[i] = char(theLocale[i]);
}
#endif
return ICUBridgeCollationCompareFunctorImpl::CollatorType::createInstance(
Locale::createFromName(theBuffer),
theStatus);
}
}
int
ICUBridgeCollationCompareFunctorImpl::doCompare(
const XalanDOMChar* theLHS,
const XalanDOMChar* theRHS,
const XalanDOMChar* theLocale,
eCaseOrder theCaseOrder) const
{
UErrorCode theStatus = U_ZERO_ERROR;
XalanAutoPtr<CollatorType> theCollator(createCollator(theLocale, theStatus));
if (U_SUCCESS(theStatus))
{
assert(theCollator.get() != 0);
return doCompare(
*theCollator.get(),
theLHS,
theRHS,
theCaseOrder);
}
else
{
return s_defaultFunctor(theLHS, theRHS, theCaseOrder);
}
}
int
ICUBridgeCollationCompareFunctorImpl::doCompareCached(
const XalanDOMChar* theLHS,
const XalanDOMChar* theRHS,
const XalanDOMChar* theLocale,
eCaseOrder theCaseOrder) const
{
CollatorType* theCollator = getCachedCollator(theLocale);
if (theCollator != 0)
{
return doCompare(*theCollator, theLHS, theRHS, theCaseOrder);
}
else
{
UErrorCode theStatus = U_ZERO_ERROR;
XalanAutoPtr<CollatorType> theCollatorGuard(createCollator(theLocale, theStatus));
if (U_SUCCESS(theStatus))
{
assert(theCollatorGuard.get() != 0);
// OK, there was no error, so cache the instance...
cacheCollator(theCollatorGuard.get(), theLocale);
// Release the collator, since it's in the cache and
// will be controlled by the cache...
theCollator = theCollatorGuard.release();
return doCompare(
*theCollator,
theLHS,
theRHS,
theCaseOrder);
}
else
{
return s_defaultFunctor(theLHS, theRHS, theCaseOrder);
}
}
}
int
ICUBridgeCollationCompareFunctorImpl::doCompare(
CollatorType& theCollator,
const XalanDOMChar* theLHS,
const XalanDOMChar* theRHS,
eCaseOrder theCaseOrder) const
{
UErrorCode theStatus = U_ZERO_ERROR;
theCollator.setAttribute(
UCOL_CASE_FIRST,
caseOrderConvert(theCaseOrder),
theStatus);
#if defined(XALAN_USE_WCHAR_CAST_HACK)
return theCollator.compare(
(const wchar_t*)theLHS,
length(theLHS),
(const wchar_t*)theRHS,
length(theRHS));
#else
return theCollator.compare(
theLHS,
length(theLHS),
theRHS,
length(theRHS));
#endif
}
int
ICUBridgeCollationCompareFunctorImpl::operator()(
const XalanDOMChar* theLHS,
const XalanDOMChar* theRHS,
eCaseOrder theCaseOrder) const
{
if (theCaseOrder == StylesheetExecutionContext::eDefault)
{
return doDefaultCompare(theLHS, theRHS);
}
else
{
return doCompare(
theLHS,
theRHS,
c_wstr(m_defaultCollatorLocaleName),
theCaseOrder);
}
}
int
ICUBridgeCollationCompareFunctorImpl::operator()(
const XalanDOMChar* theLHS,
const XalanDOMChar* theRHS,
const XalanDOMChar* theLocale,
eCaseOrder theCaseOrder) const
{
if (theCaseOrder == StylesheetExecutionContext::eDefault &&
XalanDOMString::equals(m_defaultCollatorLocaleName, theLocale) == true)
{
return doDefaultCompare(theLHS, theRHS);
}
else if (m_cacheCollators == true)
{
return doCompareCached(theLHS, theRHS, theLocale, theCaseOrder);
}
else
{
return doCompare(theLHS, theRHS, theLocale, theCaseOrder);
};
}
ICUBridgeCollationCompareFunctorImpl::CollatorType*
ICUBridgeCollationCompareFunctorImpl::getCachedCollator(const XalanDOMChar* theLocale) const
{
#if !defined(XALAN_NO_NAMESPACES)
using std::find_if;
#endif
CollatorCacheListType& theNonConstCache =
#if defined(XALAN_NO_MUTABLE)
(CollatorCacheListType*)m_collatorCache;
#else
m_collatorCache;
#endif
CollatorCacheListType::iterator i =
find_if(
theNonConstCache.begin(),
theNonConstCache.end(),
CollationCacheStruct::CollatorFindFunctor(theLocale));
if (i == theNonConstCache.end())
{
return 0;
}
else
{
// Let's do a quick check to see if we found the first entry.
// If so, we don't have to update the cache, so just return the
// appropriate value...
const CollatorCacheListType::iterator theBegin =
theNonConstCache.begin();
if (i == theBegin)
{
return (*i).m_collator;
}
else
{
// Save the collator, because splice() may invalidate
// i.
CollatorType* const theCollator = (*i).m_collator;
// Move the entry to the beginning the cache
theNonConstCache.splice(theBegin, theNonConstCache, i);
return theCollator;
}
}
}
void
ICUBridgeCollationCompareFunctorImpl::cacheCollator(
CollatorType* theCollator,
const XalanDOMChar* theLocale) const
{
assert(theCollator != 0);
assert(theLocale != 0);
CollatorCacheListType& theNonConstCache =
#if defined(XALAN_NO_MUTABLE)
(CollatorCacheListType*)m_collatorCache;
#else
m_collatorCache;
#endif
// Is the cache full?
if (theNonConstCache.size() == eCacheMax)
{
// Yes, so guard the collator instance, in case pop_back() throws...
XalanAutoPtr<CollatorType> theCollatorGuard(theNonConstCache.back().m_collator);
theNonConstCache.pop_back();
}
theNonConstCache.push_front(CollatorCacheListType::value_type());
CollatorCacheListType::value_type& theEntry =
theNonConstCache.front();
// Set the locale first, since that might throw an exception...
theEntry.m_locale = theLocale;
theEntry.m_collator = theCollator;
}
XALAN_CPP_NAMESPACE_END
<commit_msg>New ifdef for 64-bit AIX 5.1.<commit_after>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 2000-2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
#include "ICUBridgeCollationCompareFunctorImpl.hpp"
#include "ICUBridge.hpp"
#include <algorithm>
#include <cstdlib>
#include <Include/XalanAutoPtr.hpp>
#include <PlatformSupport/DOMStringHelper.hpp>
#include <PlatformSupport/XalanUnicode.hpp>
XALAN_CPP_NAMESPACE_BEGIN
const StylesheetExecutionContextDefault::DefaultCollationCompareFunctor ICUBridgeCollationCompareFunctorImpl::s_defaultFunctor;
inline ICUBridgeCollationCompareFunctorImpl::CollatorType*
createCollator(
UErrorCode& theStatus,
const Locale& theLocale,
XalanDOMString* theLocaleName = 0)
{
typedef ICUBridgeCollationCompareFunctorImpl::CollatorType CollatorType;
if (theLocaleName != 0)
{
*theLocaleName = theLocale.getName();
// Replace _ with -, since that's what xml:lang specifies...
XalanDOMString::size_type theIndex;
while((theIndex = indexOf(*theLocaleName, XalanUnicode::charLowLine)) != theLocaleName->length())
{
(*theLocaleName)[theIndex] = XalanUnicode::charHyphenMinus;
}
}
return CollatorType::createInstance(theLocale, theStatus);
}
inline ICUBridgeCollationCompareFunctorImpl::CollatorType*
createCollator(
UErrorCode& theStatus,
XalanDOMString* theLocaleName = 0)
{
const char* theLang =
#if defined(XALAN_STRICT_ANSI_HEADERS)
std::getenv("LANG");
#else
getenv("LANG");
#endif
if (theLang == 0)
{
#if defined(XALAN_ICU_DEFAULT_LOCALE_PROBLEM)
return createCollator(theStatus, Locale::US, theLocaleName);
#else
return createCollator(theStatus, Locale::getDefault(), theLocaleName);
#endif
}
else
{
return createCollator(theStatus, Locale(theLang), theLocaleName);
}
}
ICUBridgeCollationCompareFunctorImpl::ICUBridgeCollationCompareFunctorImpl(bool fCacheCollators) :
m_isValid(false),
m_defaultCollator(0),
m_defaultCollatorLocaleName(),
m_cacheCollators(fCacheCollators),
m_collatorCache()
{
UErrorCode theStatus = U_ZERO_ERROR;
m_defaultCollator = createCollator(theStatus, &m_defaultCollatorLocaleName);
if (U_SUCCESS(theStatus))
{
m_isValid = true;
}
}
ICUBridgeCollationCompareFunctorImpl::~ICUBridgeCollationCompareFunctorImpl()
{
#if !defined(XALAN_NO_NAMESPACES)
using std::for_each;
#endif
delete m_defaultCollator;
for_each(
m_collatorCache.begin(),
m_collatorCache.end(),
CollationCacheStruct::CollatorDeleteFunctor());
}
int
ICUBridgeCollationCompareFunctorImpl::doCompare(
const CollatorType& theCollator,
const XalanDOMChar* theLHS,
const XalanDOMChar* theRHS) const
{
#if defined(XALAN_USE_WCHAR_CAST_HACK) && defined(U_WCHAR_IS_UTF16)
return theCollator.compare(
(const wchar_t*)theLHS,
length(theLHS),
(const wchar_t*)theRHS,
length(theRHS));
#else
return theCollator.compare(
theLHS,
length(theLHS),
theRHS,
length(theRHS));
#endif
}
inline UColAttributeValue
caseOrderConvert(ICUBridgeCollationCompareFunctorImpl::eCaseOrder theCaseOrder)
{
switch(theCaseOrder)
{
case StylesheetExecutionContext::eLowerFirst:
return UCOL_LOWER_FIRST;
break;
case StylesheetExecutionContext::eUpperFirst:
return UCOL_UPPER_FIRST;
break;
case StylesheetExecutionContext::eDefault:
break;
default:
assert(false);
break;
}
return UCOL_DEFAULT;
}
int
ICUBridgeCollationCompareFunctorImpl::doDefaultCompare(
const XalanDOMChar* theLHS,
const XalanDOMChar* theRHS) const
{
if (isValid() == false)
{
return s_defaultFunctor(theLHS, theRHS, StylesheetExecutionContext::eDefault);
}
else
{
assert(m_defaultCollator != 0);
return doCompare(*m_defaultCollator, theLHS, theRHS);
}
}
inline ICUBridgeCollationCompareFunctorImpl::CollatorType*
createCollator(
const XalanDOMChar* theLocale,
UErrorCode& theStatus)
{
assert(theLocale != 0);
const XalanDOMString::size_type theLength = length(theLocale);
if (theLength >= ULOC_FULLNAME_CAPACITY)
{
theStatus = U_ILLEGAL_ARGUMENT_ERROR;
return 0;
}
else
{
#if defined(XALAN_NON_ASCII_PLATFORM)
CharVectorType theVector;
TranscodeToLocalCodePage(theLocale, theVector, true);
const char* const theBuffer = c_str(theVector);
#else
char theBuffer[ULOC_FULLNAME_CAPACITY];
// Since language names must be ASCII, this
// is the cheapest way to "transcode"...
for (unsigned int i = 0; i <= theLength; ++i)
{
theBuffer[i] = char(theLocale[i]);
}
#endif
return ICUBridgeCollationCompareFunctorImpl::CollatorType::createInstance(
Locale::createFromName(theBuffer),
theStatus);
}
}
int
ICUBridgeCollationCompareFunctorImpl::doCompare(
const XalanDOMChar* theLHS,
const XalanDOMChar* theRHS,
const XalanDOMChar* theLocale,
eCaseOrder theCaseOrder) const
{
UErrorCode theStatus = U_ZERO_ERROR;
XalanAutoPtr<CollatorType> theCollator(createCollator(theLocale, theStatus));
if (U_SUCCESS(theStatus))
{
assert(theCollator.get() != 0);
return doCompare(
*theCollator.get(),
theLHS,
theRHS,
theCaseOrder);
}
else
{
return s_defaultFunctor(theLHS, theRHS, theCaseOrder);
}
}
int
ICUBridgeCollationCompareFunctorImpl::doCompareCached(
const XalanDOMChar* theLHS,
const XalanDOMChar* theRHS,
const XalanDOMChar* theLocale,
eCaseOrder theCaseOrder) const
{
CollatorType* theCollator = getCachedCollator(theLocale);
if (theCollator != 0)
{
return doCompare(*theCollator, theLHS, theRHS, theCaseOrder);
}
else
{
UErrorCode theStatus = U_ZERO_ERROR;
XalanAutoPtr<CollatorType> theCollatorGuard(createCollator(theLocale, theStatus));
if (U_SUCCESS(theStatus))
{
assert(theCollatorGuard.get() != 0);
// OK, there was no error, so cache the instance...
cacheCollator(theCollatorGuard.get(), theLocale);
// Release the collator, since it's in the cache and
// will be controlled by the cache...
theCollator = theCollatorGuard.release();
return doCompare(
*theCollator,
theLHS,
theRHS,
theCaseOrder);
}
else
{
return s_defaultFunctor(theLHS, theRHS, theCaseOrder);
}
}
}
int
ICUBridgeCollationCompareFunctorImpl::doCompare(
CollatorType& theCollator,
const XalanDOMChar* theLHS,
const XalanDOMChar* theRHS,
eCaseOrder theCaseOrder) const
{
UErrorCode theStatus = U_ZERO_ERROR;
theCollator.setAttribute(
UCOL_CASE_FIRST,
caseOrderConvert(theCaseOrder),
theStatus);
#if defined(XALAN_USE_WCHAR_CAST_HACK) && defined(U_WCHAR_IS_UTF16)
return theCollator.compare(
(const wchar_t*)theLHS,
length(theLHS),
(const wchar_t*)theRHS,
length(theRHS));
#else
return theCollator.compare(
theLHS,
length(theLHS),
theRHS,
length(theRHS));
#endif
}
int
ICUBridgeCollationCompareFunctorImpl::operator()(
const XalanDOMChar* theLHS,
const XalanDOMChar* theRHS,
eCaseOrder theCaseOrder) const
{
if (theCaseOrder == StylesheetExecutionContext::eDefault)
{
return doDefaultCompare(theLHS, theRHS);
}
else
{
return doCompare(
theLHS,
theRHS,
c_wstr(m_defaultCollatorLocaleName),
theCaseOrder);
}
}
int
ICUBridgeCollationCompareFunctorImpl::operator()(
const XalanDOMChar* theLHS,
const XalanDOMChar* theRHS,
const XalanDOMChar* theLocale,
eCaseOrder theCaseOrder) const
{
if (theCaseOrder == StylesheetExecutionContext::eDefault &&
XalanDOMString::equals(m_defaultCollatorLocaleName, theLocale) == true)
{
return doDefaultCompare(theLHS, theRHS);
}
else if (m_cacheCollators == true)
{
return doCompareCached(theLHS, theRHS, theLocale, theCaseOrder);
}
else
{
return doCompare(theLHS, theRHS, theLocale, theCaseOrder);
};
}
ICUBridgeCollationCompareFunctorImpl::CollatorType*
ICUBridgeCollationCompareFunctorImpl::getCachedCollator(const XalanDOMChar* theLocale) const
{
#if !defined(XALAN_NO_NAMESPACES)
using std::find_if;
#endif
CollatorCacheListType& theNonConstCache =
#if defined(XALAN_NO_MUTABLE)
(CollatorCacheListType*)m_collatorCache;
#else
m_collatorCache;
#endif
CollatorCacheListType::iterator i =
find_if(
theNonConstCache.begin(),
theNonConstCache.end(),
CollationCacheStruct::CollatorFindFunctor(theLocale));
if (i == theNonConstCache.end())
{
return 0;
}
else
{
// Let's do a quick check to see if we found the first entry.
// If so, we don't have to update the cache, so just return the
// appropriate value...
const CollatorCacheListType::iterator theBegin =
theNonConstCache.begin();
if (i == theBegin)
{
return (*i).m_collator;
}
else
{
// Save the collator, because splice() may invalidate
// i.
CollatorType* const theCollator = (*i).m_collator;
// Move the entry to the beginning the cache
theNonConstCache.splice(theBegin, theNonConstCache, i);
return theCollator;
}
}
}
void
ICUBridgeCollationCompareFunctorImpl::cacheCollator(
CollatorType* theCollator,
const XalanDOMChar* theLocale) const
{
assert(theCollator != 0);
assert(theLocale != 0);
CollatorCacheListType& theNonConstCache =
#if defined(XALAN_NO_MUTABLE)
(CollatorCacheListType*)m_collatorCache;
#else
m_collatorCache;
#endif
// Is the cache full?
if (theNonConstCache.size() == eCacheMax)
{
// Yes, so guard the collator instance, in case pop_back() throws...
XalanAutoPtr<CollatorType> theCollatorGuard(theNonConstCache.back().m_collator);
theNonConstCache.pop_back();
}
theNonConstCache.push_front(CollatorCacheListType::value_type());
CollatorCacheListType::value_type& theEntry =
theNonConstCache.front();
// Set the locale first, since that might throw an exception...
theEntry.m_locale = theLocale;
theEntry.m_collator = theCollator;
}
XALAN_CPP_NAMESPACE_END
<|endoftext|>
|
<commit_before>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 2000-2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
#if !defined(ICUBRIDGE_COLLATIONCOMPAREFUNCTORIMPL_GUARD_1357924680)
#define ICUBRIDGE_COLLATIONCOMPAREFUNCTORIMPL_GUARD_1357924680
#include <ICUBridge/ICUBridgeDefinitions.hpp>
#include <list>
#include <XSLT/StylesheetExecutionContextDefault.hpp>
#include <unicode/coll.h>
XALAN_CPP_NAMESPACE_BEGIN
class XALAN_ICUBRIDGE_EXPORT ICUBridgeCollationCompareFunctorImpl : public StylesheetExecutionContextDefault::CollationCompareFunctor
{
public:
typedef StylesheetExecutionContextDefault::eCaseOrder eCaseOrder;
/**
* Constructor.
*
* @param fCacheCollators If true, the instance will cache collators. This is not thread-safe, so each thread must have its own instance.
*/
ICUBridgeCollationCompareFunctorImpl(bool fCacheCollators = false);
~ICUBridgeCollationCompareFunctorImpl();
int
operator()(
const XalanDOMChar* theLHS,
const XalanDOMChar* theRHS,
eCaseOrder theCaseOrder = StylesheetExecutionContextDefault::eDefault) const;
int
operator()(
const XalanDOMChar* theLHS,
const XalanDOMChar* theRHS,
const XalanDOMChar* theLocale,
eCaseOrder theCaseOrder = StylesheetExecutionContextDefault::eDefault) const;
bool
isValid() const
{
return m_isValid;
}
#if defined(XALAN_HAS_CPP_NAMESPACE)
typedef U_ICU_NAMESPACE::Collator CollatorType;
#else
typedef Collator CollatorType;
#endif
struct CollationCacheStruct
{
CollationCacheStruct(
const XalanDOMString& theLocale,
CollatorType* theCollator) :
m_locale(theLocale),
m_collator(theCollator)
{
}
CollationCacheStruct() :
m_locale(),
m_collator(0)
{
}
void
swap(CollationCacheStruct& theOther)
{
m_locale.swap(theOther.m_locale);
CollatorType* const theTemp = m_collator;
m_collator = theOther.m_collator;
theOther.m_collator = theTemp;
}
XalanDOMString m_locale;
CollatorType* m_collator;
struct CollatorDeleteFunctor
{
void
operator()(CollationCacheStruct& theStruct) const
{
delete theStruct.m_collator;
}
};
struct CollatorFindFunctor
{
CollatorFindFunctor(const XalanDOMChar* theLocale) :
m_locale(theLocale)
{
}
bool
operator()(CollationCacheStruct& theStruct) const
{
return XalanDOMString::equals(theStruct.m_locale ,m_locale);
}
const XalanDOMChar* const m_locale;
};
};
#if defined(XALAN_NO_STD_NAMESPACE)
typedef list<CollationCacheStruct> CollatorCacheListType;
#else
typedef std::list<CollationCacheStruct> CollatorCacheListType;
#endif
enum { eCacheMax = 10 };
private:
int
doDefaultCompare(
const XalanDOMChar* theLHS,
const XalanDOMChar* theRHS) const;
int
doCompare(
const XalanDOMChar* theLHS,
const XalanDOMChar* theRHS,
const XalanDOMChar* theLocale,
eCaseOrder theCaseOrder) const;
int
doCompareCached(
const XalanDOMChar* theLHS,
const XalanDOMChar* theRHS,
const XalanDOMChar* theLocale,
eCaseOrder theCaseOrder) const;
int
doCompare(
const CollatorType& theCollator,
const XalanDOMChar* theLHS,
const XalanDOMChar* theRHS) const;
int
doCompare(
CollatorType& theCollator,
const XalanDOMChar* theLHS,
const XalanDOMChar* theRHS,
eCaseOrder theCaseOrder) const;
CollatorType*
getCachedCollator(const XalanDOMChar* theLocale) const;
void
cacheCollator(
CollatorType* theCollator,
const XalanDOMChar* theLocale) const;
// Data members...
bool m_isValid;
CollatorType* m_defaultCollator;
XalanDOMString m_defaultCollatorLocaleName;
bool m_cacheCollators;
mutable CollatorCacheListType m_collatorCache;
const static StylesheetExecutionContextDefault::DefaultCollationCompareFunctor s_defaultFunctor;
};
XALAN_CPP_NAMESPACE_END
#endif // ICUBRIDGE_COLLATIONCOMPAREFUNCTORIMPL_GUARD_1357924680
<commit_msg>Added operators for brain-dead compilers.<commit_after>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 2000-2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
#if !defined(ICUBRIDGE_COLLATIONCOMPAREFUNCTORIMPL_GUARD_1357924680)
#define ICUBRIDGE_COLLATIONCOMPAREFUNCTORIMPL_GUARD_1357924680
#include <ICUBridge/ICUBridgeDefinitions.hpp>
#include <list>
#include <XSLT/StylesheetExecutionContextDefault.hpp>
#include <unicode/coll.h>
XALAN_CPP_NAMESPACE_BEGIN
class XALAN_ICUBRIDGE_EXPORT ICUBridgeCollationCompareFunctorImpl : public StylesheetExecutionContextDefault::CollationCompareFunctor
{
public:
typedef StylesheetExecutionContextDefault::eCaseOrder eCaseOrder;
/**
* Constructor.
*
* @param fCacheCollators If true, the instance will cache collators. This is not thread-safe, so each thread must have its own instance.
*/
ICUBridgeCollationCompareFunctorImpl(bool fCacheCollators = false);
~ICUBridgeCollationCompareFunctorImpl();
int
operator()(
const XalanDOMChar* theLHS,
const XalanDOMChar* theRHS,
eCaseOrder theCaseOrder = StylesheetExecutionContextDefault::eDefault) const;
int
operator()(
const XalanDOMChar* theLHS,
const XalanDOMChar* theRHS,
const XalanDOMChar* theLocale,
eCaseOrder theCaseOrder = StylesheetExecutionContextDefault::eDefault) const;
bool
isValid() const
{
return m_isValid;
}
#if defined(XALAN_HAS_CPP_NAMESPACE)
typedef U_ICU_NAMESPACE::Collator CollatorType;
#else
typedef Collator CollatorType;
#endif
struct CollationCacheStruct
{
CollationCacheStruct(
const XalanDOMString& theLocale,
CollatorType* theCollator) :
m_locale(theLocale),
m_collator(theCollator)
{
}
CollationCacheStruct() :
m_locale(),
m_collator(0)
{
}
void
swap(CollationCacheStruct& theOther)
{
m_locale.swap(theOther.m_locale);
CollatorType* const theTemp = m_collator;
m_collator = theOther.m_collator;
theOther.m_collator = theTemp;
}
#if defined(XALAN_NO_SELECTIVE_TEMPLATE_INSTANTIATION)
bool
operator<(const CollationCacheStruct& theRHS) const
{
return this < &theRHS;
}
bool
operator==(const CollationCacheStruct& theRHS) const
{
return this == &theRHS;
}
#endif
XalanDOMString m_locale;
CollatorType* m_collator;
struct CollatorDeleteFunctor
{
void
operator()(CollationCacheStruct& theStruct) const
{
delete theStruct.m_collator;
}
};
struct CollatorFindFunctor
{
CollatorFindFunctor(const XalanDOMChar* theLocale) :
m_locale(theLocale)
{
}
bool
operator()(CollationCacheStruct& theStruct) const
{
return XalanDOMString::equals(theStruct.m_locale ,m_locale);
}
const XalanDOMChar* const m_locale;
};
};
#if defined(XALAN_NO_STD_NAMESPACE)
typedef list<CollationCacheStruct> CollatorCacheListType;
#else
typedef std::list<CollationCacheStruct> CollatorCacheListType;
#endif
enum { eCacheMax = 10 };
private:
int
doDefaultCompare(
const XalanDOMChar* theLHS,
const XalanDOMChar* theRHS) const;
int
doCompare(
const XalanDOMChar* theLHS,
const XalanDOMChar* theRHS,
const XalanDOMChar* theLocale,
eCaseOrder theCaseOrder) const;
int
doCompareCached(
const XalanDOMChar* theLHS,
const XalanDOMChar* theRHS,
const XalanDOMChar* theLocale,
eCaseOrder theCaseOrder) const;
int
doCompare(
const CollatorType& theCollator,
const XalanDOMChar* theLHS,
const XalanDOMChar* theRHS) const;
int
doCompare(
CollatorType& theCollator,
const XalanDOMChar* theLHS,
const XalanDOMChar* theRHS,
eCaseOrder theCaseOrder) const;
CollatorType*
getCachedCollator(const XalanDOMChar* theLocale) const;
void
cacheCollator(
CollatorType* theCollator,
const XalanDOMChar* theLocale) const;
// Data members...
bool m_isValid;
CollatorType* m_defaultCollator;
XalanDOMString m_defaultCollatorLocaleName;
bool m_cacheCollators;
mutable CollatorCacheListType m_collatorCache;
const static StylesheetExecutionContextDefault::DefaultCollationCompareFunctor s_defaultFunctor;
};
XALAN_CPP_NAMESPACE_END
#endif // ICUBRIDGE_COLLATIONCOMPAREFUNCTORIMPL_GUARD_1357924680
<|endoftext|>
|
<commit_before>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2020 Scientific Computing and Imaging Institute,
University of Utah.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include <Modules/Legacy/Fields/CompositeModuleTestGFB_FM.h>
#include <Dataflow/Network/NetworkInterface.h>
using namespace SCIRun::Modules::Fields;
using namespace SCIRun;
MODULE_INFO_DEF(CompositeModuleTestGFB_FM, MiscField, SCIRun)
CompositeModuleTestGFB_FM::CompositeModuleTestGFB_FM() : Module(staticInfo_, false)
{
INITIALIZE_PORT(InputField);
INITIALIZE_PORT(FairedMesh);
}
void CompositeModuleTestGFB_FM::setStateDefaults()
{
auto state = get_state();
/*
state->setValue(Variables::FunctionString, std::string(
"<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<!DOCTYPE boost_serialization>
<boost_serialization signature="serialization::archive" version="18">
<networkFragment class_id="0" tracking_level="0" version="6">
<networkInfo class_id="1" tracking_level="0" version="0">
<modules class_id="2" tracking_level="0" version="0">
<count>2</count>
<item_version>0</item_version>
<item class_id="3" tracking_level="0" version="0">
<first>FairMesh:0</first>
<second class_id="4" tracking_level="0" version="0">
<module class_id="5" tracking_level="0" version="0">
<package_name_>SCIRun</package_name_>
<category_name_>NewField</category_name_>
<module_name_>FairMesh</module_name_>
</module>
<state class_id="6" tracking_level="0" version="0">
<stateMap class_id="7" tracking_level="0" version="0">
<count>5</count>
<item_version>0</item_version>
<item class_id="8" tracking_level="0" version="0">
<first class_id="9" tracking_level="0" version="0">
<name>FairMeshMethod</name>
</first>
<second class_id="10" tracking_level="0" version="0">
<name>FairMeshMethod</name>
<value class_id="11" tracking_level="1" version="0" object_id="_0">
<which>2</which>
<value>fast</value>
</value>
</second>
</item>
<item>
<first>
<name>FilterCutoff</name>
</first>
<second>
<name>FilterCutoff</name>
<value object_id="_1">
<which>1</which>
<value>1.00000000000000006e-01</value>
</value>
</second>
</item>
<item>
<first>
<name>Lambda</name>
</first>
<second>
<name>Lambda</name>
<value object_id="_2">
<which>1</which>
<value>6.30700000000000038e-01</value>
</value>
</second>
</item>
<item>
<first>
<name>NumIterations</name>
</first>
<second>
<name>NumIterations</name>
<value object_id="_3">
<which>0</which>
<value>50</value>
</value>
</second>
</item>
<item>
<first>
<name>ProgrammableInputPortEnabled</name>
</first>
<second>
<name>ProgrammableInputPortEnabled</name>
<value object_id="_4">
<which>3</which>
<value>0</value>
</value>
</second>
</item>
</stateMap>
</state>
</second>
</item>
<item>
<first>GetFieldBoundary:0</first>
<second>
<module>
<package_name_>SCIRun</package_name_>
<category_name_>NewField</category_name_>
<module_name_>GetFieldBoundary</module_name_>
</module>
<state>
<stateMap>
<count>1</count>
<item_version>0</item_version>
<item>
<first>
<name>ProgrammableInputPortEnabled</name>
</first>
<second>
<name>ProgrammableInputPortEnabled</name>
<value object_id="_5">
<which>3</which>
<value>0</value>
</value>
</second>
</item>
</stateMap>
</state>
</second>
</item>
</modules>
<connections class_id="12" tracking_level="0" version="0">
<count>1</count>
<item_version>0</item_version>
<item class_id="13" tracking_level="0" version="0">
<moduleId1_>GetFieldBoundary:0</moduleId1_>
<port1_ class_id="14" tracking_level="0" version="0">
<name>BoundaryField</name>
<id>0</id>
</port1_>
<moduleId2_>FairMesh:0</moduleId2_>
<port2_>
<name>Input_Mesh</name>
<id>0</id>
</port2_>
</item>
</connections>
</networkInfo>
<modulePositions class_id="15" tracking_level="0" version="0">
<count>2</count>
<item_version>0</item_version>
<item class_id="16" tracking_level="0" version="0">
<first>FairMesh:0</first>
<second class_id="17" tracking_level="0" version="0">
<first>-4.90000000000000000e+02</first>
<second>-3.80000000000000000e+02</second>
</second>
</item>
<item>
<first>GetFieldBoundary:0</first>
<second>
<first>-5.32000000000000000e+02</first>
<second>-4.56000000000000000e+02</second>
</second>
</item>
</modulePositions>
<moduleNotes class_id="18" tracking_level="0" version="0">
<count>0</count>
<item_version>0</item_version>
</moduleNotes>
<connectionNotes>
<count>0</count>
<item_version>0</item_version>
</connectionNotes>
<moduleTags class_id="19" tracking_level="0" version="0">
<count>2</count>
<item_version>0</item_version>
<item class_id="20" tracking_level="0" version="0">
<first>FairMesh:0</first>
<second>-1</second>
</item>
<item>
<first>GetFieldBoundary:0</first>
<second>-1</second>
</item>
</moduleTags>
<disabledModules class_id="21" tracking_level="0" version="0">
<count>0</count>
<item_version>0</item_version>
</disabledModules>
<disabledConnections>
<count>0</count>
<item_version>0</item_version>
</disabledConnections>
<moduleTagLabels class_id="22" tracking_level="0" version="0">
<count>0</count>
<item_version>0</item_version>
</moduleTagLabels>
<loadTagGroups>0</loadTagGroups>
<subnetworks class_id="23" tracking_level="0" version="0">
<count>0</count>
<item_version>0</item_version>
</subnetworks>
</networkFragment>
</boost_serialization>
" ));
*/
}
void CompositeModuleTestGFB_FM::execute()
{
remark("Basic composite module concept part 1");
auto subNet = network()->createSubnetwork();
if (subNet)
{
remark("Subnet created.");
}
else
{
error("Subnet null");
return;
}
if (!subNet->getNetwork())
{
error("Subnet's network state is null");
return;
}
auto gfb = subNet->addModule({"GetFieldBoundary", "...", ",,,"});
auto fm = subNet->addModule({"FairMesh", "...", ",,,"});
if (subNet->getNetwork()->nmodules() == 2)
{
remark("Created subnet with 2 modules");
}
else
{
error("Subnet missing modules");
return;
}
}
<commit_msg>Internal connection made<commit_after>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2020 Scientific Computing and Imaging Institute,
University of Utah.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include <Modules/Legacy/Fields/CompositeModuleTestGFB_FM.h>
#include <Dataflow/Network/NetworkInterface.h>
#include <Dataflow/Network/ConnectionId.h>
using namespace SCIRun::Modules::Fields;
using namespace SCIRun;
MODULE_INFO_DEF(CompositeModuleTestGFB_FM, MiscField, SCIRun)
CompositeModuleTestGFB_FM::CompositeModuleTestGFB_FM() : Module(staticInfo_, false)
{
INITIALIZE_PORT(InputField);
INITIALIZE_PORT(FairedMesh);
}
void CompositeModuleTestGFB_FM::setStateDefaults()
{
auto state = get_state();
/*
state->setValue(Variables::FunctionString, std::string(
"<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<!DOCTYPE boost_serialization>
<boost_serialization signature="serialization::archive" version="18">
<networkFragment class_id="0" tracking_level="0" version="6">
<networkInfo class_id="1" tracking_level="0" version="0">
<modules class_id="2" tracking_level="0" version="0">
<count>2</count>
<item_version>0</item_version>
<item class_id="3" tracking_level="0" version="0">
<first>FairMesh:0</first>
<second class_id="4" tracking_level="0" version="0">
<module class_id="5" tracking_level="0" version="0">
<package_name_>SCIRun</package_name_>
<category_name_>NewField</category_name_>
<module_name_>FairMesh</module_name_>
</module>
<state class_id="6" tracking_level="0" version="0">
<stateMap class_id="7" tracking_level="0" version="0">
<count>5</count>
<item_version>0</item_version>
<item class_id="8" tracking_level="0" version="0">
<first class_id="9" tracking_level="0" version="0">
<name>FairMeshMethod</name>
</first>
<second class_id="10" tracking_level="0" version="0">
<name>FairMeshMethod</name>
<value class_id="11" tracking_level="1" version="0" object_id="_0">
<which>2</which>
<value>fast</value>
</value>
</second>
</item>
<item>
<first>
<name>FilterCutoff</name>
</first>
<second>
<name>FilterCutoff</name>
<value object_id="_1">
<which>1</which>
<value>1.00000000000000006e-01</value>
</value>
</second>
</item>
<item>
<first>
<name>Lambda</name>
</first>
<second>
<name>Lambda</name>
<value object_id="_2">
<which>1</which>
<value>6.30700000000000038e-01</value>
</value>
</second>
</item>
<item>
<first>
<name>NumIterations</name>
</first>
<second>
<name>NumIterations</name>
<value object_id="_3">
<which>0</which>
<value>50</value>
</value>
</second>
</item>
<item>
<first>
<name>ProgrammableInputPortEnabled</name>
</first>
<second>
<name>ProgrammableInputPortEnabled</name>
<value object_id="_4">
<which>3</which>
<value>0</value>
</value>
</second>
</item>
</stateMap>
</state>
</second>
</item>
<item>
<first>GetFieldBoundary:0</first>
<second>
<module>
<package_name_>SCIRun</package_name_>
<category_name_>NewField</category_name_>
<module_name_>GetFieldBoundary</module_name_>
</module>
<state>
<stateMap>
<count>1</count>
<item_version>0</item_version>
<item>
<first>
<name>ProgrammableInputPortEnabled</name>
</first>
<second>
<name>ProgrammableInputPortEnabled</name>
<value object_id="_5">
<which>3</which>
<value>0</value>
</value>
</second>
</item>
</stateMap>
</state>
</second>
</item>
</modules>
<connections class_id="12" tracking_level="0" version="0">
<count>1</count>
<item_version>0</item_version>
<item class_id="13" tracking_level="0" version="0">
<moduleId1_>GetFieldBoundary:0</moduleId1_>
<port1_ class_id="14" tracking_level="0" version="0">
<name>BoundaryField</name>
<id>0</id>
</port1_>
<moduleId2_>FairMesh:0</moduleId2_>
<port2_>
<name>Input_Mesh</name>
<id>0</id>
</port2_>
</item>
</connections>
</networkInfo>
<modulePositions class_id="15" tracking_level="0" version="0">
<count>2</count>
<item_version>0</item_version>
<item class_id="16" tracking_level="0" version="0">
<first>FairMesh:0</first>
<second class_id="17" tracking_level="0" version="0">
<first>-4.90000000000000000e+02</first>
<second>-3.80000000000000000e+02</second>
</second>
</item>
<item>
<first>GetFieldBoundary:0</first>
<second>
<first>-5.32000000000000000e+02</first>
<second>-4.56000000000000000e+02</second>
</second>
</item>
</modulePositions>
<moduleNotes class_id="18" tracking_level="0" version="0">
<count>0</count>
<item_version>0</item_version>
</moduleNotes>
<connectionNotes>
<count>0</count>
<item_version>0</item_version>
</connectionNotes>
<moduleTags class_id="19" tracking_level="0" version="0">
<count>2</count>
<item_version>0</item_version>
<item class_id="20" tracking_level="0" version="0">
<first>FairMesh:0</first>
<second>-1</second>
</item>
<item>
<first>GetFieldBoundary:0</first>
<second>-1</second>
</item>
</moduleTags>
<disabledModules class_id="21" tracking_level="0" version="0">
<count>0</count>
<item_version>0</item_version>
</disabledModules>
<disabledConnections>
<count>0</count>
<item_version>0</item_version>
</disabledConnections>
<moduleTagLabels class_id="22" tracking_level="0" version="0">
<count>0</count>
<item_version>0</item_version>
</moduleTagLabels>
<loadTagGroups>0</loadTagGroups>
<subnetworks class_id="23" tracking_level="0" version="0">
<count>0</count>
<item_version>0</item_version>
</subnetworks>
</networkFragment>
</boost_serialization>
" ));
*/
}
void CompositeModuleTestGFB_FM::execute()
{
remark("Basic composite module concept part 1");
auto subNet = network()->createSubnetwork();
if (subNet)
{
remark("Subnet created.");
}
else
{
error("Subnet null");
return;
}
if (!subNet->getNetwork())
{
error("Subnet's network state is null");
return;
}
auto gfb = subNet->addModule({"GetFieldBoundary", "...", ",,,"});
auto fm = subNet->addModule({"FairMesh", "...", ",,,"});
if (subNet->getNetwork()->nmodules() == 2)
{
remark("Created subnet with 2 modules");
}
else
{
error("Subnet missing modules");
return;
}
auto conn = subNet->requestConnection(gfb->outputPorts()[0].get(), fm->inputPorts()[0].get());
if (conn && subNet->getNetwork()->nconnections() == 1)
{
remark("Created connection between 2 modules");
}
else
{
error("Connection error");
return;
}
}
<|endoftext|>
|
<commit_before>/**
* \file timestamp.cxx
* Provides a class for managing a timestamp (seconds & milliseconds.)
*/
// Written by Curtis Olson, started December 1998.
//
// Copyright (C) 1998 Curtis L. Olson - curt@flightgear.org
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//
// $Id$
#ifdef HAVE_CONFIG_H
# include <simgear_config.h>
#endif
#ifdef HAVE_WINDOWS_H
# include <windows.h>
#endif
#include <simgear/compiler.h>
#ifdef SG_HAVE_STD_INCLUDES
# include <ctime>
#else
# include <time.h>
#endif
#ifdef HAVE_SYS_TIMEB_H
# include <sys/timeb.h> // for ftime() and struct timeb
#endif
#ifdef HAVE_UNISTD_H
# include <unistd.h> // for gettimeofday()
#endif
#ifdef HAVE_SYS_TIME_H
# include <sys/time.h> // for get/setitimer, gettimeofday, struct timeval
#endif
// -dw- want to use metrowerks time.h
#ifdef macintosh
# include <time.h>
# include <timer.h>
#endif
#ifdef WIN32
# include <windows.h>
# if defined( __CYGWIN__ ) || defined( __CYGWIN32__ )
# define NEAR /* */
# define FAR /* */
# endif
# include <mmsystem.h>
#endif
#include "timestamp.hxx"
void SGTimeStamp::stamp() {
#if defined( WIN32 )
unsigned int t;
t = timeGetTime();
seconds = 0;
usec = t * 1000;
#elif defined( HAVE_GETTIMEOFDAY )
struct timeval current;
struct timezone tz;
// sg_timestamp currtime;
gettimeofday(¤t, &tz);
seconds = current.tv_sec;
usec = current.tv_usec;
#elif defined( HAVE_GETLOCALTIME )
SYSTEMTIME current;
GetLocalTime(¤t);
seconds = current.wSecond;
usec = current.wMilliseconds * 1000;
#elif defined( HAVE_FTIME )
struct timeb current;
ftime(¤t);
seconds = current.time;
usec = current.millitm * 1000;
// -dw- uses time manager
#elif defined( macintosh )
UnsignedWide ms;
Microseconds(&ms);
seconds = ms.lo / 1000000;
usec = ms.lo - ( seconds * 1000000 );
#else
# error Port me
#endif
}
// increment the time stamp by the number of microseconds (usec)
SGTimeStamp operator + (const SGTimeStamp& t, const long& m) {
#ifdef WIN32
return SGTimeStamp( 0, t.usec + m );
#else
return SGTimeStamp( t.seconds + ( t.usec + m ) / 1000000,
( t.usec + m ) % 1000000 );
#endif
}
// difference between time stamps in microseconds (usec)
long operator - (const SGTimeStamp& a, const SGTimeStamp& b)
{
#if defined( WIN32 )
return a.usec - b.usec;
#else
return 1000000 * (a.seconds - b.seconds) + (a.usec - b.usec);
#endif
}
<commit_msg>tweak.<commit_after>/**
* \file timestamp.cxx
* Provides a class for managing a timestamp (seconds & milliseconds.)
*/
// Written by Curtis Olson, started December 1998.
//
// Copyright (C) 1998 Curtis L. Olson - curt@flightgear.org
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//
// $Id$
#ifdef HAVE_CONFIG_H
# include <simgear_config.h>
#endif
#ifdef HAVE_WINDOWS_H
# include <windows.h>
#endif
#include <simgear/compiler.h>
#ifdef SG_HAVE_STD_INCLUDES
# include <ctime>
#else
# include <time.h>
#endif
#ifdef HAVE_SYS_TIMEB_H
# include <sys/timeb.h> // for ftime() and struct timeb
#endif
#ifdef HAVE_UNISTD_H
# include <unistd.h> // for gettimeofday()
#endif
#ifdef HAVE_SYS_TIME_H
# include <sys/time.h> // for get/setitimer, gettimeofday, struct timeval
#endif
// -dw- want to use metrowerks time.h
#ifdef macintosh
# include <time.h>
# include <timer.h>
#endif
#ifdef WIN32
# include <windows.h>
# if defined( __CYGWIN__ ) || defined( __CYGWIN32__ )
# define NEAR /* */
# define FAR /* */
# endif
# include <mmsystem.h>
#endif
#include "timestamp.hxx"
void SGTimeStamp::stamp() {
#if defined( WIN32 )
unsigned int t;
t = timeGetTime();
seconds = 0;
usec = t * 1000;
#elif defined( HAVE_GETTIMEOFDAY )
struct timeval current;
struct timezone tz;
// sg_timestamp currtime;
gettimeofday(¤t, &tz);
seconds = current.tv_sec;
usec = current.tv_usec;
#elif defined( HAVE_GETLOCALTIME )
SYSTEMTIME current;
GetLocalTime(¤t);
seconds = current.wSecond;
usec = current.wMilliseconds * 1000;
#elif defined( HAVE_FTIME )
struct timeb current;
ftime(¤t);
seconds = current.time;
usec = current.millitm * 1000;
// -dw- uses time manager
#elif defined( macintosh )
UnsignedWide ms;
Microseconds(&ms);
seconds = ms.lo / 1000000;
usec = ms.lo - ( seconds * 1000000 );
#else
# error Port me
#endif
}
// increment the time stamp by the number of microseconds (usec)
SGTimeStamp operator + (const SGTimeStamp& t, const long& m) {
#if defined( WIN32 )
return SGTimeStamp( 0, t.usec + m );
#else
return SGTimeStamp( t.seconds + ( t.usec + m ) / 1000000,
( t.usec + m ) % 1000000 );
#endif
}
// difference between time stamps in microseconds (usec)
long operator - (const SGTimeStamp& a, const SGTimeStamp& b)
{
#if defined( WIN32 )
return a.usec - b.usec;
#else
return 1000000 * (a.seconds - b.seconds) + (a.usec - b.usec);
#endif
}
<|endoftext|>
|
<commit_before>/* Siconos is a program dedicated to modeling, simulation and control
* of non smooth dynamical systems.
*
* Copyright 2022 INRIA.
*
* 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 "SiconosConfig.h"
#include "EigenProblemsTest.hpp"
#include "SiconosAlgebra.hpp"
#include "SimpleMatrixFriends.hpp"
#include "bindings_utils.hpp"
#include <limits>
#include <iostream>
#include <boost/numeric/ublas/io.hpp>
#include <boost/numeric/ublas/matrix_proxy.hpp>
#include "SiconosVector.hpp"
#define CPPUNIT_ASSERT_NOT_EQUAL(message, alpha, omega) \
if ((alpha) == (omega)) CPPUNIT_FAIL(message);
// Note FP : add tests for complex matrices and geev, if needed (?)
CPPUNIT_TEST_SUITE_REGISTRATION(EigenProblemsTest);
void EigenProblemsTest::setUp()
{
size = 5;
A.reset(new SimpleMatrix(size,size));
// Initialize A with random values.
A->randomize();
Aref.reset(new SimpleMatrix(*A));
}
void EigenProblemsTest::tearDown()
{}
void EigenProblemsTest::testSyev()
{
std::cout << "--> Test: syev." <<std::endl;
// turn A to a symmetric matrix
A->randomize_sym();
*Aref = *A;
// Initialize EigenVectors with A
SP::SiconosVector EigenValues(new SiconosVector(size));
SP::SimpleMatrix EigenVectors(new SimpleMatrix(*A));
// *EigenVectors = *A;
Siconos::eigenproblems::syev(*EigenValues, *EigenVectors);
DenseVect error(size);
error *= 0.0;
for(unsigned int i = 0; i < size; ++i)
{
error.plus_assign(ublas::prod(*A->dense(), column(*EigenVectors->dense(), i)));
error.minus_assign((*EigenValues->dense())(i)*column(*EigenVectors->dense(),i));
}
// Check ...
CPPUNIT_ASSERT_EQUAL_MESSAGE("testSyev 1: ", norm_2(error) < 10 * std::numeric_limits< double >::epsilon(), true);
// Check if A has not been modified
CPPUNIT_ASSERT_EQUAL_MESSAGE("testSyev 2: ", (*A) == (*Aref), true);
// Now compute only eigenvalues
SP::SiconosVector RefEigenValues(new SiconosVector(*EigenValues));
*EigenVectors = *A;
*EigenValues *= 0.0;
Siconos::eigenproblems::syev(*EigenValues, *EigenVectors, false);
CPPUNIT_ASSERT_EQUAL_MESSAGE("testSyev 3: ", ((*EigenValues) - (*RefEigenValues)).norm2() < 10 * std::numeric_limits< double >::epsilon(), true);
CPPUNIT_ASSERT_EQUAL_MESSAGE("testSyev 4: ", (*A) == (*Aref), true);
std::cout << "--> Syev test ended with success." <<std::endl;
}
void EigenProblemsTest::testGeev1()
{
std::cout << "--> Test: geev1." <<std::endl;
// Compute only right eigenvectors.
complex_matrix fake(1,1), rightV(size,size);
complex_vector eigenval(size);
Siconos::eigenproblems::geev(*A, eigenval, fake, rightV);
complex_vector error(size);
for(unsigned int i = 0; i < size; ++i) error(i) = 0.0;
for(unsigned int i = 0; i < size; ++i)
{
error.plus_assign(ublas::prod(*A->dense(), column(rightV, i)));
error.minus_assign(eigenval(i)*column(rightV,i));
}
// Check ...
CPPUNIT_ASSERT_EQUAL_MESSAGE("testGeev1 1: ", norm_2(error) < 10 * std::numeric_limits< double >::epsilon(), true);
// Check if A has not been modified
CPPUNIT_ASSERT_EQUAL_MESSAGE("testGeev1 2: ", (*A) == (*Aref), true);
// Now compute only eigenvalues
complex_vector RefEigenValues(size);
RefEigenValues = eigenval;
eigenval *= 0.0;
Siconos::eigenproblems::geev(*A, eigenval, fake, fake, false, false);
CPPUNIT_ASSERT_EQUAL_MESSAGE("testGeev1 3: ", norm_2(eigenval - RefEigenValues) < 10 * std::numeric_limits< double >::epsilon(), true);
CPPUNIT_ASSERT_EQUAL_MESSAGE("testGeev1 4: ", (*A) == (*Aref), true);
std::cout << "--> geev1 test ended with success." <<std::endl;
}
void EigenProblemsTest::testGeev2()
{
std::cout << "--> Test: geev2." <<std::endl;
// Compute only left eigenvectors.
complex_matrix fake(1,1), leftV(size,size);
complex_vector eigenval(size);
Siconos::eigenproblems::geev(*A, eigenval, leftV, fake, true, false);
complex_vector error(size);
for(unsigned int i = 0; i < size; ++i) error(i) = 0.0;
for(unsigned int i = 0; i < size; ++i)
{
error.plus_assign(ublas::prod(conj(column(leftV, i)), *A->dense()));
error.minus_assign(eigenval(i)*conj(column(leftV,i)));
}
// Check ...
CPPUNIT_ASSERT_EQUAL_MESSAGE("testGeev2 1: ", norm_2(error) < 10 * std::numeric_limits< double >::epsilon(), true);
// Check if A has not been modified
CPPUNIT_ASSERT_EQUAL_MESSAGE("testGeev2 2: ", (*A) == (*Aref), true);
std::cout << "--> geev1 test ended with success." <<std::endl;
}
void EigenProblemsTest::testGeev3()
{
std::cout << "--> Test: geev3." <<std::endl;
// Compute left and right eigenvectors.
complex_matrix leftV(size,size), rightV(size,size);
complex_vector eigenval(size);
Siconos::eigenproblems::geev(*A, eigenval, leftV, rightV, true, true);
complex_vector error(size);
for(unsigned int i = 0; i < size; ++i) error(i) = 0.0;
for(unsigned int i = 0; i < size; ++i)
{
error.plus_assign(ublas::prod(*A->dense(), column(rightV, i)));
error.minus_assign(eigenval(i)*column(rightV,i));
error.plus_assign(ublas::prod(conj(column(leftV, i)), *A->dense()));
error.minus_assign(eigenval(i)*conj(column(leftV,i)));
}
std::cout << norm_2(error) << std::endl;
// Check ...
CPPUNIT_ASSERT_EQUAL_MESSAGE("testGeev3 1: ", norm_2(error) < size * 10 * std::numeric_limits< double >::epsilon(), true);
// Check if A has not been modified
CPPUNIT_ASSERT_EQUAL_MESSAGE("testGeev3 2: ", (*A) == (*Aref), true);
std::cout << "--> geev3 test ended with success." <<std::endl;
}
void EigenProblemsTest::End()
{
std::cout << "======================================" <<std::endl;
std::cout << " ===== End of EigenProblems tests ===== " <<std::endl;
std::cout << "======================================" <<std::endl;
}
<commit_msg>[docker-build] Rebuild docker images. Fix failing test<commit_after>/* Siconos is a program dedicated to modeling, simulation and control
* of non smooth dynamical systems.
*
* Copyright 2022 INRIA.
*
* 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 "SiconosConfig.h"
#include "EigenProblemsTest.hpp"
#include "SiconosAlgebra.hpp"
#include "SimpleMatrixFriends.hpp"
#include "bindings_utils.hpp"
#include <limits>
#include <iostream>
#include <boost/numeric/ublas/io.hpp>
#include <boost/numeric/ublas/matrix_proxy.hpp>
#include "SiconosVector.hpp"
#define CPPUNIT_ASSERT_NOT_EQUAL(message, alpha, omega) \
if ((alpha) == (omega)) CPPUNIT_FAIL(message);
// Note FP : add tests for complex matrices and geev, if needed (?)
CPPUNIT_TEST_SUITE_REGISTRATION(EigenProblemsTest);
void EigenProblemsTest::setUp()
{
size = 5;
A.reset(new SimpleMatrix(size,size));
// Initialize A with random values.
A->randomize();
Aref.reset(new SimpleMatrix(*A));
}
void EigenProblemsTest::tearDown()
{}
void EigenProblemsTest::testSyev()
{
std::cout << "--> Test: syev." <<std::endl;
// turn A to a symmetric matrix
A->randomize_sym();
*Aref = *A;
// Initialize EigenVectors with A
SP::SiconosVector EigenValues(new SiconosVector(size));
SP::SimpleMatrix EigenVectors(new SimpleMatrix(*A));
// *EigenVectors = *A;
Siconos::eigenproblems::syev(*EigenValues, *EigenVectors);
DenseVect error(size);
error *= 0.0;
for(unsigned int i = 0; i < size; ++i)
{
error.plus_assign(ublas::prod(*A->dense(), column(*EigenVectors->dense(), i)));
error.minus_assign((*EigenValues->dense())(i)*column(*EigenVectors->dense(),i));
}
// Check ...
CPPUNIT_ASSERT_EQUAL_MESSAGE("testSyev 1: ", norm_2(error) < 10 * std::numeric_limits< double >::epsilon(), true);
// Check if A has not been modified
CPPUNIT_ASSERT_EQUAL_MESSAGE("testSyev 2: ", (*A) == (*Aref), true);
// Now compute only eigenvalues
SP::SiconosVector RefEigenValues(new SiconosVector(*EigenValues));
*EigenVectors = *A;
*EigenValues *= 0.0;
Siconos::eigenproblems::syev(*EigenValues, *EigenVectors, false);
CPPUNIT_ASSERT_EQUAL_MESSAGE("testSyev 3: ", ((*EigenValues) - (*RefEigenValues)).norm2() < 10 * std::numeric_limits< double >::epsilon(), true);
CPPUNIT_ASSERT_EQUAL_MESSAGE("testSyev 4: ", (*A) == (*Aref), true);
std::cout << "--> Syev test ended with success." <<std::endl;
}
void EigenProblemsTest::testGeev1()
{
std::cout << "--> Test: geev1." <<std::endl;
// Compute only right eigenvectors.
complex_matrix fake(1,1), rightV(size,size);
complex_vector eigenval(size);
Siconos::eigenproblems::geev(*A, eigenval, fake, rightV);
complex_vector error(size);
for(unsigned int i = 0; i < size; ++i) error(i) = 0.0;
for(unsigned int i = 0; i < size; ++i)
{
error.plus_assign(ublas::prod(*A->dense(), column(rightV, i)));
error.minus_assign(eigenval(i)*column(rightV,i));
}
// Check ...
CPPUNIT_ASSERT_EQUAL_MESSAGE("testGeev1 1: ", norm_2(error) < 12 * std::numeric_limits< double >::epsilon(), true);
// Check if A has not been modified
CPPUNIT_ASSERT_EQUAL_MESSAGE("testGeev1 2: ", (*A) == (*Aref), true);
// Now compute only eigenvalues
complex_vector RefEigenValues(size);
RefEigenValues = eigenval;
eigenval *= 0.0;
Siconos::eigenproblems::geev(*A, eigenval, fake, fake, false, false);
CPPUNIT_ASSERT_EQUAL_MESSAGE("testGeev1 3: ", norm_2(eigenval - RefEigenValues) < 10 * std::numeric_limits< double >::epsilon(), true);
CPPUNIT_ASSERT_EQUAL_MESSAGE("testGeev1 4: ", (*A) == (*Aref), true);
std::cout << "--> geev1 test ended with success." <<std::endl;
}
void EigenProblemsTest::testGeev2()
{
std::cout << "--> Test: geev2." <<std::endl;
// Compute only left eigenvectors.
complex_matrix fake(1,1), leftV(size,size);
complex_vector eigenval(size);
Siconos::eigenproblems::geev(*A, eigenval, leftV, fake, true, false);
complex_vector error(size);
for(unsigned int i = 0; i < size; ++i) error(i) = 0.0;
for(unsigned int i = 0; i < size; ++i)
{
error.plus_assign(ublas::prod(conj(column(leftV, i)), *A->dense()));
error.minus_assign(eigenval(i)*conj(column(leftV,i)));
}
// Check ...
CPPUNIT_ASSERT_EQUAL_MESSAGE("testGeev2 1: ", norm_2(error) < 10 * std::numeric_limits< double >::epsilon(), true);
// Check if A has not been modified
CPPUNIT_ASSERT_EQUAL_MESSAGE("testGeev2 2: ", (*A) == (*Aref), true);
std::cout << "--> geev1 test ended with success." <<std::endl;
}
void EigenProblemsTest::testGeev3()
{
std::cout << "--> Test: geev3." <<std::endl;
// Compute left and right eigenvectors.
complex_matrix leftV(size,size), rightV(size,size);
complex_vector eigenval(size);
Siconos::eigenproblems::geev(*A, eigenval, leftV, rightV, true, true);
complex_vector error(size);
for(unsigned int i = 0; i < size; ++i) error(i) = 0.0;
for(unsigned int i = 0; i < size; ++i)
{
error.plus_assign(ublas::prod(*A->dense(), column(rightV, i)));
error.minus_assign(eigenval(i)*column(rightV,i));
error.plus_assign(ublas::prod(conj(column(leftV, i)), *A->dense()));
error.minus_assign(eigenval(i)*conj(column(leftV,i)));
}
std::cout << norm_2(error) << std::endl;
// Check ...
CPPUNIT_ASSERT_EQUAL_MESSAGE("testGeev3 1: ", norm_2(error) < size * 10 * std::numeric_limits< double >::epsilon(), true);
// Check if A has not been modified
CPPUNIT_ASSERT_EQUAL_MESSAGE("testGeev3 2: ", (*A) == (*Aref), true);
std::cout << "--> geev3 test ended with success." <<std::endl;
}
void EigenProblemsTest::End()
{
std::cout << "======================================" <<std::endl;
std::cout << " ===== End of EigenProblems tests ===== " <<std::endl;
std::cout << "======================================" <<std::endl;
}
<|endoftext|>
|
<commit_before>// VectorInt.cpp
// Implementation of our Vector of ints class
#include "VectorInt.h"
// constructor
VectorInt::VectorInt() {
capacity = INITIAL_CAPACITY;
count = 0;
elements = new int[capacity];
}
// destructor
VectorInt::~VectorInt() {
delete [] elements;
}
// append value at end
void VectorInt::add(int value) {
if (count == capacity) {
expand();
}
// add to end of array
elements[count] = value;
count++;
}
// insert a value at index
void VectorInt::insert(int index, int value) {
if (count == capacity) {
expand();
}
// move elements after index to the right
for (int i=count; i > index; i--) {
elements[i] = elements[i-1];
}
elements[index] = value;
count++;
}
// return value at index
int VectorInt::get(int index) {
return elements[index];
}
// remove value at index
void VectorInt::remove(int index) {
for (int i=index; i < count; i++) {
elements[i] = elements[i+1];
}
count--;
}
// return the number of elements in the array
int VectorInt::size() {
return count;
}
// true if zero elements
bool VectorInt::isEmpty() {
return count == 0;
}
// overload <<
ostream &operator<<(ostream &out, VectorInt &vec) {
out << "[";
for (int i=0; i < vec.count; i++) {
out << vec.elements[i];
if (i < vec.count - 1) {
out << ", ";
}
}
out << "]";
return out;
}
// expand
void VectorInt::expand() {
// 1. create space for new array
int *newElements = new int[capacity * 2];
// 2. copy the elements
for (int i=0; i < count; i++) {
newElements[i] = elements[i];
}
// 3. delete old array
delete [] elements;
// 4. point elements to new array
elements = newElements;
// 5. update capacity
capacity *= 2;
}
<commit_msg>fixed bug in VectorInt<commit_after>// VectorInt.cpp
// Implementation of VectorInt class
#include "VectorInt.h"
// constructor
VectorInt::VectorInt(){
capacity = INITIAL_CAPACITY;
elements = new int[capacity];
count = 0;
}
// destructor
VectorInt::~VectorInt(){
delete [] elements;
}
// append value to the end of our array
void VectorInt::add(int value){
if (count == capacity) {
expand();
}
elements[count] = value;
count++;
}
// insert value at index
void VectorInt::insert(int index, int value){
if (count == capacity) {
expand();
}
for (int i=count; i > index; i--) {
elements[i] = elements[i-1];
}
elements[index] = value;
count++;
}
// return the element at index
int VectorInt::get(int index){
return elements[index];
}
// remove value from index
void VectorInt::remove(int index){
for (int i=index; i < count - 1; i++) {
elements[i] = elements[i+1];
}
count--;
}
// returns the number of elements
int VectorInt::size(){
return count;
}
// returns true if there aren't any elements
bool VectorInt::isEmpty(){
return count == 0;
}
// overload << operator
ostream &operator<<(ostream &out, VectorInt &vec){
out << "[";
for (int i=0; i < vec.count; i++) {
out << vec.elements[i];
if (i < vec.count - 1) {
out << ", ";
}
}
out << "]";
return out;
}
void VectorInt::expand() {
// 1. ask for new space for a new array
int *newElements = new int[capacity * 2];
// 2. copy the values over
for (int i=0; i < count; i++) {
newElements[i] = elements[i];
}
// 3. delete old array
delete [] elements;
// 4. point elements to new array
elements = newElements;
// 5. Update capacity
capacity *= 2;
}
<|endoftext|>
|
<commit_before>// Copyright 2010-2012 RethinkDB, all rights reserved.
#include "clustering/administration/reactor_driver.tcc"
#include "memcached/protocol.hpp"
#include "serializer/serializer.hpp"
#include "serializer/translator.hpp"
template class reactor_driver_t<memcached_protocol_t>;
<commit_msg>Removed reactor_driver_instantiate_memcached.cc.<commit_after><|endoftext|>
|
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/eff_config/plug_rules.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file plug_rules.H
/// @brief Enforcement of rules for plugging in DIMM
///
// *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com>
// *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: FSP:HB
#ifndef _MSS_PLUG_RULES_H_
#define _MSS_PLUG_RULES_H_
#include <fapi2.H>
#include <cstdint>
#include <lib/dimm/kind.H>
namespace mss
{
namespace plug_rule
{
///
/// @brief Helper to evaluate the unsupported rank config override attribute
/// @param[in] i_dimm0_ranks count of the ranks on DIMM in slot 0
/// @param[in] i_dimm1_ranks count of the ranks on DIMM in slot 1
/// @param[in] i_attr value of the attribute containing the unsupported rank configs
/// @return true iff this rank config is supported according to the unsupported attribute
/// @note not to be used to enforce populated/unpopulated - e.g., 0 ranks in both slots is ignored
///
bool unsupported_rank_helper(const uint64_t i_dimm0_ranks, const uint64_t i_dimm1_ranks,
const fapi2::buffer<uint64_t>& i_attr);
///
/// @brief Helper to find the best represented DIMM type in a vector of dimm::kind
/// @param[in, out] io_kinds a vector of dimm::kind
/// @return std::pair representing the type and the count.
/// @note the vector of kinds comes back sorted by DIMM type.
///
std::pair<uint8_t, uint64_t> dimm_type_helper(std::vector<dimm::kind>& io_kinds);
///
/// @brief Rank violation helper
/// Used to record a rank configuration violation. Broken out from other checking
/// so that we can throw a rank violation directly from VPD processing.
/// @tparam T target type for the error log
/// @param[in] i_target the target which constrains the rank violation checking
/// @param[in] l_dimm0_ranks the number of ranks on the DIMM in slot 0
/// @param[in] l_dimm1_ranks the number of ranks on the DIMM in slot 1
/// @note Commits the proper error log; does little else
/// @note Not presently used, but also not compiled in - left here because I think we're
/// gonna need it eventually.
///
template< fapi2::TargetType T >
inline void rank_violation(const fapi2::Target<T> i_target, const uint8_t l_dimm0_ranks, const uint8_t l_dimm1_ranks)
{
// fapi2::current_err will NOT be set which is important for the caller - they can return
// the original ReturnCode which got us here.
FAPI_ERR("Rank config on %s violates the rank configuration rules. DIMM0 ranks: %d DIMM1 ranks: %d",
mss::c_str(i_target), l_dimm0_ranks, l_dimm1_ranks);
fapi2::MSS_PLUG_RULES_INVALID_RANK_CONFIG()
.set_RANKS_ON_DIMM0(l_dimm0_ranks)
.set_RANKS_ON_DIMM1(l_dimm1_ranks)
.set_TARGET(i_target).execute(fapi2::FAPI2_ERRL_SEV_UNDEFINED, true);
}
///
/// @brief Enforce no mixing DIMM types
/// @param[in] i_kinds a vector of DIMM (sorted while procesing)
/// @return fapi2::FAPI2_RC_SUCCESS if okay, otherwise a MSS_PLUG_RULE error code
/// @note This function will commit error logs representing the mixing failure
/// @note The list of DIMM represents all the DIMM to check. So, if you want to
/// check the consistency of types across an MCS, give the list of DIMM on that MCS.
/// If you want to check across an MCBIST, system, etc., give that list of DIMM.
///
fapi2::ReturnCode dimm_type_mixing(std::vector<dimm::kind>& io_kinds);
///
/// @brief Enforce rank configs
/// Enforces rank configurations which are not part of the VPD/rank config thing.
/// @note Reads an MRW attribute to further limit rank configs.
/// @param[in] i_target the port
/// @param[in] i_kinds a vector of DIMM (sorted while processing)
/// @param[in] i_ranks_override value of mrw_unsupported_rank_config attribute
/// @return fapi2::FAPI2_RC_SUCCESS if okay
/// @note Expects the kind array to represent the DIMM on the port.
///
fapi2::ReturnCode check_rank_config(const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target,
const std::vector<dimm::kind>& i_kinds,
const uint64_t i_ranks_override);
} // plug_rule
} // mss
#endif // _MSS_PLUG_RULES_H_
<commit_msg>Implement BC attributes and make eff_dimm class<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/eff_config/plug_rules.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file plug_rules.H
/// @brief Enforcement of rules for plugging in DIMM
///
// *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com>
// *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: FSP:HB
#ifndef _MSS_PLUG_RULES_H_
#define _MSS_PLUG_RULES_H_
#include <fapi2.H>
#include <cstdint>
#include <lib/dimm/kind.H>
namespace mss
{
namespace plug_rule
{
///
/// @brief Enforce the plug-rules per MCS
/// @param[in] i_target FAPI2 target (MCS)
/// @return fapi2::FAPI2_RC_SUCCESS if okay, otherwise a MSS_PLUG_RULE error code
///
fapi2::ReturnCode enforce_plug_rules(const fapi2::Target<fapi2::TARGET_TYPE_MCS>& i_target);
///
/// @brief Enforce the plug-rules per MCA
/// @param[in] i_target FAPI2 target (MCA)
/// @return fapi2::FAPI2_RC_SUCCESS if okay, otherwise a MSS_PLUG_RULE error code
///
fapi2::ReturnCode enforce_plug_rules(const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target);
///
/// @brief Helper to evaluate the unsupported rank config override attribute
/// @param[in] i_dimm0_ranks count of the ranks on DIMM in slot 0
/// @param[in] i_dimm1_ranks count of the ranks on DIMM in slot 1
/// @param[in] i_attr value of the attribute containing the unsupported rank configs
/// @return true iff this rank config is supported according to the unsupported attribute
/// @note not to be used to enforce populated/unpopulated - e.g., 0 ranks in both slots is ignored
///
bool unsupported_rank_helper(const uint64_t i_dimm0_ranks, const uint64_t i_dimm1_ranks,
const fapi2::buffer<uint64_t>& i_attr);
///
/// @brief Helper to find the best represented DIMM type in a vector of dimm::kind
/// @param[in, out] io_kinds a vector of dimm::kind
/// @return std::pair representing the type and the count.
/// @note the vector of kinds comes back sorted by DIMM type.
///
std::pair<uint8_t, uint64_t> dimm_type_helper(std::vector<dimm::kind>& io_kinds);
///
/// @brief Rank violation helper
/// Used to record a rank configuration violation. Broken out from other checking
/// so that we can throw a rank violation directly from VPD processing.
/// @tparam T target type for the error log
/// @param[in] i_target the target which constrains the rank violation checking
/// @param[in] l_dimm0_ranks the number of ranks on the DIMM in slot 0
/// @param[in] l_dimm1_ranks the number of ranks on the DIMM in slot 1
/// @note Commits the proper error log; does little else
/// @note Not presently used, but also not compiled in - left here because I think we're
/// gonna need it eventually.
///
template< fapi2::TargetType T >
inline void rank_violation(const fapi2::Target<T> i_target, const uint8_t l_dimm0_ranks, const uint8_t l_dimm1_ranks)
{
// fapi2::current_err will NOT be set which is important for the caller - they can return
// the original ReturnCode which got us here.
FAPI_ERR("Rank config on %s violates the rank configuration rules. DIMM0 ranks: %d DIMM1 ranks: %d",
mss::c_str(i_target), l_dimm0_ranks, l_dimm1_ranks);
fapi2::MSS_PLUG_RULES_INVALID_RANK_CONFIG()
.set_RANKS_ON_DIMM0(l_dimm0_ranks)
.set_RANKS_ON_DIMM1(l_dimm1_ranks)
.set_TARGET(i_target).execute(fapi2::FAPI2_ERRL_SEV_UNDEFINED, true);
}
///
/// @brief Enforce no mixing DIMM types
/// @param[in] i_kinds a vector of DIMM (sorted while procesing)
/// @return fapi2::FAPI2_RC_SUCCESS if okay, otherwise a MSS_PLUG_RULE error code
/// @note This function will commit error logs representing the mixing failure
/// @note The list of DIMM represents all the DIMM to check. So, if you want to
/// check the consistency of types across an MCS, give the list of DIMM on that MCS.
/// If you want to check across an MCBIST, system, etc., give that list of DIMM.
///
fapi2::ReturnCode dimm_type_mixing(std::vector<dimm::kind>& io_kinds);
///
/// @brief Enforce rank configs
/// Enforces rank configurations which are not part of the VPD/rank config thing.
/// @note Reads an MRW attribute to further limit rank configs.
/// @param[in] i_target the port
/// @param[in] i_kinds a vector of DIMM (sorted while processing)
/// @param[in] i_ranks_override value of mrw_unsupported_rank_config attribute
/// @return fapi2::FAPI2_RC_SUCCESS if okay
/// @note Expects the kind array to represent the DIMM on the port.
///
fapi2::ReturnCode check_rank_config(const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target,
const std::vector<dimm::kind>& i_kinds,
const uint64_t i_ranks_override);
} // plug_rule
} // mss
#endif // _MSS_PLUG_RULES_H_
<|endoftext|>
|
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_eff_config_thermal.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_mss_eff_config_thermal.C
/// @brief Perform thermal calculations as part of the effective configuration
///
// *HWP HWP Owner: Jacob Harvey <jlharvey@us.ibm.com>
// *HWP HWP Backup: Brian Silver <bsilver@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: FSP:HB
#include <fapi2.H>
#include <vector>
#include <p9_mss_eff_config_thermal.H>
#include <p9_mss_bulk_pwr_throttles.H>
#include <lib/power_thermal/throttle.H>
#include <lib/power_thermal/decoder.H>
#include <lib/dimm/kind.H>
#include <lib/utils/count_dimm.H>
#include <mss.H>
extern "C"
{
///
/// @brief Perform thermal calculations as part of the effective configuration
/// @param[in] i_targets an array of MCS targets all on the same VDDR domain
/// @return FAPI2_RC_SUCCESS iff ok
///
fapi2::ReturnCode p9_mss_eff_config_thermal( const std::vector< fapi2::Target<fapi2::TARGET_TYPE_MCS> >& i_targets )
{
FAPI_INF("Start effective config thermal");
uint16_t l_vddr_slope [mss::PORTS_PER_MCS][mss::MAX_DIMM_PER_PORT] = {};
uint16_t l_vddr_int [mss::PORTS_PER_MCS][mss::MAX_DIMM_PER_PORT] = {};
uint16_t l_total_slope [mss::PORTS_PER_MCS][mss::MAX_DIMM_PER_PORT] = {};
uint16_t l_total_int [mss::PORTS_PER_MCS][mss::MAX_DIMM_PER_PORT] = {};
uint32_t l_thermal_power [mss::PORTS_PER_MCS][mss::MAX_DIMM_PER_PORT] = {};
//Gotta convert into fapi2::buffers. Not very elegant
//Do it here or in the encode and decode functions
//Not that pretty :(
std::vector< uint64_t > l_tslope (mss::power_thermal::SIZE_OF_POWER_CURVES_ATTRS, 0);
std::vector< uint64_t > l_tintercept (mss::power_thermal::SIZE_OF_POWER_CURVES_ATTRS, 0);
std::vector< uint64_t > l_tthermal_power_limit (mss::power_thermal::SIZE_OF_THERMAL_ATTR, 0);
std::vector<fapi2::buffer< uint64_t>> l_slope = {};
std::vector<fapi2::buffer< uint64_t>> l_intercept = {};
std::vector<fapi2::buffer< uint64_t>> l_thermal_power_limit = {};
FAPI_TRY( mss::mrw_pwr_slope (l_tslope.data() ));
FAPI_TRY( mss::mrw_pwr_intercept (l_tintercept.data()) );
FAPI_TRY( mss::mrw_thermal_memory_power_limit (l_tthermal_power_limit.data()) );
{
for (auto l_tslope_iter = l_tslope.begin(); l_tslope_iter != l_tslope.end(); ++l_tslope_iter)
{
auto l_slope_buf = fapi2::buffer<uint64_t> (*l_tslope_iter);
if (l_slope_buf != 0)
{
l_slope.push_back(l_slope_buf);
}
}
for (auto l_tintercept_iter = l_tintercept.begin(); l_tintercept_iter != l_tintercept.end(); ++l_tintercept_iter)
{
auto l_intercept_buf = fapi2::buffer<uint64_t> (*l_tintercept_iter);
if (l_intercept_buf != 0)
{
l_intercept.push_back(l_intercept_buf);
}
}
for (auto l_tthermal_iter = l_tthermal_power_limit.begin();
l_tthermal_iter != l_tthermal_power_limit.end();
++l_tthermal_iter)
{
auto l_tthermal_buf = fapi2::buffer<uint64_t> (*l_tthermal_iter);
if (l_tthermal_buf != 0)
{
l_thermal_power_limit.push_back(l_tthermal_buf);
}
}
}
//Restore runtime_throttles from safemode setting
//Decode and set power curve attributes at the same time
for (const auto& l_mcs : i_targets )
{
//Not doing any work if there are no dimms installed
if (mss::count_dimm(l_mcs) == 0)
{
continue;
}
FAPI_TRY( mss::power_thermal::get_power_attrs(l_mcs,
l_slope,
l_intercept,
l_thermal_power_limit,
l_vddr_slope,
l_vddr_int,
l_total_slope,
l_total_int,
l_thermal_power));
//Sets throttles to max_databus_util value
FAPI_INF("Restoring throttles");
FAPI_TRY( mss::power_thermal::restore_runtime_throttles(l_mcs));
//Set the power attribute (TOTAL_PWR) to just VDDR for the POWER bulk_pwr_throttles, restore to vddr+vpp later for OCC
FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_MSS_TOTAL_PWR_SLOPE,
l_mcs,
l_vddr_slope));
FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_MSS_TOTAL_PWR_INTERCEPT,
l_mcs,
l_vddr_int));
FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_MSS_DIMM_THERMAL_LIMIT,
l_mcs,
l_thermal_power));
}
FAPI_INF("Starting bulk_pwr");
//get the thermal limits, done per dimm and set to worst case for the slot and port throttles
//Bulk_pwr sets the general, all purpose ATTR_MSS_MEM_THROTTLED_N_COMMANDS_PER_SLOT, _PER_PORT, and MAXPOWER ATTRs
FAPI_TRY( p9_mss_bulk_pwr_throttles(i_targets, POWER));
//Set runtime throttles to worst case between ATTR_MSS_MEM_THROTTLED_N_COMMANDS_PER_SLOT
//and ATTR_MSS_MEM_RUNTIME_THROTTLED_N_COMMANDS_PER_SLOT and the _PORT equivalents also
FAPI_INF("Starting update");
FAPI_TRY( mss::power_thermal::update_runtime_throttles (i_targets));
FAPI_INF("finished update");
//Set VDDR+VPP power curve values
for ( const auto& l_mcs : i_targets )
{
FAPI_TRY( mss::power_thermal::get_power_attrs(l_mcs,
l_slope,
l_intercept,
l_thermal_power_limit,
l_vddr_slope,
l_vddr_int,
l_total_slope,
l_total_int,
l_thermal_power));
FAPI_INF( "VDDR+VPP power curve slope is %d, int is %d, thermal_power is %d", l_total_slope[0][0], l_total_int[0][0],
l_thermal_power[0][0]);
//Set the power attribute (TOTAL_PWR) to vpp+vdd power slope
FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_MSS_TOTAL_PWR_SLOPE,
l_mcs,
l_total_slope));
FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_MSS_TOTAL_PWR_INTERCEPT,
l_mcs,
l_total_int));
}
//Run thermal throttles with the VDDR+VPP power curves
FAPI_TRY( p9_mss_bulk_pwr_throttles(i_targets, THERMAL));
//Update everything to worst case
FAPI_TRY( mss::power_thermal::update_runtime_throttles (i_targets));
//Done
FAPI_INF( "End effective config thermal");
fapi_try_exit:
return fapi2::FAPI2_RC_SUCCESS;
}
} //extern C
<commit_msg>Fixing bulk_pwr_throttles calculations<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_eff_config_thermal.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_mss_eff_config_thermal.C
/// @brief Perform thermal calculations as part of the effective configuration
///
// *HWP HWP Owner: Jacob Harvey <jlharvey@us.ibm.com>
// *HWP HWP Backup: Brian Silver <bsilver@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: FSP:HB
#include <fapi2.H>
#include <vector>
#include <p9_mss_eff_config_thermal.H>
#include <p9_mss_bulk_pwr_throttles.H>
#include <lib/power_thermal/throttle.H>
#include <lib/power_thermal/decoder.H>
#include <lib/dimm/kind.H>
#include <lib/utils/count_dimm.H>
#include <mss.H>
extern "C"
{
///
/// @brief Perform thermal calculations as part of the effective configuration
/// @param[in] i_targets an array of MCS targets all on the same VDDR domain
/// @return FAPI2_RC_SUCCESS iff ok
///
fapi2::ReturnCode p9_mss_eff_config_thermal( const std::vector< fapi2::Target<fapi2::TARGET_TYPE_MCS> >& i_targets )
{
FAPI_INF("Start effective config thermal");
uint16_t l_vddr_slope [mss::PORTS_PER_MCS][mss::MAX_DIMM_PER_PORT] = {};
uint16_t l_vddr_int [mss::PORTS_PER_MCS][mss::MAX_DIMM_PER_PORT] = {};
uint16_t l_total_slope [mss::PORTS_PER_MCS][mss::MAX_DIMM_PER_PORT] = {};
uint16_t l_total_int [mss::PORTS_PER_MCS][mss::MAX_DIMM_PER_PORT] = {};
uint32_t l_thermal_power [mss::PORTS_PER_MCS][mss::MAX_DIMM_PER_PORT] = {};
fapi2::ReturnCode l_rc;
//Gotta convert into fapi2::buffers. Not very elegant
//Do it here or in the encode and decode functions
//Not that pretty :(
std::vector< uint64_t > l_tslope (mss::power_thermal::SIZE_OF_POWER_CURVES_ATTRS, 0);
std::vector< uint64_t > l_tintercept (mss::power_thermal::SIZE_OF_POWER_CURVES_ATTRS, 0);
std::vector< uint64_t > l_tthermal_power_limit (mss::power_thermal::SIZE_OF_THERMAL_ATTR, 0);
std::vector<fapi2::buffer< uint64_t>> l_slope = {};
std::vector<fapi2::buffer< uint64_t>> l_intercept = {};
std::vector<fapi2::buffer< uint64_t>> l_thermal_power_limit = {};
FAPI_TRY( mss::mrw_pwr_slope (l_tslope.data() ));
FAPI_TRY( mss::mrw_pwr_intercept (l_tintercept.data()) );
FAPI_TRY( mss::mrw_thermal_memory_power_limit (l_tthermal_power_limit.data()) );
FAPI_TRY( mss::power_thermal::set_runtime_m_and_watt_limit(i_targets));
for (size_t i = 0; i < mss::power_thermal::SIZE_OF_POWER_CURVES_ATTRS; ++i)
{
for (const auto l_cur : l_tslope)
{
fapi2::buffer<uint64_t> l_slope_buf = l_cur;
if (l_slope_buf != 0)
{
l_slope.push_back(l_slope_buf);
}
}
for (auto l_cur : l_tintercept)
{
fapi2::buffer<uint64_t> l_intercept_buf = l_cur;
if (l_intercept_buf != 0)
{
l_intercept.push_back(l_intercept_buf);
}
}
for (auto l_cur : l_tthermal_power_limit)
{
fapi2::buffer<uint64_t> l_tthermal_buf = l_cur;
if (l_tthermal_buf != 0)
{
l_thermal_power_limit.push_back(l_tthermal_buf);
}
}
}
//Restore runtime_throttles from safemode setting
//Decode and set power curve attributes at the same time
for (const auto& l_mcs : i_targets )
{
//Not doing any work if there are no dimms installed
if (mss::count_dimm(l_mcs) == 0)
{
continue;
}
FAPI_TRY( mss::power_thermal::get_power_attrs(l_mcs,
l_slope,
l_intercept,
l_thermal_power_limit,
l_vddr_slope,
l_vddr_int,
l_total_slope,
l_total_int,
l_thermal_power));
//Sets throttles to max_databus_util value
FAPI_INF("Restoring throttles");
FAPI_TRY( mss::power_thermal::restore_runtime_throttles(l_mcs));
//Set the power attribute (TOTAL_PWR) to just VDDR for the POWER bulk_pwr_throttles, restore to vddr+vpp later for OCC
FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_MSS_TOTAL_PWR_SLOPE,
l_mcs,
l_vddr_slope));
FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_MSS_TOTAL_PWR_INTERCEPT,
l_mcs,
l_vddr_int));
FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_MSS_DIMM_THERMAL_LIMIT,
l_mcs,
l_thermal_power));
}
FAPI_INF("Starting bulk_pwr");
//get the thermal limits, done per dimm and set to worst case for the slot and port throttles
//Bulk_pwr sets the general, all purpose ATTR_MSS_MEM_THROTTLED_N_COMMANDS_PER_SLOT, _PER_PORT, and MAXPOWER ATTRs
FAPI_EXEC_HWP(l_rc, p9_mss_bulk_pwr_throttles, i_targets, POWER);
FAPI_TRY(l_rc);
//Set runtime throttles to worst case between ATTR_MSS_MEM_THROTTLED_N_COMMANDS_PER_SLOT
//and ATTR_MSS_MEM_RUNTIME_THROTTLED_N_COMMANDS_PER_SLOT and the _PORT equivalents also
FAPI_INF("Starting update");
FAPI_TRY( mss::power_thermal::update_runtime_throttles (i_targets));
FAPI_INF("finished update");
//Set VDDR+VPP power curve values
for ( const auto& l_mcs : i_targets )
{
FAPI_TRY( mss::power_thermal::get_power_attrs(l_mcs,
l_slope,
l_intercept,
l_thermal_power_limit,
l_vddr_slope,
l_vddr_int,
l_total_slope,
l_total_int,
l_thermal_power));
FAPI_INF( "VDDR+VPP power curve slope is %d, int is %d, thermal_power is %d", l_total_slope[0][0], l_total_int[0][0],
l_thermal_power[0][0]);
//Set the power attribute (TOTAL_PWR) to vpp+vdd power slope
FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_MSS_TOTAL_PWR_SLOPE,
l_mcs,
l_total_slope));
FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_MSS_TOTAL_PWR_INTERCEPT,
l_mcs,
l_total_int));
}
//Run thermal throttles with the VDDR+VPP power curves
FAPI_EXEC_HWP(l_rc, p9_mss_bulk_pwr_throttles, i_targets, THERMAL);
FAPI_TRY(l_rc);
//Update everything to worst case
FAPI_TRY( mss::power_thermal::update_runtime_throttles (i_targets));
//Done
FAPI_INF( "End effective config thermal");
fapi_try_exit:
return fapi2::FAPI2_RC_SUCCESS;
}
} //extern C
<|endoftext|>
|
<commit_before>#include <mimelib/boyermor.h>
#include <mimelib/string.h>
#include <iostream>
using std::cerr;
using std::cout;
using std::endl;
static const char * _haystack =
"haystackNeedleHaystackneedlehaYstackneeDlehaystack";
int main( int argc, char * argv[] ) {
if ( argc == 3 ) { // manual test
DwString needle( argv[1] );
DwString haystack( argv[2] );
DwBoyerMoore csbm( needle ); // case-sensitive
DwBoyerMoore cisbm( needle ); // case-insensitive
cout << "Case-sensitive search found ";
for ( size_t idx = 0 ; ( idx = csbm.FindIn( haystack, idx ) ) != DwString::npos ; ++idx )
cout << (int)idx << " ";
cout << endl;
cout << "Case-insensitive search found ";
for ( size_t idx = 0 ; ( idx = cisbm.FindIn( haystack, idx, false ) ) != DwString::npos ; ++idx )
cout << (int)idx << " ";
cout << endl;
exit( 0 );
} else if ( argc == 1 ) { // automated test
DwString haystack( _haystack );
DwBoyerMoore needle_cs( "needle" );
DwBoyerMoore needle_cis( "needle" );
DwBoyerMoore Needle_cs( "Needle" );
DwBoyerMoore Needle_cis( "Needle" );
DwBoyerMoore neeDle_cs( "neeDle" );
DwBoyerMoore neeDle_cis( "neeDle" );
assert( needle_cs.FindIn( haystack, 0 ) == 22 );
assert( needle_cs.FindIn( haystack, 23 ) == DwString::npos );
assert( needle_cis.FindIn( haystack, 0, false ) == 8 );
assert( needle_cis.FindIn( haystack, 9, false ) == 22 );
assert( needle_cis.FindIn( haystack, 23, false ) == 36 );
assert( needle_cis.FindIn( haystack, 37, false ) == DwString::npos );
assert( Needle_cs.FindIn( haystack, 0 ) == 8 );
assert( Needle_cs.FindIn( haystack, 9 ) == DwString::npos );
assert( Needle_cis.FindIn( haystack, 0, false ) == 8 );
assert( Needle_cis.FindIn( haystack, 9, false ) == 22 );
assert( Needle_cis.FindIn( haystack, 23, false ) == 36 );
assert( Needle_cis.FindIn( haystack, 37, false ) == DwString::npos );
assert( neeDle_cs.FindIn( haystack, 0 ) == 36 );
assert( neeDle_cs.FindIn( haystack, 37 ) == DwString::npos );
assert( neeDle_cis.FindIn( haystack, 0, false ) == 8 );
assert( neeDle_cis.FindIn( haystack, 9, false ) == 22 );
assert( neeDle_cis.FindIn( haystack, 23, false ) == 36 );
assert( neeDle_cis.FindIn( haystack, 37, false ) == DwString::npos );
} else {
cerr << "usage: test_boyermor [ <needle> <haystack> ]" << endl;
exit( 1 );
}
return 0;
};
<commit_msg>pedantic++<commit_after>#include <mimelib/boyermor.h>
#include <mimelib/string.h>
#include <iostream>
using std::cerr;
using std::cout;
using std::endl;
static const char * _haystack =
"haystackNeedleHaystackneedlehaYstackneeDlehaystack";
int main( int argc, char * argv[] ) {
if ( argc == 3 ) { // manual test
DwString needle( argv[1] );
DwString haystack( argv[2] );
DwBoyerMoore csbm( needle ); // case-sensitive
DwBoyerMoore cisbm( needle ); // case-insensitive
cout << "Case-sensitive search found ";
for ( size_t idx = 0 ; ( idx = csbm.FindIn( haystack, idx ) ) != DwString::npos ; ++idx )
cout << (int)idx << " ";
cout << endl;
cout << "Case-insensitive search found ";
for ( size_t idx = 0 ; ( idx = cisbm.FindIn( haystack, idx, false ) ) != DwString::npos ; ++idx )
cout << (int)idx << " ";
cout << endl;
exit( 0 );
} else if ( argc == 1 ) { // automated test
DwString haystack( _haystack );
DwBoyerMoore needle_cs( "needle" );
DwBoyerMoore needle_cis( "needle" );
DwBoyerMoore Needle_cs( "Needle" );
DwBoyerMoore Needle_cis( "Needle" );
DwBoyerMoore neeDle_cs( "neeDle" );
DwBoyerMoore neeDle_cis( "neeDle" );
assert( needle_cs.FindIn( haystack, 0 ) == 22 );
assert( needle_cs.FindIn( haystack, 23 ) == DwString::npos );
assert( needle_cis.FindIn( haystack, 0, false ) == 8 );
assert( needle_cis.FindIn( haystack, 9, false ) == 22 );
assert( needle_cis.FindIn( haystack, 23, false ) == 36 );
assert( needle_cis.FindIn( haystack, 37, false ) == DwString::npos );
assert( Needle_cs.FindIn( haystack, 0 ) == 8 );
assert( Needle_cs.FindIn( haystack, 9 ) == DwString::npos );
assert( Needle_cis.FindIn( haystack, 0, false ) == 8 );
assert( Needle_cis.FindIn( haystack, 9, false ) == 22 );
assert( Needle_cis.FindIn( haystack, 23, false ) == 36 );
assert( Needle_cis.FindIn( haystack, 37, false ) == DwString::npos );
assert( neeDle_cs.FindIn( haystack, 0 ) == 36 );
assert( neeDle_cs.FindIn( haystack, 37 ) == DwString::npos );
assert( neeDle_cis.FindIn( haystack, 0, false ) == 8 );
assert( neeDle_cis.FindIn( haystack, 9, false ) == 22 );
assert( neeDle_cis.FindIn( haystack, 23, false ) == 36 );
assert( neeDle_cis.FindIn( haystack, 37, false ) == DwString::npos );
} else {
cerr << "usage: test_boyermor [ <needle> <haystack> ]" << endl;
exit( 1 );
}
return 0;
}
<|endoftext|>
|
<commit_before>#include "BoundaryConditions.h"
namespace Halide {
namespace BoundaryConditions {
Func repeat_edge(const Func &source,
const std::vector<std::pair<Expr, Expr> > &bounds) {
std::vector<Var> args(source.args());
user_assert(args.size() >= bounds.size()) <<
"repeat_edge called with more bounds (" << bounds.size() <<
") than dimensions (" << args.size() << ") Func " <<
source.name() << "has.\n";
Func bounded;
std::vector<Expr> actuals;
for (size_t i = 0; i < bounds.size(); i++) {
Var arg_var = args[i];
Expr min = bounds[i].first;
Expr extent = bounds[i].second;
if (min.defined() && extent.defined()) {
actuals.push_back(clamp(likely(arg_var), min, min + extent - 1));
} else if (!min.defined() && !extent.defined()) {
actuals.push_back(arg_var);
} else {
user_error << "Partially undefined bounds for " << arg_var << "\n";
}
}
// If there were fewer bounds than dimensions, regard the ones at the end as unbounded.
actuals.insert(actuals.end(), args.begin() + actuals.size(), args.end());
bounded(args) = source(actuals);
return bounded;
}
Func constant_exterior(const Func &source, Expr value,
const std::vector<std::pair<Expr, Expr> > &bounds) {
std::vector<Var> args(source.args());
user_assert(args.size() >= bounds.size()) <<
"constant_exterior called with more bounds (" << bounds.size() <<
") than dimensions (" << source.args().size() << ") Func " <<
source.name() << "has.\n";
Func bounded;
Expr out_of_bounds = cast<bool>(false);
for (size_t i = 0; i < bounds.size(); i++) {
Var arg_var = source.args()[i];
Expr min = bounds[i].first;
Expr extent = bounds[i].second;
if (min.defined() && extent.defined()) {
out_of_bounds = (out_of_bounds ||
arg_var < min ||
arg_var >= min + extent);
} else if (min.defined() || extent.defined()) {
user_error << "Partially undefined bounds for " << arg_var << "\n";
}
}
bounded(args) = select(out_of_bounds, value, repeat_edge(source, bounds)(args));
return bounded;
}
Func repeat_image(const Func &source,
const std::vector<std::pair<Expr, Expr> > &bounds) {
std::vector<Var> args(source.args());
user_assert(args.size() >= bounds.size()) <<
"repeat_image called with more bounds (" << bounds.size() <<
") than dimensions (" << args.size() << ") Func " <<
source.name() << "has.\n";
std::vector<Expr> actuals;
for (size_t i = 0; i < bounds.size(); i++) {
Var arg_var = args[i];
Expr min = bounds[i].first;
Expr extent = bounds[i].second;
if (min.defined() && extent.defined()) {
Expr coord = arg_var - min; // Enforce zero origin.
coord = coord % extent; // Range is 0 to w-1
coord = coord + min; // Restore correct min
coord = select(arg_var < min || arg_var >= min + extent, coord,
clamp(likely(arg_var), min, min + extent - 1));
actuals.push_back(coord);
} else if (!min.defined() && !extent.defined()) {
actuals.push_back(arg_var);
} else {
user_error << "Partially undefined bounds for " << arg_var << "\n";
}
}
// If there were fewer bounds than dimensions, regard the ones at the end as unbounded.
internal_assert(args.begin() + actuals.size() == args.end());
actuals.insert(actuals.end(), args.begin() + actuals.size(), args.end());
Func bounded;
bounded(args) = source(actuals);
return bounded;
}
Func mirror_image(const Func &source,
const std::vector<std::pair<Expr, Expr> > &bounds) {
std::vector<Var> args(source.args());
user_assert(args.size() >= bounds.size()) <<
"mirror_image called with more bounds (" << bounds.size() <<
") than dimensions (" << args.size() << ") Func " <<
source.name() << "has.\n";
std::vector<Expr> actuals;
for (size_t i = 0; i < bounds.size(); i++) {
Var arg_var = args[i];
Expr min = bounds[i].first;
Expr extent = bounds[i].second;
if (min.defined() && extent.defined()) {
Expr coord = arg_var - min; // Enforce zero origin.
coord = coord % (2 * extent); // Range is 0 to 2w-1
coord = select(coord >= extent, 2 * extent - 1 - coord, coord); // Range is -w+1, w
coord = coord + min; // Restore correct min
coord = clamp(coord, min, min + extent - 1);
coord = select(arg_var < min || arg_var >= min + extent, coord,
clamp(likely(arg_var), min, min + extent-1));
actuals.push_back(coord);
} else if (!min.defined() && !extent.defined()) {
actuals.push_back(arg_var);
} else {
user_error << "Partially undefined bounds for " << arg_var << "\n";
}
}
// If there were fewer bounds than dimensions, regard the ones at the end as unbounded.
actuals.insert(actuals.end(), args.begin() + actuals.size(), args.end());
Func bounded;
bounded(args) = source(actuals);
return bounded;
}
Func mirror_interior(const Func &source,
const std::vector<std::pair<Expr, Expr> > &bounds) {
std::vector<Var> args(source.args());
user_assert(args.size() >= bounds.size()) <<
"mirror_interior called with more bounds (" << bounds.size() <<
") than dimensions (" << args.size() << ") Func " <<
source.name() << "has.\n";
Func mirrored;
std::vector<Expr> actuals;
for (size_t i = 0; i < bounds.size(); i++) {
Var arg_var = args[i];
Expr min = bounds[i].first;
Expr extent = bounds[i].second;
if (min.defined() && extent.defined()) {
Expr limit = extent - 1;
Expr coord = arg_var - min; // Enforce zero origin.
coord = coord % (2 * limit); // Range is 0 to 2w-1
coord = coord - limit; // Range is -w, w
coord = abs(coord); // Range is 0, w
coord = limit - coord; // Range is 0, w
coord = coord + min; // Restore correct min
// The boundary condition probably doesn't apply
coord = select(arg_var < min || arg_var >= min + extent, coord,
clamp(likely(arg_var), min, min + extent - 1));
actuals.push_back(coord);
} else if (!min.defined() && !extent.defined()) {
actuals.push_back(arg_var);
} else {
user_error << "Partially undefined bounds for " << arg_var << "\n";
}
}
// If there were fewer bounds than dimensions, regard the ones at the end as unbounded.
actuals.insert(actuals.end(), args.begin() + actuals.size(), args.end());
Func bounded;
bounded(args) = source(actuals);
return bounded;
}
}
}
<commit_msg>Generated meaningful name for bounded Funcs, a few small cleanups.<commit_after>#include "BoundaryConditions.h"
namespace Halide {
namespace BoundaryConditions {
Func repeat_edge(const Func &source,
const std::vector<std::pair<Expr, Expr> > &bounds) {
std::vector<Var> args(source.args());
user_assert(args.size() >= bounds.size()) <<
"repeat_edge called with more bounds (" << bounds.size() <<
") than dimensions (" << args.size() << ") Func " <<
source.name() << "has.\n";
std::vector<Expr> actuals;
for (size_t i = 0; i < bounds.size(); i++) {
Var arg_var = args[i];
Expr min = bounds[i].first;
Expr extent = bounds[i].second;
if (min.defined() && extent.defined()) {
actuals.push_back(clamp(likely(arg_var), min, min + extent - 1));
} else if (!min.defined() && !extent.defined()) {
actuals.push_back(arg_var);
} else {
user_error << "Partially undefined bounds for dimension " << arg_var
<< " of Func " << source.name() << "\n";
}
}
// If there were fewer bounds than dimensions, regard the ones at the end as unbounded.
actuals.insert(actuals.end(), args.begin() + actuals.size(), args.end());
Func bounded(source.name() + "_bounded");
bounded(args) = source(actuals);
return bounded;
}
Func constant_exterior(const Func &source, Expr value,
const std::vector<std::pair<Expr, Expr> > &bounds) {
std::vector<Var> args(source.args());
user_assert(args.size() >= bounds.size()) <<
"constant_exterior called with more bounds (" << bounds.size() <<
") than dimensions (" << source.args().size() << ") Func " <<
source.name() << "has.\n";
Expr out_of_bounds = cast<bool>(false);
for (size_t i = 0; i < bounds.size(); i++) {
Var arg_var = source.args()[i];
Expr min = bounds[i].first;
Expr extent = bounds[i].second;
if (min.defined() && extent.defined()) {
out_of_bounds = (out_of_bounds ||
arg_var < min ||
arg_var >= min + extent);
} else if (min.defined() || extent.defined()) {
user_error << "Partially undefined bounds for dimension " << arg_var
<< " of Func " << source.name() << "\n";
}
}
Func bounded(source.name() + "_bounded");
bounded(args) = select(out_of_bounds, value, repeat_edge(source, bounds)(args));
return bounded;
}
Func repeat_image(const Func &source,
const std::vector<std::pair<Expr, Expr> > &bounds) {
std::vector<Var> args(source.args());
user_assert(args.size() >= bounds.size()) <<
"repeat_image called with more bounds (" << bounds.size() <<
") than dimensions (" << args.size() << ") Func " <<
source.name() << "has.\n";
std::vector<Expr> actuals;
for (size_t i = 0; i < bounds.size(); i++) {
Var arg_var = args[i];
Expr min = bounds[i].first;
Expr extent = bounds[i].second;
if (min.defined() && extent.defined()) {
Expr coord = arg_var - min; // Enforce zero origin.
coord = coord % extent; // Range is 0 to w-1
coord = coord + min; // Restore correct min
coord = select(arg_var < min || arg_var >= min + extent, coord,
clamp(likely(arg_var), min, min + extent - 1));
actuals.push_back(coord);
} else if (!min.defined() && !extent.defined()) {
actuals.push_back(arg_var);
} else {
user_error << "Partially undefined bounds for dimension " << arg_var
<< " of Func " << source.name() << "\n";
}
}
// If there were fewer bounds than dimensions, regard the ones at the end as unbounded.
actuals.insert(actuals.end(), args.begin() + actuals.size(), args.end());
Func bounded(source.name() + "_bounded");
bounded(args) = source(actuals);
return bounded;
}
Func mirror_image(const Func &source,
const std::vector<std::pair<Expr, Expr> > &bounds) {
std::vector<Var> args(source.args());
user_assert(args.size() >= bounds.size()) <<
"mirror_image called with more bounds (" << bounds.size() <<
") than dimensions (" << args.size() << ") Func " <<
source.name() << "has.\n";
std::vector<Expr> actuals;
for (size_t i = 0; i < bounds.size(); i++) {
Var arg_var = args[i];
Expr min = bounds[i].first;
Expr extent = bounds[i].second;
if (min.defined() && extent.defined()) {
Expr coord = arg_var - min; // Enforce zero origin.
coord = coord % (2 * extent); // Range is 0 to 2w-1
coord = select(coord >= extent, 2 * extent - 1 - coord, coord); // Range is -w+1, w
coord = coord + min; // Restore correct min
coord = clamp(coord, min, min + extent - 1);
coord = select(arg_var < min || arg_var >= min + extent, coord,
clamp(likely(arg_var), min, min + extent-1));
actuals.push_back(coord);
} else if (!min.defined() && !extent.defined()) {
actuals.push_back(arg_var);
} else {
user_error << "Partially undefined bounds for dimension " << arg_var
<< " of Func " << source.name() << "\n";
}
}
// If there were fewer bounds than dimensions, regard the ones at the end as unbounded.
actuals.insert(actuals.end(), args.begin() + actuals.size(), args.end());
Func bounded(source.name() + "_bounded");
bounded(args) = source(actuals);
return bounded;
}
Func mirror_interior(const Func &source,
const std::vector<std::pair<Expr, Expr> > &bounds) {
std::vector<Var> args(source.args());
user_assert(args.size() >= bounds.size()) <<
"mirror_interior called with more bounds (" << bounds.size() <<
") than dimensions (" << args.size() << ") Func " <<
source.name() << "has.\n";
std::vector<Expr> actuals;
for (size_t i = 0; i < bounds.size(); i++) {
Var arg_var = args[i];
Expr min = bounds[i].first;
Expr extent = bounds[i].second;
if (min.defined() && extent.defined()) {
Expr limit = extent - 1;
Expr coord = arg_var - min; // Enforce zero origin.
coord = coord % (2 * limit); // Range is 0 to 2w-1
coord = coord - limit; // Range is -w, w
coord = abs(coord); // Range is 0, w
coord = limit - coord; // Range is 0, w
coord = coord + min; // Restore correct min
// The boundary condition probably doesn't apply
coord = select(arg_var < min || arg_var >= min + extent, coord,
clamp(likely(arg_var), min, min + extent - 1));
actuals.push_back(coord);
} else if (!min.defined() && !extent.defined()) {
actuals.push_back(arg_var);
} else {
user_error << "Partially undefined bounds for dimension " << arg_var
<< " of Func " << source.name() << "\n";
}
}
// If there were fewer bounds than dimensions, regard the ones at the end as unbounded.
actuals.insert(actuals.end(), args.begin() + actuals.size(), args.end());
Func bounded(source.name() + "_bounded");
bounded(args) = source(actuals);
return bounded;
}
}
}
<|endoftext|>
|
<commit_before>/************************************************************************
filename: CEGUIWindowManager.cpp
created: 21/2/2004
author: Paul D Turner
purpose: Implements the WindowManager class
*************************************************************************/
/*************************************************************************
Crazy Eddie's GUI System (http://www.cegui.org.uk)
Copyright (C)2004 - 2005 Paul D Turner (paul@cegui.org.uk)
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*************************************************************************/
#include "CEGUIWindowManager.h"
#include "CEGUIWindowFactoryManager.h"
#include "CEGUIWindowFactory.h"
#include "CEGUIWindow.h"
#include "CEGUIExceptions.h"
#include "CEGUIGUILayout_xmlHandler.h"
#include <xercesc/sax2/SAX2XMLReader.hpp>
#include <xercesc/sax2/XMLReaderFactory.hpp>
#include "xercesc/framework/MemBufInputSource.hpp"
// Start of CEGUI namespace section
namespace CEGUI
{
/*************************************************************************
Static Data Definitions
*************************************************************************/
// singleton instance pointer
template<> WindowManager* Singleton<WindowManager>::ms_Singleton = NULL;
/*************************************************************************
Definition of constant data for WindowManager
*************************************************************************/
// Declared in WindowManager
const char WindowManager::GUILayoutSchemaName[] = "GUILayout.xsd";
/*************************************************************************
Destructor
*************************************************************************/
WindowManager::~WindowManager(void)
{
destroyAllWindows();
Logger::getSingleton().logEvent((utf8*)"CEGUI::WindowManager singleton destroyed");
}
/*************************************************************************
Create a new window of the specified type
*************************************************************************/
Window* WindowManager::createWindow(const String& type, const String& name)
{
if (isWindowPresent(name))
{
throw AlreadyExistsException("WindowManager::createWindow - A Window object with the name '" + name +"' already exists within the system.");
}
WindowFactory* factory = WindowFactoryManager::getSingleton().getFactory(type);
Window* newWindow = factory->createWindow(name);
d_windowRegistry[name] = newWindow;
Logger::getSingleton().logEvent((utf8*)"Window '" + name +"' of type '" + type + "' has been created.", Informative);
return newWindow;
}
/*************************************************************************
Destroy the given window by pointer
*************************************************************************/
void WindowManager::destroyWindow(Window* window)
{
if (window != NULL)
{
// this is done because the name is used for the log after the window is destroyed,
// if we just did getName() we would get a const ref to the Window's internal name
// string which is destroyed along with the window so wouldn't exist when the log tried
// to use it (as I soon discovered).
String name = window->getName();
destroyWindow(name);
}
}
/*************************************************************************
Destroy the given window by name
*************************************************************************/
void WindowManager::destroyWindow(const String& window)
{
WindowRegistry::iterator wndpos = d_windowRegistry.find(window);
if (wndpos != d_windowRegistry.end())
{
WindowFactory* factory = WindowFactoryManager::getSingleton().getFactory(wndpos->second->getType());
factory->destroyWindow(wndpos->second);
// notify system object of the window destruction
System::getSingleton().notifyWindowDestroyed(wndpos->second);
// remove entry from the WindowRegistry.
d_windowRegistry.erase(wndpos);
Logger::getSingleton().logEvent((utf8*)"Window '" + window + "' has been destroyed.", Informative);
}
}
/*************************************************************************
Return a pointer to the named window
*************************************************************************/
Window* WindowManager::getWindow(const String& name) const
{
WindowRegistry::const_iterator pos = d_windowRegistry.find(name);
if (pos == d_windowRegistry.end())
{
throw UnknownObjectException("WindowManager::getWindow - A Window object with the name '" + name +"' does not exist within the system");
}
return pos->second;
}
/*************************************************************************
Return true if a window with the given name is present
*************************************************************************/
bool WindowManager::isWindowPresent(const String& name) const
{
return (d_windowRegistry.find(name) != d_windowRegistry.end());
}
/*************************************************************************
Destroy all Window objects
*************************************************************************/
void WindowManager::destroyAllWindows(void)
{
String window_name;
while (!d_windowRegistry.empty())
{
window_name = d_windowRegistry.begin()->first;
destroyWindow(window_name);
}
}
/*************************************************************************
Creates a set of windows (a Gui layout) from the information in the
specified XML file.
*************************************************************************/
Window* WindowManager::loadWindowLayout(const String& filename, const String& name_prefix, PropertyCallback* callback, void* userdata)
{
XERCES_CPP_NAMESPACE_USE
if (filename.empty() || (filename == (utf8*)""))
{
throw InvalidRequestException((utf8*)"WindowManager::loadWindowLayout - Filename supplied for gui-layout loading must be valid.");
}
// log the fact we are about to load a layout
Logger::getSingleton().logEvent((utf8*)"---- Beginning loading of GUI layout from '" + filename + "' ----", Informative);
SAX2XMLReader* parser = XMLReaderFactory::createXMLReader();
// set basic settings we want from parser
parser->setFeature(XMLUni::fgSAX2CoreValidation, true);
parser->setFeature(XMLUni::fgSAX2CoreNameSpaces, true);
parser->setFeature(XMLUni::fgXercesSchema, true);
parser->setFeature(XMLUni::fgXercesValidationErrorAsFatal, true);
// InputSourceContainer layoutSchemaData;
// System::getSingleton().getResourceProvider()->loadInputSourceContainer(GUILayoutSchemaName, layoutSchemaData);
// parser->loadGrammar(*(layoutSchemaData.getDataPtr()), Grammar::SchemaGrammarType, true);
RawDataContainer rawSchemaData;
System::getSingleton().getResourceProvider()->loadRawDataContainer(GUILayoutSchemaName, rawSchemaData);
MemBufInputSource layoutSchemaData(rawSchemaData.getDataPtr(), rawSchemaData.getSize(), GUILayoutSchemaName, false);
parser->loadGrammar(layoutSchemaData, Grammar::SchemaGrammarType, true);
// enable grammar reuse
parser->setFeature(XMLUni::fgXercesUseCachedGrammarInParse, true);
// setup schema for gui-layout data
XMLCh* pval = XMLString::transcode(GUILayoutSchemaName);
parser->setProperty(XMLUni::fgXercesSchemaExternalNoNameSpaceSchemaLocation, pval);
XMLString::release(&pval);
// setup handler object
GUILayout_xmlHandler handler(name_prefix, callback, userdata);
parser->setContentHandler(&handler);
parser->setErrorHandler(&handler);
// InputSourceContainer layoutData;
// System::getSingleton().getResourceProvider()->loadInputSourceContainer(filename, layoutData);
RawDataContainer rawXMLData;
System::getSingleton().getResourceProvider()->loadRawDataContainer(filename, rawXMLData);
MemBufInputSource layoutData(rawXMLData.getDataPtr(), rawXMLData.getSize(), filename.c_str(), false);
// do parse (which uses handler to create actual data)
try
{
// parser->parse(*(layoutData.getDataPtr()));
parser->parse(layoutData);
// log the completion of loading
Logger::getSingleton().logEvent((utf8*)"---- Successfully completed loading of GUI layout from '" + filename + "' ----", Standard);
}
catch(const XMLException& exc)
{
if (exc.getCode() != XMLExcepts::NoError)
{
delete parser;
char* excmsg = XMLString::transcode(exc.getMessage());
String message((utf8*)"WindowManager::loadWindowLayout - An error occurred while parsing gui-layout file '" + filename + "'. Additional information: ");
message += (utf8*)excmsg;
XMLString::release(&excmsg);
throw FileIOException(message);
}
}
catch(const SAXParseException& exc)
{
delete parser;
char* excmsg = XMLString::transcode(exc.getMessage());
String message((utf8*)"WindowManager::loadWindowLayout - An error occurred while parsing gui-layout file '" + filename + "'. Additional information: ");
message += (utf8*)excmsg;
XMLString::release(&excmsg);
throw FileIOException(message);
}
catch(...)
{
delete parser;
throw FileIOException((utf8*)"WindowManager::loadWindowLayout - An unexpected error occurred while parsing gui-layout file '" + filename + "'.");
}
// cleanup
delete parser;
return handler.getLayoutRootWindow();
}
WindowManager& WindowManager::getSingleton(void)
{
return Singleton<WindowManager>::getSingleton();
}
WindowManager* WindowManager::getSingletonPtr(void)
{
return Singleton<WindowManager>::getSingletonPtr();
}
/*************************************************************************
Return a WindowManager::WindowIterator object to iterate over the
currently defined Windows.
*************************************************************************/
WindowManager::WindowIterator WindowManager::getIterator(void) const
{
return WindowIterator(d_windowRegistry.begin(), d_windowRegistry.end());
}
} // End of CEGUI namespace section
<commit_msg>Patch #1112329: Throw CEGUI layout loading errors out of xercesc parser.<commit_after>/************************************************************************
filename: CEGUIWindowManager.cpp
created: 21/2/2004
author: Paul D Turner
purpose: Implements the WindowManager class
*************************************************************************/
/*************************************************************************
Crazy Eddie's GUI System (http://www.cegui.org.uk)
Copyright (C)2004 - 2005 Paul D Turner (paul@cegui.org.uk)
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*************************************************************************/
#include "CEGUIWindowManager.h"
#include "CEGUIWindowFactoryManager.h"
#include "CEGUIWindowFactory.h"
#include "CEGUIWindow.h"
#include "CEGUIExceptions.h"
#include "CEGUIGUILayout_xmlHandler.h"
#include <xercesc/sax2/SAX2XMLReader.hpp>
#include <xercesc/sax2/XMLReaderFactory.hpp>
#include "xercesc/framework/MemBufInputSource.hpp"
// Start of CEGUI namespace section
namespace CEGUI
{
/*************************************************************************
Static Data Definitions
*************************************************************************/
// singleton instance pointer
template<> WindowManager* Singleton<WindowManager>::ms_Singleton = NULL;
/*************************************************************************
Definition of constant data for WindowManager
*************************************************************************/
// Declared in WindowManager
const char WindowManager::GUILayoutSchemaName[] = "GUILayout.xsd";
/*************************************************************************
Destructor
*************************************************************************/
WindowManager::~WindowManager(void)
{
destroyAllWindows();
Logger::getSingleton().logEvent((utf8*)"CEGUI::WindowManager singleton destroyed");
}
/*************************************************************************
Create a new window of the specified type
*************************************************************************/
Window* WindowManager::createWindow(const String& type, const String& name)
{
if (isWindowPresent(name))
{
throw AlreadyExistsException("WindowManager::createWindow - A Window object with the name '" + name +"' already exists within the system.");
}
WindowFactory* factory = WindowFactoryManager::getSingleton().getFactory(type);
Window* newWindow = factory->createWindow(name);
d_windowRegistry[name] = newWindow;
Logger::getSingleton().logEvent((utf8*)"Window '" + name +"' of type '" + type + "' has been created.", Informative);
return newWindow;
}
/*************************************************************************
Destroy the given window by pointer
*************************************************************************/
void WindowManager::destroyWindow(Window* window)
{
if (window != NULL)
{
// this is done because the name is used for the log after the window is destroyed,
// if we just did getName() we would get a const ref to the Window's internal name
// string which is destroyed along with the window so wouldn't exist when the log tried
// to use it (as I soon discovered).
String name = window->getName();
destroyWindow(name);
}
}
/*************************************************************************
Destroy the given window by name
*************************************************************************/
void WindowManager::destroyWindow(const String& window)
{
WindowRegistry::iterator wndpos = d_windowRegistry.find(window);
if (wndpos != d_windowRegistry.end())
{
WindowFactory* factory = WindowFactoryManager::getSingleton().getFactory(wndpos->second->getType());
factory->destroyWindow(wndpos->second);
// notify system object of the window destruction
System::getSingleton().notifyWindowDestroyed(wndpos->second);
// remove entry from the WindowRegistry.
d_windowRegistry.erase(wndpos);
Logger::getSingleton().logEvent((utf8*)"Window '" + window + "' has been destroyed.", Informative);
}
}
/*************************************************************************
Return a pointer to the named window
*************************************************************************/
Window* WindowManager::getWindow(const String& name) const
{
WindowRegistry::const_iterator pos = d_windowRegistry.find(name);
if (pos == d_windowRegistry.end())
{
throw UnknownObjectException("WindowManager::getWindow - A Window object with the name '" + name +"' does not exist within the system");
}
return pos->second;
}
/*************************************************************************
Return true if a window with the given name is present
*************************************************************************/
bool WindowManager::isWindowPresent(const String& name) const
{
return (d_windowRegistry.find(name) != d_windowRegistry.end());
}
/*************************************************************************
Destroy all Window objects
*************************************************************************/
void WindowManager::destroyAllWindows(void)
{
String window_name;
while (!d_windowRegistry.empty())
{
window_name = d_windowRegistry.begin()->first;
destroyWindow(window_name);
}
}
/*************************************************************************
Creates a set of windows (a Gui layout) from the information in the
specified XML file.
*************************************************************************/
Window* WindowManager::loadWindowLayout(const String& filename, const String& name_prefix, PropertyCallback* callback, void* userdata)
{
XERCES_CPP_NAMESPACE_USE
if (filename.empty() || (filename == (utf8*)""))
{
throw InvalidRequestException((utf8*)"WindowManager::loadWindowLayout - Filename supplied for gui-layout loading must be valid.");
}
// log the fact we are about to load a layout
Logger::getSingleton().logEvent((utf8*)"---- Beginning loading of GUI layout from '" + filename + "' ----", Informative);
SAX2XMLReader* parser = XMLReaderFactory::createXMLReader();
// set basic settings we want from parser
parser->setFeature(XMLUni::fgSAX2CoreValidation, true);
parser->setFeature(XMLUni::fgSAX2CoreNameSpaces, true);
parser->setFeature(XMLUni::fgXercesSchema, true);
parser->setFeature(XMLUni::fgXercesValidationErrorAsFatal, true);
// InputSourceContainer layoutSchemaData;
// System::getSingleton().getResourceProvider()->loadInputSourceContainer(GUILayoutSchemaName, layoutSchemaData);
// parser->loadGrammar(*(layoutSchemaData.getDataPtr()), Grammar::SchemaGrammarType, true);
RawDataContainer rawSchemaData;
System::getSingleton().getResourceProvider()->loadRawDataContainer(GUILayoutSchemaName, rawSchemaData);
MemBufInputSource layoutSchemaData(rawSchemaData.getDataPtr(), rawSchemaData.getSize(), GUILayoutSchemaName, false);
parser->loadGrammar(layoutSchemaData, Grammar::SchemaGrammarType, true);
// enable grammar reuse
parser->setFeature(XMLUni::fgXercesUseCachedGrammarInParse, true);
// setup schema for gui-layout data
XMLCh* pval = XMLString::transcode(GUILayoutSchemaName);
parser->setProperty(XMLUni::fgXercesSchemaExternalNoNameSpaceSchemaLocation, pval);
XMLString::release(&pval);
// setup handler object
GUILayout_xmlHandler handler(name_prefix, callback, userdata);
parser->setContentHandler(&handler);
parser->setErrorHandler(&handler);
// InputSourceContainer layoutData;
// System::getSingleton().getResourceProvider()->loadInputSourceContainer(filename, layoutData);
RawDataContainer rawXMLData;
System::getSingleton().getResourceProvider()->loadRawDataContainer(filename, rawXMLData);
MemBufInputSource layoutData(rawXMLData.getDataPtr(), rawXMLData.getSize(), filename.c_str(), false);
// do parse (which uses handler to create actual data)
try
{
// parser->parse(*(layoutData.getDataPtr()));
parser->parse(layoutData);
// log the completion of loading
Logger::getSingleton().logEvent((utf8*)"---- Successfully completed loading of GUI layout from '" + filename + "' ----", Standard);
}
catch(const XMLException& exc)
{
if (exc.getCode() != XMLExcepts::NoError)
{
delete parser;
char* excmsg = XMLString::transcode(exc.getMessage());
String message((utf8*)"WindowManager::loadWindowLayout - An error occurred while parsing gui-layout file '" + filename + "'. Additional information: ");
message += (utf8*)excmsg;
XMLString::release(&excmsg);
throw FileIOException(message);
}
}
catch(const SAXParseException& exc)
{
delete parser;
char* excmsg = XMLString::transcode(exc.getMessage());
String message((utf8*)"WindowManager::loadWindowLayout - An error occurred while parsing gui-layout file '" + filename + "'. Additional information: ");
message += (utf8*)excmsg;
XMLString::release(&excmsg);
throw FileIOException(message);
}
catch(const CEGUI::Exception&)
{
delete parser;
throw;
}
catch(...)
{
delete parser;
throw FileIOException((utf8*)"WindowManager::loadWindowLayout - An unexpected error occurred while parsing gui-layout file '" + filename + "'.");
}
// cleanup
delete parser;
return handler.getLayoutRootWindow();
}
WindowManager& WindowManager::getSingleton(void)
{
return Singleton<WindowManager>::getSingleton();
}
WindowManager* WindowManager::getSingletonPtr(void)
{
return Singleton<WindowManager>::getSingletonPtr();
}
/*************************************************************************
Return a WindowManager::WindowIterator object to iterate over the
currently defined Windows.
*************************************************************************/
WindowManager::WindowIterator WindowManager::getIterator(void) const
{
return WindowIterator(d_windowRegistry.begin(), d_windowRegistry.end());
}
} // End of CEGUI namespace section
<|endoftext|>
|
<commit_before>#include "OutputPrinter.h"
OutputPrinter::OutputPrinter(const std::string& outputFileName)
: m_outputFileName(outputFileName)
{
TiXmlDeclaration* decl = new TiXmlDeclaration("1.0", "", "");
m_document.LinkEndChild(decl);
m_resultsElement = new TiXmlElement("results");
}
void OutputPrinter::Save()
{
m_document.LinkEndChild(m_resultsElement);
m_document.SaveFile(m_outputFileName);
}
void OutputPrinter::PrintRuleViolation(const std::string& ruleName,
Severity severity,
const std::string& description,
const clang::SourceLocation& location,
clang::SourceManager& sourceManager)
{
TiXmlElement* errorElement = new TiXmlElement("error");
errorElement->SetAttribute("file", sourceManager.getFilename(location).str());
errorElement->SetAttribute("line", std::to_string(sourceManager.getSpellingLineNumber(location)));
errorElement->SetAttribute("id", ruleName);
errorElement->SetAttribute("severity", GetSeverityString(severity));
errorElement->SetAttribute("message", description);
m_resultsElement->LinkEndChild(errorElement);
}
std::string OutputPrinter::GetSeverityString(Severity severity)
{
std::string str;
switch (severity)
{
case Severity::Style:
str = "style";
break;
case Severity::Error:
str = "error";
break;
case Severity::Warning:
str = "warning";
break;
case Severity::Information:
str = "information";
break;
}
return str;
}
<commit_msg>Fix XML output<commit_after>#include "OutputPrinter.h"
OutputPrinter::OutputPrinter(const std::string& outputFileName)
: m_outputFileName(outputFileName)
{
TiXmlDeclaration* decl = new TiXmlDeclaration("1.0", "", "");
m_document.LinkEndChild(decl);
m_resultsElement = new TiXmlElement("results");
}
void OutputPrinter::Save()
{
m_document.LinkEndChild(m_resultsElement);
m_document.SaveFile(m_outputFileName);
}
void OutputPrinter::PrintRuleViolation(const std::string& ruleName,
Severity severity,
const std::string& description,
const clang::SourceLocation& location,
clang::SourceManager& sourceManager)
{
TiXmlElement* errorElement = new TiXmlElement("error");
errorElement->SetAttribute("file", sourceManager.getFilename(location).str());
errorElement->SetAttribute("line", std::to_string(sourceManager.getSpellingLineNumber(location)));
errorElement->SetAttribute("id", ruleName);
errorElement->SetAttribute("severity", GetSeverityString(severity));
errorElement->SetAttribute("msg", description);
m_resultsElement->LinkEndChild(errorElement);
}
std::string OutputPrinter::GetSeverityString(Severity severity)
{
std::string str;
switch (severity)
{
case Severity::Style:
str = "style";
break;
case Severity::Error:
str = "error";
break;
case Severity::Warning:
str = "warning";
break;
case Severity::Information:
str = "information";
break;
}
return str;
}
<|endoftext|>
|
<commit_before>/* mbed Microcontroller Library
* Copyright (c) 2017 ARM Limited
*
* 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.
*/
#if !DEVICE_SLEEP
#error [NOT_SUPPORTED] sleep not supported for this target
#endif
#include "mbed.h"
#include "utest/utest.h"
#include "unity/unity.h"
#include "greentea-client/test_env.h"
#include "sleep_api_tests.h"
#define US_PER_S 1000000
using namespace utest::v1;
/* The following ticker frequencies are possible:
* high frequency ticker: 250 KHz (1 tick per 4 us) - 8 Mhz (1 tick per 1/8 us)
* low power ticker: 8 KHz (1 tick per 125 us) - 64 KHz (1 tick per ~15.6 us)
*/
/* Used for regular sleep mode, a target should be awake within 10 us. Define us delta value as follows:
* delta = default 10 us + worst ticker resolution + extra time for code execution */
static const uint32_t sleep_mode_delta_us = (10 + 4 + 5);
/* Used for deep-sleep mode, a target should be awake within 10 ms. Define us delta value as follows:
* delta = default 10 ms + worst ticker resolution + extra time for code execution */
static const uint32_t deepsleep_mode_delta_us = (10000 + 125 + 5);
unsigned int ticks_to_us(unsigned int ticks, unsigned int freq)
{
return (unsigned int)((unsigned long long)ticks * US_PER_S / freq);
}
unsigned int us_to_ticks(unsigned int us, unsigned int freq)
{
return (unsigned int)((unsigned long long)us * freq / US_PER_S);
}
unsigned int overflow_protect(unsigned int timestamp, unsigned int ticker_width)
{
unsigned int counter_mask = ((1 << ticker_width) - 1);
return (timestamp & counter_mask);
}
bool compare_timestamps(unsigned int delta_ticks, unsigned int ticker_width, unsigned int expected, unsigned int actual)
{
const unsigned int counter_mask = ((1 << ticker_width) - 1);
const unsigned int lower_bound = ((expected - delta_ticks) & counter_mask);
const unsigned int upper_bound = ((expected + delta_ticks) & counter_mask);
if(lower_bound < upper_bound) {
if (actual >= lower_bound && actual <= upper_bound) {
return true;
} else {
return false;
}
} else {
if ((actual >= lower_bound && actual <= counter_mask) ||
(actual >= 0 && actual <= upper_bound)) {
return true;
} else {
return false;
}
}
}
void us_ticker_isr(const ticker_data_t *const ticker_data)
{
us_ticker_clear_interrupt();
}
#ifdef DEVICE_LOWPOWERTIMER
void lp_ticker_isr(const ticker_data_t *const ticker_data)
{
lp_ticker_clear_interrupt();
}
#endif
/* Test that wake-up time from sleep should be less than 10 us and
* high frequency ticker interrupt can wake-up target from sleep. */
void sleep_usticker_test()
{
Timeout timeout;
const ticker_data_t * ticker = get_us_ticker_data();
const unsigned int ticker_freq = ticker->interface->get_info()->frequency;
const unsigned int ticker_width = ticker->interface->get_info()->bits;
const ticker_irq_handler_type us_ticker_irq_handler_org = set_us_ticker_irq_handler(us_ticker_isr);
/* Test only sleep functionality. */
sleep_manager_lock_deep_sleep();
TEST_ASSERT_FALSE_MESSAGE(sleep_manager_can_deep_sleep(), "deep sleep should be locked");
/* Testing wake-up time 10 us. */
for (timestamp_t i = 100; i < 1000; i += 100) {
/* note: us_ticker_read() operates on ticks. */
const timestamp_t next_match_timestamp = overflow_protect(us_ticker_read() + us_to_ticks(i, ticker_freq),
ticker_width);
us_ticker_set_interrupt(next_match_timestamp);
sleep();
const unsigned int wakeup_timestamp = us_ticker_read();
TEST_ASSERT(
compare_timestamps(us_to_ticks(sleep_mode_delta_us, ticker_freq), ticker_width, next_match_timestamp,
wakeup_timestamp));
}
set_us_ticker_irq_handler(us_ticker_irq_handler_org);
sleep_manager_unlock_deep_sleep();
TEST_ASSERT_TRUE(sleep_manager_can_deep_sleep());
}
#ifdef DEVICE_LOWPOWERTIMER
/* Test that wake-up time from sleep should be less than 10 ms and
* low power ticker interrupt can wake-up target from sleep. */
void deepsleep_lpticker_test()
{
const ticker_data_t * ticker = get_us_ticker_data();
const unsigned int ticker_freq = ticker->interface->get_info()->frequency;
const unsigned int ticker_width = ticker->interface->get_info()->bits;
const ticker_irq_handler_type lp_ticker_irq_handler_org = set_lp_ticker_irq_handler(lp_ticker_isr);
/* Give some time Green Tea to finish UART transmission before entering
* deep-sleep mode.
*/
wait_ms(10);
TEST_ASSERT_TRUE_MESSAGE(sleep_manager_can_deep_sleep(), "deep sleep should not be locked");
/* Testing wake-up time 10 ms. */
for (timestamp_t i = 20000; i < 200000; i += 20000) {
/* note: lp_ticker_read() operates on ticks. */
const timestamp_t next_match_timestamp = overflow_protect(lp_ticker_read() + us_to_ticks(i, ticker_freq), ticker_width);
lp_ticker_set_interrupt(next_match_timestamp);
sleep();
const timestamp_t wakeup_timestamp = lp_ticker_read();
TEST_ASSERT(compare_timestamps(us_to_ticks(deepsleep_mode_delta_us, ticker_freq), ticker_width, next_match_timestamp, wakeup_timestamp));
}
set_lp_ticker_irq_handler(lp_ticker_irq_handler_org);
}
void deepsleep_high_speed_clocks_turned_off_test()
{
const ticker_data_t * us_ticker = get_us_ticker_data();
const ticker_data_t * lp_ticker = get_lp_ticker_data();
const unsigned int us_ticker_freq = us_ticker->interface->get_info()->frequency;
const unsigned int lp_ticker_freq = lp_ticker->interface->get_info()->frequency;
const unsigned int us_ticker_width = us_ticker->interface->get_info()->bits;
const unsigned int lp_ticker_width = lp_ticker->interface->get_info()->bits;
const unsigned int us_ticker_mask = ((1 << us_ticker_width) - 1);
/* Give some time Green Tea to finish UART transmission before entering
* deep-sleep mode.
*/
wait_ms(10);
TEST_ASSERT_TRUE_MESSAGE(sleep_manager_can_deep_sleep(), "deep sleep should not be locked");
const unsigned int us_ticks_before_sleep = us_ticker_read();
const timestamp_t wakeup_time = lp_ticker_read() + us_to_ticks(200000, lp_ticker_freq);
lp_ticker_set_interrupt(wakeup_time);
sleep();
const unsigned int us_ticks_after_sleep = us_ticker_read();
const unsigned int lp_ticks_after_sleep = lp_ticker_read();
/* High freqency ticker should be disabled in deep-sleep mode. We expect that time difference between
* ticker reads before and after the sleep represents only code execution time between calls.
* Since we went to sleep for about 200 ms check if time counted by high frequency timer does not
* exceed 1 ms.
*/
const unsigned int us_ticks_diff = (us_ticks_before_sleep <= us_ticks_after_sleep) ? (us_ticks_after_sleep - us_ticks_before_sleep) : (us_ticker_mask - us_ticks_before_sleep + us_ticks_after_sleep + 1);
TEST_ASSERT_UINT32_WITHIN(1000, 0, ticks_to_us(us_ticks_diff, us_ticker_freq));
/* Check if we have woken-up after expected time. */
TEST_ASSERT(compare_timestamps(us_to_ticks(deepsleep_mode_delta_us, lp_ticker_freq), lp_ticker_width, wakeup_time, lp_ticks_after_sleep));
}
#endif
utest::v1::status_t greentea_failure_handler(const Case * const source, const failure_t reason)
{
greentea_case_failure_abort_handler(source, reason);
return STATUS_CONTINUE;
}
utest::v1::status_t greentea_test_setup(const size_t number_of_cases)
{
GREENTEA_SETUP(60, "default_auto");
us_ticker_init();
#if DEVICE_LOWPOWERTIMER
lp_ticker_init();
#endif
/* Suspend RTOS Kernel to enable sleep modes. */
osKernelSuspend();
return greentea_test_setup_handler(number_of_cases);
}
Case cases[] = {
Case("sleep - source of wake-up - us ticker", sleep_usticker_test, greentea_failure_handler),
#if DEVICE_LOWPOWERTIMER
Case("deep-sleep - source of wake-up - lp ticker",deepsleep_lpticker_test, greentea_failure_handler),
Case("deep-sleep - high-speed clocks are turned off",deepsleep_high_speed_clocks_turned_off_test, greentea_failure_handler),
#endif
};
Specification specification(greentea_test_setup, cases, greentea_test_teardown_handler);
int main() {
Harness::run(specification);
}
<commit_msg>tests-mbed_hal-sleep: use lp ticker data while testing deepsleep.<commit_after>/* mbed Microcontroller Library
* Copyright (c) 2017 ARM Limited
*
* 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.
*/
#if !DEVICE_SLEEP
#error [NOT_SUPPORTED] sleep not supported for this target
#endif
#include "mbed.h"
#include "utest/utest.h"
#include "unity/unity.h"
#include "greentea-client/test_env.h"
#include "sleep_api_tests.h"
#define US_PER_S 1000000
using namespace utest::v1;
/* The following ticker frequencies are possible:
* high frequency ticker: 250 KHz (1 tick per 4 us) - 8 Mhz (1 tick per 1/8 us)
* low power ticker: 8 KHz (1 tick per 125 us) - 64 KHz (1 tick per ~15.6 us)
*/
/* Used for regular sleep mode, a target should be awake within 10 us. Define us delta value as follows:
* delta = default 10 us + worst ticker resolution + extra time for code execution */
static const uint32_t sleep_mode_delta_us = (10 + 4 + 5);
/* Used for deep-sleep mode, a target should be awake within 10 ms. Define us delta value as follows:
* delta = default 10 ms + worst ticker resolution + extra time for code execution */
static const uint32_t deepsleep_mode_delta_us = (10000 + 125 + 5);
unsigned int ticks_to_us(unsigned int ticks, unsigned int freq)
{
return (unsigned int)((unsigned long long)ticks * US_PER_S / freq);
}
unsigned int us_to_ticks(unsigned int us, unsigned int freq)
{
return (unsigned int)((unsigned long long)us * freq / US_PER_S);
}
unsigned int overflow_protect(unsigned int timestamp, unsigned int ticker_width)
{
unsigned int counter_mask = ((1 << ticker_width) - 1);
return (timestamp & counter_mask);
}
bool compare_timestamps(unsigned int delta_ticks, unsigned int ticker_width, unsigned int expected, unsigned int actual)
{
const unsigned int counter_mask = ((1 << ticker_width) - 1);
const unsigned int lower_bound = ((expected - delta_ticks) & counter_mask);
const unsigned int upper_bound = ((expected + delta_ticks) & counter_mask);
if(lower_bound < upper_bound) {
if (actual >= lower_bound && actual <= upper_bound) {
return true;
} else {
return false;
}
} else {
if ((actual >= lower_bound && actual <= counter_mask) ||
(actual >= 0 && actual <= upper_bound)) {
return true;
} else {
return false;
}
}
}
void us_ticker_isr(const ticker_data_t *const ticker_data)
{
us_ticker_clear_interrupt();
}
#ifdef DEVICE_LOWPOWERTIMER
void lp_ticker_isr(const ticker_data_t *const ticker_data)
{
lp_ticker_clear_interrupt();
}
#endif
/* Test that wake-up time from sleep should be less than 10 us and
* high frequency ticker interrupt can wake-up target from sleep. */
void sleep_usticker_test()
{
Timeout timeout;
const ticker_data_t * ticker = get_us_ticker_data();
const unsigned int ticker_freq = ticker->interface->get_info()->frequency;
const unsigned int ticker_width = ticker->interface->get_info()->bits;
const ticker_irq_handler_type us_ticker_irq_handler_org = set_us_ticker_irq_handler(us_ticker_isr);
/* Test only sleep functionality. */
sleep_manager_lock_deep_sleep();
TEST_ASSERT_FALSE_MESSAGE(sleep_manager_can_deep_sleep(), "deep sleep should be locked");
/* Testing wake-up time 10 us. */
for (timestamp_t i = 100; i < 1000; i += 100) {
/* note: us_ticker_read() operates on ticks. */
const timestamp_t next_match_timestamp = overflow_protect(us_ticker_read() + us_to_ticks(i, ticker_freq),
ticker_width);
us_ticker_set_interrupt(next_match_timestamp);
sleep();
const unsigned int wakeup_timestamp = us_ticker_read();
TEST_ASSERT(
compare_timestamps(us_to_ticks(sleep_mode_delta_us, ticker_freq), ticker_width, next_match_timestamp,
wakeup_timestamp));
}
set_us_ticker_irq_handler(us_ticker_irq_handler_org);
sleep_manager_unlock_deep_sleep();
TEST_ASSERT_TRUE(sleep_manager_can_deep_sleep());
}
#ifdef DEVICE_LOWPOWERTIMER
/* Test that wake-up time from sleep should be less than 10 ms and
* low power ticker interrupt can wake-up target from sleep. */
void deepsleep_lpticker_test()
{
const ticker_data_t * ticker = get_lp_ticker_data();
const unsigned int ticker_freq = ticker->interface->get_info()->frequency;
const unsigned int ticker_width = ticker->interface->get_info()->bits;
const ticker_irq_handler_type lp_ticker_irq_handler_org = set_lp_ticker_irq_handler(lp_ticker_isr);
/* Give some time Green Tea to finish UART transmission before entering
* deep-sleep mode.
*/
wait_ms(10);
TEST_ASSERT_TRUE_MESSAGE(sleep_manager_can_deep_sleep(), "deep sleep should not be locked");
/* Testing wake-up time 10 ms. */
for (timestamp_t i = 20000; i < 200000; i += 20000) {
/* note: lp_ticker_read() operates on ticks. */
const timestamp_t next_match_timestamp = overflow_protect(lp_ticker_read() + us_to_ticks(i, ticker_freq), ticker_width);
lp_ticker_set_interrupt(next_match_timestamp);
sleep();
const timestamp_t wakeup_timestamp = lp_ticker_read();
TEST_ASSERT(compare_timestamps(us_to_ticks(deepsleep_mode_delta_us, ticker_freq), ticker_width, next_match_timestamp, wakeup_timestamp));
}
set_lp_ticker_irq_handler(lp_ticker_irq_handler_org);
}
void deepsleep_high_speed_clocks_turned_off_test()
{
const ticker_data_t * us_ticker = get_us_ticker_data();
const ticker_data_t * lp_ticker = get_lp_ticker_data();
const unsigned int us_ticker_freq = us_ticker->interface->get_info()->frequency;
const unsigned int lp_ticker_freq = lp_ticker->interface->get_info()->frequency;
const unsigned int us_ticker_width = us_ticker->interface->get_info()->bits;
const unsigned int lp_ticker_width = lp_ticker->interface->get_info()->bits;
const unsigned int us_ticker_mask = ((1 << us_ticker_width) - 1);
/* Give some time Green Tea to finish UART transmission before entering
* deep-sleep mode.
*/
wait_ms(10);
TEST_ASSERT_TRUE_MESSAGE(sleep_manager_can_deep_sleep(), "deep sleep should not be locked");
const unsigned int us_ticks_before_sleep = us_ticker_read();
const timestamp_t wakeup_time = lp_ticker_read() + us_to_ticks(200000, lp_ticker_freq);
lp_ticker_set_interrupt(wakeup_time);
sleep();
const unsigned int us_ticks_after_sleep = us_ticker_read();
const unsigned int lp_ticks_after_sleep = lp_ticker_read();
/* High freqency ticker should be disabled in deep-sleep mode. We expect that time difference between
* ticker reads before and after the sleep represents only code execution time between calls.
* Since we went to sleep for about 200 ms check if time counted by high frequency timer does not
* exceed 1 ms.
*/
const unsigned int us_ticks_diff = (us_ticks_before_sleep <= us_ticks_after_sleep) ? (us_ticks_after_sleep - us_ticks_before_sleep) : (us_ticker_mask - us_ticks_before_sleep + us_ticks_after_sleep + 1);
TEST_ASSERT_UINT32_WITHIN(1000, 0, ticks_to_us(us_ticks_diff, us_ticker_freq));
/* Check if we have woken-up after expected time. */
TEST_ASSERT(compare_timestamps(us_to_ticks(deepsleep_mode_delta_us, lp_ticker_freq), lp_ticker_width, wakeup_time, lp_ticks_after_sleep));
}
#endif
utest::v1::status_t greentea_failure_handler(const Case * const source, const failure_t reason)
{
greentea_case_failure_abort_handler(source, reason);
return STATUS_CONTINUE;
}
utest::v1::status_t greentea_test_setup(const size_t number_of_cases)
{
GREENTEA_SETUP(60, "default_auto");
us_ticker_init();
#if DEVICE_LOWPOWERTIMER
lp_ticker_init();
#endif
/* Suspend RTOS Kernel to enable sleep modes. */
osKernelSuspend();
return greentea_test_setup_handler(number_of_cases);
}
Case cases[] = {
Case("sleep - source of wake-up - us ticker", sleep_usticker_test, greentea_failure_handler),
#if DEVICE_LOWPOWERTIMER
Case("deep-sleep - source of wake-up - lp ticker",deepsleep_lpticker_test, greentea_failure_handler),
Case("deep-sleep - high-speed clocks are turned off",deepsleep_high_speed_clocks_turned_off_test, greentea_failure_handler),
#endif
};
Specification specification(greentea_test_setup, cases, greentea_test_teardown_handler);
int main() {
Harness::run(specification);
}
<|endoftext|>
|
<commit_before>//===- InstrInfoEmitter.cpp - Generate a Instruction Set Desc. ------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This tablegen backend is responsible for emitting a description of the target
// instruction set for the code generator.
//
//===----------------------------------------------------------------------===//
#include "InstrInfoEmitter.h"
#include "CodeGenTarget.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "Record.h"
#include <algorithm>
using namespace llvm;
// runEnums - Print out enum values for all of the instructions.
void InstrInfoEmitter::runEnums(std::ostream &OS) {
EmitSourceFileHeader("Target Instruction Enum Values", OS);
OS << "namespace llvm {\n\n";
CodeGenTarget Target;
// We must emit the PHI opcode first...
std::string Namespace;
for (CodeGenTarget::inst_iterator II = Target.inst_begin(),
E = Target.inst_end(); II != E; ++II) {
if (II->second.Namespace != "TargetInstrInfo") {
Namespace = II->second.Namespace;
break;
}
}
if (Namespace.empty()) {
cerr << "No instructions defined!\n";
exit(1);
}
std::vector<const CodeGenInstruction*> NumberedInstructions;
Target.getInstructionsByEnumValue(NumberedInstructions);
OS << "namespace " << Namespace << " {\n";
OS << " enum {\n";
for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
OS << " " << NumberedInstructions[i]->TheDef->getName()
<< "\t= " << i << ",\n";
}
OS << " INSTRUCTION_LIST_END = " << NumberedInstructions.size() << "\n";
OS << " };\n}\n";
OS << "} // End llvm namespace \n";
}
void InstrInfoEmitter::printDefList(const std::vector<Record*> &Uses,
unsigned Num, std::ostream &OS) const {
OS << "static const unsigned ImplicitList" << Num << "[] = { ";
for (unsigned i = 0, e = Uses.size(); i != e; ++i)
OS << getQualifiedName(Uses[i]) << ", ";
OS << "0 };\n";
}
std::vector<std::string>
InstrInfoEmitter::GetOperandInfo(const CodeGenInstruction &Inst) {
std::vector<std::string> Result;
for (unsigned i = 0, e = Inst.OperandList.size(); i != e; ++i) {
// Handle aggregate operands and normal operands the same way by expanding
// either case into a list of operands for this op.
std::vector<CodeGenInstruction::OperandInfo> OperandList;
// This might be a multiple operand thing. Targets like X86 have
// registers in their multi-operand operands. It may also be an anonymous
// operand, which has a single operand, but no declared class for the
// operand.
DagInit *MIOI = Inst.OperandList[i].MIOperandInfo;
if (!MIOI || MIOI->getNumArgs() == 0) {
// Single, anonymous, operand.
OperandList.push_back(Inst.OperandList[i]);
} else {
for (unsigned j = 0, e = Inst.OperandList[i].MINumOperands; j != e; ++j) {
OperandList.push_back(Inst.OperandList[i]);
Record *OpR = dynamic_cast<DefInit*>(MIOI->getArg(j))->getDef();
OperandList.back().Rec = OpR;
}
}
for (unsigned j = 0, e = OperandList.size(); j != e; ++j) {
Record *OpR = OperandList[j].Rec;
std::string Res;
if (OpR->isSubClassOf("RegisterClass"))
Res += getQualifiedName(OpR) + "RegClassID, ";
else
Res += "0, ";
// Fill in applicable flags.
Res += "0";
// Ptr value whose register class is resolved via callback.
if (OpR->getName() == "ptr_rc")
Res += "|M_LOOK_UP_PTR_REG_CLASS";
// Predicate operands. Check to see if the original unexpanded operand
// was of type PredicateOperand.
if (Inst.OperandList[i].Rec->isSubClassOf("PredicateOperand"))
Res += "|M_PREDICATE_OPERAND";
// Optional def operands. Check to see if the original unexpanded operand
// was of type OptionalDefOperand.
if (Inst.OperandList[i].Rec->isSubClassOf("OptionalDefOperand"))
Res += "|M_OPTIONAL_DEF_OPERAND";
// Fill in constraint info.
Res += ", " + Inst.OperandList[i].Constraints[j];
Result.push_back(Res);
}
}
return Result;
}
// run - Emit the main instruction description records for the target...
void InstrInfoEmitter::run(std::ostream &OS) {
GatherItinClasses();
EmitSourceFileHeader("Target Instruction Descriptors", OS);
OS << "namespace llvm {\n\n";
CodeGenTarget Target;
const std::string &TargetName = Target.getName();
Record *InstrInfo = Target.getInstructionSet();
// Keep track of all of the def lists we have emitted already.
std::map<std::vector<Record*>, unsigned> EmittedLists;
unsigned ListNumber = 0;
// Emit all of the instruction's implicit uses and defs.
for (CodeGenTarget::inst_iterator II = Target.inst_begin(),
E = Target.inst_end(); II != E; ++II) {
Record *Inst = II->second.TheDef;
std::vector<Record*> Uses = Inst->getValueAsListOfDefs("Uses");
if (!Uses.empty()) {
unsigned &IL = EmittedLists[Uses];
if (!IL) printDefList(Uses, IL = ++ListNumber, OS);
}
std::vector<Record*> Defs = Inst->getValueAsListOfDefs("Defs");
if (!Defs.empty()) {
unsigned &IL = EmittedLists[Defs];
if (!IL) printDefList(Defs, IL = ++ListNumber, OS);
}
}
std::map<std::vector<std::string>, unsigned> OperandInfosEmitted;
unsigned OperandListNum = 0;
OperandInfosEmitted[std::vector<std::string>()] = ++OperandListNum;
// Emit all of the operand info records.
OS << "\n";
for (CodeGenTarget::inst_iterator II = Target.inst_begin(),
E = Target.inst_end(); II != E; ++II) {
std::vector<std::string> OperandInfo = GetOperandInfo(II->second);
unsigned &N = OperandInfosEmitted[OperandInfo];
if (N == 0) {
N = ++OperandListNum;
OS << "static const TargetOperandInfo OperandInfo" << N << "[] = { ";
for (unsigned i = 0, e = OperandInfo.size(); i != e; ++i)
OS << "{ " << OperandInfo[i] << " }, ";
OS << "};\n";
}
}
// Emit all of the TargetInstrDescriptor records in their ENUM ordering.
//
OS << "\nstatic const TargetInstrDescriptor " << TargetName
<< "Insts[] = {\n";
std::vector<const CodeGenInstruction*> NumberedInstructions;
Target.getInstructionsByEnumValue(NumberedInstructions);
for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i)
emitRecord(*NumberedInstructions[i], i, InstrInfo, EmittedLists,
OperandInfosEmitted, OS);
OS << "};\n";
OS << "} // End llvm namespace \n";
}
void InstrInfoEmitter::emitRecord(const CodeGenInstruction &Inst, unsigned Num,
Record *InstrInfo,
std::map<std::vector<Record*>, unsigned> &EmittedLists,
std::map<std::vector<std::string>, unsigned> &OpInfo,
std::ostream &OS) {
int MinOperands;
if (!Inst.OperandList.empty())
// Each logical operand can be multiple MI operands.
MinOperands = Inst.OperandList.back().MIOperandNo +
Inst.OperandList.back().MINumOperands;
else
MinOperands = 0;
OS << " { ";
OS << Num << ",\t" << MinOperands << ",\t"
<< Inst.NumDefs << ",\t\"";
if (Inst.Name.empty())
OS << Inst.TheDef->getName();
else
OS << Inst.Name;
unsigned ItinClass = !IsItineraries ? 0 :
ItinClassNumber(Inst.TheDef->getValueAsDef("Itinerary")->getName());
OS << "\",\t" << ItinClass << ", 0";
// Try to determine (from the pattern), if the instruction is a store.
bool isStore = false;
if (dynamic_cast<ListInit*>(Inst.TheDef->getValueInit("Pattern"))) {
ListInit *LI = Inst.TheDef->getValueAsListInit("Pattern");
if (LI && LI->getSize() > 0) {
DagInit *Dag = (DagInit *)LI->getElement(0);
DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
if (OpDef) {
Record *Operator = OpDef->getDef();
if (Operator->isSubClassOf("SDNode")) {
const std::string Opcode = Operator->getValueAsString("Opcode");
if (Opcode == "ISD::STORE" || Opcode == "ISD::TRUNCSTORE")
isStore = true;
}
}
}
}
// Emit all of the target indepedent flags...
if (Inst.isReturn) OS << "|M_RET_FLAG";
if (Inst.isBranch) OS << "|M_BRANCH_FLAG";
if (Inst.isIndirectBranch) OS << "|M_INDIRECT_FLAG";
if (Inst.isBarrier) OS << "|M_BARRIER_FLAG";
if (Inst.hasDelaySlot) OS << "|M_DELAY_SLOT_FLAG";
if (Inst.isCall) OS << "|M_CALL_FLAG";
if (Inst.isLoad) OS << "|M_LOAD_FLAG";
if (Inst.isStore || isStore) OS << "|M_STORE_FLAG";
if (Inst.isImplicitDef)OS << "|M_IMPLICIT_DEF_FLAG";
if (Inst.isPredicable) OS << "|M_PREDICABLE";
if (Inst.isConvertibleToThreeAddress) OS << "|M_CONVERTIBLE_TO_3_ADDR";
if (Inst.isCommutable) OS << "|M_COMMUTABLE";
if (Inst.isTerminator) OS << "|M_TERMINATOR_FLAG";
if (Inst.isReMaterializable) OS << "|M_REMATERIALIZIBLE";
if (Inst.isNotDuplicable) OS << "|M_NOT_DUPLICABLE";
if (Inst.hasOptionalDef) OS << "|M_HAS_OPTIONAL_DEF";
if (Inst.usesCustomDAGSchedInserter)
OS << "|M_USES_CUSTOM_DAG_SCHED_INSERTION";
if (Inst.hasVariableNumberOfOperands) OS << "|M_VARIABLE_OPS";
if (Inst.mayHaveSideEffects) OS << "|M_MAY_HAVE_SIDE_EFFECTS";
if (Inst.neverHasSideEffects) OS << "|M_NEVER_HAS_SIDE_EFFECTS";
OS << ", 0";
// Emit all of the target-specific flags...
ListInit *LI = InstrInfo->getValueAsListInit("TSFlagsFields");
ListInit *Shift = InstrInfo->getValueAsListInit("TSFlagsShifts");
if (LI->getSize() != Shift->getSize())
throw "Lengths of " + InstrInfo->getName() +
":(TargetInfoFields, TargetInfoPositions) must be equal!";
for (unsigned i = 0, e = LI->getSize(); i != e; ++i)
emitShiftedValue(Inst.TheDef, dynamic_cast<StringInit*>(LI->getElement(i)),
dynamic_cast<IntInit*>(Shift->getElement(i)), OS);
OS << ", ";
// Emit the implicit uses and defs lists...
std::vector<Record*> UseList = Inst.TheDef->getValueAsListOfDefs("Uses");
if (UseList.empty())
OS << "NULL, ";
else
OS << "ImplicitList" << EmittedLists[UseList] << ", ";
std::vector<Record*> DefList = Inst.TheDef->getValueAsListOfDefs("Defs");
if (DefList.empty())
OS << "NULL, ";
else
OS << "ImplicitList" << EmittedLists[DefList] << ", ";
// Emit the operand info.
std::vector<std::string> OperandInfo = GetOperandInfo(Inst);
if (OperandInfo.empty())
OS << "0";
else
OS << "OperandInfo" << OpInfo[OperandInfo];
OS << " }, // Inst #" << Num << " = " << Inst.TheDef->getName() << "\n";
}
struct LessRecord {
bool operator()(const Record *Rec1, const Record *Rec2) const {
return Rec1->getName() < Rec2->getName();
}
};
void InstrInfoEmitter::GatherItinClasses() {
std::vector<Record*> DefList =
Records.getAllDerivedDefinitions("InstrItinClass");
IsItineraries = !DefList.empty();
if (!IsItineraries) return;
std::sort(DefList.begin(), DefList.end(), LessRecord());
for (unsigned i = 0, N = DefList.size(); i < N; i++) {
Record *Def = DefList[i];
ItinClassMap[Def->getName()] = i;
}
}
unsigned InstrInfoEmitter::ItinClassNumber(std::string ItinName) {
return ItinClassMap[ItinName];
}
void InstrInfoEmitter::emitShiftedValue(Record *R, StringInit *Val,
IntInit *ShiftInt, std::ostream &OS) {
if (Val == 0 || ShiftInt == 0)
throw std::string("Illegal value or shift amount in TargetInfo*!");
RecordVal *RV = R->getValue(Val->getValue());
int Shift = ShiftInt->getValue();
if (RV == 0 || RV->getValue() == 0) {
// This isn't an error if this is a builtin instruction.
if (R->getName() != "PHI" &&
R->getName() != "INLINEASM" &&
R->getName() != "LABEL" &&
R->getName() != "EXTRACT_SUBREG" &&
R->getName() != "INSERT_SUBREG")
throw R->getName() + " doesn't have a field named '" +
Val->getValue() + "'!";
return;
}
Init *Value = RV->getValue();
if (BitInit *BI = dynamic_cast<BitInit*>(Value)) {
if (BI->getValue()) OS << "|(1<<" << Shift << ")";
return;
} else if (BitsInit *BI = dynamic_cast<BitsInit*>(Value)) {
// Convert the Bits to an integer to print...
Init *I = BI->convertInitializerTo(new IntRecTy());
if (I)
if (IntInit *II = dynamic_cast<IntInit*>(I)) {
if (II->getValue()) {
if (Shift)
OS << "|(" << II->getValue() << "<<" << Shift << ")";
else
OS << "|" << II->getValue();
}
return;
}
} else if (IntInit *II = dynamic_cast<IntInit*>(Value)) {
if (II->getValue()) {
if (Shift)
OS << "|(" << II->getValue() << "<<" << Shift << ")";
else
OS << II->getValue();
}
return;
}
cerr << "Unhandled initializer: " << *Val << "\n";
throw "In record '" + R->getName() + "' for TSFlag emission.";
}
<commit_msg>tblgen shouldn't include headers from llvm codegen.<commit_after>//===- InstrInfoEmitter.cpp - Generate a Instruction Set Desc. ------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This tablegen backend is responsible for emitting a description of the target
// instruction set for the code generator.
//
//===----------------------------------------------------------------------===//
#include "InstrInfoEmitter.h"
#include "CodeGenTarget.h"
#include "Record.h"
#include <algorithm>
#include <iostream>
using namespace llvm;
// runEnums - Print out enum values for all of the instructions.
void InstrInfoEmitter::runEnums(std::ostream &OS) {
EmitSourceFileHeader("Target Instruction Enum Values", OS);
OS << "namespace llvm {\n\n";
CodeGenTarget Target;
// We must emit the PHI opcode first...
std::string Namespace;
for (CodeGenTarget::inst_iterator II = Target.inst_begin(),
E = Target.inst_end(); II != E; ++II) {
if (II->second.Namespace != "TargetInstrInfo") {
Namespace = II->second.Namespace;
break;
}
}
if (Namespace.empty()) {
std::cerr << "No instructions defined!\n";
exit(1);
}
std::vector<const CodeGenInstruction*> NumberedInstructions;
Target.getInstructionsByEnumValue(NumberedInstructions);
OS << "namespace " << Namespace << " {\n";
OS << " enum {\n";
for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
OS << " " << NumberedInstructions[i]->TheDef->getName()
<< "\t= " << i << ",\n";
}
OS << " INSTRUCTION_LIST_END = " << NumberedInstructions.size() << "\n";
OS << " };\n}\n";
OS << "} // End llvm namespace \n";
}
void InstrInfoEmitter::printDefList(const std::vector<Record*> &Uses,
unsigned Num, std::ostream &OS) const {
OS << "static const unsigned ImplicitList" << Num << "[] = { ";
for (unsigned i = 0, e = Uses.size(); i != e; ++i)
OS << getQualifiedName(Uses[i]) << ", ";
OS << "0 };\n";
}
std::vector<std::string>
InstrInfoEmitter::GetOperandInfo(const CodeGenInstruction &Inst) {
std::vector<std::string> Result;
for (unsigned i = 0, e = Inst.OperandList.size(); i != e; ++i) {
// Handle aggregate operands and normal operands the same way by expanding
// either case into a list of operands for this op.
std::vector<CodeGenInstruction::OperandInfo> OperandList;
// This might be a multiple operand thing. Targets like X86 have
// registers in their multi-operand operands. It may also be an anonymous
// operand, which has a single operand, but no declared class for the
// operand.
DagInit *MIOI = Inst.OperandList[i].MIOperandInfo;
if (!MIOI || MIOI->getNumArgs() == 0) {
// Single, anonymous, operand.
OperandList.push_back(Inst.OperandList[i]);
} else {
for (unsigned j = 0, e = Inst.OperandList[i].MINumOperands; j != e; ++j) {
OperandList.push_back(Inst.OperandList[i]);
Record *OpR = dynamic_cast<DefInit*>(MIOI->getArg(j))->getDef();
OperandList.back().Rec = OpR;
}
}
for (unsigned j = 0, e = OperandList.size(); j != e; ++j) {
Record *OpR = OperandList[j].Rec;
std::string Res;
if (OpR->isSubClassOf("RegisterClass"))
Res += getQualifiedName(OpR) + "RegClassID, ";
else
Res += "0, ";
// Fill in applicable flags.
Res += "0";
// Ptr value whose register class is resolved via callback.
if (OpR->getName() == "ptr_rc")
Res += "|M_LOOK_UP_PTR_REG_CLASS";
// Predicate operands. Check to see if the original unexpanded operand
// was of type PredicateOperand.
if (Inst.OperandList[i].Rec->isSubClassOf("PredicateOperand"))
Res += "|M_PREDICATE_OPERAND";
// Optional def operands. Check to see if the original unexpanded operand
// was of type OptionalDefOperand.
if (Inst.OperandList[i].Rec->isSubClassOf("OptionalDefOperand"))
Res += "|M_OPTIONAL_DEF_OPERAND";
// Fill in constraint info.
Res += ", " + Inst.OperandList[i].Constraints[j];
Result.push_back(Res);
}
}
return Result;
}
// run - Emit the main instruction description records for the target...
void InstrInfoEmitter::run(std::ostream &OS) {
GatherItinClasses();
EmitSourceFileHeader("Target Instruction Descriptors", OS);
OS << "namespace llvm {\n\n";
CodeGenTarget Target;
const std::string &TargetName = Target.getName();
Record *InstrInfo = Target.getInstructionSet();
// Keep track of all of the def lists we have emitted already.
std::map<std::vector<Record*>, unsigned> EmittedLists;
unsigned ListNumber = 0;
// Emit all of the instruction's implicit uses and defs.
for (CodeGenTarget::inst_iterator II = Target.inst_begin(),
E = Target.inst_end(); II != E; ++II) {
Record *Inst = II->second.TheDef;
std::vector<Record*> Uses = Inst->getValueAsListOfDefs("Uses");
if (!Uses.empty()) {
unsigned &IL = EmittedLists[Uses];
if (!IL) printDefList(Uses, IL = ++ListNumber, OS);
}
std::vector<Record*> Defs = Inst->getValueAsListOfDefs("Defs");
if (!Defs.empty()) {
unsigned &IL = EmittedLists[Defs];
if (!IL) printDefList(Defs, IL = ++ListNumber, OS);
}
}
std::map<std::vector<std::string>, unsigned> OperandInfosEmitted;
unsigned OperandListNum = 0;
OperandInfosEmitted[std::vector<std::string>()] = ++OperandListNum;
// Emit all of the operand info records.
OS << "\n";
for (CodeGenTarget::inst_iterator II = Target.inst_begin(),
E = Target.inst_end(); II != E; ++II) {
std::vector<std::string> OperandInfo = GetOperandInfo(II->second);
unsigned &N = OperandInfosEmitted[OperandInfo];
if (N == 0) {
N = ++OperandListNum;
OS << "static const TargetOperandInfo OperandInfo" << N << "[] = { ";
for (unsigned i = 0, e = OperandInfo.size(); i != e; ++i)
OS << "{ " << OperandInfo[i] << " }, ";
OS << "};\n";
}
}
// Emit all of the TargetInstrDescriptor records in their ENUM ordering.
//
OS << "\nstatic const TargetInstrDescriptor " << TargetName
<< "Insts[] = {\n";
std::vector<const CodeGenInstruction*> NumberedInstructions;
Target.getInstructionsByEnumValue(NumberedInstructions);
for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i)
emitRecord(*NumberedInstructions[i], i, InstrInfo, EmittedLists,
OperandInfosEmitted, OS);
OS << "};\n";
OS << "} // End llvm namespace \n";
}
void InstrInfoEmitter::emitRecord(const CodeGenInstruction &Inst, unsigned Num,
Record *InstrInfo,
std::map<std::vector<Record*>, unsigned> &EmittedLists,
std::map<std::vector<std::string>, unsigned> &OpInfo,
std::ostream &OS) {
int MinOperands;
if (!Inst.OperandList.empty())
// Each logical operand can be multiple MI operands.
MinOperands = Inst.OperandList.back().MIOperandNo +
Inst.OperandList.back().MINumOperands;
else
MinOperands = 0;
OS << " { ";
OS << Num << ",\t" << MinOperands << ",\t"
<< Inst.NumDefs << ",\t\"";
if (Inst.Name.empty())
OS << Inst.TheDef->getName();
else
OS << Inst.Name;
unsigned ItinClass = !IsItineraries ? 0 :
ItinClassNumber(Inst.TheDef->getValueAsDef("Itinerary")->getName());
OS << "\",\t" << ItinClass << ", 0";
// Try to determine (from the pattern), if the instruction is a store.
bool isStore = false;
if (dynamic_cast<ListInit*>(Inst.TheDef->getValueInit("Pattern"))) {
ListInit *LI = Inst.TheDef->getValueAsListInit("Pattern");
if (LI && LI->getSize() > 0) {
DagInit *Dag = (DagInit *)LI->getElement(0);
DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
if (OpDef) {
Record *Operator = OpDef->getDef();
if (Operator->isSubClassOf("SDNode")) {
const std::string Opcode = Operator->getValueAsString("Opcode");
if (Opcode == "ISD::STORE" || Opcode == "ISD::TRUNCSTORE")
isStore = true;
}
}
}
}
// Emit all of the target indepedent flags...
if (Inst.isReturn) OS << "|M_RET_FLAG";
if (Inst.isBranch) OS << "|M_BRANCH_FLAG";
if (Inst.isIndirectBranch) OS << "|M_INDIRECT_FLAG";
if (Inst.isBarrier) OS << "|M_BARRIER_FLAG";
if (Inst.hasDelaySlot) OS << "|M_DELAY_SLOT_FLAG";
if (Inst.isCall) OS << "|M_CALL_FLAG";
if (Inst.isLoad) OS << "|M_LOAD_FLAG";
if (Inst.isStore || isStore) OS << "|M_STORE_FLAG";
if (Inst.isImplicitDef)OS << "|M_IMPLICIT_DEF_FLAG";
if (Inst.isPredicable) OS << "|M_PREDICABLE";
if (Inst.isConvertibleToThreeAddress) OS << "|M_CONVERTIBLE_TO_3_ADDR";
if (Inst.isCommutable) OS << "|M_COMMUTABLE";
if (Inst.isTerminator) OS << "|M_TERMINATOR_FLAG";
if (Inst.isReMaterializable) OS << "|M_REMATERIALIZIBLE";
if (Inst.isNotDuplicable) OS << "|M_NOT_DUPLICABLE";
if (Inst.hasOptionalDef) OS << "|M_HAS_OPTIONAL_DEF";
if (Inst.usesCustomDAGSchedInserter)
OS << "|M_USES_CUSTOM_DAG_SCHED_INSERTION";
if (Inst.hasVariableNumberOfOperands) OS << "|M_VARIABLE_OPS";
if (Inst.mayHaveSideEffects) OS << "|M_MAY_HAVE_SIDE_EFFECTS";
if (Inst.neverHasSideEffects) OS << "|M_NEVER_HAS_SIDE_EFFECTS";
OS << ", 0";
// Emit all of the target-specific flags...
ListInit *LI = InstrInfo->getValueAsListInit("TSFlagsFields");
ListInit *Shift = InstrInfo->getValueAsListInit("TSFlagsShifts");
if (LI->getSize() != Shift->getSize())
throw "Lengths of " + InstrInfo->getName() +
":(TargetInfoFields, TargetInfoPositions) must be equal!";
for (unsigned i = 0, e = LI->getSize(); i != e; ++i)
emitShiftedValue(Inst.TheDef, dynamic_cast<StringInit*>(LI->getElement(i)),
dynamic_cast<IntInit*>(Shift->getElement(i)), OS);
OS << ", ";
// Emit the implicit uses and defs lists...
std::vector<Record*> UseList = Inst.TheDef->getValueAsListOfDefs("Uses");
if (UseList.empty())
OS << "NULL, ";
else
OS << "ImplicitList" << EmittedLists[UseList] << ", ";
std::vector<Record*> DefList = Inst.TheDef->getValueAsListOfDefs("Defs");
if (DefList.empty())
OS << "NULL, ";
else
OS << "ImplicitList" << EmittedLists[DefList] << ", ";
// Emit the operand info.
std::vector<std::string> OperandInfo = GetOperandInfo(Inst);
if (OperandInfo.empty())
OS << "0";
else
OS << "OperandInfo" << OpInfo[OperandInfo];
OS << " }, // Inst #" << Num << " = " << Inst.TheDef->getName() << "\n";
}
struct LessRecord {
bool operator()(const Record *Rec1, const Record *Rec2) const {
return Rec1->getName() < Rec2->getName();
}
};
void InstrInfoEmitter::GatherItinClasses() {
std::vector<Record*> DefList =
Records.getAllDerivedDefinitions("InstrItinClass");
IsItineraries = !DefList.empty();
if (!IsItineraries) return;
std::sort(DefList.begin(), DefList.end(), LessRecord());
for (unsigned i = 0, N = DefList.size(); i < N; i++) {
Record *Def = DefList[i];
ItinClassMap[Def->getName()] = i;
}
}
unsigned InstrInfoEmitter::ItinClassNumber(std::string ItinName) {
return ItinClassMap[ItinName];
}
void InstrInfoEmitter::emitShiftedValue(Record *R, StringInit *Val,
IntInit *ShiftInt, std::ostream &OS) {
if (Val == 0 || ShiftInt == 0)
throw std::string("Illegal value or shift amount in TargetInfo*!");
RecordVal *RV = R->getValue(Val->getValue());
int Shift = ShiftInt->getValue();
if (RV == 0 || RV->getValue() == 0) {
// This isn't an error if this is a builtin instruction.
if (R->getName() != "PHI" &&
R->getName() != "INLINEASM" &&
R->getName() != "LABEL" &&
R->getName() != "EXTRACT_SUBREG" &&
R->getName() != "INSERT_SUBREG")
throw R->getName() + " doesn't have a field named '" +
Val->getValue() + "'!";
return;
}
Init *Value = RV->getValue();
if (BitInit *BI = dynamic_cast<BitInit*>(Value)) {
if (BI->getValue()) OS << "|(1<<" << Shift << ")";
return;
} else if (BitsInit *BI = dynamic_cast<BitsInit*>(Value)) {
// Convert the Bits to an integer to print...
Init *I = BI->convertInitializerTo(new IntRecTy());
if (I)
if (IntInit *II = dynamic_cast<IntInit*>(I)) {
if (II->getValue()) {
if (Shift)
OS << "|(" << II->getValue() << "<<" << Shift << ")";
else
OS << "|" << II->getValue();
}
return;
}
} else if (IntInit *II = dynamic_cast<IntInit*>(Value)) {
if (II->getValue()) {
if (Shift)
OS << "|(" << II->getValue() << "<<" << Shift << ")";
else
OS << II->getValue();
}
return;
}
std::cerr << "Unhandled initializer: " << *Val << "\n";
throw "In record '" + R->getName() + "' for TSFlag emission.";
}
<|endoftext|>
|
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2013. All rights reserved
*/
#include "../StroikaPreComp.h"
#include "../Characters/Format.h"
#include "../Time/Date.h"
#include "../Time/DateTime.h"
#include "ObjectVariantMapper.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::DataExchangeFormat;
using Time::Date;
using Time::DateTime;
/*
********************************************************************************
******* DataExchangeFormat::ObjectVariantMapper::TypeMappingDetails ************
********************************************************************************
*/
ObjectVariantMapper::TypeMappingDetails::TypeMappingDetails (
const type_index& forTypeInfo,
const std::function<VariantValue(ObjectVariantMapper* mapper, const Byte* objOfType)>& toVariantMapper,
const std::function<void(ObjectVariantMapper* mapper, const VariantValue& d, Byte* into)>& fromVariantMapper
)
: fForType (forTypeInfo)
, fToVariantMapper (toVariantMapper)
, fFromVariantMapper (fromVariantMapper)
{
}
/*
********************************************************************************
****************** DataExchangeFormat::ObjectVariantMapper *********************
********************************************************************************
*/
ObjectVariantMapper::ObjectVariantMapper ()
{
RegisterCommonSerializers ();
}
void ObjectVariantMapper::RegisterSerializer (const TypeMappingDetails& serializerInfo)
{
fSerializers_.Add (serializerInfo);
}
void ObjectVariantMapper::ClearRegistry ()
{
fSerializers_.clear ();
}
void ObjectVariantMapper::ResetToDefaultRegistry ()
{
ClearRegistry ();
RegisterCommonSerializers ();
}
namespace {
template <typename T, typename UseVariantType>
ObjectVariantMapper::TypeMappingDetails mkSerializerInfo_ ()
{
auto toVariantMapper = [] (ObjectVariantMapper * mapper, const Byte * objOfType) -> VariantValue {
return VariantValue (static_cast<UseVariantType> (*reinterpret_cast<const T*> (objOfType)));
};
auto fromVariantMapper = [] (ObjectVariantMapper * mapper, const VariantValue & d, Byte * into) -> void {
*reinterpret_cast<T*> (into) = static_cast<T> (d.As<UseVariantType> ());
};
return ObjectVariantMapper::TypeMappingDetails (typeid (T), toVariantMapper, fromVariantMapper);
}
}
void ObjectVariantMapper::RegisterCommonSerializers ()
{
RegisterSerializer (mkSerializerInfo_<bool, bool> ());
RegisterSerializer (mkSerializerInfo_<int, int> ());
RegisterSerializer (mkSerializerInfo_<float, VariantValue::FloatType> ());
RegisterSerializer (mkSerializerInfo_<double, VariantValue::FloatType> ());
RegisterSerializer (mkSerializerInfo_<Date, Date> ());
RegisterSerializer (mkSerializerInfo_<DateTime, DateTime> ());
/// TODO - ARRAY??? Maybe using Sequence???
RegisterSerializer (mkSerializerInfo_<String, String> ());
}
VariantValue ObjectVariantMapper::Serialize (const type_index& forTypeInfo, const Byte* objOfType)
{
Require (Lookup_ (forTypeInfo).fToVariantMapper);
return Lookup_ (forTypeInfo).fToVariantMapper (this, objOfType);
}
void ObjectVariantMapper::Deserialize (const type_index& forTypeInfo, const VariantValue& d, Byte* into)
{
Require (Lookup_ (forTypeInfo).fFromVariantMapper);
Lookup_ (forTypeInfo).fFromVariantMapper (this, d, into);
}
ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::mkSerializerForStruct (const type_index& forTypeInfo, size_t n, const Sequence<StructureFieldInfo>& fields)
{
#if qDebug
for (auto i : fields) {
Require (i.fOffset < n);
}
#endif
// foo magic (could do cleaner?) to assure lifetime for whats captured in lambda
struct foo {
Sequence<StructureFieldInfo> fields;
};
shared_ptr<foo> fooptr (new foo ());
fooptr->fields = fields;
auto toVariantMapper = [fooptr] (ObjectVariantMapper * mapper, const Byte * objOfType) -> VariantValue {
Mapping<String, VariantValue> m;
for (auto i : fooptr->fields) {
const Byte* fieldObj = objOfType + i.fOffset;
m.Add (i.fSerializedFieldName, mapper->Serialize (i.fTypeInfo, objOfType + i.fOffset));
}
return VariantValue (m);
};
auto fromVariantMapper = [fooptr] (ObjectVariantMapper * mapper, const VariantValue & d, Byte * into) -> void {
Mapping<String, VariantValue> m = d.As<Mapping<String, VariantValue>> ();
for (auto i : fooptr->fields) {
Memory::Optional<VariantValue> o = m.Lookup (i.fSerializedFieldName);
if (not o.empty ()) {
mapper->Deserialize (i.fTypeInfo, *o, into + i.fOffset);
}
}
};
return TypeMappingDetails (forTypeInfo, toVariantMapper, fromVariantMapper);
}
ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::Lookup_ (const type_index& forTypeInfo) const
{
TypeMappingDetails foo (forTypeInfo, nullptr, nullptr);
auto i = fSerializers_.Lookup (foo);
Require (i.IsPresent ()); // if not present, this is a usage error - only use types which are registered
return *i;
}
<commit_msg>Assertions in ObjectVariantMapper::mkSerializerForStr ()<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2013. All rights reserved
*/
#include "../StroikaPreComp.h"
#include "../Characters/Format.h"
#include "../Containers/Tally.h"
#include "../Time/Date.h"
#include "../Time/DateTime.h"
#include "ObjectVariantMapper.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::DataExchangeFormat;
using Time::Date;
using Time::DateTime;
/*
********************************************************************************
******* DataExchangeFormat::ObjectVariantMapper::TypeMappingDetails ************
********************************************************************************
*/
ObjectVariantMapper::TypeMappingDetails::TypeMappingDetails (
const type_index& forTypeInfo,
const std::function<VariantValue(ObjectVariantMapper* mapper, const Byte* objOfType)>& toVariantMapper,
const std::function<void(ObjectVariantMapper* mapper, const VariantValue& d, Byte* into)>& fromVariantMapper
)
: fForType (forTypeInfo)
, fToVariantMapper (toVariantMapper)
, fFromVariantMapper (fromVariantMapper)
{
}
/*
********************************************************************************
****************** DataExchangeFormat::ObjectVariantMapper *********************
********************************************************************************
*/
ObjectVariantMapper::ObjectVariantMapper ()
{
RegisterCommonSerializers ();
}
void ObjectVariantMapper::RegisterSerializer (const TypeMappingDetails& serializerInfo)
{
fSerializers_.Add (serializerInfo);
}
void ObjectVariantMapper::ClearRegistry ()
{
fSerializers_.clear ();
}
void ObjectVariantMapper::ResetToDefaultRegistry ()
{
ClearRegistry ();
RegisterCommonSerializers ();
}
namespace {
template <typename T, typename UseVariantType>
ObjectVariantMapper::TypeMappingDetails mkSerializerInfo_ ()
{
auto toVariantMapper = [] (ObjectVariantMapper * mapper, const Byte * objOfType) -> VariantValue {
return VariantValue (static_cast<UseVariantType> (*reinterpret_cast<const T*> (objOfType)));
};
auto fromVariantMapper = [] (ObjectVariantMapper * mapper, const VariantValue & d, Byte * into) -> void {
*reinterpret_cast<T*> (into) = static_cast<T> (d.As<UseVariantType> ());
};
return ObjectVariantMapper::TypeMappingDetails (typeid (T), toVariantMapper, fromVariantMapper);
}
}
void ObjectVariantMapper::RegisterCommonSerializers ()
{
RegisterSerializer (mkSerializerInfo_<bool, bool> ());
RegisterSerializer (mkSerializerInfo_<int, int> ());
RegisterSerializer (mkSerializerInfo_<float, VariantValue::FloatType> ());
RegisterSerializer (mkSerializerInfo_<double, VariantValue::FloatType> ());
RegisterSerializer (mkSerializerInfo_<Date, Date> ());
RegisterSerializer (mkSerializerInfo_<DateTime, DateTime> ());
/// TODO - ARRAY??? Maybe using Sequence???
RegisterSerializer (mkSerializerInfo_<String, String> ());
}
VariantValue ObjectVariantMapper::Serialize (const type_index& forTypeInfo, const Byte* objOfType)
{
Require (Lookup_ (forTypeInfo).fToVariantMapper);
return Lookup_ (forTypeInfo).fToVariantMapper (this, objOfType);
}
void ObjectVariantMapper::Deserialize (const type_index& forTypeInfo, const VariantValue& d, Byte* into)
{
Require (Lookup_ (forTypeInfo).fFromVariantMapper);
Lookup_ (forTypeInfo).fFromVariantMapper (this, d, into);
}
ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::mkSerializerForStruct (const type_index& forTypeInfo, size_t n, const Sequence<StructureFieldInfo>& fields)
{
#if qDebug
for (auto i : fields) {
Require (i.fOffset < n);
}
{
// assure each field unique
Containers::Tally<size_t> t;
for (auto i : fields) {
t.Add (i.fOffset);
}
for (auto i : t) {
Require (i.fCount == 1);
}
}
{
// Assure for each field type is registered
for (auto i : fields) {
Require (Lookup_ (i.fTypeInfo).fFromVariantMapper);
Require (Lookup_ (i.fTypeInfo).fToVariantMapper);
}
}
#endif
// foo magic (could do cleaner?) to assure lifetime for whats captured in lambda
struct foo {
Sequence<StructureFieldInfo> fields;
};
shared_ptr<foo> fooptr (new foo ());
fooptr->fields = fields;
auto toVariantMapper = [fooptr] (ObjectVariantMapper * mapper, const Byte * objOfType) -> VariantValue {
Mapping<String, VariantValue> m;
for (auto i : fooptr->fields) {
const Byte* fieldObj = objOfType + i.fOffset;
m.Add (i.fSerializedFieldName, mapper->Serialize (i.fTypeInfo, objOfType + i.fOffset));
}
return VariantValue (m);
};
auto fromVariantMapper = [fooptr] (ObjectVariantMapper * mapper, const VariantValue & d, Byte * into) -> void {
Mapping<String, VariantValue> m = d.As<Mapping<String, VariantValue>> ();
for (auto i : fooptr->fields) {
Memory::Optional<VariantValue> o = m.Lookup (i.fSerializedFieldName);
if (not o.empty ()) {
mapper->Deserialize (i.fTypeInfo, *o, into + i.fOffset);
}
}
};
return TypeMappingDetails (forTypeInfo, toVariantMapper, fromVariantMapper);
}
ObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::Lookup_ (const type_index& forTypeInfo) const
{
TypeMappingDetails foo (forTypeInfo, nullptr, nullptr);
auto i = fSerializers_.Lookup (foo);
Require (i.IsPresent ()); // if not present, this is a usage error - only use types which are registered
return *i;
}
<|endoftext|>
|
<commit_before>/**
* For conditions of distribution and use, see copyright notice in license.txt
*
* @file UiService.cpp
* @brief Light-weight UI service. Implements UiServiceInterface and provides
* means of embedding Qt widgets to the same scene/canvas as the 3D in-world
* view. Uses only one UI scene for everything.
*/
#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include "UiService.h"
#include "UiProxyWidget.h"
#include "MemoryLeakCheck.h"
#include <QUiLoader>
UiService::UiService(QGraphicsView *view) : view_(view), scene_(view->scene())
{
assert(view_);
assert(scene_);
connect(scene_, SIGNAL(sceneRectChanged(const QRectF &)), SLOT(SceneRectChanged(const QRectF &)));
}
UiService::~UiService()
{
}
UiProxyWidget *UiService::AddWidgetToScene(QWidget *widget, Qt::WindowFlags flags)
{
/* QGraphicsProxyWidget maintains symmetry for the following states:
* state, enabled, visible, geometry, layoutDirection, style, palette,
* font, cursor, sizeHint, getContentsMargins and windowTitle
*/
UiProxyWidget *proxy = new UiProxyWidget(widget, flags);
// Synchorize windowState flags
proxy->widget()->setWindowState(widget->windowState());
AddWidgetToScene(proxy);
// If the widget has WA_DeleteOnClose on, connect its proxy's visibleChanged()
// signal to a slot which handles the deletion. This must be done because closing
// proxy window in our system doesn't yield closeEvent, but hideEvent instead.
if (widget->testAttribute(Qt::WA_DeleteOnClose))
connect(proxy, SIGNAL(visibleChanged()), SLOT(DeleteCallingWidgetOnClose()));
return proxy;
}
bool UiService::AddWidgetToScene(UiProxyWidget *widget)
{
if (widgets_.contains(widget))
return false;
widgets_.append(widget);
if (widget->isVisible())
widget->hide();
// If no position has been set for Qt::Dialog widget, use default one so that the window's title
// bar - or any other critical part, doesn't go outside the view.
if ((widget->windowFlags() & Qt::Dialog) && widget->pos() == QPointF())
widget->setPos(10.0, 200.0);
// Resize full screen widgets to fit the scene rect.
if (widget->widget()->windowState() & Qt::WindowFullScreen)
{
fullScreenWidgets_ << widget;
widget->setGeometry(scene_->sceneRect().toRect());
}
scene_->addItem(widget);
return true;
}
void UiService::AddWidgetToMenu(QWidget *widget)
{
}
void UiService::AddWidgetToMenu(QWidget *widget, const QString &entry, const QString &menu, const QString &icon)
{
}
void UiService::AddWidgetToMenu(UiProxyWidget *widget, const QString &entry, const QString &menu, const QString &icon)
{
}
void UiService::RemoveWidgetFromScene(QWidget *widget)
{
scene_->removeItem(widget->graphicsProxyWidget());
widgets_.removeOne(widget->graphicsProxyWidget());
fullScreenWidgets_.removeOne(widget->graphicsProxyWidget());
}
void UiService::RemoveWidgetFromScene(QGraphicsProxyWidget *widget)
{
scene_->removeItem(widget);
widgets_.removeOne(widget);
fullScreenWidgets_.removeOne(widget);
}
QWidget *UiService::LoadFromFile(const QString &file_path, bool add_to_scene, QWidget *parent)
{
QWidget *widget = 0;
QUiLoader loader;
QFile file(file_path);
file.open(QFile::ReadOnly);
widget = loader.load(&file, parent);
if(add_to_scene && widget)
AddWidgetToScene(widget);
return widget;
}
void UiService::RemoveWidgetFromMenu(QWidget *widget)
{
}
void UiService::RemoveWidgetFromMenu(QGraphicsProxyWidget *widget)
{
}
void UiService::ShowWidget(QWidget *widget) const
{
widget->graphicsProxyWidget()->show();
}
void UiService::HideWidget(QWidget *widget) const
{
widget->graphicsProxyWidget()->hide();
}
void UiService::BringWidgetToFront(QWidget *widget) const
{
ShowWidget(widget);
scene_->setActiveWindow(widget->graphicsProxyWidget());
scene_->setFocusItem(widget->graphicsProxyWidget(), Qt::ActiveWindowFocusReason);
}
void UiService::BringWidgetToFront(QGraphicsProxyWidget *widget) const
{
scene_->setActiveWindow(widget);
scene_->setFocusItem(widget, Qt::ActiveWindowFocusReason);
}
void UiService::SceneRectChanged(const QRectF &rect)
{
foreach(QGraphicsProxyWidget *widget, fullScreenWidgets_)
widget->setGeometry(rect);
}
void UiService::DeleteCallingWidgetOnClose()
{
QGraphicsProxyWidget *proxy = dynamic_cast<QGraphicsProxyWidget *>(sender());
if (proxy && !proxy->isVisible())
proxy->deleteLater();
}
<commit_msg>Added null pointer access guards to UiService.cpp.<commit_after>/**
* For conditions of distribution and use, see copyright notice in license.txt
*
* @file UiService.cpp
* @brief Light-weight UI service. Implements UiServiceInterface and provides
* means of embedding Qt widgets to the same scene/canvas as the 3D in-world
* view. Uses only one UI scene for everything.
*/
#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include "UiService.h"
#include "UiProxyWidget.h"
#include "MemoryLeakCheck.h"
#include <QUiLoader>
UiService::UiService(QGraphicsView *view) : view_(view), scene_(view->scene())
{
assert(view_);
assert(scene_);
connect(scene_, SIGNAL(sceneRectChanged(const QRectF &)), SLOT(SceneRectChanged(const QRectF &)));
}
UiService::~UiService()
{
}
UiProxyWidget *UiService::AddWidgetToScene(QWidget *widget, Qt::WindowFlags flags)
{
if (!widget)
return 0;
/* QGraphicsProxyWidget maintains symmetry for the following states:
* state, enabled, visible, geometry, layoutDirection, style, palette,
* font, cursor, sizeHint, getContentsMargins and windowTitle
*/
UiProxyWidget *proxy = new UiProxyWidget(widget, flags);
assert(proxy->widget());
// Synchorize windowState flags
proxy->widget()->setWindowState(widget->windowState());
AddWidgetToScene(proxy);
// If the widget has WA_DeleteOnClose on, connect its proxy's visibleChanged()
// signal to a slot which handles the deletion. This must be done because closing
// proxy window in our system doesn't yield closeEvent, but hideEvent instead.
if (widget->testAttribute(Qt::WA_DeleteOnClose))
connect(proxy, SIGNAL(visibleChanged()), SLOT(DeleteCallingWidgetOnClose()));
return proxy;
}
bool UiService::AddWidgetToScene(UiProxyWidget *widget)
{
if (!widget)
return false;
if (widgets_.contains(widget))
return false;
widgets_.append(widget);
if (widget->isVisible())
widget->hide();
// If no position has been set for Qt::Dialog widget, use default one so that the window's title
// bar - or any other critical part, doesn't go outside the view.
if ((widget->windowFlags() & Qt::Dialog) && widget->pos() == QPointF())
widget->setPos(10.0, 200.0);
// Resize full screen widgets to fit the scene rect.
if (widget->widget()->windowState() & Qt::WindowFullScreen)
{
fullScreenWidgets_ << widget;
widget->setGeometry(scene_->sceneRect().toRect());
}
scene_->addItem(widget);
return true;
}
void UiService::AddWidgetToMenu(QWidget *widget)
{
}
void UiService::AddWidgetToMenu(QWidget *widget, const QString &entry, const QString &menu, const QString &icon)
{
}
void UiService::AddWidgetToMenu(UiProxyWidget *widget, const QString &entry, const QString &menu, const QString &icon)
{
}
void UiService::RemoveWidgetFromScene(QWidget *widget)
{
if (!widget)
return;
if (scene_)
scene_->removeItem(widget->graphicsProxyWidget());
widgets_.removeOne(widget->graphicsProxyWidget());
fullScreenWidgets_.removeOne(widget->graphicsProxyWidget());
}
void UiService::RemoveWidgetFromScene(QGraphicsProxyWidget *widget)
{
if (!widget)
return;
if (scene_)
scene_->removeItem(widget);
widgets_.removeOne(widget);
fullScreenWidgets_.removeOne(widget);
}
QWidget *UiService::LoadFromFile(const QString &file_path, bool add_to_scene, QWidget *parent)
{
QWidget *widget = 0;
QUiLoader loader;
QFile file(file_path);
file.open(QFile::ReadOnly);
widget = loader.load(&file, parent);
if(add_to_scene && widget)
AddWidgetToScene(widget);
return widget;
}
void UiService::RemoveWidgetFromMenu(QWidget *widget)
{
}
void UiService::RemoveWidgetFromMenu(QGraphicsProxyWidget *widget)
{
}
void UiService::ShowWidget(QWidget *widget) const
{
if (!widget)
return;
if (widget->graphicsProxyWidget())
widget->graphicsProxyWidget()->show();
else
widget->show();
}
void UiService::HideWidget(QWidget *widget) const
{
if (!widget)
return;
if (widget->graphicsProxyWidget())
widget->graphicsProxyWidget()->hide();
else
widget->hide();
}
void UiService::BringWidgetToFront(QWidget *widget) const
{
if (!widget)
return;
ShowWidget(widget);
scene_->setActiveWindow(widget->graphicsProxyWidget());
scene_->setFocusItem(widget->graphicsProxyWidget(), Qt::ActiveWindowFocusReason);
}
void UiService::BringWidgetToFront(QGraphicsProxyWidget *widget) const
{
if (!widget)
return;
scene_->setActiveWindow(widget);
scene_->setFocusItem(widget, Qt::ActiveWindowFocusReason);
}
void UiService::SceneRectChanged(const QRectF &rect)
{
foreach(QGraphicsProxyWidget *widget, fullScreenWidgets_)
widget->setGeometry(rect);
}
void UiService::DeleteCallingWidgetOnClose()
{
QGraphicsProxyWidget *proxy = dynamic_cast<QGraphicsProxyWidget *>(sender());
if (proxy && !proxy->isVisible())
proxy->deleteLater();
}
<|endoftext|>
|
<commit_before>// Copyright 2014 Alessio Sclocco <a.sclocco@vu.nl>
//
// 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 <iostream>
#include <string>
#include <vector>
#include <exception>
#include <fstream>
#include <iomanip>
#include <limits>
#include <ArgumentList.hpp>
#include <Observation.hpp>
#include <InitializeOpenCL.hpp>
#include <Kernel.hpp>
#include <Shifts.hpp>
#include <Dedispersion.hpp>
#include <utils.hpp>
#include <Timer.hpp>
#include <Stats.hpp>
// Define the data types
typedef float inputDataType;
std::string inputTypeName("float");
std::string intermediateTypeName("float");
typedef float outputDataType;
std::string outputTypeName("float");
void initializeDeviceMemory(cl::Context & clContext, cl::CommandQueue * clQueue, std::vector< float > * shifts, cl::Buffer * shifts_d, cl::Buffer * dispersedData_d, const unsigned int dispersedData_size, cl::Buffer * dedispersedData_d, const unsigned int dedispersedData_size);
int main(int argc, char * argv[]) {
bool reInit = false;
uint8_t inputBits = 0;
unsigned int splitSeconds = 0;
unsigned int nrIterations = 0;
unsigned int clPlatformID = 0;
unsigned int clDeviceID = 0;
unsigned int minThreads = 0;
unsigned int maxThreads = 0;
unsigned int maxRows = 0;
unsigned int maxColumns = 0;
unsigned int threadUnit = 0;
unsigned int threadIncrement = 0;
unsigned int maxItems = 0;
unsigned int maxUnroll = 0;
unsigned int maxLoopBodySize = 0;
AstroData::Observation observation;
PulsarSearch::DedispersionConf conf;
cl::Event event;
try {
isa::utils::ArgumentList args(argc, argv);
nrIterations = args.getSwitchArgument< unsigned int >("-iterations");
clPlatformID = args.getSwitchArgument< unsigned int >("-opencl_platform");
clDeviceID = args.getSwitchArgument< unsigned int >("-opencl_device");
conf.setSplitSeconds(args.getSwitch("-split_seconds"));
conf.setLocalMem(args.getSwitch("-local"));
observation.setPadding(args.getSwitchArgument< unsigned int >("-padding"));
inputBits = args.getSwitchArgument< unsigned int >("-input_bits");
threadUnit = args.getSwitchArgument< unsigned int >("-thread_unit");
minThreads = args.getSwitchArgument< unsigned int >("-min_threads");
maxThreads = args.getSwitchArgument< unsigned int >("-max_threads");
maxRows = args.getSwitchArgument< unsigned int >("-max_rows");
maxColumns = args.getSwitchArgument< unsigned int >("-max_columns");
threadIncrement = args.getSwitchArgument< unsigned int >("-thread_increment");
maxItems = args.getSwitchArgument< unsigned int >("-max_items");
maxUnroll = args.getSwitchArgument< unsigned int >("-max_unroll");
maxLoopBodySize = args.getSwitchArgument< unsigned int >("-max_loopsize");
observation.setFrequencyRange(args.getSwitchArgument< unsigned int >("-channels"), args.getSwitchArgument< float >("-min_freq"), args.getSwitchArgument< float >("-channel_bandwidth"));
observation.setNrSamplesPerSecond(args.getSwitchArgument< unsigned int >("-samples"));
observation.setDMRange(args.getSwitchArgument< unsigned int >("-dms"), args.getSwitchArgument< float >("-dm_first"), args.getSwitchArgument< float >("-dm_step"));
} catch ( isa::utils::EmptyCommandLine & err ) {
std::cerr << argv[0] << " -iterations ... -opencl_platform ... -opencl_device ... [-split_seconds] [-local] -input_bits ... -padding ... -thread_unit ... -min_threads ... -max_threads ... -max_items ... -max_unroll ... -max_loopsize ... -max_columns ... -max_rows ... -thread_increment ... -min_freq ... -channel_bandwidth ... -samples ... -channels ... -dms ... -dm_first ... -dm_step ..." << std::endl;
return 1;
} catch ( std::exception & err ) {
std::cerr << err.what() << std::endl;
return 1;
}
// Allocate host memory
std::vector< float > * shifts = PulsarSearch::getShifts(observation);
if ( conf.getSplitSeconds() ) {
if ( (observation.getNrSamplesPerSecond() + static_cast< unsigned int >(shifts->at(0) * (observation.getFirstDM() + ((observation.getNrDMs() - 1) * observation.getDMStep())))) % observation.getNrSamplesPerSecond() == 0 ) {
splitSeconds = (observation.getNrSamplesPerSecond() + static_cast< unsigned int >(shifts->at(0) * (observation.getFirstDM() + ((observation.getNrDMs() - 1) * observation.getDMStep())))) / observation.getNrSamplesPerSecond();
} else {
splitSeconds = ((observation.getNrSamplesPerSecond() + static_cast< unsigned int >(shifts->at(0) * (observation.getFirstDM() + ((observation.getNrDMs() - 1) * observation.getDMStep())))) / observation.getNrSamplesPerSecond()) + 1;
}
} else {
observation.setNrSamplesPerDispersedChannel(observation.getNrSamplesPerSecond() + static_cast< unsigned int >(shifts->at(0) * (observation.getFirstDM() + ((observation.getNrDMs() - 1) * observation.getDMStep()))));
}
// Initialize OpenCL
cl::Context clContext;
std::vector< cl::Platform > * clPlatforms = new std::vector< cl::Platform >();
std::vector< cl::Device > * clDevices = new std::vector< cl::Device >();
std::vector< std::vector< cl::CommandQueue > > * clQueues = new std::vector< std::vector < cl::CommandQueue > >();
isa::OpenCL::initializeOpenCL(clPlatformID, 1, clPlatforms, &clContext, clDevices, clQueues);
// Allocate device memory
cl::Buffer shifts_d;
cl::Buffer dispersedData_d;
cl::Buffer dedispersedData_d;
try {
if ( conf.getSplitSeconds() ) {
initializeDeviceMemory(clContext, &(clQueues->at(clDeviceID)[0]), shifts, &shifts_d, &dispersedData_d, splitSeconds * observation.getNrChannels() * observation.getNrSamplesPerPaddedSecond(), &dedispersedData_d, observation.getNrDMs() * observation.getNrSamplesPerPaddedSecond());
} else {
initializeDeviceMemory(clContext, &(clQueues->at(clDeviceID)[0]), shifts, &shifts_d, &dispersedData_d, observation.getNrChannels() * observation.getNrSamplesPerDispersedChannel(), &dedispersedData_d, observation.getNrDMs() * observation.getNrSamplesPerPaddedSecond());
}
} catch ( cl::Error & err ) {
std::cerr << err.what() << std::endl;
return -1;
}
// Find the parameters
std::vector< unsigned int > samplesPerBlock;
for ( unsigned int samples = minThreads; samples <= maxColumns; samples += threadIncrement ) {
if ( (observation.getNrSamplesPerSecond() % samples) == 0 || (observation.getNrSamplesPerPaddedSecond() % samples) == 0 ) {
samplesPerBlock.push_back(samples);
}
}
std::vector< unsigned int > DMsPerBlock;
for ( unsigned int DMs = 1; DMs <= maxRows; DMs++ ) {
if ( (observation.getNrDMs() % DMs) == 0 ) {
DMsPerBlock.push_back(DMs);
}
}
std::cout << std::fixed << std::endl;
std::cout << "# nrDMs nrChannels nrSamples splitSeconds local unroll samplesPerBlock DMsPerBlock samplesPerThread DMsPerThread GFLOP/s time stdDeviation COV" << std::endl << std::endl;
for ( std::vector< unsigned int >::iterator samples = samplesPerBlock.begin(); samples != samplesPerBlock.end(); ++samples ) {
conf.setNrSamplesPerBlock(*samples);
for ( std::vector< unsigned int >::iterator DMs = DMsPerBlock.begin(); DMs != DMsPerBlock.end(); ++DMs ) {
conf.setNrDMsPerBlock(*DMs);
if ( conf.getNrSamplesPerBlock() * conf.getNrDMsPerBlock() > maxThreads ) {
break;
} else if ( (conf.getNrSamplesPerBlock() * conf.getNrDMsPerBlock()) % threadUnit != 0 ) {
continue;
}
for ( unsigned int samplesPerThread = 1; samplesPerThread <= maxItems; samplesPerThread++ ) {
conf.setNrSamplesPerThread(samplesPerThread);
if ( (observation.getNrSamplesPerSecond() % (conf.getNrSamplesPerBlock() * conf.getNrSamplesPerThread())) != 0 && (observation.getNrSamplesPerPaddedSecond() % (conf.getNrSamplesPerBlock() * conf.getNrSamplesPerThread())) != 0 ) {
continue;
}
for ( unsigned int DMsPerThread = 1; DMsPerThread <= maxItems; DMsPerThread++ ) {
conf.setNrDMsPerThread(DMsPerThread);
if ( (observation.getNrDMs() % (conf.getNrDMsPerBlock() * conf.getNrDMsPerThread())) != 0 ) {
continue;
} else if ( (conf.getNrSamplesPerThread() * conf.getNrDMsPerThread()) + conf.getNrDMsPerThread() > maxItems ) {
break;
}
for ( unsigned int unroll = 1; unroll <= maxUnroll; unroll++ ) {
conf.setUnroll(unroll);
if ( (observation.getNrChannels() - 1) % conf.getUnroll() != 0 ) {
continue;
} else if ( (conf.getNrSamplesPerThread() * conf.getNrDMsPerThread() * conf.getUnroll()) > maxLoopBodySize ) {
break;
}
// Generate kernel
double gflops = isa::utils::giga(static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrChannels() * observation.getNrSamplesPerSecond());
isa::utils::Timer timer;
cl::Kernel * kernel;
std::string * code = PulsarSearch::getDedispersionOpenCL(conf, inputBits, inputTypeName, intermediateTypeName, outputTypeName, observation, *shifts);
if ( reInit ) {
delete clQueues;
clQueues = new std::vector< std::vector < cl::CommandQueue > >();
isa::OpenCL::initializeOpenCL(clPlatformID, 1, clPlatforms, &clContext, clDevices, clQueues);
try {
initializeDeviceMemory(clContext, &(clQueues->at(clDeviceID)[0]), shifts, &shifts_d, &dispersedData_d, observation.getNrChannels() * observation.getNrSamplesPerDispersedChannel(), &dedispersedData_d, observation.getNrDMs() * observation.getNrSamplesPerPaddedSecond());
} catch ( cl::Error & err ) {
return -1;
}
reInit = false;
}
try {
kernel = isa::OpenCL::compile("dedispersion", *code, "-cl-mad-enable -Werror", clContext, clDevices->at(clDeviceID));
} catch ( isa::OpenCL::OpenCLError & err ) {
std::cerr << err.what() << std::endl;
delete code;
break;
}
delete code;
unsigned int nrThreads = 0;
if ( observation.getNrSamplesPerSecond() % (conf.getNrSamplesPerBlock() * conf.getNrSamplesPerThread()) == 0 ) {
nrThreads = observation.getNrSamplesPerSecond() / conf.getNrSamplesPerThread();
} else {
nrThreads = observation.getNrSamplesPerPaddedSecond() / conf.getNrSamplesPerThread();
}
cl::NDRange global(nrThreads, observation.getNrDMs() / conf.getNrDMsPerThread());
cl::NDRange local(conf.getNrSamplesPerBlock(), conf.getNrDMsPerBlock());
kernel->setArg(0, dispersedData_d);
kernel->setArg(1, dedispersedData_d);
kernel->setArg(2, shifts_d);
try {
// Warm-up run
clQueues->at(clDeviceID)[0].finish();
clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &event);
event.wait();
// Tuning runs
for ( unsigned int iteration = 0; iteration < nrIterations; iteration++ ) {
timer.start();
clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &event);
event.wait();
timer.stop();
}
} catch ( cl::Error & err ) {
std::cerr << "OpenCL error kernel execution (";
std::cerr << conf.print() << "): ";
std::cerr << isa::utils::toString(err.err()) << "." << std::endl;
delete kernel;
if ( err.err() == -4 || err.err() == -61 ) {
return -1;
}
reInit = true;
break;
}
delete kernel;
std::cout << observation.getNrDMs() << " " << observation.getNrChannels() << " " << observation.getNrSamplesPerSecond() << " ";
std::cout << conf.print() << " ";
std::cout << std::setprecision(3);
std::cout << gflops / timer.getAverageTime() << " ";
std::cout << std::setprecision(6);
std::cout << timer.getAverageTime() << " " << timer.getStandardDeviation() << " ";
std::cout << timer.getCoefficientOfVariation() << std::endl;
}
}
}
}
}
std::cout << std::endl;
return 0;
}
void initializeDeviceMemory(cl::Context & clContext, cl::CommandQueue * clQueue, std::vector< float > * shifts, cl::Buffer * shifts_d, cl::Buffer * dispersedData_d, const unsigned int dispersedData_size, cl::Buffer * dedispersedData_d, const unsigned int dedispersedData_size) {
try {
*shifts_d = cl::Buffer(clContext, CL_MEM_READ_ONLY, shifts->size() * sizeof(float), 0, 0);
*dispersedData_d = cl::Buffer(clContext, CL_MEM_READ_ONLY, dispersedData_size * sizeof(inputDataType), 0, 0);
*dedispersedData_d = cl::Buffer(clContext, CL_MEM_READ_WRITE, dedispersedData_size * sizeof(outputDataType), 0, 0);
clQueue->enqueueWriteBuffer(*shifts_d, CL_FALSE, 0, shifts->size() * sizeof(float), reinterpret_cast< void * >(shifts->data()));
clQueue->finish();
} catch ( cl::Error & err ) {
std::cerr << "OpenCL error: " << isa::utils::toString(err.err()) << "." << std::endl;
throw;
}
}
<commit_msg>The version that uses split seconds needs a parameter more.<commit_after>// Copyright 2014 Alessio Sclocco <a.sclocco@vu.nl>
//
// 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 <iostream>
#include <string>
#include <vector>
#include <exception>
#include <fstream>
#include <iomanip>
#include <limits>
#include <ArgumentList.hpp>
#include <Observation.hpp>
#include <InitializeOpenCL.hpp>
#include <Kernel.hpp>
#include <Shifts.hpp>
#include <Dedispersion.hpp>
#include <utils.hpp>
#include <Timer.hpp>
#include <Stats.hpp>
// Define the data types
typedef float inputDataType;
std::string inputTypeName("float");
std::string intermediateTypeName("float");
typedef float outputDataType;
std::string outputTypeName("float");
void initializeDeviceMemory(cl::Context & clContext, cl::CommandQueue * clQueue, std::vector< float > * shifts, cl::Buffer * shifts_d, cl::Buffer * dispersedData_d, const unsigned int dispersedData_size, cl::Buffer * dedispersedData_d, const unsigned int dedispersedData_size);
int main(int argc, char * argv[]) {
bool reInit = false;
uint8_t inputBits = 0;
unsigned int splitSeconds = 0;
unsigned int nrIterations = 0;
unsigned int clPlatformID = 0;
unsigned int clDeviceID = 0;
unsigned int minThreads = 0;
unsigned int maxThreads = 0;
unsigned int maxRows = 0;
unsigned int maxColumns = 0;
unsigned int threadUnit = 0;
unsigned int threadIncrement = 0;
unsigned int maxItems = 0;
unsigned int maxUnroll = 0;
unsigned int maxLoopBodySize = 0;
AstroData::Observation observation;
PulsarSearch::DedispersionConf conf;
cl::Event event;
try {
isa::utils::ArgumentList args(argc, argv);
nrIterations = args.getSwitchArgument< unsigned int >("-iterations");
clPlatformID = args.getSwitchArgument< unsigned int >("-opencl_platform");
clDeviceID = args.getSwitchArgument< unsigned int >("-opencl_device");
conf.setSplitSeconds(args.getSwitch("-split_seconds"));
conf.setLocalMem(args.getSwitch("-local"));
observation.setPadding(args.getSwitchArgument< unsigned int >("-padding"));
inputBits = args.getSwitchArgument< unsigned int >("-input_bits");
threadUnit = args.getSwitchArgument< unsigned int >("-thread_unit");
minThreads = args.getSwitchArgument< unsigned int >("-min_threads");
maxThreads = args.getSwitchArgument< unsigned int >("-max_threads");
maxRows = args.getSwitchArgument< unsigned int >("-max_rows");
maxColumns = args.getSwitchArgument< unsigned int >("-max_columns");
threadIncrement = args.getSwitchArgument< unsigned int >("-thread_increment");
maxItems = args.getSwitchArgument< unsigned int >("-max_items");
maxUnroll = args.getSwitchArgument< unsigned int >("-max_unroll");
maxLoopBodySize = args.getSwitchArgument< unsigned int >("-max_loopsize");
observation.setFrequencyRange(args.getSwitchArgument< unsigned int >("-channels"), args.getSwitchArgument< float >("-min_freq"), args.getSwitchArgument< float >("-channel_bandwidth"));
observation.setNrSamplesPerSecond(args.getSwitchArgument< unsigned int >("-samples"));
observation.setDMRange(args.getSwitchArgument< unsigned int >("-dms"), args.getSwitchArgument< float >("-dm_first"), args.getSwitchArgument< float >("-dm_step"));
} catch ( isa::utils::EmptyCommandLine & err ) {
std::cerr << argv[0] << " -iterations ... -opencl_platform ... -opencl_device ... [-split_seconds] [-local] -input_bits ... -padding ... -thread_unit ... -min_threads ... -max_threads ... -max_items ... -max_unroll ... -max_loopsize ... -max_columns ... -max_rows ... -thread_increment ... -min_freq ... -channel_bandwidth ... -samples ... -channels ... -dms ... -dm_first ... -dm_step ..." << std::endl;
return 1;
} catch ( std::exception & err ) {
std::cerr << err.what() << std::endl;
return 1;
}
// Allocate host memory
std::vector< float > * shifts = PulsarSearch::getShifts(observation);
if ( conf.getSplitSeconds() ) {
if ( (observation.getNrSamplesPerSecond() + static_cast< unsigned int >(shifts->at(0) * (observation.getFirstDM() + ((observation.getNrDMs() - 1) * observation.getDMStep())))) % observation.getNrSamplesPerSecond() == 0 ) {
splitSeconds = (observation.getNrSamplesPerSecond() + static_cast< unsigned int >(shifts->at(0) * (observation.getFirstDM() + ((observation.getNrDMs() - 1) * observation.getDMStep())))) / observation.getNrSamplesPerSecond();
} else {
splitSeconds = ((observation.getNrSamplesPerSecond() + static_cast< unsigned int >(shifts->at(0) * (observation.getFirstDM() + ((observation.getNrDMs() - 1) * observation.getDMStep())))) / observation.getNrSamplesPerSecond()) + 1;
}
} else {
observation.setNrSamplesPerDispersedChannel(observation.getNrSamplesPerSecond() + static_cast< unsigned int >(shifts->at(0) * (observation.getFirstDM() + ((observation.getNrDMs() - 1) * observation.getDMStep()))));
}
// Initialize OpenCL
cl::Context clContext;
std::vector< cl::Platform > * clPlatforms = new std::vector< cl::Platform >();
std::vector< cl::Device > * clDevices = new std::vector< cl::Device >();
std::vector< std::vector< cl::CommandQueue > > * clQueues = new std::vector< std::vector < cl::CommandQueue > >();
isa::OpenCL::initializeOpenCL(clPlatformID, 1, clPlatforms, &clContext, clDevices, clQueues);
// Allocate device memory
cl::Buffer shifts_d;
cl::Buffer dispersedData_d;
cl::Buffer dedispersedData_d;
try {
if ( conf.getSplitSeconds() ) {
initializeDeviceMemory(clContext, &(clQueues->at(clDeviceID)[0]), shifts, &shifts_d, &dispersedData_d, splitSeconds * observation.getNrChannels() * observation.getNrSamplesPerPaddedSecond(), &dedispersedData_d, observation.getNrDMs() * observation.getNrSamplesPerPaddedSecond());
} else {
initializeDeviceMemory(clContext, &(clQueues->at(clDeviceID)[0]), shifts, &shifts_d, &dispersedData_d, observation.getNrChannels() * observation.getNrSamplesPerDispersedChannel(), &dedispersedData_d, observation.getNrDMs() * observation.getNrSamplesPerPaddedSecond());
}
} catch ( cl::Error & err ) {
std::cerr << err.what() << std::endl;
return -1;
}
// Find the parameters
std::vector< unsigned int > samplesPerBlock;
for ( unsigned int samples = minThreads; samples <= maxColumns; samples += threadIncrement ) {
if ( (observation.getNrSamplesPerSecond() % samples) == 0 || (observation.getNrSamplesPerPaddedSecond() % samples) == 0 ) {
samplesPerBlock.push_back(samples);
}
}
std::vector< unsigned int > DMsPerBlock;
for ( unsigned int DMs = 1; DMs <= maxRows; DMs++ ) {
if ( (observation.getNrDMs() % DMs) == 0 ) {
DMsPerBlock.push_back(DMs);
}
}
std::cout << std::fixed << std::endl;
std::cout << "# nrDMs nrChannels nrSamples splitSeconds local unroll samplesPerBlock DMsPerBlock samplesPerThread DMsPerThread GFLOP/s time stdDeviation COV" << std::endl << std::endl;
for ( std::vector< unsigned int >::iterator samples = samplesPerBlock.begin(); samples != samplesPerBlock.end(); ++samples ) {
conf.setNrSamplesPerBlock(*samples);
for ( std::vector< unsigned int >::iterator DMs = DMsPerBlock.begin(); DMs != DMsPerBlock.end(); ++DMs ) {
conf.setNrDMsPerBlock(*DMs);
if ( conf.getNrSamplesPerBlock() * conf.getNrDMsPerBlock() > maxThreads ) {
break;
} else if ( (conf.getNrSamplesPerBlock() * conf.getNrDMsPerBlock()) % threadUnit != 0 ) {
continue;
}
for ( unsigned int samplesPerThread = 1; samplesPerThread <= maxItems; samplesPerThread++ ) {
conf.setNrSamplesPerThread(samplesPerThread);
if ( (observation.getNrSamplesPerSecond() % (conf.getNrSamplesPerBlock() * conf.getNrSamplesPerThread())) != 0 && (observation.getNrSamplesPerPaddedSecond() % (conf.getNrSamplesPerBlock() * conf.getNrSamplesPerThread())) != 0 ) {
continue;
}
for ( unsigned int DMsPerThread = 1; DMsPerThread <= maxItems; DMsPerThread++ ) {
conf.setNrDMsPerThread(DMsPerThread);
if ( (observation.getNrDMs() % (conf.getNrDMsPerBlock() * conf.getNrDMsPerThread())) != 0 ) {
continue;
} else if ( (conf.getNrSamplesPerThread() * conf.getNrDMsPerThread()) + conf.getNrDMsPerThread() > maxItems ) {
break;
}
for ( unsigned int unroll = 1; unroll <= maxUnroll; unroll++ ) {
conf.setUnroll(unroll);
if ( (observation.getNrChannels() - 1) % conf.getUnroll() != 0 ) {
continue;
} else if ( (conf.getNrSamplesPerThread() * conf.getNrDMsPerThread() * conf.getUnroll()) > maxLoopBodySize ) {
break;
}
// Generate kernel
double gflops = isa::utils::giga(static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrChannels() * observation.getNrSamplesPerSecond());
isa::utils::Timer timer;
cl::Kernel * kernel;
std::string * code = PulsarSearch::getDedispersionOpenCL(conf, inputBits, inputTypeName, intermediateTypeName, outputTypeName, observation, *shifts);
if ( reInit ) {
delete clQueues;
clQueues = new std::vector< std::vector < cl::CommandQueue > >();
isa::OpenCL::initializeOpenCL(clPlatformID, 1, clPlatforms, &clContext, clDevices, clQueues);
try {
initializeDeviceMemory(clContext, &(clQueues->at(clDeviceID)[0]), shifts, &shifts_d, &dispersedData_d, observation.getNrChannels() * observation.getNrSamplesPerDispersedChannel(), &dedispersedData_d, observation.getNrDMs() * observation.getNrSamplesPerPaddedSecond());
} catch ( cl::Error & err ) {
return -1;
}
reInit = false;
}
try {
kernel = isa::OpenCL::compile("dedispersion", *code, "-cl-mad-enable -Werror", clContext, clDevices->at(clDeviceID));
} catch ( isa::OpenCL::OpenCLError & err ) {
std::cerr << err.what() << std::endl;
delete code;
break;
}
delete code;
unsigned int nrThreads = 0;
if ( observation.getNrSamplesPerSecond() % (conf.getNrSamplesPerBlock() * conf.getNrSamplesPerThread()) == 0 ) {
nrThreads = observation.getNrSamplesPerSecond() / conf.getNrSamplesPerThread();
} else {
nrThreads = observation.getNrSamplesPerPaddedSecond() / conf.getNrSamplesPerThread();
}
cl::NDRange global(nrThreads, observation.getNrDMs() / conf.getNrDMsPerThread());
cl::NDRange local(conf.getNrSamplesPerBlock(), conf.getNrDMsPerBlock());
if ( conf.getSplitSeconds() ) {
kernel->setArg(0, 0);
kernel->setArg(1, dispersedData_d);
kernel->setArg(2, dedispersedData_d);
kernel->setArg(3, shifts_d);
} else {
kernel->setArg(0, dispersedData_d);
kernel->setArg(1, dedispersedData_d);
kernel->setArg(2, shifts_d);
}
try {
// Warm-up run
clQueues->at(clDeviceID)[0].finish();
clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &event);
event.wait();
// Tuning runs
for ( unsigned int iteration = 0; iteration < nrIterations; iteration++ ) {
timer.start();
clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &event);
event.wait();
timer.stop();
}
} catch ( cl::Error & err ) {
std::cerr << "OpenCL error kernel execution (";
std::cerr << conf.print() << "): ";
std::cerr << isa::utils::toString(err.err()) << "." << std::endl;
delete kernel;
if ( err.err() == -4 || err.err() == -61 ) {
return -1;
}
reInit = true;
break;
}
delete kernel;
std::cout << observation.getNrDMs() << " " << observation.getNrChannels() << " " << observation.getNrSamplesPerSecond() << " ";
std::cout << conf.print() << " ";
std::cout << std::setprecision(3);
std::cout << gflops / timer.getAverageTime() << " ";
std::cout << std::setprecision(6);
std::cout << timer.getAverageTime() << " " << timer.getStandardDeviation() << " ";
std::cout << timer.getCoefficientOfVariation() << std::endl;
}
}
}
}
}
std::cout << std::endl;
return 0;
}
void initializeDeviceMemory(cl::Context & clContext, cl::CommandQueue * clQueue, std::vector< float > * shifts, cl::Buffer * shifts_d, cl::Buffer * dispersedData_d, const unsigned int dispersedData_size, cl::Buffer * dedispersedData_d, const unsigned int dedispersedData_size) {
try {
*shifts_d = cl::Buffer(clContext, CL_MEM_READ_ONLY, shifts->size() * sizeof(float), 0, 0);
*dispersedData_d = cl::Buffer(clContext, CL_MEM_READ_ONLY, dispersedData_size * sizeof(inputDataType), 0, 0);
*dedispersedData_d = cl::Buffer(clContext, CL_MEM_READ_WRITE, dedispersedData_size * sizeof(outputDataType), 0, 0);
clQueue->enqueueWriteBuffer(*shifts_d, CL_FALSE, 0, shifts->size() * sizeof(float), reinterpret_cast< void * >(shifts->data()));
clQueue->finish();
} catch ( cl::Error & err ) {
std::cerr << "OpenCL error: " << isa::utils::toString(err.err()) << "." << std::endl;
throw;
}
}
<|endoftext|>
|
<commit_before>/*******************************
Copyright (C) 2013-2015 gregoire ANGERAND
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.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
**********************************/
#include "DeferredCommon.h"
#include "GLContext.h"
#include "VertexArrayFactory.h"
namespace n {
namespace graphics {
const VertexArrayObject<> &getSphere() {
static VertexArrayObject<> *sphere = 0;
if(!sphere) {
sphere = new VertexArrayObject<>(GLContext::getContext()->getVertexArrayFactory()(TriangleBuffer<>::getSphere()));
}
return *sphere;
}
const VertexArrayObject<> &getBox() {
static VertexArrayObject<> *box = 0;
if(!box) {
box = new VertexArrayObject<>(GLContext::getContext()->getVertexArrayFactory()(TriangleBuffer<>::getCube()));
}
return *box;
}
core::String getBRDFs() {
return
// [Walter et al. 2007, "Microfacet models for refraction through rough surfaces"]
"float D_GGX(float NoH, float a2) {"
"float d = (NoH * a2 - NoH) * NoH + 1.0;"
"return a2 / (pi * d * d);"
"}"
// [Schlick 1994, "An Inexpensive BRDF Model for Physically-Based Rendering"]
"float F_Schlick(float VoH, float F0) {"
"float Fc = pow(1 - VoH, 5.0);"
"return Fc + (1.0 - Fc) * F0;"
"}"
"vec3 F_Schlick(float VoH, vec3 F0) {"
"float Fc = pow(1 - VoH, 5.0);"
"return Fc + (1.0 - Fc) * F0;"
"}"
"float V_Schlick(float NoL, float NoV, float a) {"
"float k = a * 0.5;"
"float GV = NoV * (1.0 - k) + k;"
"float GL = NoL * (1.0 - k) + k;"
"return 0.25 / (GL * GV + epsilon);"
"}"
"float V_Smith(float NoL, float NoV, float a2) {"
"float GV = NoV + sqrt(NoV * (NoV - NoV * a2) + a2);"
"float GL = NoL + sqrt(NoL * (NoL - NoL * a2) + a2);"
"return 1.0 / (GL * GV + epsilon);"
"}"
"float V_SmithApprox(float NoL, float NoV, float a) {"
"float GV = NoL * (NoV * (1.0 - a) + a);"
"float GL = NoV * (NoL * (1.0 - a) + a);"
"return 0.5 / (GV + GL + epsilon);"
"}"
"float brdf_cook_torrance(vec3 L, vec3 V, vec3 N, vec4 M) {"
"vec3 H = normalize(L + V);"
"float NoL = saturate(dot(N, L));"
"float NoV = max(dot(N, V), epsilon);"
"float VoH = saturate(dot(V, H));"
"float NoH = saturate(dot(N, H));"
"float roughness = saturate(M.x + epsilon);"
"float a = sqr(roughness);"
"float a2 = sqr(a);"
"return "
"F_Schlick(VoH, M.z) * "
"D_GGX(NoH, a) * "
"V_Schlick(NoL, NoV, a);"
"}"
"float brdf_lambert(vec3 L, vec3 V, vec3 N, vec4 M) {"
"return 1.0 / pi;"
"}"
//http://blog.selfshadow.com/publications/s2013-shading-course/#course_content
"vec3 brdf_importance_sample(vec2 Xi, float a) {"
"float phi = 2.0 * pi * Xi.x;"
"float cosT = sqrt((1.0 - Xi.y) / (1.0 + (a * a - 1.0) * Xi.y));"
"float sinT = sqrt(1.0 - cosT * cosT);"
"return vec3(sinT * cos(phi), sinT * sin(phi), cosT);"
"}";
}
}
}
<commit_msg>Fixed Schlick to match unreal roughness scale.<commit_after>/*******************************
Copyright (C) 2013-2015 gregoire ANGERAND
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.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
**********************************/
#include "DeferredCommon.h"
#include "GLContext.h"
#include "VertexArrayFactory.h"
namespace n {
namespace graphics {
const VertexArrayObject<> &getSphere() {
static VertexArrayObject<> *sphere = 0;
if(!sphere) {
sphere = new VertexArrayObject<>(GLContext::getContext()->getVertexArrayFactory()(TriangleBuffer<>::getSphere()));
}
return *sphere;
}
const VertexArrayObject<> &getBox() {
static VertexArrayObject<> *box = 0;
if(!box) {
box = new VertexArrayObject<>(GLContext::getContext()->getVertexArrayFactory()(TriangleBuffer<>::getCube()));
}
return *box;
}
core::String getBRDFs() {
return
// [Walter et al. 2007, "Microfacet models for refraction through rough surfaces"]
"float D_GGX(float NoH, float a2) {"
"float d = (NoH * a2 - NoH) * NoH + 1.0;"
"return a2 / (pi * d * d);"
"}"
// [Schlick 1994, "An Inexpensive BRDF Model for Physically-Based Rendering"]
"float F_Schlick(float VoH, float F0) {"
"float Fc = pow(1 - VoH, 5.0);"
"return Fc + (1.0 - Fc) * F0;"
"}"
"vec3 F_Schlick(float VoH, vec3 F0) {"
"float Fc = pow(1 - VoH, 5.0);"
"return Fc + (1.0 - Fc) * F0;"
"}"
"float V_Schlick(float NoL, float NoV, float roughness) {"
"float k = sqr((roughness + 1.0) * 0.5);"
"float GV = NoV * (1.0 - k) + k;"
"float GL = NoL * (1.0 - k) + k;"
"return 0.25 / (GL * GV + epsilon);"
"}"
"float V_Smith(float NoL, float NoV, float a2) {"
"float GV = NoV + sqrt(NoV * (NoV - NoV * a2) + a2);"
"float GL = NoL + sqrt(NoL * (NoL - NoL * a2) + a2);"
"return 1.0 / (GL * GV + epsilon);"
"}"
"float V_SmithApprox(float NoL, float NoV, float a) {"
"float GV = NoL * (NoV * (1.0 - a) + a);"
"float GL = NoV * (NoL * (1.0 - a) + a);"
"return 0.5 / (GV + GL + epsilon);"
"}"
"float brdf_cook_torrance(vec3 L, vec3 V, vec3 N, vec4 M) {"
"vec3 H = normalize(L + V);"
"float NoL = saturate(dot(N, L));"
"float NoV = max(dot(N, V), epsilon);"
"float VoH = saturate(dot(V, H));"
"float NoH = saturate(dot(N, H));"
"float roughness = saturate(M.x + epsilon);"
"float a = sqr(roughness);"
"return "
"F_Schlick(VoH, M.z) * "
"D_GGX(NoH, a) * "
"V_Schlick(NoL, NoV, roughness);"
"}"
"float brdf_lambert(vec3 L, vec3 V, vec3 N, vec4 M) {"
"return 1.0 / pi;"
"}"
//http://blog.selfshadow.com/publications/s2013-shading-course/#course_content
"vec3 brdf_importance_sample(vec2 Xi, float a) {"
"float phi = 2.0 * pi * Xi.x;"
"float cosT = sqrt((1.0 - Xi.y) / (1.0 + (a * a - 1.0) * Xi.y));"
"float sinT = sqrt(1.0 - cosT * cosT);"
"return vec3(sinT * cos(phi), sinT * sin(phi), cosT);"
"}";
}
}
}
<|endoftext|>
|
<commit_before>#include "Plater/Plate2D.hpp"
// libslic3r includes
#include "Geometry.hpp"
#include "Log.hpp"
// wx includes
#include <wx/colour.h>
#include <wx/dcbuffer.h>
namespace Slic3r { namespace GUI {
Plate2D::Plate2D(wxWindow* parent, const wxSize& size, std::vector<Plater2DObject>& _objects, std::shared_ptr<Model> _model, std::shared_ptr<Config> _config, std::shared_ptr<Settings> _settings) :
wxPanel(parent, wxID_ANY, wxDefaultPosition, size, wxTAB_TRAVERSAL), objects(_objects), model(_model), config(_config), settings(_settings)
{
this->Bind(wxEVT_PAINT, [=](wxPaintEvent &e) { this->repaint(e); });
this->Bind(wxEVT_MOTION, [=](wxMouseEvent &e) { this->mouse_drag(e); });
if (user_drawn_background) {
this->Bind(wxEVT_ERASE_BACKGROUND, [=](wxEraseEvent& e){ });
}
this->Bind(wxEVT_SIZE, [=](wxSizeEvent &e) { this->update_bed_size(); this->Refresh(); });
// Bind the varying mouse events
// Set the brushes
set_colors();
}
void Plate2D::repaint(wxPaintEvent& e) {
// Need focus to catch keyboard events.
this->SetFocus();
auto dc {new wxAutoBufferedPaintDC(this)};
const auto& size = this->GetSize();
if (this->user_drawn_background) {
// On all systems the AutoBufferedPaintDC() achieves double buffering.
// On MacOS the background is erased, on Windows the background is not erased
// and on Linux/GTK the background is erased to gray color.
// Fill DC with the background on Windows & Linux/GTK.
const auto& brush_background {wxBrush(this->settings->color->BACKGROUND255(), wxBRUSHSTYLE_SOLID)};
const auto& pen_background {wxPen(this->settings->color->BACKGROUND255(), 1, wxPENSTYLE_SOLID)};
dc->SetPen(pen_background);
dc->SetBrush(brush_background);
const auto& rect {this->GetUpdateRegion().GetBox()};
dc->DrawRectangle(rect.GetLeft(), rect.GetTop(), rect.GetWidth(), rect.GetHeight());
}
// Draw bed
{
dc->SetPen(this->print_center_pen);
dc->SetBrush(this->bed_brush);
dc->DrawPolygon(scaled_points_to_pixel(this->bed_polygon, true), 0, 0);
}
}
void Plate2D::mouse_drag(wxMouseEvent& e) {
if (e.Dragging()) {
Slic3r::Log::info(LogChannel, L"Mouse dragging");
} else {
Slic3r::Log::info(LogChannel, L"Mouse moving");
}
}
void Plate2D::set_colors() {
this->SetBackgroundColour(settings->color->BACKGROUND255());
this->objects_brush.SetColour(settings->color->BED_OBJECTS());
this->objects_brush.SetStyle(wxBRUSHSTYLE_SOLID);
this->instance_brush.SetColour(settings->color->BED_INSTANCE());
this->instance_brush.SetStyle(wxBRUSHSTYLE_SOLID);
this->selected_brush.SetColour(settings->color->BED_SELECTED());
this->selected_brush.SetStyle(wxBRUSHSTYLE_SOLID);
this->dragged_brush.SetColour(settings->color->BED_DRAGGED());
this->dragged_brush.SetStyle(wxBRUSHSTYLE_SOLID);
this->bed_brush.SetColour(settings->color->BED_COLOR());
this->bed_brush.SetStyle(wxBRUSHSTYLE_SOLID);
this->transparent_brush.SetColour(wxColour(0,0,0));
this->transparent_brush.SetStyle(wxBRUSHSTYLE_TRANSPARENT);
this->grid_pen.SetColour(settings->color->BED_GRID());
this->grid_pen.SetWidth(1);
this->grid_pen.SetStyle(wxPENSTYLE_SOLID);
this->print_center_pen.SetColour(settings->color->BED_CENTER());
this->print_center_pen.SetWidth(1);
this->print_center_pen.SetStyle(wxPENSTYLE_SOLID);
this->clearance_pen.SetColour(settings->color->BED_CLEARANCE());
this->clearance_pen.SetWidth(1);
this->clearance_pen.SetStyle(wxPENSTYLE_SOLID);
this->skirt_pen.SetColour(settings->color->BED_SKIRT());
this->skirt_pen.SetWidth(1);
this->skirt_pen.SetStyle(wxPENSTYLE_SOLID);
this->dark_pen.SetColour(settings->color->BED_DARK());
this->dark_pen.SetWidth(1);
this->dark_pen.SetStyle(wxPENSTYLE_SOLID);
}
void Plate2D::nudge_key(wxKeyEvent& e) {
const auto key = e.GetKeyCode();
switch( key ) {
case WXK_LEFT:
this->nudge(MoveDirection::Left);
case WXK_RIGHT:
this->nudge(MoveDirection::Right);
case WXK_DOWN:
this->nudge(MoveDirection::Down);
case WXK_UP:
this->nudge(MoveDirection::Up);
default:
break; // do nothing
}
}
void Plate2D::nudge(MoveDirection dir) {
if (this->selected_instance < this->objects.size()) {
auto i = 0U;
for (auto& obj : this->objects) {
if (obj.selected()) {
if (obj.selected_instance != -1) {
}
}
i++;
}
}
if (selected_instance >= this->objects.size()) {
Slic3r::Log::warn(LogChannel, L"Nudge failed because there is no selected instance.");
return; // Abort
}
}
void Plate2D::update_bed_size() {
const auto& canvas_size {this->GetSize()};
const auto& canvas_w {canvas_size.GetWidth()};
const auto& canvas_h {canvas_size.GetHeight()};
if (canvas_w == 0) return; // Abort early if we haven't drawn canvas yet.
this->bed_polygon = Slic3r::Polygon();
const auto& polygon = bed_polygon;
const auto& bb = bed_polygon.bounding_box();
const auto& size = bb.size();
this->scaling_factor = std::min(static_cast<double>(canvas_w) / unscale(size.x),
static_cast<double>(canvas_h) / unscale(size.y));
assert(this->scaling_factor != 0);
std::vector<wxPoint> Plate2D::scaled_points_to_pixel(const Slic3r::Polygon& poly, bool unscale) {
return this->scaled_points_to_pixel(Polyline(poly), unscale);
}
std::vector<wxPoint> Plate2D::scaled_points_to_pixel(const Slic3r::Polyline& poly, bool unscale) {
std::vector<wxPoint> result;
for (const auto& pt : poly.points) {
const auto tmp {wxPoint(pt.x, pt.y)};
result.push_back( (unscale ? unscaled_point_to_pixel(tmp) : tmp) );
}
return result;
}
} } // Namespace Slic3r::GUI
<commit_msg>Set BackgroundStyle because wxWidgets wants us to.<commit_after>#include "Plater/Plate2D.hpp"
// libslic3r includes
#include "Geometry.hpp"
#include "Log.hpp"
// wx includes
#include <wx/colour.h>
#include <wx/dcbuffer.h>
namespace Slic3r { namespace GUI {
Plate2D::Plate2D(wxWindow* parent, const wxSize& size, std::vector<Plater2DObject>& _objects, std::shared_ptr<Model> _model, std::shared_ptr<Config> _config, std::shared_ptr<Settings> _settings) :
wxPanel(parent, wxID_ANY, wxDefaultPosition, size, wxTAB_TRAVERSAL), objects(_objects), model(_model), config(_config), settings(_settings)
{
this->Bind(wxEVT_PAINT, [=](wxPaintEvent &e) { this->repaint(e); });
this->Bind(wxEVT_MOTION, [=](wxMouseEvent &e) { this->mouse_drag(e); });
if (user_drawn_background) {
this->Bind(wxEVT_ERASE_BACKGROUND, [=](wxEraseEvent& e){ });
}
this->Bind(wxEVT_SIZE, [=](wxSizeEvent &e) { this->update_bed_size(); this->Refresh(); });
// Bind the varying mouse events
// Set the brushes
set_colors();
this->SetBackgroundStyle(wxBG_STYLE_PAINT);
}
void Plate2D::repaint(wxPaintEvent& e) {
// Need focus to catch keyboard events.
this->SetFocus();
auto dc {new wxAutoBufferedPaintDC(this)};
const auto& size = this->GetSize();
if (this->user_drawn_background) {
// On all systems the AutoBufferedPaintDC() achieves double buffering.
// On MacOS the background is erased, on Windows the background is not erased
// and on Linux/GTK the background is erased to gray color.
// Fill DC with the background on Windows & Linux/GTK.
const auto& brush_background {wxBrush(this->settings->color->BACKGROUND255(), wxBRUSHSTYLE_SOLID)};
const auto& pen_background {wxPen(this->settings->color->BACKGROUND255(), 1, wxPENSTYLE_SOLID)};
dc->SetPen(pen_background);
dc->SetBrush(brush_background);
const auto& rect {this->GetUpdateRegion().GetBox()};
dc->DrawRectangle(rect.GetLeft(), rect.GetTop(), rect.GetWidth(), rect.GetHeight());
}
// Draw bed
{
dc->SetPen(this->print_center_pen);
dc->SetBrush(this->bed_brush);
dc->DrawPolygon(scaled_points_to_pixel(this->bed_polygon, true), 0, 0);
}
}
void Plate2D::mouse_drag(wxMouseEvent& e) {
if (e.Dragging()) {
Slic3r::Log::info(LogChannel, L"Mouse dragging");
} else {
Slic3r::Log::info(LogChannel, L"Mouse moving");
}
}
void Plate2D::set_colors() {
this->SetBackgroundColour(settings->color->BACKGROUND255());
this->objects_brush.SetColour(settings->color->BED_OBJECTS());
this->objects_brush.SetStyle(wxBRUSHSTYLE_SOLID);
this->instance_brush.SetColour(settings->color->BED_INSTANCE());
this->instance_brush.SetStyle(wxBRUSHSTYLE_SOLID);
this->selected_brush.SetColour(settings->color->BED_SELECTED());
this->selected_brush.SetStyle(wxBRUSHSTYLE_SOLID);
this->dragged_brush.SetColour(settings->color->BED_DRAGGED());
this->dragged_brush.SetStyle(wxBRUSHSTYLE_SOLID);
this->bed_brush.SetColour(settings->color->BED_COLOR());
this->bed_brush.SetStyle(wxBRUSHSTYLE_SOLID);
this->transparent_brush.SetColour(wxColour(0,0,0));
this->transparent_brush.SetStyle(wxBRUSHSTYLE_TRANSPARENT);
this->grid_pen.SetColour(settings->color->BED_GRID());
this->grid_pen.SetWidth(1);
this->grid_pen.SetStyle(wxPENSTYLE_SOLID);
this->print_center_pen.SetColour(settings->color->BED_CENTER());
this->print_center_pen.SetWidth(1);
this->print_center_pen.SetStyle(wxPENSTYLE_SOLID);
this->clearance_pen.SetColour(settings->color->BED_CLEARANCE());
this->clearance_pen.SetWidth(1);
this->clearance_pen.SetStyle(wxPENSTYLE_SOLID);
this->skirt_pen.SetColour(settings->color->BED_SKIRT());
this->skirt_pen.SetWidth(1);
this->skirt_pen.SetStyle(wxPENSTYLE_SOLID);
this->dark_pen.SetColour(settings->color->BED_DARK());
this->dark_pen.SetWidth(1);
this->dark_pen.SetStyle(wxPENSTYLE_SOLID);
}
void Plate2D::nudge_key(wxKeyEvent& e) {
const auto key = e.GetKeyCode();
switch( key ) {
case WXK_LEFT:
this->nudge(MoveDirection::Left);
case WXK_RIGHT:
this->nudge(MoveDirection::Right);
case WXK_DOWN:
this->nudge(MoveDirection::Down);
case WXK_UP:
this->nudge(MoveDirection::Up);
default:
break; // do nothing
}
}
void Plate2D::nudge(MoveDirection dir) {
if (this->selected_instance < this->objects.size()) {
auto i = 0U;
for (auto& obj : this->objects) {
if (obj.selected()) {
if (obj.selected_instance != -1) {
}
}
i++;
}
}
if (selected_instance >= this->objects.size()) {
Slic3r::Log::warn(LogChannel, L"Nudge failed because there is no selected instance.");
return; // Abort
}
}
void Plate2D::update_bed_size() {
const auto& canvas_size {this->GetSize()};
const auto& canvas_w {canvas_size.GetWidth()};
const auto& canvas_h {canvas_size.GetHeight()};
if (canvas_w == 0) return; // Abort early if we haven't drawn canvas yet.
this->bed_polygon = Slic3r::Polygon();
const auto& polygon = bed_polygon;
const auto& bb = bed_polygon.bounding_box();
const auto& size = bb.size();
this->scaling_factor = std::min(static_cast<double>(canvas_w) / unscale(size.x),
static_cast<double>(canvas_h) / unscale(size.y));
assert(this->scaling_factor != 0);
std::vector<wxPoint> Plate2D::scaled_points_to_pixel(const Slic3r::Polygon& poly, bool unscale) {
return this->scaled_points_to_pixel(Polyline(poly), unscale);
}
std::vector<wxPoint> Plate2D::scaled_points_to_pixel(const Slic3r::Polyline& poly, bool unscale) {
std::vector<wxPoint> result;
for (const auto& pt : poly.points) {
const auto tmp {wxPoint(pt.x, pt.y)};
result.push_back( (unscale ? unscaled_point_to_pixel(tmp) : tmp) );
}
return result;
}
} } // Namespace Slic3r::GUI
<|endoftext|>
|
<commit_before>#ifndef INC_MUSPELHEIM_HPP
#define INC_MUSPELHEIM_HPP
#include <iostream>
#include <functional>
#include <random>
#include <vector>
#include <boost/gil/extension/io/png_dynamic_io.hpp>
#include <boost/gil/image.hpp>
#include <boost/gil/typedefs.hpp>
// Make sure that multiplying points by floating-point values works correctly.
namespace boost { namespace gil {
template <typename T, typename U>
point2<T> operator *(const point2<T> &p, U t) {
return point2<T>(p.x*t, p.y*t);
}
template <typename T, typename U>
point2<U> operator *(T t, const point2<U> &p) {
return point2<U>(t*p.x, t*p.y);
}
} }
namespace muspelheim {
template<typename Pixel, typename T = double>
class flame_function {
public:
using point_type = boost::gil::point2<T>;
using pixel_type = Pixel;
using function_type = std::function<
point_type(const point_type &, const affine_transform<T> &)
>;
using value_type = std::pair<function_type, T>;
flame_function(const function_type &f,
const affine_transform<T> &transform,
const Pixel &color,
const affine_transform<T> &post = {1, 0, 0, 0, 1, 0})
: f_({{f, 1}}), transform_(transform), color_(color), post_(post) {}
flame_function(const std::initializer_list<value_type> &f,
const affine_transform<T> &transform,
const Pixel &color,
const affine_transform<T> &post = {1, 0, 0, 0, 1, 0})
: f_(f), transform_(transform), color_(color), post_(post) {}
inline point_type operator ()(const point_type &p) const {
point_type value = {0, 0};
const auto &transformed = transform_(p);
for(const auto &i : f_)
value += i.second * i.first(transformed, transform_);
return post_(value);
}
inline pixel_type color() const {
return color_;
}
private:
std::vector<value_type> f_;
affine_transform<T> transform_;
Pixel color_;
affine_transform<T> post_;
};
template<typename Pixel, typename T = double>
using flame_function_set = std::vector<flame_function<Pixel, T>>;
template<typename ChannelValue, typename Layout>
boost::gil::pixel<ChannelValue, Layout>
blend(const boost::gil::pixel<ChannelValue, Layout> &a,
const boost::gil::pixel<ChannelValue, Layout> &b, double ratio) {
boost::gil::pixel<ChannelValue, Layout> p;
constexpr size_t channels = boost::mpl::size<
typename Layout::color_space_t
>::value;
for(int i = 0; i < channels; i++)
p[i] = a[i] * ratio + b[i] * (1 - ratio);
return p;
}
template<typename View, typename Pixel, typename T>
void chaos_game(const View &dst, const flame_function_set<Pixel, T> &funcs,
size_t num_iterations = 10000000) {
using namespace boost::gil;
using biunit_pt = point2<T>;
using image_pt = point2<ptrdiff_t>;
using color_image_t = image<Pixel, false>;
std::mt19937 engine;
std::uniform_int_distribution<size_t> random_func(0, funcs.size() - 1);
std::uniform_real_distribution<T> random_biunit(-1, 1);
gray32_image_t alpha_img(dst.dimensions(), gray32_pixel_t(0), 0);
gray32_image_t::view_t alpha = view(alpha_img);
bits32 max_alpha = 0;
color_image_t color_img(dst.dimensions(), Pixel(0), 0);
typename color_image_t::view_t color = view(color_img);
biunit_pt point(random_biunit(engine), random_biunit(engine));
for(size_t i = 0; i < 20; i++)
point = funcs[random_func(engine)](point);
for(size_t i = 0; i < num_iterations; i++) {
auto &f = funcs[random_func(engine)];
point = f(point);
if(point.x >= -1 && point.x < 1 && point.y >= -1 && point.y < 1) {
image_pt pt(
static_cast<ptrdiff_t>((point.x + 1) / 2 * alpha.width()),
static_cast<ptrdiff_t>((point.y + 1) / 2 * alpha.height())
);
if(!alpha(pt)[0])
color(pt) = f.color();
else
color(pt) = blend(color(pt), f.color(), 0.9);
alpha(pt)[0]++;
if(alpha(pt)[0] > max_alpha)
max_alpha = alpha(pt)[0];
}
}
auto logmax = std::log(static_cast<T>(max_alpha));
for(size_t x = 0; x < dst.width(); x++) {
for(size_t y = 0; y < dst.height(); y++) {
auto a = std::log(static_cast<T>(alpha(x, y)[0])) / logmax;
auto &c = color(x, y);
dst(x, y) = typename View::value_type(c[0] * a, c[1] * a, c[2] * a);
}
}
}
} // namespace muspelheim
#endif
<commit_msg>Simplify flame_function's constructors<commit_after>#ifndef INC_MUSPELHEIM_HPP
#define INC_MUSPELHEIM_HPP
#include <iostream>
#include <functional>
#include <random>
#include <vector>
#include <boost/gil/extension/io/png_dynamic_io.hpp>
#include <boost/gil/image.hpp>
#include <boost/gil/typedefs.hpp>
// Make sure that multiplying points by floating-point values works correctly.
namespace boost { namespace gil {
template <typename T, typename U>
point2<T> operator *(const point2<T> &p, U t) {
return point2<T>(p.x*t, p.y*t);
}
template <typename T, typename U>
point2<U> operator *(T t, const point2<U> &p) {
return point2<U>(t*p.x, t*p.y);
}
} }
namespace muspelheim {
template<typename Pixel, typename T = double>
class flame_function {
public:
using point_type = boost::gil::point2<T>;
using pixel_type = Pixel;
using function_type = std::function<
point_type(const point_type &, const affine_transform<T> &)
>;
using value_type = std::pair<function_type, T>;
flame_function(const function_type &f,
const affine_transform<T> &transform,
const Pixel &color,
const affine_transform<T> &post = {1, 0, 0, 0, 1, 0})
: flame_function({{f, 1}}, transform, color, post) {}
flame_function(const std::initializer_list<value_type> &f,
const affine_transform<T> &transform,
const Pixel &color,
const affine_transform<T> &post = {1, 0, 0, 0, 1, 0})
: f_(f), transform_(transform), color_(color), post_(post) {}
inline point_type operator ()(const point_type &p) const {
point_type value = {0, 0};
const auto &transformed = transform_(p);
for(const auto &i : f_)
value += i.second * i.first(transformed, transform_);
return post_(value);
}
inline pixel_type color() const {
return color_;
}
private:
std::vector<value_type> f_;
affine_transform<T> transform_;
Pixel color_;
affine_transform<T> post_;
};
template<typename Pixel, typename T = double>
using flame_function_set = std::vector<flame_function<Pixel, T>>;
template<typename ChannelValue, typename Layout>
boost::gil::pixel<ChannelValue, Layout>
blend(const boost::gil::pixel<ChannelValue, Layout> &a,
const boost::gil::pixel<ChannelValue, Layout> &b, double ratio) {
boost::gil::pixel<ChannelValue, Layout> p;
constexpr size_t channels = boost::mpl::size<
typename Layout::color_space_t
>::value;
for(int i = 0; i < channels; i++)
p[i] = a[i] * ratio + b[i] * (1 - ratio);
return p;
}
template<typename View, typename Pixel, typename T>
void chaos_game(const View &dst, const flame_function_set<Pixel, T> &funcs,
size_t num_iterations = 10000000) {
using namespace boost::gil;
using biunit_pt = point2<T>;
using image_pt = point2<ptrdiff_t>;
using color_image_t = image<Pixel, false>;
std::mt19937 engine;
std::uniform_int_distribution<size_t> random_func(0, funcs.size() - 1);
std::uniform_real_distribution<T> random_biunit(-1, 1);
gray32_image_t alpha_img(dst.dimensions(), gray32_pixel_t(0), 0);
gray32_image_t::view_t alpha = view(alpha_img);
bits32 max_alpha = 0;
color_image_t color_img(dst.dimensions(), Pixel(0), 0);
typename color_image_t::view_t color = view(color_img);
biunit_pt point(random_biunit(engine), random_biunit(engine));
for(size_t i = 0; i < 20; i++)
point = funcs[random_func(engine)](point);
for(size_t i = 0; i < num_iterations; i++) {
auto &f = funcs[random_func(engine)];
point = f(point);
if(point.x >= -1 && point.x < 1 && point.y >= -1 && point.y < 1) {
image_pt pt(
static_cast<ptrdiff_t>((point.x + 1) / 2 * alpha.width()),
static_cast<ptrdiff_t>((point.y + 1) / 2 * alpha.height())
);
if(!alpha(pt)[0])
color(pt) = f.color();
else
color(pt) = blend(color(pt), f.color(), 0.9);
alpha(pt)[0]++;
if(alpha(pt)[0] > max_alpha)
max_alpha = alpha(pt)[0];
}
}
auto logmax = std::log(static_cast<T>(max_alpha));
for(size_t x = 0; x < dst.width(); x++) {
for(size_t y = 0; y < dst.height(); y++) {
auto a = std::log(static_cast<T>(alpha(x, y)[0])) / logmax;
auto &c = color(x, y);
dst(x, y) = typename View::value_type(c[0] * a, c[1] * a, c[2] * a);
}
}
}
} // namespace muspelheim
#endif
<|endoftext|>
|
<commit_before>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/lite/delegates/gpu/cl/kernels/mean_stddev_normalization.h"
#include <string>
#include "tensorflow/lite/delegates/gpu/cl/cl_program.h"
#include "tensorflow/lite/delegates/gpu/cl/device_info.h"
#include "tensorflow/lite/delegates/gpu/cl/kernels/util.h"
#include "tensorflow/lite/delegates/gpu/cl/kernels/work_group_picking.h"
#include "tensorflow/lite/delegates/gpu/cl/precision.h"
namespace tflite {
namespace gpu {
namespace cl {
namespace {
std::string GetVectorReduceCode() {
return R"(static inline float reduce_vector(float4 v) {
return dot(v, (float4)(1.0f));
})";
}
std::string GetReduceCode() {
// If it is supported, use the built-in work_group_reduce_add function.
// Otherwise, implement a reduction using __local memory. Note this only works
// with power-of-two work group sizes.
return R"(
#if (__OPENCL_C_VERSION__ >= 200) && (__OPENCL_C_VERSION__ < 300) && \
!defined(__opencl_c_work_group_collective_functions)
#define __opencl_c_work_group_collective_functions 1
#endif
#ifdef __opencl_c_work_group_collective_functions
#define local_reduce(input, tmp) work_group_reduce_add(input)
#else // !defined(__opencl_c_work_group_collective_functions)
static inline float local_reduce(float input, __local float* tmp) {
const int local_id = get_local_id(0);
tmp[local_id] = input;
barrier(CLK_LOCAL_MEM_FENCE);
int reduction_size = get_local_size(0) / 2;
while (reduction_size > 0) {
if (local_id < reduction_size) {
tmp[local_id] += tmp[local_id + reduction_size];
}
barrier(CLK_LOCAL_MEM_FENCE);
reduction_size /= 2;
}
return tmp[0];
}
#endif // defined(__opencl_c_work_group_collective_functions)
)";
}
std::string GetFilterCode() {
return R"(
static inline float4 filter_outside_tensor(float4 x, int num_channels, int slice) {
return select(x, (float4)(0.0f), slice * 4 + (int4)(0, 1, 2, 3) >= num_channels);
}
)";
}
} // namespace
MeanStdDevNormalization::MeanStdDevNormalization(const OperationDef& definition,
const DeviceInfo& device_info)
: GPUOperation(definition) {
// The kernel code does not inherently need a fixed size, but in order to not
// hardcode the __local array's size for the reductions, we would need to pass
// that size to the kernel at runtime, and that is currently not supported.
// For now, fix workgroup size to 128 threads.
work_group_size_.x = 128;
work_group_size_.y = 1; // Required
work_group_size_.z = 1; // Required
code_ = GetNormalizationCode();
if (device_info.cl_version >= OpenCLVersion::CL_3_0) {
compiler_options_.push_back(CompilerOptions::CL_3_0);
} else if (device_info.cl_version >= OpenCLVersion::CL_2_0) {
compiler_options_.push_back(CompilerOptions::CL_2_0);
}
}
std::string MeanStdDevNormalization::GetNormalizationCode() {
AddSrcTensor("src_tensor", definition_.src_tensors[0]);
AddDstTensor("dst_tensor", definition_.dst_tensors[0]);
std::string c = GetCommonDefines(definition_.precision);
c += GetVectorReduceCode();
c += GetReduceCode();
c += GetFilterCode();
c += "__attribute__((reqd_work_group_size(" +
std::to_string(work_group_size_.x) + ", 1, 1)))\n";
c += R"(__kernel void main_function($0) {
#ifndef __opencl_c_work_group_collective_functions
__local float tmp[)" +
std::to_string(work_group_size_.x) + R"(];
#endif
const int B = get_global_id(1);
if (get_global_id(2) > 0) { return; }
if (B >= args.src_tensor.Batch()) { return; }
// Calculate the total sum of the input tensor.
// First, get a local sum of input[local_id_x + N*local_size_x] for all N.
float4 private_sum4 = (float4)(0.0f);
for (int S = get_local_id(0); S < args.src_tensor.Slices(); S += get_local_size(0)) {
const float4 t = args.src_tensor.Read<float>(0, 0, S, B);
private_sum4 += filter_outside_tensor(t, args.src_tensor.Channels(), S);
}
// Reduce the vector to a single float and do a workgroup reduce.
const float private_sum = reduce_vector(private_sum4);
const float sum = local_reduce(private_sum, tmp);
// Calculate the mean
const float mean = sum / args.src_tensor.Channels();
// Calculate the squared sum of the difference from the mean.
float4 private_sum_diff_sq4 = (float4)(0.0f);
for (int S = get_local_id(0); S < args.src_tensor.Slices(); S += get_local_size(0)) {
const float4 t = args.src_tensor.Read<float>(0, 0, S, B);
const float4 diff = filter_outside_tensor(t - mean, args.src_tensor.Channels(), S);
// sum_diff_sq += diff²
private_sum_diff_sq4 = mad(diff, diff, private_sum_diff_sq4);
}
// Reduce
const float private_sum_diff_sq = reduce_vector(private_sum_diff_sq4);
const float sum_diff_sq = local_reduce(private_sum_diff_sq, tmp);
// Calculate 1/stddev (with the 'regulazing constant' as in tensor_utils.cc)
const float variance = sum_diff_sq / args.src_tensor.Channels();
const float stddev_inv = rsqrt(variance + 1.0e-8f);
// Calculate (t-mean)/stddev for each element
for (int S = get_local_id(0); S < args.src_tensor.Slices(); S += get_local_size(0)) {
const float4 t = args.src_tensor.Read<float>(0, 0, S, B);
FLT4 result = TO_FLT4((t - mean) * stddev_inv);
args.dst_tensor.Write(result, 0, 0, S, B);
}
})";
return c;
}
int3 MeanStdDevNormalization::GetGridSize() const {
// To avoid dealing with global reductions, we restrict the grid size to the
// work group size in the first dimension.
const int grid_x = work_group_size_.x;
const int grid_y = src_[0]->Batch();
const int grid_z = 1;
return int3(grid_x, grid_y, grid_z);
}
MeanStdDevNormalization CreateMeanStdDevNormalization(
const OperationDef& definition, const DeviceInfo& device_info) {
return MeanStdDevNormalization(definition, device_info);
}
} // namespace cl
} // namespace gpu
} // namespace tflite
<commit_msg>Use native_rsqrt in MeanStdDevNormalization. It seems to have enough precision on tested hardware.<commit_after>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/lite/delegates/gpu/cl/kernels/mean_stddev_normalization.h"
#include <string>
#include "tensorflow/lite/delegates/gpu/cl/cl_program.h"
#include "tensorflow/lite/delegates/gpu/cl/device_info.h"
#include "tensorflow/lite/delegates/gpu/cl/kernels/util.h"
#include "tensorflow/lite/delegates/gpu/cl/kernels/work_group_picking.h"
#include "tensorflow/lite/delegates/gpu/cl/precision.h"
namespace tflite {
namespace gpu {
namespace cl {
namespace {
std::string GetVectorReduceCode() {
return R"(static inline float reduce_vector(float4 v) {
return dot(v, (float4)(1.0f));
})";
}
std::string GetReduceCode() {
// If it is supported, use the built-in work_group_reduce_add function.
// Otherwise, implement a reduction using __local memory. Note this only works
// with power-of-two work group sizes.
return R"(
#if (__OPENCL_C_VERSION__ >= 200) && (__OPENCL_C_VERSION__ < 300) && \
!defined(__opencl_c_work_group_collective_functions)
#define __opencl_c_work_group_collective_functions 1
#endif
#ifdef __opencl_c_work_group_collective_functions
#define local_reduce(input, tmp) work_group_reduce_add(input)
#else // !defined(__opencl_c_work_group_collective_functions)
static inline float local_reduce(float input, __local float* tmp) {
const int local_id = get_local_id(0);
tmp[local_id] = input;
barrier(CLK_LOCAL_MEM_FENCE);
int reduction_size = get_local_size(0) / 2;
while (reduction_size > 0) {
if (local_id < reduction_size) {
tmp[local_id] += tmp[local_id + reduction_size];
}
barrier(CLK_LOCAL_MEM_FENCE);
reduction_size /= 2;
}
return tmp[0];
}
#endif // defined(__opencl_c_work_group_collective_functions)
)";
}
std::string GetFilterCode() {
return R"(
static inline float4 filter_outside_tensor(float4 x, int num_channels, int slice) {
return select(x, (float4)(0.0f), slice * 4 + (int4)(0, 1, 2, 3) >= num_channels);
}
)";
}
} // namespace
MeanStdDevNormalization::MeanStdDevNormalization(const OperationDef& definition,
const DeviceInfo& device_info)
: GPUOperation(definition) {
// The kernel code does not inherently need a fixed size, but in order to not
// hardcode the __local array's size for the reductions, we would need to pass
// that size to the kernel at runtime, and that is currently not supported.
// For now, fix workgroup size to 128 threads.
work_group_size_.x = 128;
work_group_size_.y = 1; // Required
work_group_size_.z = 1; // Required
code_ = GetNormalizationCode();
if (device_info.cl_version >= OpenCLVersion::CL_3_0) {
compiler_options_.push_back(CompilerOptions::CL_3_0);
} else if (device_info.cl_version >= OpenCLVersion::CL_2_0) {
compiler_options_.push_back(CompilerOptions::CL_2_0);
}
}
std::string MeanStdDevNormalization::GetNormalizationCode() {
AddSrcTensor("src_tensor", definition_.src_tensors[0]);
AddDstTensor("dst_tensor", definition_.dst_tensors[0]);
std::string c = GetCommonDefines(definition_.precision);
c += GetVectorReduceCode();
c += GetReduceCode();
c += GetFilterCode();
c += "__attribute__((reqd_work_group_size(" +
std::to_string(work_group_size_.x) + ", 1, 1)))\n";
c += R"(__kernel void main_function($0) {
#ifndef __opencl_c_work_group_collective_functions
__local float tmp[)" +
std::to_string(work_group_size_.x) + R"(];
#endif
const int B = get_global_id(1);
if (get_global_id(2) > 0) { return; }
if (B >= args.src_tensor.Batch()) { return; }
// Calculate the total sum of the input tensor.
// First, get a local sum of input[local_id_x + N*local_size_x] for all N.
float4 private_sum4 = (float4)(0.0f);
for (int S = get_local_id(0); S < args.src_tensor.Slices(); S += get_local_size(0)) {
const float4 t = args.src_tensor.Read<float>(0, 0, S, B);
private_sum4 += filter_outside_tensor(t, args.src_tensor.Channels(), S);
}
// Reduce the vector to a single float and do a workgroup reduce.
const float private_sum = reduce_vector(private_sum4);
const float sum = local_reduce(private_sum, tmp);
// Calculate the mean
const float mean = sum / args.src_tensor.Channels();
// Calculate the squared sum of the difference from the mean.
float4 private_sum_diff_sq4 = (float4)(0.0f);
for (int S = get_local_id(0); S < args.src_tensor.Slices(); S += get_local_size(0)) {
const float4 t = args.src_tensor.Read<float>(0, 0, S, B);
const float4 diff = filter_outside_tensor(t - mean, args.src_tensor.Channels(), S);
// sum_diff_sq += diff²
private_sum_diff_sq4 = mad(diff, diff, private_sum_diff_sq4);
}
// Reduce
const float private_sum_diff_sq = reduce_vector(private_sum_diff_sq4);
const float sum_diff_sq = local_reduce(private_sum_diff_sq, tmp);
// Calculate 1/stddev (with the 'regulazing constant' as in tensor_utils.cc)
const float variance = sum_diff_sq / args.src_tensor.Channels();
const float stddev_inv = native_rsqrt(variance + 1.0e-8f);
// Calculate (t-mean)/stddev for each element
for (int S = get_local_id(0); S < args.src_tensor.Slices(); S += get_local_size(0)) {
const float4 t = args.src_tensor.Read<float>(0, 0, S, B);
FLT4 result = TO_FLT4((t - mean) * stddev_inv);
args.dst_tensor.Write(result, 0, 0, S, B);
}
})";
return c;
}
int3 MeanStdDevNormalization::GetGridSize() const {
// To avoid dealing with global reductions, we restrict the grid size to the
// work group size in the first dimension.
const int grid_x = work_group_size_.x;
const int grid_y = src_[0]->Batch();
const int grid_z = 1;
return int3(grid_x, grid_y, grid_z);
}
MeanStdDevNormalization CreateMeanStdDevNormalization(
const OperationDef& definition, const DeviceInfo& device_info) {
return MeanStdDevNormalization(definition, device_info);
}
} // namespace cl
} // namespace gpu
} // namespace tflite
<|endoftext|>
|
<commit_before>/* Copyright (c) 2010-2019, Delft University of Technology
* All rigths reserved
*
* This file is part of the Tudat. Redistribution and use in source and
* binary forms, with or without modification, are permitted exclusively
* under the terms of the Modified BSD license. You should have received
* a copy of the license with this file. If not, please or visit:
* http://tudat.tudelft.nl/LICENSE.
*
*/
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN
#include <boost/test/unit_test.hpp>
#include <Eigen/Core>
#include <vector>
#include "tudat/basics/testMacros.h"
#include "tudat/basics/utilities.h"
#include "tudat/io/matrixTextFileReader.h"
#include "tudat/math/interpolators/createInterpolator.h"
#include "tudat/io/basicInputOutput.h"
#include "tudat/interface/spice/spiceInterface.h"
namespace tudat
{
namespace unit_tests
{
using namespace interpolators;
BOOST_AUTO_TEST_SUITE( test_interpolator_vector_conversion )
BOOST_AUTO_TEST_CASE( testInterpolatorVectorConversion )
{
spice_interface::loadStandardSpiceKernels( );
std::map< double, Eigen::Vector6d > vector6dInterpolatorInput;
std::map< double, Eigen::VectorXd > vectorXdInterpolatorInput;
std::map< double, Eigen::MatrixXd > matrixXdInterpolatorInput;
for( int i = 0; i < 30; i++ )
{
double time = static_cast< double >( i ) * 86400.0;
vector6dInterpolatorInput[ time ] = spice_interface::getBodyCartesianStateAtEpoch(
"Moon", "Earth", "J2000", "None", time );
vectorXdInterpolatorInput[ time ] = vector6dInterpolatorInput[ time ];
matrixXdInterpolatorInput[ time ] = vector6dInterpolatorInput[ time ];
}
std::vector< double > interpolationTimes = { 1.0, 5.0 * 86400.0, 12.43 * 86400.0 };
for( int i = 0; i < 4; i++ )
{
std::shared_ptr< InterpolatorSettings > interpolatorSettings;
switch( i )
{
case 0:
interpolatorSettings =
std::make_shared< InterpolatorSettings >( linear_interpolator );
break;
case 1:
interpolatorSettings =
std::make_shared< InterpolatorSettings >( cubic_spline_interpolator );
break;
case 2:
interpolatorSettings =
std::make_shared< LagrangeInterpolatorSettings >( 8 );
break;
// case 3:
// interpolatorSettings =
// std::make_shared< InterpolatorSettings >( hermite_spline_interpolator );
// break;
case 3:
interpolatorSettings =
std::make_shared< InterpolatorSettings >( piecewise_constant_interpolator );
break;
}
std::shared_ptr< OneDimensionalInterpolator< double, Eigen::Vector6d > > direct6dInterpolator =
createOneDimensionalInterpolator( vector6dInterpolatorInput, interpolatorSettings );
std::shared_ptr< OneDimensionalInterpolator< double, Eigen::VectorXd > > directXdInterpolator =
createOneDimensionalInterpolator( vectorXdInterpolatorInput, interpolatorSettings );
std::shared_ptr< OneDimensionalInterpolator< double, Eigen::MatrixXd > > directXdMatrixInterpolator =
createOneDimensionalInterpolator( matrixXdInterpolatorInput, interpolatorSettings );
std::shared_ptr< OneDimensionalInterpolator< double, Eigen::Vector6d > > converted6dInterpolator =
convertBetweenStaticDynamicEigenTypeInterpolators< double, double, -1, 1, 6, 1 >( directXdInterpolator );
std::shared_ptr< OneDimensionalInterpolator< double, Eigen::Vector6d > > converted6dInterpolator2 =
convertBetweenStaticDynamicEigenTypeInterpolators< double, double, -1, -1, 6, 1 >( directXdMatrixInterpolator );
std::shared_ptr< OneDimensionalInterpolator< double, Eigen::VectorXd > > convertedXdInterpolator =
convertBetweenStaticDynamicEigenTypeInterpolators< double, double, 6, 1, -1, 1 >( direct6dInterpolator );
std::shared_ptr< OneDimensionalInterpolator< double, Eigen::VectorXd > > convertedXdInterpolator2 =
convertBetweenStaticDynamicEigenTypeInterpolators< double, double, -1, -1, -1, 1 >( directXdMatrixInterpolator );
std::shared_ptr< OneDimensionalInterpolator< double, Eigen::MatrixXd > > convertedXdMatrixInterpolator =
convertBetweenStaticDynamicEigenTypeInterpolators< double, double, 6, 1, -1, -1 >( direct6dInterpolator );
std::shared_ptr< OneDimensionalInterpolator< double, Eigen::MatrixXd > > convertedXdMatrixInterpolator2 =
convertBetweenStaticDynamicEigenTypeInterpolators< double, double, -1, 1, -1, -1 >( directXdInterpolator );
for( unsigned int j = 0; j < interpolationTimes.size( ); j++ )
{
std::vector< Eigen::MatrixXd > testMatrices;
testMatrices.push_back( direct6dInterpolator->interpolate( interpolationTimes.at( j ) ) );
testMatrices.push_back( directXdInterpolator->interpolate( interpolationTimes.at( j ) ) );
testMatrices.push_back( directXdMatrixInterpolator->interpolate( interpolationTimes.at( j ) ) );
testMatrices.push_back( converted6dInterpolator->interpolate( interpolationTimes.at( j ) ) );
testMatrices.push_back( converted6dInterpolator2->interpolate( interpolationTimes.at( j ) ) );
testMatrices.push_back( convertedXdInterpolator->interpolate( interpolationTimes.at( j ) ) );
testMatrices.push_back( convertedXdInterpolator2->interpolate( interpolationTimes.at( j ) ) );
testMatrices.push_back( convertedXdMatrixInterpolator->interpolate( interpolationTimes.at( j ) ) );
testMatrices.push_back( convertedXdMatrixInterpolator2->interpolate( interpolationTimes.at( j ) ) );
for( unsigned int k = 1; k < testMatrices.size( ); k++ )
{
TUDAT_CHECK_MATRIX_CLOSE_FRACTION(
( testMatrices.at( 0 ) ), ( testMatrices.at( k ) ), std::numeric_limits< double >::epsilon( ) );
}
}
}
}
BOOST_AUTO_TEST_SUITE_END( )
} // namespace unit_tests
} // namespace tudat
<commit_msg>Finalized tests of interpolator eigen type conversion<commit_after>/* Copyright (c) 2010-2019, Delft University of Technology
* All rigths reserved
*
* This file is part of the Tudat. Redistribution and use in source and
* binary forms, with or without modification, are permitted exclusively
* under the terms of the Modified BSD license. You should have received
* a copy of the license with this file. If not, please or visit:
* http://tudat.tudelft.nl/LICENSE.
*
*/
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN
#include <boost/test/unit_test.hpp>
#include <Eigen/Core>
#include <vector>
#include "tudat/math/basic/numericalDerivative.h"
#include "tudat/basics/testMacros.h"
#include "tudat/basics/utilities.h"
#include "tudat/io/matrixTextFileReader.h"
#include "tudat/math/interpolators/createInterpolator.h"
#include "tudat/io/basicInputOutput.h"
#include "tudat/interface/spice/spiceInterface.h"
namespace tudat
{
namespace unit_tests
{
template< typename TimeType, typename StateScalarType >
std::vector< Eigen::Matrix< StateScalarType, 6, 1 > > computeSecondOrderCentralDifferenceCartesianStateDerivative(
const std::map< TimeType, Eigen::Matrix< StateScalarType, 6, 1 > >& cartesianStateMap )
{
std::vector< Eigen::Matrix< StateScalarType, 6, 1 > > cartesianStateDerivativeMap;
auto lowerIterator = cartesianStateMap.begin( );
auto centralIterator = cartesianStateMap.begin( );
std::advance( centralIterator, 1 );
auto upperIterator = cartesianStateMap.begin( );
std::advance( upperIterator, 2 );
Eigen::Matrix< StateScalarType, 6, 1 > currentStateDerivative;
while( upperIterator != cartesianStateMap.end( ) )
{
if( lowerIterator == cartesianStateMap.begin( ) )
{
currentStateDerivative.segment( 0, 3 ) = lowerIterator->second.segment( 3, 3 );
currentStateDerivative.segment( 3, 3 ) =
( upperIterator->second.segment( 3, 3 ) - centralIterator->second.segment( 3, 3 ) ) /
( upperIterator->first - centralIterator->first );
cartesianStateDerivativeMap.push_back( currentStateDerivative );
}
currentStateDerivative.segment( 0, 3 ) = centralIterator->second.segment( 3, 3 );
currentStateDerivative.segment( 3, 3 ) =
( upperIterator->second.segment( 3, 3 ) - lowerIterator->second.segment( 3, 3 ) ) /
( upperIterator->first - lowerIterator->first );
cartesianStateDerivativeMap.push_back( currentStateDerivative );
lowerIterator++;
centralIterator++;
upperIterator++;
if( upperIterator == cartesianStateMap.end( ) )
{
currentStateDerivative.segment( 0, 3 ) = upperIterator->second.segment( 3, 3 );
currentStateDerivative.segment( 3, 3 ) =
( centralIterator->second.segment( 3, 3 ) - lowerIterator->second.segment( 3, 3 ) ) /
( centralIterator->first - lowerIterator->first );
cartesianStateDerivativeMap.push_back( currentStateDerivative );
}
}
return cartesianStateDerivativeMap;
}
using namespace interpolators;
BOOST_AUTO_TEST_SUITE( test_interpolator_vector_conversion )
BOOST_AUTO_TEST_CASE( testInterpolatorVectorConversion )
{
spice_interface::loadStandardSpiceKernels( );
std::map< double, Eigen::Vector6d > vector6dInterpolatorInput;
std::map< double, Eigen::VectorXd > vectorXdInterpolatorInput;
std::map< double, Eigen::MatrixXd > matrixXdInterpolatorInput;
for( int i = 0; i < 30; i++ )
{
double time = static_cast< double >( i ) * 86400.0;
vector6dInterpolatorInput[ time ] = spice_interface::getBodyCartesianStateAtEpoch(
"Moon", "Earth", "J2000", "None", time );
vectorXdInterpolatorInput[ time ] = vector6dInterpolatorInput[ time ];
matrixXdInterpolatorInput[ time ] = vector6dInterpolatorInput[ time ];
}
std::vector< Eigen::Vector6d > vector6dDerivativeInput =
computeSecondOrderCentralDifferenceCartesianStateDerivative(
vector6dInterpolatorInput );
std::vector< Eigen::VectorXd > vectorXdDerivativeInput;
std::vector< Eigen::MatrixXd > matrixXdDerivativeInput;
for( unsigned int i = 0; i < vector6dDerivativeInput.size( ); i++ )
{
vectorXdDerivativeInput.push_back( vector6dDerivativeInput.at( i ) );
matrixXdDerivativeInput.push_back( vector6dDerivativeInput.at( i ) );
}
std::vector< double > interpolationTimes = { 1.0, 5.0 * 86400.0, 12.43 * 86400.0 };
for( int i = 0; i < 5; i++ )
{
std::shared_ptr< InterpolatorSettings > interpolatorSettings;
switch( i )
{
case 0:
interpolatorSettings =
std::make_shared< InterpolatorSettings >( linear_interpolator );
break;
case 1:
interpolatorSettings =
std::make_shared< InterpolatorSettings >( cubic_spline_interpolator );
break;
case 2:
interpolatorSettings =
std::make_shared< LagrangeInterpolatorSettings >( 8 );
break;
case 3:
interpolatorSettings =
std::make_shared< InterpolatorSettings >( hermite_spline_interpolator );
break;
case 4:
interpolatorSettings =
std::make_shared< InterpolatorSettings >( piecewise_constant_interpolator );
break;
}
std::shared_ptr< OneDimensionalInterpolator< double, Eigen::Vector6d > > direct6dInterpolator =
createOneDimensionalInterpolator(
vector6dInterpolatorInput, interpolatorSettings,
std::make_pair( IdentityElement::getAdditionIdentity< Eigen::Vector6d >( ),
IdentityElement::getAdditionIdentity< Eigen::Vector6d >( ) ),
vector6dDerivativeInput );
std::shared_ptr< OneDimensionalInterpolator< double, Eigen::VectorXd > > directXdInterpolator =
createOneDimensionalInterpolator(
vectorXdInterpolatorInput, interpolatorSettings,
std::make_pair( IdentityElement::getAdditionIdentity< Eigen::VectorXd >( ),
IdentityElement::getAdditionIdentity< Eigen::VectorXd >( ) ),
vectorXdDerivativeInput );
std::shared_ptr< OneDimensionalInterpolator< double, Eigen::MatrixXd > > directXdMatrixInterpolator =
createOneDimensionalInterpolator(
matrixXdInterpolatorInput, interpolatorSettings,
std::make_pair( IdentityElement::getAdditionIdentity< Eigen::MatrixXd >( ),
IdentityElement::getAdditionIdentity< Eigen::MatrixXd >( ) ),
matrixXdDerivativeInput);
std::shared_ptr< OneDimensionalInterpolator< double, Eigen::Vector6d > > converted6dInterpolator =
convertBetweenStaticDynamicEigenTypeInterpolators< double, double, -1, 1, 6, 1 >( directXdInterpolator );
std::shared_ptr< OneDimensionalInterpolator< double, Eigen::Vector6d > > converted6dInterpolator2 =
convertBetweenStaticDynamicEigenTypeInterpolators< double, double, -1, -1, 6, 1 >( directXdMatrixInterpolator );
std::shared_ptr< OneDimensionalInterpolator< double, Eigen::VectorXd > > convertedXdInterpolator =
convertBetweenStaticDynamicEigenTypeInterpolators< double, double, 6, 1, -1, 1 >( direct6dInterpolator );
std::shared_ptr< OneDimensionalInterpolator< double, Eigen::VectorXd > > convertedXdInterpolator2 =
convertBetweenStaticDynamicEigenTypeInterpolators< double, double, -1, -1, -1, 1 >( directXdMatrixInterpolator );
std::shared_ptr< OneDimensionalInterpolator< double, Eigen::MatrixXd > > convertedXdMatrixInterpolator =
convertBetweenStaticDynamicEigenTypeInterpolators< double, double, 6, 1, -1, -1 >( direct6dInterpolator );
std::shared_ptr< OneDimensionalInterpolator< double, Eigen::MatrixXd > > convertedXdMatrixInterpolator2 =
convertBetweenStaticDynamicEigenTypeInterpolators< double, double, -1, 1, -1, -1 >( directXdInterpolator );
for( unsigned int j = 0; j < interpolationTimes.size( ); j++ )
{
std::vector< Eigen::MatrixXd > testMatrices;
testMatrices.push_back( direct6dInterpolator->interpolate( interpolationTimes.at( j ) ) );
testMatrices.push_back( directXdInterpolator->interpolate( interpolationTimes.at( j ) ) );
testMatrices.push_back( directXdMatrixInterpolator->interpolate( interpolationTimes.at( j ) ) );
testMatrices.push_back( converted6dInterpolator->interpolate( interpolationTimes.at( j ) ) );
testMatrices.push_back( converted6dInterpolator2->interpolate( interpolationTimes.at( j ) ) );
testMatrices.push_back( convertedXdInterpolator->interpolate( interpolationTimes.at( j ) ) );
testMatrices.push_back( convertedXdInterpolator2->interpolate( interpolationTimes.at( j ) ) );
testMatrices.push_back( convertedXdMatrixInterpolator->interpolate( interpolationTimes.at( j ) ) );
testMatrices.push_back( convertedXdMatrixInterpolator2->interpolate( interpolationTimes.at( j ) ) );
for( unsigned int k = 1; k < testMatrices.size( ); k++ )
{
TUDAT_CHECK_MATRIX_CLOSE_FRACTION(
( testMatrices.at( 0 ) ), ( testMatrices.at( k ) ), std::numeric_limits< double >::epsilon( ) );
}
}
}
}
BOOST_AUTO_TEST_SUITE_END( )
} // namespace unit_tests
} // namespace tudat
<|endoftext|>
|
<commit_before>/*
@Copyright Barrett Adair 2015-2017
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
#ifndef BOOST_CLBL_TRTS_REMOVE_MEMBER_CV_HPP
#define BOOST_CLBL_TRTS_REMOVE_MEMBER_CV_HPP
#include <boost/callable_traits/detail/core.hpp>
namespace boost { namespace callable_traits {
//[ remove_member_cv_hpp
/*`
[section:ref_remove_member_cv remove_member_cv]
[heading Header]
``#include <boost/callable_traits/remove_member_cv.hpp>``
[heading Definition]
*/
template<typename T>
using remove_member_cv_t = //see below
//<-
detail::try_but_fail_if_invalid<
typename detail::traits<T>::remove_member_cv,
member_qualifiers_are_illegal_for_this_type>;
namespace detail {
template<typename T, typename = std::false_type>
struct remove_member_cv_impl {};
template<typename T>
struct remove_member_cv_impl <T, typename std::is_same<
remove_member_cv_t<T>, detail::dummy>::type>
{
using type = remove_member_cv_t<T>;
};
}
//->
template<typename T>
struct remove_member_cv : detail::remove_member_cv_impl<T> {};
//<-
}} // namespace boost::callable_traits
//->
/*`
[heading Constraints]
* `T` must be a function type or a member function pointer type
* If `T` is a pointer, it may not be cv/ref qualified
[heading Behavior]
* A substitution failure occurs if the constraints are violated.
* Removes member `const` and/or `volatile` qualifiers from `T`, if present.
[heading Input/Output Examples]
[table
[[`T`] [`remove_member_cv_t<T>`]]
[[`int() const volatile`] [`int()`]]
[[`int(foo::*)() const volatile`] [`int(foo::*)()`]]
[[`int(foo::*)() volatile`] [`int(foo::*)()`]]
[[`int(foo::*)() const`] [`int(foo::*)()`]]
[[`int(foo::*)() const &`] [`int(foo::*)() &`]]
[[`int(foo::*)() const &&`] [`int(foo::*)() &&`]]
[[`int(foo::*)() const`] [`int(foo::*)()`]]
[[`int`] [(substitution failure)]]
[[`int (&)()`] [(substitution failure)]]
[[`int (*)()`] [(substitution failure)]]
[[`int foo::*`] [(substitution failure)]]
[[`int (foo::* const)()`] [(substitution failure)]]
]
[heading Example Program]
[import ../example/remove_member_cv.cpp]
[remove_member_cv]
[endsect]
*/
//]
#endif // #ifndef BOOST_CLBL_TRTS_REMOVE_MEMBER_CV_HPP
<commit_msg>Delete remove_member_cv.hpp<commit_after><|endoftext|>
|
<commit_before>/*
* Copyright (c) 2015 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 <algorithm>
#include <limits>
#include <vector>
#include "webrtc/modules/remote_bitrate_estimator/include/send_time_history.h"
#include "webrtc/modules/rtp_rtcp/include/rtp_rtcp_defines.h"
#include "webrtc/system_wrappers/include/clock.h"
#include "webrtc/test/gtest.h"
namespace webrtc {
namespace test {
static const int kDefaultHistoryLengthMs = 1000;
class SendTimeHistoryTest : public ::testing::Test {
protected:
SendTimeHistoryTest()
: clock_(0), history_(&clock_, kDefaultHistoryLengthMs) {}
~SendTimeHistoryTest() {}
virtual void SetUp() {}
virtual void TearDown() {}
void AddPacketWithSendTime(uint16_t sequence_number,
size_t length,
int64_t send_time_ms,
const PacedPacketInfo& pacing_info) {
PacketFeedback packet(clock_.TimeInMilliseconds(), sequence_number, length,
0, 0, pacing_info);
history_.AddAndRemoveOld(packet);
history_.OnSentPacket(sequence_number, send_time_ms);
}
webrtc::SimulatedClock clock_;
SendTimeHistory history_;
};
TEST_F(SendTimeHistoryTest, SaveAndRestoreNetworkId) {
const PacedPacketInfo kPacingInfo(0, 5, 1200);
uint16_t sequence_number = 0;
int64_t now_ms = clock_.TimeInMilliseconds();
for (int i = 1; i < 5; ++i) {
PacketFeedback packet(now_ms, sequence_number++, 1000, i, i - 1,
kPacingInfo);
history_.AddAndRemoveOld(packet);
history_.OnSentPacket(sequence_number, now_ms);
PacketFeedback restored(now_ms, sequence_number);
EXPECT_TRUE(history_.GetFeedback(&restored, sequence_number));
EXPECT_EQ(packet.local_net_id, restored.local_net_id);
EXPECT_EQ(packet.remote_net_id, restored.remote_net_id);
}
}
TEST_F(SendTimeHistoryTest, AddRemoveOne) {
const uint16_t kSeqNo = 10;
// TODO(philipel): Fix PacedPacketInfo constructor?
const PacedPacketInfo kPacingInfo(0, 5, 1200);
const PacketFeedback kSentPacket(0, 1, kSeqNo, 1, kPacingInfo);
AddPacketWithSendTime(kSeqNo, 1, 1, kPacingInfo);
PacketFeedback received_packet(0, 0, kSeqNo, 0, kPacingInfo);
EXPECT_TRUE(history_.GetFeedback(&received_packet, false));
EXPECT_EQ(kSentPacket, received_packet);
PacketFeedback received_packet2(0, 0, kSeqNo, 0, kPacingInfo);
EXPECT_TRUE(history_.GetFeedback(&received_packet2, true));
EXPECT_EQ(kSentPacket, received_packet2);
PacketFeedback received_packet3(0, 0, kSeqNo, 0, kPacingInfo);
EXPECT_FALSE(history_.GetFeedback(&received_packet3, true));
}
TEST_F(SendTimeHistoryTest, PopulatesExpectedFields) {
const uint16_t kSeqNo = 10;
const int64_t kSendTime = 1000;
const int64_t kReceiveTime = 2000;
const size_t kPayloadSize = 42;
const PacedPacketInfo kPacingInfo(3, 10, 1212);
AddPacketWithSendTime(kSeqNo, kPayloadSize, kSendTime, kPacingInfo);
PacketFeedback packet_feedback(kReceiveTime, kSeqNo);
EXPECT_TRUE(history_.GetFeedback(&packet_feedback, true));
EXPECT_EQ(kReceiveTime, packet_feedback.arrival_time_ms);
EXPECT_EQ(kSendTime, packet_feedback.send_time_ms);
EXPECT_EQ(kSeqNo, packet_feedback.sequence_number);
EXPECT_EQ(kPayloadSize, packet_feedback.payload_size);
EXPECT_EQ(kPacingInfo, packet_feedback.pacing_info);
}
TEST_F(SendTimeHistoryTest, AddThenRemoveOutOfOrder) {
std::vector<PacketFeedback> sent_packets;
std::vector<PacketFeedback> received_packets;
const size_t num_items = 100;
const size_t kPacketSize = 400;
const size_t kTransmissionTime = 1234;
const PacedPacketInfo kPacingInfo(1, 2, 200);
for (size_t i = 0; i < num_items; ++i) {
sent_packets.push_back(PacketFeedback(0, static_cast<int64_t>(i),
static_cast<uint16_t>(i), kPacketSize,
kPacingInfo));
received_packets.push_back(PacketFeedback(
static_cast<int64_t>(i) + kTransmissionTime, 0,
static_cast<uint16_t>(i), kPacketSize, PacedPacketInfo()));
}
for (size_t i = 0; i < num_items; ++i) {
PacketFeedback packet = sent_packets[i];
packet.arrival_time_ms = -1;
packet.send_time_ms = -1;
history_.AddAndRemoveOld(packet);
}
for (size_t i = 0; i < num_items; ++i)
history_.OnSentPacket(sent_packets[i].sequence_number,
sent_packets[i].send_time_ms);
std::random_shuffle(received_packets.begin(), received_packets.end());
for (size_t i = 0; i < num_items; ++i) {
PacketFeedback packet = received_packets[i];
EXPECT_TRUE(history_.GetFeedback(&packet, false));
PacketFeedback sent_packet = sent_packets[packet.sequence_number];
sent_packet.arrival_time_ms = packet.arrival_time_ms;
EXPECT_EQ(sent_packet, packet);
EXPECT_TRUE(history_.GetFeedback(&packet, true));
}
for (PacketFeedback packet : sent_packets)
EXPECT_FALSE(history_.GetFeedback(&packet, false));
}
TEST_F(SendTimeHistoryTest, HistorySize) {
const int kItems = kDefaultHistoryLengthMs / 100;
for (int i = 0; i < kItems; ++i) {
clock_.AdvanceTimeMilliseconds(100);
AddPacketWithSendTime(i, 0, i * 100, PacedPacketInfo());
}
for (int i = 0; i < kItems; ++i) {
PacketFeedback packet(0, 0, static_cast<uint16_t>(i), 0, PacedPacketInfo());
EXPECT_TRUE(history_.GetFeedback(&packet, false));
EXPECT_EQ(i * 100, packet.send_time_ms);
}
clock_.AdvanceTimeMilliseconds(101);
AddPacketWithSendTime(kItems, 0, kItems * 101, PacedPacketInfo());
PacketFeedback packet(0, 0, 0, 0, PacedPacketInfo());
EXPECT_FALSE(history_.GetFeedback(&packet, false));
for (int i = 1; i < (kItems + 1); ++i) {
PacketFeedback packet2(0, 0, static_cast<uint16_t>(i), 0,
PacedPacketInfo());
EXPECT_TRUE(history_.GetFeedback(&packet2, false));
int64_t expected_time_ms = (i == kItems) ? i * 101 : i * 100;
EXPECT_EQ(expected_time_ms, packet2.send_time_ms);
}
}
TEST_F(SendTimeHistoryTest, HistorySizeWithWraparound) {
const uint16_t kMaxSeqNo = std::numeric_limits<uint16_t>::max();
AddPacketWithSendTime(kMaxSeqNo - 2, 0, 0, PacedPacketInfo());
clock_.AdvanceTimeMilliseconds(100);
AddPacketWithSendTime(kMaxSeqNo - 1, 1, 100, PacedPacketInfo());
clock_.AdvanceTimeMilliseconds(100);
AddPacketWithSendTime(kMaxSeqNo, 0, 200, PacedPacketInfo());
clock_.AdvanceTimeMilliseconds(kDefaultHistoryLengthMs - 200 + 1);
AddPacketWithSendTime(0, 0, kDefaultHistoryLengthMs, PacedPacketInfo());
PacketFeedback packet(0, static_cast<uint16_t>(kMaxSeqNo - 2));
EXPECT_FALSE(history_.GetFeedback(&packet, false));
PacketFeedback packet2(0, static_cast<uint16_t>(kMaxSeqNo - 1));
EXPECT_TRUE(history_.GetFeedback(&packet2, false));
PacketFeedback packet3(0, static_cast<uint16_t>(kMaxSeqNo));
EXPECT_TRUE(history_.GetFeedback(&packet3, false));
PacketFeedback packet4(0, 0);
EXPECT_TRUE(history_.GetFeedback(&packet4, false));
// Create a gap (kMaxSeqNo - 1) -> 0.
PacketFeedback packet5(0, kMaxSeqNo);
EXPECT_TRUE(history_.GetFeedback(&packet5, true));
clock_.AdvanceTimeMilliseconds(100);
AddPacketWithSendTime(1, 0, 1100, PacedPacketInfo());
PacketFeedback packet6(0, static_cast<uint16_t>(kMaxSeqNo - 2));
EXPECT_FALSE(history_.GetFeedback(&packet6, false));
PacketFeedback packet7(0, static_cast<uint16_t>(kMaxSeqNo - 1));
EXPECT_FALSE(history_.GetFeedback(&packet7, false));
PacketFeedback packet8(0, kMaxSeqNo);
EXPECT_FALSE(history_.GetFeedback(&packet8, false));
PacketFeedback packet9(0, 0);
EXPECT_TRUE(history_.GetFeedback(&packet9, false));
PacketFeedback packet10(0, 1);
EXPECT_TRUE(history_.GetFeedback(&packet10, false));
}
TEST_F(SendTimeHistoryTest, InterlievedGetAndRemove) {
const uint16_t kSeqNo = 1;
const int64_t kTimestamp = 2;
const PacedPacketInfo kPacingInfo1(1, 1, 100);
const PacedPacketInfo kPacingInfo2(2, 2, 200);
const PacedPacketInfo kPacingInfo3(3, 3, 300);
PacketFeedback packets[3] = {
{0, kTimestamp, kSeqNo, 0, kPacingInfo1},
{0, kTimestamp + 1, kSeqNo + 1, 0, kPacingInfo2},
{0, kTimestamp + 2, kSeqNo + 2, 0, kPacingInfo3}};
AddPacketWithSendTime(packets[0].sequence_number, packets[0].payload_size,
packets[0].send_time_ms, packets[0].pacing_info);
AddPacketWithSendTime(packets[1].sequence_number, packets[1].payload_size,
packets[1].send_time_ms, packets[1].pacing_info);
PacketFeedback packet(0, 0, packets[0].sequence_number, 0, PacedPacketInfo());
EXPECT_TRUE(history_.GetFeedback(&packet, true));
EXPECT_EQ(packets[0], packet);
AddPacketWithSendTime(packets[2].sequence_number, packets[2].payload_size,
packets[2].send_time_ms, packets[2].pacing_info);
PacketFeedback packet2(0, 0, packets[1].sequence_number, 0, kPacingInfo1);
EXPECT_TRUE(history_.GetFeedback(&packet2, true));
EXPECT_EQ(packets[1], packet2);
PacketFeedback packet3(0, 0, packets[2].sequence_number, 0, kPacingInfo2);
EXPECT_TRUE(history_.GetFeedback(&packet3, true));
EXPECT_EQ(packets[2], packet3);
}
} // namespace test
} // namespace webrtc
<commit_msg>Fix broken test landed in r17243.<commit_after>/*
* Copyright (c) 2015 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 <algorithm>
#include <limits>
#include <vector>
#include "webrtc/modules/remote_bitrate_estimator/include/send_time_history.h"
#include "webrtc/modules/rtp_rtcp/include/rtp_rtcp_defines.h"
#include "webrtc/system_wrappers/include/clock.h"
#include "webrtc/test/gtest.h"
namespace webrtc {
namespace test {
static const int kDefaultHistoryLengthMs = 1000;
class SendTimeHistoryTest : public ::testing::Test {
protected:
SendTimeHistoryTest()
: clock_(0), history_(&clock_, kDefaultHistoryLengthMs) {}
~SendTimeHistoryTest() {}
virtual void SetUp() {}
virtual void TearDown() {}
void AddPacketWithSendTime(uint16_t sequence_number,
size_t length,
int64_t send_time_ms,
const PacedPacketInfo& pacing_info) {
PacketFeedback packet(clock_.TimeInMilliseconds(), sequence_number, length,
0, 0, pacing_info);
history_.AddAndRemoveOld(packet);
history_.OnSentPacket(sequence_number, send_time_ms);
}
webrtc::SimulatedClock clock_;
SendTimeHistory history_;
};
TEST_F(SendTimeHistoryTest, SaveAndRestoreNetworkId) {
const PacedPacketInfo kPacingInfo(0, 5, 1200);
uint16_t sequence_number = 0;
int64_t now_ms = clock_.TimeInMilliseconds();
for (int i = 1; i < 5; ++i) {
PacketFeedback packet(now_ms, sequence_number, 1000, i, i - 1,
kPacingInfo);
history_.AddAndRemoveOld(packet);
history_.OnSentPacket(sequence_number, now_ms);
PacketFeedback restored(now_ms, sequence_number);
EXPECT_TRUE(history_.GetFeedback(&restored, sequence_number++));
EXPECT_EQ(packet.local_net_id, restored.local_net_id);
EXPECT_EQ(packet.remote_net_id, restored.remote_net_id);
}
}
TEST_F(SendTimeHistoryTest, AddRemoveOne) {
const uint16_t kSeqNo = 10;
// TODO(philipel): Fix PacedPacketInfo constructor?
const PacedPacketInfo kPacingInfo(0, 5, 1200);
const PacketFeedback kSentPacket(0, 1, kSeqNo, 1, kPacingInfo);
AddPacketWithSendTime(kSeqNo, 1, 1, kPacingInfo);
PacketFeedback received_packet(0, 0, kSeqNo, 0, kPacingInfo);
EXPECT_TRUE(history_.GetFeedback(&received_packet, false));
EXPECT_EQ(kSentPacket, received_packet);
PacketFeedback received_packet2(0, 0, kSeqNo, 0, kPacingInfo);
EXPECT_TRUE(history_.GetFeedback(&received_packet2, true));
EXPECT_EQ(kSentPacket, received_packet2);
PacketFeedback received_packet3(0, 0, kSeqNo, 0, kPacingInfo);
EXPECT_FALSE(history_.GetFeedback(&received_packet3, true));
}
TEST_F(SendTimeHistoryTest, PopulatesExpectedFields) {
const uint16_t kSeqNo = 10;
const int64_t kSendTime = 1000;
const int64_t kReceiveTime = 2000;
const size_t kPayloadSize = 42;
const PacedPacketInfo kPacingInfo(3, 10, 1212);
AddPacketWithSendTime(kSeqNo, kPayloadSize, kSendTime, kPacingInfo);
PacketFeedback packet_feedback(kReceiveTime, kSeqNo);
EXPECT_TRUE(history_.GetFeedback(&packet_feedback, true));
EXPECT_EQ(kReceiveTime, packet_feedback.arrival_time_ms);
EXPECT_EQ(kSendTime, packet_feedback.send_time_ms);
EXPECT_EQ(kSeqNo, packet_feedback.sequence_number);
EXPECT_EQ(kPayloadSize, packet_feedback.payload_size);
EXPECT_EQ(kPacingInfo, packet_feedback.pacing_info);
}
TEST_F(SendTimeHistoryTest, AddThenRemoveOutOfOrder) {
std::vector<PacketFeedback> sent_packets;
std::vector<PacketFeedback> received_packets;
const size_t num_items = 100;
const size_t kPacketSize = 400;
const size_t kTransmissionTime = 1234;
const PacedPacketInfo kPacingInfo(1, 2, 200);
for (size_t i = 0; i < num_items; ++i) {
sent_packets.push_back(PacketFeedback(0, static_cast<int64_t>(i),
static_cast<uint16_t>(i), kPacketSize,
kPacingInfo));
received_packets.push_back(PacketFeedback(
static_cast<int64_t>(i) + kTransmissionTime, 0,
static_cast<uint16_t>(i), kPacketSize, PacedPacketInfo()));
}
for (size_t i = 0; i < num_items; ++i) {
PacketFeedback packet = sent_packets[i];
packet.arrival_time_ms = -1;
packet.send_time_ms = -1;
history_.AddAndRemoveOld(packet);
}
for (size_t i = 0; i < num_items; ++i)
history_.OnSentPacket(sent_packets[i].sequence_number,
sent_packets[i].send_time_ms);
std::random_shuffle(received_packets.begin(), received_packets.end());
for (size_t i = 0; i < num_items; ++i) {
PacketFeedback packet = received_packets[i];
EXPECT_TRUE(history_.GetFeedback(&packet, false));
PacketFeedback sent_packet = sent_packets[packet.sequence_number];
sent_packet.arrival_time_ms = packet.arrival_time_ms;
EXPECT_EQ(sent_packet, packet);
EXPECT_TRUE(history_.GetFeedback(&packet, true));
}
for (PacketFeedback packet : sent_packets)
EXPECT_FALSE(history_.GetFeedback(&packet, false));
}
TEST_F(SendTimeHistoryTest, HistorySize) {
const int kItems = kDefaultHistoryLengthMs / 100;
for (int i = 0; i < kItems; ++i) {
clock_.AdvanceTimeMilliseconds(100);
AddPacketWithSendTime(i, 0, i * 100, PacedPacketInfo());
}
for (int i = 0; i < kItems; ++i) {
PacketFeedback packet(0, 0, static_cast<uint16_t>(i), 0, PacedPacketInfo());
EXPECT_TRUE(history_.GetFeedback(&packet, false));
EXPECT_EQ(i * 100, packet.send_time_ms);
}
clock_.AdvanceTimeMilliseconds(101);
AddPacketWithSendTime(kItems, 0, kItems * 101, PacedPacketInfo());
PacketFeedback packet(0, 0, 0, 0, PacedPacketInfo());
EXPECT_FALSE(history_.GetFeedback(&packet, false));
for (int i = 1; i < (kItems + 1); ++i) {
PacketFeedback packet2(0, 0, static_cast<uint16_t>(i), 0,
PacedPacketInfo());
EXPECT_TRUE(history_.GetFeedback(&packet2, false));
int64_t expected_time_ms = (i == kItems) ? i * 101 : i * 100;
EXPECT_EQ(expected_time_ms, packet2.send_time_ms);
}
}
TEST_F(SendTimeHistoryTest, HistorySizeWithWraparound) {
const uint16_t kMaxSeqNo = std::numeric_limits<uint16_t>::max();
AddPacketWithSendTime(kMaxSeqNo - 2, 0, 0, PacedPacketInfo());
clock_.AdvanceTimeMilliseconds(100);
AddPacketWithSendTime(kMaxSeqNo - 1, 1, 100, PacedPacketInfo());
clock_.AdvanceTimeMilliseconds(100);
AddPacketWithSendTime(kMaxSeqNo, 0, 200, PacedPacketInfo());
clock_.AdvanceTimeMilliseconds(kDefaultHistoryLengthMs - 200 + 1);
AddPacketWithSendTime(0, 0, kDefaultHistoryLengthMs, PacedPacketInfo());
PacketFeedback packet(0, static_cast<uint16_t>(kMaxSeqNo - 2));
EXPECT_FALSE(history_.GetFeedback(&packet, false));
PacketFeedback packet2(0, static_cast<uint16_t>(kMaxSeqNo - 1));
EXPECT_TRUE(history_.GetFeedback(&packet2, false));
PacketFeedback packet3(0, static_cast<uint16_t>(kMaxSeqNo));
EXPECT_TRUE(history_.GetFeedback(&packet3, false));
PacketFeedback packet4(0, 0);
EXPECT_TRUE(history_.GetFeedback(&packet4, false));
// Create a gap (kMaxSeqNo - 1) -> 0.
PacketFeedback packet5(0, kMaxSeqNo);
EXPECT_TRUE(history_.GetFeedback(&packet5, true));
clock_.AdvanceTimeMilliseconds(100);
AddPacketWithSendTime(1, 0, 1100, PacedPacketInfo());
PacketFeedback packet6(0, static_cast<uint16_t>(kMaxSeqNo - 2));
EXPECT_FALSE(history_.GetFeedback(&packet6, false));
PacketFeedback packet7(0, static_cast<uint16_t>(kMaxSeqNo - 1));
EXPECT_FALSE(history_.GetFeedback(&packet7, false));
PacketFeedback packet8(0, kMaxSeqNo);
EXPECT_FALSE(history_.GetFeedback(&packet8, false));
PacketFeedback packet9(0, 0);
EXPECT_TRUE(history_.GetFeedback(&packet9, false));
PacketFeedback packet10(0, 1);
EXPECT_TRUE(history_.GetFeedback(&packet10, false));
}
TEST_F(SendTimeHistoryTest, InterlievedGetAndRemove) {
const uint16_t kSeqNo = 1;
const int64_t kTimestamp = 2;
const PacedPacketInfo kPacingInfo1(1, 1, 100);
const PacedPacketInfo kPacingInfo2(2, 2, 200);
const PacedPacketInfo kPacingInfo3(3, 3, 300);
PacketFeedback packets[3] = {
{0, kTimestamp, kSeqNo, 0, kPacingInfo1},
{0, kTimestamp + 1, kSeqNo + 1, 0, kPacingInfo2},
{0, kTimestamp + 2, kSeqNo + 2, 0, kPacingInfo3}};
AddPacketWithSendTime(packets[0].sequence_number, packets[0].payload_size,
packets[0].send_time_ms, packets[0].pacing_info);
AddPacketWithSendTime(packets[1].sequence_number, packets[1].payload_size,
packets[1].send_time_ms, packets[1].pacing_info);
PacketFeedback packet(0, 0, packets[0].sequence_number, 0, PacedPacketInfo());
EXPECT_TRUE(history_.GetFeedback(&packet, true));
EXPECT_EQ(packets[0], packet);
AddPacketWithSendTime(packets[2].sequence_number, packets[2].payload_size,
packets[2].send_time_ms, packets[2].pacing_info);
PacketFeedback packet2(0, 0, packets[1].sequence_number, 0, kPacingInfo1);
EXPECT_TRUE(history_.GetFeedback(&packet2, true));
EXPECT_EQ(packets[1], packet2);
PacketFeedback packet3(0, 0, packets[2].sequence_number, 0, kPacingInfo2);
EXPECT_TRUE(history_.GetFeedback(&packet3, true));
EXPECT_EQ(packets[2], packet3);
}
} // namespace test
} // namespace webrtc
<|endoftext|>
|
<commit_before>#include <gecode/driver.hh>
#include <gecode/int.hh>
#include <gecode/minimodel.hh>
#include <gecode/gist.hh>
#include <gecode/search.hh>
#include "dep_selector_to_gecode.h"
#include <limits>
#include <iostream>
#include <vector>
#define DEBUG
using namespace Gecode;
const int VersionProblem::UNRESOLVED_VARIABLE = INT_MIN;
const int VersionProblem::MIN_TRUST_LEVEL = 0;
const int VersionProblem::MAX_TRUST_LEVEL = 10;
VersionProblem::VersionProblem(int packageCount)
: size(packageCount), finalized(false), cur_package(0), package_versions(*this, packageCount),
disabled_package_variables(*this, packageCount, 0, 1), total_disabled(*this, 0, packageCount*MAX_TRUST_LEVEL),
disabled_package_weights(new int[packageCount]), preferred_at_latest(*this, packageCount, 0, 1),
total_preferred_at_latest(*this, 0, packageCount), preferred_at_latest_weights(new int[packageCount])
{
for (int i = 0; i < packageCount; i++)
{
disabled_package_weights[i] = MAX_TRUST_LEVEL;
preferred_at_latest_weights[i] = 0;
}
}
VersionProblem::VersionProblem(bool share, VersionProblem & s)
: Space(share, s), size(s.size),
finalized(s.finalized), cur_package(s.cur_package),
disabled_package_variables(s.disabled_package_variables), total_disabled(s.total_disabled),
disabled_package_weights(NULL), preferred_at_latest(s.preferred_at_latest),
total_preferred_at_latest(s.total_preferred_at_latest), preferred_at_latest_weights(NULL)
{
package_versions.update(*this, share, s.package_versions);
disabled_package_variables.update(*this, share, s.disabled_package_variables);
total_disabled.update(*this, share, s.total_disabled);
preferred_at_latest.update(*this, share, s.preferred_at_latest);
total_preferred_at_latest.update(*this, share, s.total_preferred_at_latest);
}
// Support for gecode
Space* VersionProblem::copy(bool share)
{
return new VersionProblem(share,*this);
}
VersionProblem::~VersionProblem()
{
delete[] disabled_package_weights;
delete[] preferred_at_latest_weights;
}
int VersionProblem::Size()
{
return size;
}
int VersionProblem::PackageCount()
{
return cur_package;
}
int
VersionProblem::AddPackage(int minVersion, int maxVersion, int currentVersion)
{
if (cur_package == size) {
return -1;
}
#ifdef DEBUG
std::cout << "Adding package id " << cur_package << '/' << size << ": min = " << minVersion << ", max = " << maxVersion << ", current verison " << currentVersion << std::endl;
std::cout.flush();
#endif // DEBUG
int index = cur_package;
cur_package++;
// IntVar version(*this, minVersion, maxVersion);
package_versions[index] = IntVar(*this, minVersion, maxVersion);
// register the binding of package to version that corresponds to the package's latest
rel(*this, package_versions[index], IRT_EQ, maxVersion, preferred_at_latest[index]);
return index;
}
bool
VersionProblem::AddVersionConstraint(int packageId, int version,
int dependentPackageId, int minDependentVersion, int maxDependentVersion)
{
BoolVar version_match(*this, 0, 1);
BoolVar depend_match(*this, 0, 1);
BoolVar predicated_depend_match(*this, 0, 1);
#ifdef DEBUG
std::cout << "Add VC for " << packageId << " @ " << version << " depPkg " << dependentPackageId;
std::cout << " [ " << minDependentVersion << ", " << maxDependentVersion << " ]" << std::endl;
std::cout.flush();
#endif // DEBUG
//version_flags << version_match;
// Constrain pred to reify package @ version
rel(*this, package_versions[packageId], IRT_EQ, version, version_match);
// Add the predicated version constraints imposed on dependent package
// package_versions[dependendPackageId] in domain [minDependentVersion,maxDependentVersion] <=> depend_match
dom(*this, package_versions[dependentPackageId], minDependentVersion, maxDependentVersion, depend_match);
// disabled_package_variables[dependentPackageId] OR depend_match <=> predicated_depend_match
// rel(*this, disabled_package_variables[dependentPackageId], BOT_OR, depend_match, version_match);
rel(*this, disabled_package_variables[dependentPackageId], BOT_OR, depend_match, predicated_depend_match);
rel(*this, version_match, BOT_IMP, predicated_depend_match, 1);
}
void
VersionProblem::MarkPackageSuspicious(int packageId, int trustLevel)
{
disabled_package_weights[packageId] = std::max(MIN_TRUST_LEVEL, std::min(disabled_package_weights[packageId], trustLevel));
}
void
VersionProblem::MarkPackagePreferredToBeAtLatest(int packageId, int weight)
{
preferred_at_latest_weights[packageId] = weight;
}
void VersionProblem::Finalize()
{
#ifdef DEBUG
std::cout << "Finalization Started" << std::endl;
std::cout.flush();
#endif // DEBUG
finalized = true;
// Setup constraint for cost
// linear(*this, disabled_package_weights, disabled_package_variables, IRT_EQ, total_disabled);
IntArgs disabled_package_weights_args(size, disabled_package_weights);
//IntArgs package_weights = IntArgs::create(size, 1, 0);
#ifdef DEBUG
std::cout << "disabled_package_weights_args: " << disabled_package_weights_args << std::endl;
#endif DEBUG
linear(*this, disabled_package_weights_args, disabled_package_variables, IRT_EQ, total_disabled);
// linear(*this, disabled_package_variables, IRT_EQ, total_disabled);
IntArgs preferred_at_latest_weights_args(size, preferred_at_latest_weights);
linear(*this, preferred_at_latest_weights_args, preferred_at_latest, IRT_EQ, total_preferred_at_latest);
// Assign a dummy variable to elements greater than actually used.
for (int i = cur_package; i < size; i++) {
package_versions[i] = IntVar(*this, -1, -1);
disabled_package_variables[i] = BoolVar(*this, 1, 1);
}
#ifdef DEBUG
std::cout << "preferred_at_latest_weights_args: " << preferred_at_latest_weights_args << std::endl;
std::cout << "Adding branching" << std::endl;
std::cout.flush();
#endif // DEBUG
branch(*this, disabled_package_variables, INT_VAR_SIZE_MIN, INT_VAL_MIN);
branch(*this, package_versions, INT_VAR_SIZE_MIN, INT_VAL_MAX);
branch(*this, total_disabled, INT_VAL_MIN);
branch(*this, preferred_at_latest, INT_VAR_SIZE_MIN, INT_VAL_MAX);
branch(*this, total_preferred_at_latest, INT_VAL_MAX);
#ifdef DEBUG
std::cout << "Finalization Done" << std::endl;
std::cout.flush();
#endif // DEBUG
}
// _best_known_soln is the most recent satisfying assignment of
// variables that Gecode has found. This method examines the solution
// and adds additional constraints that are applied after restarting
// the search, which means that the next time a solution that's found
// must be strictly better than the current best known solution.
//
// Our model requires us to have a series of objective functions where
// each successive objective function is evaluated if and only if all
// higher precedent objective functions are tied.
//
// [TODO: DESCRIBE WHAT THE ACTUAL SERIES OF OBJECTIVE FUNCTIONS IS]
//
// Lower precedent objective functions are modeled as the consequent
// of an implication whose antecedent is the conjunction of all the
// higher precedent objective functions being assigned to their best
// known value; thus, the optimal value of an objection function
// "activates" the next highest objective function. This has the
// effect of isolating the logic of each objective function such that
// it is only applied to the set of equally preferable solutions under
// the higher precedent objective functions. The objective function
// then applies its constraints, the solution space is restarted and
// walks the space until it finds another, more constrained solution.
void VersionProblem::constrain(const Space & _best_known_solution)
{
const VersionProblem& best_known_solution = static_cast<const VersionProblem &>(_best_known_solution);
// add first-level objective function minimization (failing packages, weighted)
// new constraint: total_disabled < best_known_total_disabled_value)
int best_known_total_disabled_value = best_known_solution.total_disabled.val();
rel(*this, total_disabled, IRT_LE, best_known_total_disabled_value);
// add second-level objective function maximization (preferred packages are at latest, weighted)
AddPackagesPreferredToBeAtLatestObjectiveFunction(best_known_solution);
#ifdef DEBUG
std::cout << "best_known_total_disabled_value: " << best_known_total_disabled_value << std::endl;
#endif
}
void VersionProblem::AddPackagesPreferredToBeAtLatestObjectiveFunction(const VersionProblem & best_known_solution)
{
// Make sure we respect total_disabled first by only constraining on
// latestness of preferred packages if the solution's total_disabled
// is equivalent to the best known, which is what
// is_at_best_known_disabled_value represents.
// is_at_best_known_disabled_value <=> (total_disabled == best_known_total_disabled_value)
BoolVar is_at_best_known_disabled_value(*this, 0, 1);
rel(*this, total_disabled, IRT_EQ, best_known_solution.total_disabled.val(), is_at_best_known_disabled_value);
// is_better_total_preferred_at_latest <=> (total_preferred_at_latest > best_known_total_preferred_at_latest_value)
int best_known_total_preferred_at_latest_value = best_known_solution.total_preferred_at_latest.val();
BoolVar is_better_total_preferred_at_latest(*this, 0, 1);
rel(*this, total_preferred_at_latest, IRT_GR, best_known_total_preferred_at_latest_value, is_better_total_preferred_at_latest);
// new constraint: is_at_best_known_disabled_value -> is_better_total_preferred_at_latest
rel(*this, is_at_best_known_disabled_value, BOT_IMP, is_better_total_preferred_at_latest, 1);
#ifdef DEBUG
std::cout << "best_known_total_preferred_at_latest_value: " << best_known_total_preferred_at_latest_value << std::endl;
#endif
}
IntVar & VersionProblem::GetPackageVersionVar(int packageId)
{
if (packageId < cur_package) {
return package_versions[packageId];
} else {
#ifdef DEBUG
std::cout << "Bad package Id " << packageId << " >= " << cur_package << std::endl;
std::cout.flush();
#endif //DEBUG
// return 0;
}
}
int VersionProblem::GetPackageVersion(int packageId)
{
IntVar & var = GetPackageVersionVar(packageId);
if (1 == var.size()) return var.val();
return UNRESOLVED_VARIABLE;
}
bool VersionProblem::GetPackageDisabledState(int packageId)
{
return disabled_package_variables[packageId].val() == 1;
}
int VersionProblem::GetAFC(int packageId)
{
return GetPackageVersionVar(packageId).afc();
}
int VersionProblem::GetMax(int packageId)
{
return GetPackageVersionVar(packageId).max();
}
int VersionProblem::GetMin(int packageId)
{
return GetPackageVersionVar(packageId).min();
}
int VersionProblem::GetDisabledVariableCount()
{
if (total_disabled.min() == total_disabled.max()) {
return total_disabled.min();
} else {
return UNRESOLVED_VARIABLE;
}
}
// Utility
void VersionProblem::Print(std::ostream & out)
{
out << "Version problem dump: " << cur_package << "/" << size << " packages used/allocated" << std::endl;
out << "Disabled Variables: " << disabled_package_variables << std::endl;
out << "Total Disabled variables: " << total_disabled << std::endl;
out << "preferred_at_latest: " << preferred_at_latest << std::endl;
out << "total_preferred_at_latest: " << total_preferred_at_latest << std::endl;
for (int i = 0; i < cur_package; i++) {
out << "\t";
PrintPackageVar(out, i);
out << std::endl;
}
out.flush();
}
// TODO: Validate package ids !
void VersionProblem::PrintPackageVar(std::ostream & out, int packageId)
{
// Hack Alert: we could have the package variable in one of two places, but we don't clearly distinguish where.
IntVar & var = GetPackageVersionVar(packageId);
out << "PackageId: " << packageId << " Sltn: " << var << " afc: " << var.afc();
out << " disabled: " << disabled_package_variables[packageId];
}
bool VersionProblem::CheckPackageId(int id)
{
return (id < size);
}
VersionProblem * VersionProblem::Solve(VersionProblem * problem)
{
problem->Finalize();
problem->status();
#ifdef DEBUG
std::cout << "Before solve" << std::endl;
problem->Print(std::cout);
#endif //DEBUG
Restart<VersionProblem> solver(problem);
VersionProblem *best_solution = NULL;
while (VersionProblem *solution = solver.next())
{
if (best_solution != NULL)
{
delete best_solution;
}
best_solution = solution;
++i;
#ifdef DEBUG
std::cout << "Trial Solution #" << i << "===============================" << std::endl;
const Search::Statistics & stats = solver.statistics();
std::cout << "Solver stats: Prop:" << stats.propagate << " Fail:" << stats.fail << " Node:" << stats.node;
std::cout << " Depth:" << stats.depth << " memory:" << stats.memory << std::endl;
// std::cout << stats << std::endl;
solution->Print(std::cout);
#endif //DEBUG
}
return best_solution;
}
//
//
//
//
// Version Problem
//
//
//
//
<commit_msg>More descriptive output, and fix missing variable decl<commit_after>#include <gecode/driver.hh>
#include <gecode/int.hh>
#include <gecode/minimodel.hh>
#include <gecode/gist.hh>
#include <gecode/search.hh>
#include "dep_selector_to_gecode.h"
#include <limits>
#include <iostream>
#include <vector>
#define DEBUG
using namespace Gecode;
const int VersionProblem::UNRESOLVED_VARIABLE = INT_MIN;
const int VersionProblem::MIN_TRUST_LEVEL = 0;
const int VersionProblem::MAX_TRUST_LEVEL = 10;
VersionProblem::VersionProblem(int packageCount)
: size(packageCount), finalized(false), cur_package(0), package_versions(*this, packageCount),
disabled_package_variables(*this, packageCount, 0, 1), total_disabled(*this, 0, packageCount*MAX_TRUST_LEVEL),
disabled_package_weights(new int[packageCount]), preferred_at_latest(*this, packageCount, 0, 1),
total_preferred_at_latest(*this, 0, packageCount), preferred_at_latest_weights(new int[packageCount])
{
for (int i = 0; i < packageCount; i++)
{
disabled_package_weights[i] = MAX_TRUST_LEVEL;
preferred_at_latest_weights[i] = 0;
}
}
VersionProblem::VersionProblem(bool share, VersionProblem & s)
: Space(share, s), size(s.size),
finalized(s.finalized), cur_package(s.cur_package),
disabled_package_variables(s.disabled_package_variables), total_disabled(s.total_disabled),
disabled_package_weights(NULL), preferred_at_latest(s.preferred_at_latest),
total_preferred_at_latest(s.total_preferred_at_latest), preferred_at_latest_weights(NULL)
{
package_versions.update(*this, share, s.package_versions);
disabled_package_variables.update(*this, share, s.disabled_package_variables);
total_disabled.update(*this, share, s.total_disabled);
preferred_at_latest.update(*this, share, s.preferred_at_latest);
total_preferred_at_latest.update(*this, share, s.total_preferred_at_latest);
}
// Support for gecode
Space* VersionProblem::copy(bool share)
{
return new VersionProblem(share,*this);
}
VersionProblem::~VersionProblem()
{
delete[] disabled_package_weights;
delete[] preferred_at_latest_weights;
}
int VersionProblem::Size()
{
return size;
}
int VersionProblem::PackageCount()
{
return cur_package;
}
int
VersionProblem::AddPackage(int minVersion, int maxVersion, int currentVersion)
{
if (cur_package == size) {
return -1;
}
#ifdef DEBUG
std::cout << "Adding package id " << cur_package << '/' << size << ": min = " << minVersion << ", max = " << maxVersion << ", current verison " << currentVersion << std::endl;
std::cout.flush();
#endif // DEBUG
int index = cur_package;
cur_package++;
// IntVar version(*this, minVersion, maxVersion);
package_versions[index] = IntVar(*this, minVersion, maxVersion);
// register the binding of package to version that corresponds to the package's latest
rel(*this, package_versions[index], IRT_EQ, maxVersion, preferred_at_latest[index]);
return index;
}
bool
VersionProblem::AddVersionConstraint(int packageId, int version,
int dependentPackageId, int minDependentVersion, int maxDependentVersion)
{
BoolVar version_match(*this, 0, 1);
BoolVar depend_match(*this, 0, 1);
BoolVar predicated_depend_match(*this, 0, 1);
#ifdef DEBUG
std::cout << "Add VC for " << packageId << " @ " << version << " depPkg " << dependentPackageId;
std::cout << " [ " << minDependentVersion << ", " << maxDependentVersion << " ]" << std::endl;
std::cout.flush();
#endif // DEBUG
//version_flags << version_match;
// Constrain pred to reify package @ version
rel(*this, package_versions[packageId], IRT_EQ, version, version_match);
// Add the predicated version constraints imposed on dependent package
// package_versions[dependendPackageId] in domain [minDependentVersion,maxDependentVersion] <=> depend_match
dom(*this, package_versions[dependentPackageId], minDependentVersion, maxDependentVersion, depend_match);
// disabled_package_variables[dependentPackageId] OR depend_match <=> predicated_depend_match
// rel(*this, disabled_package_variables[dependentPackageId], BOT_OR, depend_match, version_match);
rel(*this, disabled_package_variables[dependentPackageId], BOT_OR, depend_match, predicated_depend_match);
rel(*this, version_match, BOT_IMP, predicated_depend_match, 1);
}
void
VersionProblem::MarkPackageSuspicious(int packageId, int trustLevel)
{
disabled_package_weights[packageId] = std::max(MIN_TRUST_LEVEL, std::min(disabled_package_weights[packageId], trustLevel));
}
void
VersionProblem::MarkPackagePreferredToBeAtLatest(int packageId, int weight)
{
preferred_at_latest_weights[packageId] = weight;
}
void VersionProblem::Finalize()
{
#ifdef DEBUG
std::cout << "Finalization Started" << std::endl;
std::cout.flush();
#endif // DEBUG
finalized = true;
// Setup constraint for cost
// linear(*this, disabled_package_weights, disabled_package_variables, IRT_EQ, total_disabled);
IntArgs disabled_package_weights_args(size, disabled_package_weights);
//IntArgs package_weights = IntArgs::create(size, 1, 0);
#ifdef DEBUG
std::cout << "disabled_package_weights_args: " << disabled_package_weights_args << std::endl;
#endif DEBUG
linear(*this, disabled_package_weights_args, disabled_package_variables, IRT_EQ, total_disabled);
// linear(*this, disabled_package_variables, IRT_EQ, total_disabled);
IntArgs preferred_at_latest_weights_args(size, preferred_at_latest_weights);
linear(*this, preferred_at_latest_weights_args, preferred_at_latest, IRT_EQ, total_preferred_at_latest);
// Assign a dummy variable to elements greater than actually used.
for (int i = cur_package; i < size; i++) {
package_versions[i] = IntVar(*this, -1, -1);
disabled_package_variables[i] = BoolVar(*this, 1, 1);
}
#ifdef DEBUG
std::cout << "preferred_at_latest_weights_args: " << preferred_at_latest_weights_args << std::endl;
std::cout << "Adding branching" << std::endl;
std::cout.flush();
#endif // DEBUG
branch(*this, disabled_package_variables, INT_VAR_SIZE_MIN, INT_VAL_MIN);
branch(*this, package_versions, INT_VAR_SIZE_MIN, INT_VAL_MAX);
branch(*this, total_disabled, INT_VAL_MIN);
branch(*this, preferred_at_latest, INT_VAR_SIZE_MIN, INT_VAL_MAX);
branch(*this, total_preferred_at_latest, INT_VAL_MAX);
#ifdef DEBUG
std::cout << "Finalization Done" << std::endl;
std::cout.flush();
#endif // DEBUG
}
// _best_known_soln is the most recent satisfying assignment of
// variables that Gecode has found. This method examines the solution
// and adds additional constraints that are applied after restarting
// the search, which means that the next time a solution that's found
// must be strictly better than the current best known solution.
//
// Our model requires us to have a series of objective functions where
// each successive objective function is evaluated if and only if all
// higher precedent objective functions are tied.
//
// [TODO: DESCRIBE WHAT THE ACTUAL SERIES OF OBJECTIVE FUNCTIONS IS]
//
// Lower precedent objective functions are modeled as the consequent
// of an implication whose antecedent is the conjunction of all the
// higher precedent objective functions being assigned to their best
// known value; thus, the optimal value of an objection function
// "activates" the next highest objective function. This has the
// effect of isolating the logic of each objective function such that
// it is only applied to the set of equally preferable solutions under
// the higher precedent objective functions. The objective function
// then applies its constraints, the solution space is restarted and
// walks the space until it finds another, more constrained solution.
void VersionProblem::constrain(const Space & _best_known_solution)
{
const VersionProblem& best_known_solution = static_cast<const VersionProblem &>(_best_known_solution);
// add first-level objective function minimization (failing packages, weighted)
// new constraint: total_disabled < best_known_total_disabled_value)
int best_known_total_disabled_value = best_known_solution.total_disabled.val();
rel(*this, total_disabled, IRT_LE, best_known_total_disabled_value);
#ifdef DEBUG
std::cout << "Constrain: best_known_total_disabled_value: " << best_known_total_disabled_value << std::endl;
#endif
// add second-level objective function maximization (preferred packages are at latest, weighted)
AddPackagesPreferredToBeAtLatestObjectiveFunction(best_known_solution);
}
void VersionProblem::AddPackagesPreferredToBeAtLatestObjectiveFunction(const VersionProblem & best_known_solution)
{
// Make sure we respect total_disabled first by only constraining on
// latestness of preferred packages if the solution's total_disabled
// is equivalent to the best known, which is what
// is_at_best_known_disabled_value represents.
// is_at_best_known_disabled_value <=> (total_disabled == best_known_total_disabled_value)
BoolVar is_at_best_known_disabled_value(*this, 0, 1);
rel(*this, total_disabled, IRT_EQ, best_known_solution.total_disabled.val(), is_at_best_known_disabled_value);
// is_better_total_preferred_at_latest <=> (total_preferred_at_latest > best_known_total_preferred_at_latest_value)
int best_known_total_preferred_at_latest_value = best_known_solution.total_preferred_at_latest.val();
BoolVar is_better_total_preferred_at_latest(*this, 0, 1);
rel(*this, total_preferred_at_latest, IRT_GR, best_known_total_preferred_at_latest_value, is_better_total_preferred_at_latest);
// new constraint: is_at_best_known_disabled_value -> is_better_total_preferred_at_latest
rel(*this, is_at_best_known_disabled_value, BOT_IMP, is_better_total_preferred_at_latest, 1);
#ifdef DEBUG
std::cout << "Constrain: best_known_total_preferred_at_latest_value: " << best_known_total_preferred_at_latest_value << std::endl;
#endif
}
IntVar & VersionProblem::GetPackageVersionVar(int packageId)
{
if (packageId < cur_package) {
return package_versions[packageId];
} else {
#ifdef DEBUG
std::cout << "Bad package Id " << packageId << " >= " << cur_package << std::endl;
std::cout.flush();
#endif //DEBUG
// return 0;
}
}
int VersionProblem::GetPackageVersion(int packageId)
{
IntVar & var = GetPackageVersionVar(packageId);
if (1 == var.size()) return var.val();
return UNRESOLVED_VARIABLE;
}
bool VersionProblem::GetPackageDisabledState(int packageId)
{
return disabled_package_variables[packageId].val() == 1;
}
int VersionProblem::GetAFC(int packageId)
{
return GetPackageVersionVar(packageId).afc();
}
int VersionProblem::GetMax(int packageId)
{
return GetPackageVersionVar(packageId).max();
}
int VersionProblem::GetMin(int packageId)
{
return GetPackageVersionVar(packageId).min();
}
int VersionProblem::GetDisabledVariableCount()
{
if (total_disabled.min() == total_disabled.max()) {
return total_disabled.min();
} else {
return UNRESOLVED_VARIABLE;
}
}
// Utility
void VersionProblem::Print(std::ostream & out)
{
out << "Version problem dump: " << cur_package << "/" << size << " packages used/allocated" << std::endl;
out << "Disabled Variables: " << disabled_package_variables << std::endl;
out << "Total Disabled variables: " << total_disabled << std::endl;
out << "preferred_at_latest: " << preferred_at_latest << std::endl;
out << "total_preferred_at_latest: " << total_preferred_at_latest << std::endl;
for (int i = 0; i < cur_package; i++) {
out << "\t";
PrintPackageVar(out, i);
out << std::endl;
}
out.flush();
}
// TODO: Validate package ids !
void VersionProblem::PrintPackageVar(std::ostream & out, int packageId)
{
// Hack Alert: we could have the package variable in one of two places, but we don't clearly distinguish where.
IntVar & var = GetPackageVersionVar(packageId);
out << "PackageId: " << packageId << " Sltn: " << var << " afc: " << var.afc();
out << " disabled: " << disabled_package_variables[packageId];
}
bool VersionProblem::CheckPackageId(int id)
{
return (id < size);
}
VersionProblem * VersionProblem::Solve(VersionProblem * problem)
{
problem->Finalize();
problem->status();
#ifdef DEBUG
std::cout << "Before solve" << std::endl;
problem->Print(std::cout);
#endif //DEBUG
Restart<VersionProblem> solver(problem);
int i = 0;
VersionProblem *best_solution = NULL;
while (VersionProblem *solution = solver.next())
{
if (best_solution != NULL)
{
delete best_solution;
}
best_solution = solution;
++i;
#ifdef DEBUG
std::cout << "Trial Solution #" << i << "===============================" << std::endl;
const Search::Statistics & stats = solver.statistics();
std::cout << "Solver stats: Prop:" << stats.propagate << " Fail:" << stats.fail << " Node:" << stats.node;
std::cout << " Depth:" << stats.depth << " memory:" << stats.memory << std::endl;
// std::cout << stats << std::endl;
solution->Print(std::cout);
#endif //DEBUG
}
return best_solution;
}
//
//
//
//
// Version Problem
//
//
//
//
<|endoftext|>
|
<commit_before>#include <SDL.h>
#include <iostream>
#include <math.h>
#include <vector>
#include <map>
#include <functional>
#include <algorithm>
#include <lua.hpp>
#include <LuaBridge.h>
#include "types.h"
#include "wrappers.h"
#include "auxiliary.h"
#include "entity.h"
#include "commands.h"
#include "player.h"
using namespace te;
namespace te
{
class LuaGameState
{
public:
LuaGameState(const std::string& filename = "init.lua")
: mpL(luaL_newstate(), [](lua_State* L){ lua_close(L); })
, mHandleCount(0)
, mEntities()
, mPositionMap()
, mVelocityMap()
, mBoundingBoxMap()
, mDimensionMap()
, mKeyPressTable(luabridge::newTable(mpL.get()))
, mKeyReleaseTable(luabridge::newTable(mpL.get()))
, mCollisionHandlerMap()
{
lua_State* pL = mpL.get();
luaL_openlibs(pL);
luabridge::getGlobalNamespace(pL)
.beginClass<LuaGameState>("GameState")
.addFunction("createEntity", &LuaGameState::createEntity)
.addFunction("setPosition", &LuaGameState::setPosition)
.addFunction("getPosition", &LuaGameState::getPosition)
.addFunction("setVelocity", &LuaGameState::setVelocity)
.addFunction("getVelocity", &LuaGameState::getVelocity)
.addFunction("setBoundingBox", &LuaGameState::setBoundingBox)
.addFunction("getBoundingBox", &LuaGameState::getBoundingBox)
.addFunction("getIntersection", &LuaGameState::getIntersection)
.addFunction("setSprite", &LuaGameState::setSprite)
.addFunction("handleCollision", &LuaGameState::handleCollision)
.addFunction("destroyEntity", &LuaGameState::destroyEntity)
.addFunction("registerKeyPressTable", &LuaGameState::registerKeyPressTable)
.addFunction("registerKeyReleaseTable", &LuaGameState::registerKeyReleaseTable)
.endClass()
.beginClass<Vector2f>("Vector2")
.addConstructor<void(*)(void)>()
.addConstructor<void(*)(float, float)>()
.addData("x", &te::Vector2f::x)
.addData("y", &te::Vector2f::y)
.endClass()
.addFunction<te::Vector2f(*)(te::Vector2f, te::Vector2f)>("addV", &te::operator+)
.addFunction<te::Vector2f(*)(te::Vector2f, te::Vector2f)>("subtractV", &te::operator-)
.addFunction<te::Vector2f(*)(float, te::Vector2f)>("multiplyV", &te::operator*)
.addFunction<te::Vector2f(*)(te::Vector2f, float)>("divideV", &te::operator/)
.addFunction<float(*)(te::Vector2f)>("lengthV", &te::length)
.addFunction<te::Vector2f(*)(te::Vector2f)>("normalizeV", &te::normalize)
.beginClass<SDL_Rect>("Rect")
.addData("h", &SDL_Rect::h)
.addData("w", &SDL_Rect::w)
.addData("x", &SDL_Rect::x)
.addData("y", &SDL_Rect::y)
.endClass();
luabridge::push(pL, this);
lua_setglobal(pL, "game");
luaL_dofile(pL, filename.c_str());
luabridge::getGlobal(pL, "main")();
}
typedef unsigned int EntityHandle;
typedef std::pair<EntityHandle, EntityHandle> EntityPair;
EntityHandle createEntity(const Vector2f& position, const Vector2f& velocity)
{
EntityHandle handle = mHandleCount++;
mEntities.push_back(handle);
mPositionMap.insert(std::make_pair(handle, position));
mVelocityMap.insert(std::make_pair(handle, velocity));
mBoundingBoxMap.insert(std::make_pair(handle, Vector2i(0, 0)));
return handle;
}
void setPosition(EntityHandle handle, const Vector2f& position)
{
if (!exists(handle)) return;
mPositionMap[handle] = position;
}
Vector2f getPosition(EntityHandle handle)
{
if (!exists(handle)) return Vector2f(0.f, 0.f);
return mPositionMap[handle];
}
void setVelocity(EntityHandle handle, const Vector2f& velocity)
{
if (!exists(handle)) return;
mVelocityMap[handle] = velocity;
}
Vector2f getVelocity(EntityHandle handle)
{
if (!exists(handle)) return Vector2f(0.f, 0.f);
return mVelocityMap[handle];
}
void setBoundingBox(EntityHandle handle, const Vector2f& dimensions)
{
if (!exists(handle)) return;
mBoundingBoxMap[handle] = convertVector2<int>(dimensions);
}
void setSprite(EntityHandle handle, const Vector2f& dimensions)
{
if (!exists(handle)) return;
insertOrAssign(mDimensionMap, std::make_pair(
handle, convertVector2<int>(dimensions)));
}
void handleCollision(EntityHandle e1, EntityHandle e2, luabridge::LuaRef handler)
{
if (!exists(e1) || !exists(e2)) return;
auto key = std::make_pair(e1, e2);
auto it = mCollisionHandlerMap.find(key);
if (it == mCollisionHandlerMap.end())
{
mCollisionHandlerMap.insert(std::make_pair(
key,
handler));
}
else
{
it->second = handler;
}
}
void registerKeyPressTable(luabridge::LuaRef table)
{
mKeyPressTable = table;
}
void registerKeyReleaseTable(luabridge::LuaRef table)
{
mKeyReleaseTable = table;
}
bool exists(EntityHandle handle)
{
auto it = std::find(std::begin(mEntities), std::end(mEntities), handle);
return it != std::end(mEntities);
}
void destroyEntity(EntityHandle handle)
{
mEntities.erase(
std::remove(mEntities.begin(), mEntities.end(), handle),
mEntities.end());
auto positionIt = mPositionMap.find(handle);
if (positionIt != mPositionMap.end())
{
mPositionMap.erase(positionIt);
}
auto velocityIt = mVelocityMap.find(handle);
if (velocityIt != mVelocityMap.end())
{
mVelocityMap.erase(velocityIt);
}
auto boundingBoxIt = mBoundingBoxMap.find(handle);
if (boundingBoxIt != mBoundingBoxMap.end())
{
mBoundingBoxMap.erase(boundingBoxIt);
}
auto dimensionIt = mDimensionMap.find(handle);
if (dimensionIt != mDimensionMap.end())
{
mDimensionMap.erase(dimensionIt);
}
}
void processInput(const SDL_Event& evt)
{
if (evt.type == SDL_KEYDOWN)
{
if (mKeyPressTable[evt.key.keysym.sym].isFunction())
{
mKeyPressTable[evt.key.keysym.sym]();
}
}
else if (evt.type == SDL_KEYUP)
{
if (mKeyReleaseTable[evt.key.keysym.sym].isFunction())
{
mKeyReleaseTable[evt.key.keysym.sym]();
}
}
}
void update(float dt)
{
forEachEntity([&](const EntityHandle& handle)
{
mPositionMap[handle] += dt * mVelocityMap[handle];
});
std::for_each(
mCollisionHandlerMap.begin(),
mCollisionHandlerMap.end(),
[&](std::pair<const EntityPair, luabridge::LuaRef> kv)
{
if (checkCollision(
getBoundingBox(kv.first.first),
getBoundingBox(kv.first.second)))
{
kv.second(kv.first.first, kv.first.second, dt);
}
});
}
SDL_Rect getBoundingBox(EntityHandle handle)
{
Vector2f position = mPositionMap[handle];
Vector2i boundingBox = mBoundingBoxMap[handle];
return SDL_Rect{
(int)position.x - (boundingBox.x / 2),
(int)position.y - (boundingBox.y / 2),
boundingBox.x,
boundingBox.y
};
}
SDL_Rect getIntersection(EntityHandle a, EntityHandle b)
{
SDL_Rect aRect = getBoundingBox(a);
SDL_Rect bRect = getBoundingBox(b);
return te::getIntersection(aRect, bRect);
}
void draw(RendererPtr pRenderer)
{
forEachEntity([&](const EntityHandle& handle)
{
auto positionIt = mPositionMap.find(handle);
auto spriteIt = mDimensionMap.find(handle);
if (spriteIt != mDimensionMap.end())
{
Vector2f& pos = positionIt->second;
Vector2i& dim = spriteIt->second;
SDL_SetRenderDrawColor(pRenderer.get(), 0xFF, 0xFF, 0xFF, 0xFF);
SDL_Rect rect = {
(int)pos.x - (dim.x / 2),
(int)pos.y - (dim.y / 2),
dim.x,
dim.y
};
SDL_RenderFillRect(pRenderer.get(), &rect);
}
});
}
void forEachEntity(const std::function<void(const EntityHandle&)>& func)
{
std::for_each(mEntities.begin(), mEntities.end(), func);
}
private:
std::shared_ptr<lua_State> mpL;
EntityHandle mHandleCount;
std::vector<EntityHandle> mEntities;
std::map<EntityHandle, Vector2f> mPositionMap;
std::map<EntityHandle, Vector2f> mVelocityMap;
std::map<EntityHandle, Vector2i> mBoundingBoxMap;
std::map<EntityHandle, Vector2i> mDimensionMap;
luabridge::LuaRef mKeyPressTable;
luabridge::LuaRef mKeyReleaseTable;
std::map<EntityPair, luabridge::LuaRef> mCollisionHandlerMap;
};
}
int main(int argc, char** argv)
{
te::Initialization init;
LuaGameState state;
const int WIDTH = 640;
const int HEIGHT = 480;
te::WindowPtr pWindow = te::wrapWindow(
SDL_CreateWindow("Pong", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WIDTH, HEIGHT, SDL_WINDOW_SHOWN)
);
te::RendererPtr pRenderer = te::createRenderer(pWindow);
SDL_Event e;
bool running = true;
Uint32 FPS = 60;
Uint32 TIME_PER_FRAME = 1000 / FPS;
Uint64 t0 = SDL_GetPerformanceCounter();
while (running)
{
while (SDL_PollEvent(&e) != 0)
{
if (e.type == SDL_QUIT)
{
running = false;
}
state.processInput(e);
}
Uint64 now = SDL_GetPerformanceCounter();
float dt = (float)(now - t0) / SDL_GetPerformanceFrequency();
state.update(dt);
SDL_SetRenderDrawColor(pRenderer.get(), 0x00, 0x00, 0x00, 0xFF);
SDL_RenderClear(pRenderer.get());
state.draw(pRenderer);
SDL_RenderPresent(pRenderer.get());
t0 = now;
}
return 0;
}
<commit_msg>Destroy entities safely with pending queue<commit_after>#include <SDL.h>
#include <iostream>
#include <math.h>
#include <vector>
#include <map>
#include <functional>
#include <algorithm>
#include <lua.hpp>
#include <LuaBridge.h>
#include "types.h"
#include "wrappers.h"
#include "auxiliary.h"
#include "entity.h"
#include "commands.h"
#include "player.h"
using namespace te;
namespace te
{
class LuaGameState
{
public:
LuaGameState(const std::string& filename = "init.lua")
: mpL(luaL_newstate(), [](lua_State* L){ lua_close(L); })
, mHandleCount(0)
, mEntities()
, mPositionMap()
, mVelocityMap()
, mBoundingBoxMap()
, mDimensionMap()
, mPendingDestroys()
, mKeyPressTable(luabridge::newTable(mpL.get()))
, mKeyReleaseTable(luabridge::newTable(mpL.get()))
, mCollisionHandlerMap()
{
lua_State* pL = mpL.get();
luaL_openlibs(pL);
luabridge::getGlobalNamespace(pL)
.beginClass<LuaGameState>("GameState")
.addFunction("createEntity", &LuaGameState::createEntity)
.addFunction("setPosition", &LuaGameState::setPosition)
.addFunction("getPosition", &LuaGameState::getPosition)
.addFunction("setVelocity", &LuaGameState::setVelocity)
.addFunction("getVelocity", &LuaGameState::getVelocity)
.addFunction("setBoundingBox", &LuaGameState::setBoundingBox)
.addFunction("getBoundingBox", &LuaGameState::getBoundingBox)
.addFunction("getIntersection", &LuaGameState::getIntersection)
.addFunction("setSprite", &LuaGameState::setSprite)
.addFunction("handleCollision", &LuaGameState::handleCollision)
.addFunction("destroyEntity", &LuaGameState::addPendingDestroy)
.addFunction("registerKeyPressTable", &LuaGameState::registerKeyPressTable)
.addFunction("registerKeyReleaseTable", &LuaGameState::registerKeyReleaseTable)
.endClass()
.beginClass<Vector2f>("Vector2")
.addConstructor<void(*)(void)>()
.addConstructor<void(*)(float, float)>()
.addData("x", &te::Vector2f::x)
.addData("y", &te::Vector2f::y)
.endClass()
.addFunction<te::Vector2f(*)(te::Vector2f, te::Vector2f)>("addV", &te::operator+)
.addFunction<te::Vector2f(*)(te::Vector2f, te::Vector2f)>("subtractV", &te::operator-)
.addFunction<te::Vector2f(*)(float, te::Vector2f)>("multiplyV", &te::operator*)
.addFunction<te::Vector2f(*)(te::Vector2f, float)>("divideV", &te::operator/)
.addFunction<float(*)(te::Vector2f)>("lengthV", &te::length)
.addFunction<te::Vector2f(*)(te::Vector2f)>("normalizeV", &te::normalize)
.beginClass<SDL_Rect>("Rect")
.addData("h", &SDL_Rect::h)
.addData("w", &SDL_Rect::w)
.addData("x", &SDL_Rect::x)
.addData("y", &SDL_Rect::y)
.endClass();
luabridge::push(pL, this);
lua_setglobal(pL, "game");
luaL_dofile(pL, filename.c_str());
luabridge::getGlobal(pL, "main")();
}
typedef unsigned int EntityHandle;
typedef std::pair<EntityHandle, EntityHandle> EntityPair;
EntityHandle createEntity(const Vector2f& position, const Vector2f& velocity)
{
EntityHandle handle = mHandleCount++;
mEntities.push_back(handle);
mPositionMap.insert(std::make_pair(handle, position));
mVelocityMap.insert(std::make_pair(handle, velocity));
mBoundingBoxMap.insert(std::make_pair(handle, Vector2i(0, 0)));
return handle;
}
void setPosition(EntityHandle handle, const Vector2f& position)
{
if (!exists(handle)) return;
mPositionMap[handle] = position;
}
Vector2f getPosition(EntityHandle handle)
{
if (!exists(handle)) return Vector2f(0.f, 0.f);
return mPositionMap[handle];
}
void setVelocity(EntityHandle handle, const Vector2f& velocity)
{
if (!exists(handle)) return;
mVelocityMap[handle] = velocity;
}
Vector2f getVelocity(EntityHandle handle)
{
if (!exists(handle)) return Vector2f(0.f, 0.f);
return mVelocityMap[handle];
}
void setBoundingBox(EntityHandle handle, const Vector2f& dimensions)
{
if (!exists(handle)) return;
mBoundingBoxMap[handle] = convertVector2<int>(dimensions);
}
void setSprite(EntityHandle handle, const Vector2f& dimensions)
{
if (!exists(handle)) return;
insertOrAssign(mDimensionMap, std::make_pair(
handle, convertVector2<int>(dimensions)));
}
void handleCollision(EntityHandle e1, EntityHandle e2, luabridge::LuaRef handler)
{
if (!exists(e1) || !exists(e2)) return;
auto key = std::make_pair(e1, e2);
auto it = mCollisionHandlerMap.find(key);
if (it == mCollisionHandlerMap.end())
{
mCollisionHandlerMap.insert(std::make_pair(
key,
handler));
}
else
{
it->second = handler;
}
}
void registerKeyPressTable(luabridge::LuaRef table)
{
mKeyPressTable = table;
}
void registerKeyReleaseTable(luabridge::LuaRef table)
{
mKeyReleaseTable = table;
}
bool exists(EntityHandle handle)
{
auto it = std::find(std::begin(mEntities), std::end(mEntities), handle);
return it != std::end(mEntities);
}
void addPendingDestroy(EntityHandle handle)
{
mPendingDestroys.push_back(handle);
}
void destroyEntity(EntityHandle handle)
{
if (!exists(handle)) return;
auto positionIt = mPositionMap.find(handle);
if (positionIt != mPositionMap.end())
{
mPositionMap.erase(positionIt);
}
auto velocityIt = mVelocityMap.find(handle);
if (velocityIt != mVelocityMap.end())
{
mVelocityMap.erase(velocityIt);
}
auto boundingBoxIt = mBoundingBoxMap.find(handle);
if (boundingBoxIt != mBoundingBoxMap.end())
{
mBoundingBoxMap.erase(boundingBoxIt);
}
auto dimensionIt = mDimensionMap.find(handle);
if (dimensionIt != mDimensionMap.end())
{
mDimensionMap.erase(dimensionIt);
}
mEntities.erase(
std::remove(mEntities.begin(), mEntities.end(), handle),
mEntities.end());
}
void destroyEntities()
{
std::for_each(
mPendingDestroys.begin(),
mPendingDestroys.end(),
[&](const EntityHandle& handle)
{
destroyEntity(handle);
});
mPendingDestroys.clear();
}
void processInput(const SDL_Event& evt)
{
if (evt.type == SDL_KEYDOWN)
{
if (mKeyPressTable[evt.key.keysym.sym].isFunction())
{
mKeyPressTable[evt.key.keysym.sym]();
}
}
else if (evt.type == SDL_KEYUP)
{
if (mKeyReleaseTable[evt.key.keysym.sym].isFunction())
{
mKeyReleaseTable[evt.key.keysym.sym]();
}
}
}
void update(float dt)
{
forEachEntity([&](const EntityHandle& handle)
{
mPositionMap[handle] += dt * mVelocityMap[handle];
});
std::for_each(
mCollisionHandlerMap.begin(),
mCollisionHandlerMap.end(),
[&](std::pair<const EntityPair, luabridge::LuaRef> kv)
{
if (checkCollision(
getBoundingBox(kv.first.first),
getBoundingBox(kv.first.second)))
{
kv.second(kv.first.first, kv.first.second, dt);
}
});
destroyEntities();
}
SDL_Rect getBoundingBox(EntityHandle handle)
{
Vector2f position = mPositionMap[handle];
Vector2i boundingBox = mBoundingBoxMap[handle];
return SDL_Rect{
(int)position.x - (boundingBox.x / 2),
(int)position.y - (boundingBox.y / 2),
boundingBox.x,
boundingBox.y
};
}
SDL_Rect getIntersection(EntityHandle a, EntityHandle b)
{
SDL_Rect aRect = getBoundingBox(a);
SDL_Rect bRect = getBoundingBox(b);
return te::getIntersection(aRect, bRect);
}
void draw(RendererPtr pRenderer)
{
forEachEntity([&](const EntityHandle& handle)
{
auto positionIt = mPositionMap.find(handle);
auto spriteIt = mDimensionMap.find(handle);
if (spriteIt != mDimensionMap.end())
{
Vector2f& pos = positionIt->second;
Vector2i& dim = spriteIt->second;
SDL_SetRenderDrawColor(pRenderer.get(), 0xFF, 0xFF, 0xFF, 0xFF);
SDL_Rect rect = {
(int)pos.x - (dim.x / 2),
(int)pos.y - (dim.y / 2),
dim.x,
dim.y
};
SDL_RenderFillRect(pRenderer.get(), &rect);
}
});
}
void forEachEntity(const std::function<void(const EntityHandle&)>& func)
{
std::for_each(mEntities.begin(), mEntities.end(), func);
}
private:
std::shared_ptr<lua_State> mpL;
EntityHandle mHandleCount;
std::vector<EntityHandle> mEntities;
std::map<EntityHandle, Vector2f> mPositionMap;
std::map<EntityHandle, Vector2f> mVelocityMap;
std::map<EntityHandle, Vector2i> mBoundingBoxMap;
std::map<EntityHandle, Vector2i> mDimensionMap;
std::vector<EntityHandle> mPendingDestroys;
luabridge::LuaRef mKeyPressTable;
luabridge::LuaRef mKeyReleaseTable;
std::map<EntityPair, luabridge::LuaRef> mCollisionHandlerMap;
};
}
int main(int argc, char** argv)
{
te::Initialization init;
LuaGameState state;
const int WIDTH = 640;
const int HEIGHT = 480;
te::WindowPtr pWindow = te::wrapWindow(
SDL_CreateWindow("Pong", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WIDTH, HEIGHT, SDL_WINDOW_SHOWN)
);
te::RendererPtr pRenderer = te::createRenderer(pWindow);
SDL_Event e;
bool running = true;
Uint32 FPS = 60;
Uint32 TIME_PER_FRAME = 1000 / FPS;
Uint64 t0 = SDL_GetPerformanceCounter();
while (running)
{
while (SDL_PollEvent(&e) != 0)
{
if (e.type == SDL_QUIT)
{
running = false;
}
state.processInput(e);
}
Uint64 now = SDL_GetPerformanceCounter();
float dt = (float)(now - t0) / SDL_GetPerformanceFrequency();
state.update(dt);
SDL_SetRenderDrawColor(pRenderer.get(), 0x00, 0x00, 0x00, 0xFF);
SDL_RenderClear(pRenderer.get());
state.draw(pRenderer);
SDL_RenderPresent(pRenderer.get());
t0 = now;
}
return 0;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2011 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/stringprintf.h"
#include "chrome/browser/sync/profile_sync_service_harness.h"
#include "chrome/browser/sync/test/integration/extensions_helper.h"
#include "chrome/browser/sync/test/integration/performance/sync_timing_helper.h"
#include "chrome/browser/sync/test/integration/sync_test.h"
using extensions_helper::AllProfilesHaveSameExtensions;
using extensions_helper::AllProfilesHaveSameExtensionsAsVerifier;
using extensions_helper::DisableExtension;
using extensions_helper::EnableExtension;
using extensions_helper::GetInstalledExtensions;
using extensions_helper::InstallExtension;
using extensions_helper::InstallExtensionsPendingForSync;
using extensions_helper::IsExtensionEnabled;
using extensions_helper::UninstallExtension;
// TODO(braffert): Replicate these tests for apps.
static const int kNumExtensions = 150;
class ExtensionsSyncPerfTest : public SyncTest {
public:
ExtensionsSyncPerfTest()
: SyncTest(TWO_CLIENT),
extension_number_(0) {}
// Adds |num_extensions| new unique extensions to |profile|.
void AddExtensions(int profile, int num_extensions);
// Updates the enabled/disabled state for all extensions in |profile|.
void UpdateExtensions(int profile);
// Uninstalls all currently installed extensions from |profile|.
void RemoveExtensions(int profile);
// Returns the number of currently installed extensions for |profile|.
int GetExtensionCount(int profile);
private:
int extension_number_;
DISALLOW_COPY_AND_ASSIGN(ExtensionsSyncPerfTest);
};
void ExtensionsSyncPerfTest::AddExtensions(int profile, int num_extensions) {
for (int i = 0; i < num_extensions; ++i) {
InstallExtension(GetProfile(profile), extension_number_++);
}
}
void ExtensionsSyncPerfTest::UpdateExtensions(int profile) {
std::vector<int> extensions = GetInstalledExtensions(GetProfile(profile));
for (std::vector<int>::iterator it = extensions.begin();
it != extensions.end(); ++it) {
if (IsExtensionEnabled(GetProfile(profile), *it)) {
DisableExtension(GetProfile(profile), *it);
} else {
EnableExtension(GetProfile(profile), *it);
}
}
}
int ExtensionsSyncPerfTest::GetExtensionCount(int profile) {
return GetInstalledExtensions(GetProfile(profile)).size();
}
void ExtensionsSyncPerfTest::RemoveExtensions(int profile) {
std::vector<int> extensions = GetInstalledExtensions(GetProfile(profile));
for (std::vector<int>::iterator it = extensions.begin();
it != extensions.end(); ++it) {
UninstallExtension(GetProfile(profile), *it);
}
}
IN_PROC_BROWSER_TEST_F(ExtensionsSyncPerfTest, P0) {
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
int num_default_extensions = GetExtensionCount(0);
int expected_extension_count = num_default_extensions + kNumExtensions;
// TCM ID - 7563874.
AddExtensions(0, kNumExtensions);
base::TimeDelta dt =
SyncTimingHelper::TimeMutualSyncCycle(GetClient(0), GetClient(1));
InstallExtensionsPendingForSync(GetProfile(1));
ASSERT_EQ(expected_extension_count, GetExtensionCount(1));
SyncTimingHelper::PrintResult("extensions", "add_extensions", dt);
// TCM ID - 7655397.
UpdateExtensions(0);
dt = SyncTimingHelper::TimeMutualSyncCycle(GetClient(0), GetClient(1));
ASSERT_EQ(expected_extension_count, GetExtensionCount(1));
SyncTimingHelper::PrintResult("extensions", "update_extensions", dt);
// TCM ID - 7567721.
RemoveExtensions(0);
dt = SyncTimingHelper::TimeMutualSyncCycle(GetClient(0), GetClient(1));
ASSERT_EQ(num_default_extensions, GetExtensionCount(1));
SyncTimingHelper::PrintResult("extensions", "delete_extensions", dt);
}
<commit_msg>Performance - Disabled ExtensionsSyncPerfTest on Windows to fix the windows performance bots to go green<commit_after>// Copyright (c) 2012 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/stringprintf.h"
#include "chrome/browser/sync/profile_sync_service_harness.h"
#include "chrome/browser/sync/test/integration/extensions_helper.h"
#include "chrome/browser/sync/test/integration/performance/sync_timing_helper.h"
#include "chrome/browser/sync/test/integration/sync_test.h"
using extensions_helper::AllProfilesHaveSameExtensions;
using extensions_helper::AllProfilesHaveSameExtensionsAsVerifier;
using extensions_helper::DisableExtension;
using extensions_helper::EnableExtension;
using extensions_helper::GetInstalledExtensions;
using extensions_helper::InstallExtension;
using extensions_helper::InstallExtensionsPendingForSync;
using extensions_helper::IsExtensionEnabled;
using extensions_helper::UninstallExtension;
// TODO(braffert): Replicate these tests for apps.
static const int kNumExtensions = 150;
class ExtensionsSyncPerfTest : public SyncTest {
public:
ExtensionsSyncPerfTest()
: SyncTest(TWO_CLIENT),
extension_number_(0) {}
// Adds |num_extensions| new unique extensions to |profile|.
void AddExtensions(int profile, int num_extensions);
// Updates the enabled/disabled state for all extensions in |profile|.
void UpdateExtensions(int profile);
// Uninstalls all currently installed extensions from |profile|.
void RemoveExtensions(int profile);
// Returns the number of currently installed extensions for |profile|.
int GetExtensionCount(int profile);
private:
int extension_number_;
DISALLOW_COPY_AND_ASSIGN(ExtensionsSyncPerfTest);
};
void ExtensionsSyncPerfTest::AddExtensions(int profile, int num_extensions) {
for (int i = 0; i < num_extensions; ++i) {
InstallExtension(GetProfile(profile), extension_number_++);
}
}
void ExtensionsSyncPerfTest::UpdateExtensions(int profile) {
std::vector<int> extensions = GetInstalledExtensions(GetProfile(profile));
for (std::vector<int>::iterator it = extensions.begin();
it != extensions.end(); ++it) {
if (IsExtensionEnabled(GetProfile(profile), *it)) {
DisableExtension(GetProfile(profile), *it);
} else {
EnableExtension(GetProfile(profile), *it);
}
}
}
int ExtensionsSyncPerfTest::GetExtensionCount(int profile) {
return GetInstalledExtensions(GetProfile(profile)).size();
}
void ExtensionsSyncPerfTest::RemoveExtensions(int profile) {
std::vector<int> extensions = GetInstalledExtensions(GetProfile(profile));
for (std::vector<int>::iterator it = extensions.begin();
it != extensions.end(); ++it) {
UninstallExtension(GetProfile(profile), *it);
}
}
// Flaky on Windows, see http://crbug.com/111072
#if defined(OS_WIN)
#define MAYBE_P0 DISABLED_P0
#else
#define MAYBE_P0 P0
#endif
IN_PROC_BROWSER_TEST_F(ExtensionsSyncPerfTest, MAYBE_P0) {
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
int num_default_extensions = GetExtensionCount(0);
int expected_extension_count = num_default_extensions + kNumExtensions;
// TCM ID - 7563874.
AddExtensions(0, kNumExtensions);
base::TimeDelta dt =
SyncTimingHelper::TimeMutualSyncCycle(GetClient(0), GetClient(1));
InstallExtensionsPendingForSync(GetProfile(1));
ASSERT_EQ(expected_extension_count, GetExtensionCount(1));
SyncTimingHelper::PrintResult("extensions", "add_extensions", dt);
// TCM ID - 7655397.
UpdateExtensions(0);
dt = SyncTimingHelper::TimeMutualSyncCycle(GetClient(0), GetClient(1));
ASSERT_EQ(expected_extension_count, GetExtensionCount(1));
SyncTimingHelper::PrintResult("extensions", "update_extensions", dt);
// TCM ID - 7567721.
RemoveExtensions(0);
dt = SyncTimingHelper::TimeMutualSyncCycle(GetClient(0), GetClient(1));
ASSERT_EQ(num_default_extensions, GetExtensionCount(1));
SyncTimingHelper::PrintResult("extensions", "delete_extensions", dt);
}
<|endoftext|>
|
<commit_before>#include "gc.hh"
#include "atomic.hh"
#include "radix.hh"
#include "cpputil.hh"
#include "hwvm.hh"
#include "uwq.hh"
#include "distref.hh"
#include "bit_spinlock.hh"
#include "radix_array.hh"
#include "kalloc.hh"
#include "page_info.hh"
struct padded_length;
using std::atomic;
// A virtual memory descriptor that maintains metadata for pages in an
// address space. This plays a similar role to the more traditional
// "virtual memory area," but this does not know its size (it could
// represent a single page or the entire address space).
struct vmdesc
{
enum {
// Bit used for radix tree range locking
FLAG_LOCK_BIT = 0,
FLAG_LOCK = 1<<FLAG_LOCK_BIT,
// Set if this virtual page frame has been mapped
FLAG_MAPPED = 1<<1,
// Set if this virtual page frame is copy-on-write. A write fault
// to this page frame should copy page and unset the COW bit. A
// read fault should map the existing page read-only. This flag
// should be zero if this VPF has no backing page.
FLAG_COW = 1<<2,
// Set if this page frame maps anonymous memory. Cleared if this
// page frame maps a file (in which case ip and start are used).
FLAG_ANON = 1<<3,
};
// Flags
u64 flags;
// The physical page mapped in this frame, or null if no page has
// been allocated for this frame.
sref<class page_info> page;
// XXX We could pack the following fields into a union if there's
// anything we can overlap with them for anonymous memory. However,
// then we have to use C++11 unrestricted unions because of the
// sref, so we'd have to define all of vmdesc's special methods
// ourselves.
// The file mapped at this page frame.
sref<struct inode> inode;
// If a file is mapped at this page frame, the virtual address of
// that file's 0 byte. For anonymous memory, this must be 0. We
// record this instead of the page frame's offset in the file so
// that a range of page frames mapping a sequence of pages from a
// file will be identical (and hence compressable in the radix
// tree).
intptr_t start;
// Construct a descriptor for unmapped memory.
vmdesc() : flags(0), start(0) { }
// Construct a descriptor that maps the beginning of ip's file to
// virtual address start (which may be negative).
vmdesc(const sref<struct inode> &ip, intptr_t start)
: flags(FLAG_MAPPED), inode(ip), start(start) { }
// The anonymous memory descriptor.
static struct vmdesc anon_desc;
// Radix_array element methods
bit_spinlock get_lock()
{
return bit_spinlock(&flags, FLAG_LOCK_BIT);
}
bool is_set() const
{
return flags & FLAG_MAPPED;
}
private:
vmdesc(u64 flags)
: flags(flags), page(), inode(), start() { }
};
void to_stream(class print_stream *s, const vmdesc &vmd);
// An address space. This manages the mapping from virtual addresses
// to virtual memory descriptors.
struct vmap {
struct radix vmas;
static vmap* alloc();
atomic<u64> ref;
char *const kshared;
void decref();
void incref();
// Copy this vmap's structure and share pages copy-on-write.
vmap* copy(proc_pgmap* pgmap);
// Map desc from virtual addresses start to start+len.
long insert(const vmdesc &desc, uptr start, uptr len, proc_pgmap* pgmap,
bool dotlb = true);
// Unmap from virtual addresses start to start+len.
int remove(uptr start, uptr len, proc_pgmap* pgmap);
int pagefault(uptr va, u32 err, proc_pgmap* pgmap);
// Map virtual address va in this address space to a kernel virtual
// address, performing the equivalent of a read page fault if
// necessary. Returns nullptr if va is not mapped. Needless to
// say, this mapping is only valid within the returned page.
void* pagelookup(uptr va);
// Copy len bytes from p to user address va in vmap. Most useful
// when vmap is not the current page table.
int copyout(uptr va, void *p, u64 len);
int sbrk(ssize_t n, uptr *addr);
void add_pgmap(proc_pgmap* pgmap);
void rem_pgmap(proc_pgmap* pgmap);
// Print this vmap to the console
void dump();
uptr brk_; // Top of heap
private:
vmap();
vmap(const vmap&);
vmap& operator=(const vmap&);
~vmap();
NEW_DELETE_OPS(vmap)
uptr unmapped_area(size_t n);
// Virtual page frames
typedef radix_array<vmdesc, USERTOP / PGSIZE, PGSIZE,
kalloc_allocator<vmdesc> > vpf_array;
vpf_array vpfs_;
struct spinlock brklock_;
enum class access_type
{
READ, WRITE
};
// Ensure there is a backing page at @c it. The caller is
// responsible for ensuring that there is a mapping at @c it and for
// locking vpfs_ at @c it. This throws bad_alloc if a page must be
// allocated and cannot be.
page_info *ensure_page(const vpf_array::iterator &it, access_type type);
// XXX(sbw) most likely an awful hash function
static u64 proc_pgmap_hash(proc_pgmap* const & p)
{
return (u64) p;
}
xns<proc_pgmap*, proc_pgmap*, proc_pgmap_hash> pgmap_list_;
};
<commit_msg>vm: Fix crash with large mappings<commit_after>#include "gc.hh"
#include "atomic.hh"
#include "radix.hh"
#include "cpputil.hh"
#include "hwvm.hh"
#include "uwq.hh"
#include "distref.hh"
#include "bit_spinlock.hh"
#include "radix_array.hh"
#include "kalloc.hh"
#include "page_info.hh"
struct padded_length;
using std::atomic;
// A virtual memory descriptor that maintains metadata for pages in an
// address space. This plays a similar role to the more traditional
// "virtual memory area," but this does not know its size (it could
// represent a single page or the entire address space).
struct vmdesc
{
enum {
// Bit used for radix tree range locking
FLAG_LOCK_BIT = 0,
FLAG_LOCK = 1<<FLAG_LOCK_BIT,
// Set if this virtual page frame has been mapped
FLAG_MAPPED = 1<<1,
// Set if this virtual page frame is copy-on-write. A write fault
// to this page frame should copy page and unset the COW bit. A
// read fault should map the existing page read-only. This flag
// should be zero if this VPF has no backing page.
FLAG_COW = 1<<2,
// Set if this page frame maps anonymous memory. Cleared if this
// page frame maps a file (in which case ip and start are used).
FLAG_ANON = 1<<3,
};
// Flags
u64 flags;
// The physical page mapped in this frame, or null if no page has
// been allocated for this frame.
sref<class page_info> page;
// XXX We could pack the following fields into a union if there's
// anything we can overlap with them for anonymous memory. However,
// then we have to use C++11 unrestricted unions because of the
// sref, so we'd have to define all of vmdesc's special methods
// ourselves.
// The file mapped at this page frame.
sref<struct inode> inode;
// If a file is mapped at this page frame, the virtual address of
// that file's 0 byte. For anonymous memory, this must be 0. We
// record this instead of the page frame's offset in the file so
// that a range of page frames mapping a sequence of pages from a
// file will be identical (and hence compressable in the radix
// tree).
intptr_t start;
// Construct a descriptor for unmapped memory.
vmdesc() : flags(0), start(0) { }
// Construct a descriptor that maps the beginning of ip's file to
// virtual address start (which may be negative).
vmdesc(const sref<struct inode> &ip, intptr_t start)
: flags(FLAG_MAPPED), inode(ip), start(start) { }
// The anonymous memory descriptor.
static struct vmdesc anon_desc;
// Radix_array element methods
bit_spinlock get_lock()
{
return bit_spinlock(&flags, FLAG_LOCK_BIT);
}
bool is_set() const
{
return flags & FLAG_MAPPED;
}
// We need new/delete so the radix_array can allocate external nodes
// when performing node compression.
NEW_DELETE_OPS(vmdesc)
private:
vmdesc(u64 flags)
: flags(flags), page(), inode(), start() { }
};
void to_stream(class print_stream *s, const vmdesc &vmd);
// An address space. This manages the mapping from virtual addresses
// to virtual memory descriptors.
struct vmap {
struct radix vmas;
static vmap* alloc();
atomic<u64> ref;
char *const kshared;
void decref();
void incref();
// Copy this vmap's structure and share pages copy-on-write.
vmap* copy(proc_pgmap* pgmap);
// Map desc from virtual addresses start to start+len.
long insert(const vmdesc &desc, uptr start, uptr len, proc_pgmap* pgmap,
bool dotlb = true);
// Unmap from virtual addresses start to start+len.
int remove(uptr start, uptr len, proc_pgmap* pgmap);
int pagefault(uptr va, u32 err, proc_pgmap* pgmap);
// Map virtual address va in this address space to a kernel virtual
// address, performing the equivalent of a read page fault if
// necessary. Returns nullptr if va is not mapped. Needless to
// say, this mapping is only valid within the returned page.
void* pagelookup(uptr va);
// Copy len bytes from p to user address va in vmap. Most useful
// when vmap is not the current page table.
int copyout(uptr va, void *p, u64 len);
int sbrk(ssize_t n, uptr *addr);
void add_pgmap(proc_pgmap* pgmap);
void rem_pgmap(proc_pgmap* pgmap);
// Print this vmap to the console
void dump();
uptr brk_; // Top of heap
private:
vmap();
vmap(const vmap&);
vmap& operator=(const vmap&);
~vmap();
NEW_DELETE_OPS(vmap)
uptr unmapped_area(size_t n);
// Virtual page frames
typedef radix_array<vmdesc, USERTOP / PGSIZE, PGSIZE,
kalloc_allocator<vmdesc> > vpf_array;
vpf_array vpfs_;
struct spinlock brklock_;
enum class access_type
{
READ, WRITE
};
// Ensure there is a backing page at @c it. The caller is
// responsible for ensuring that there is a mapping at @c it and for
// locking vpfs_ at @c it. This throws bad_alloc if a page must be
// allocated and cannot be.
page_info *ensure_page(const vpf_array::iterator &it, access_type type);
// XXX(sbw) most likely an awful hash function
static u64 proc_pgmap_hash(proc_pgmap* const & p)
{
return (u64) p;
}
xns<proc_pgmap*, proc_pgmap*, proc_pgmap_hash> pgmap_list_;
};
<|endoftext|>
|
<commit_before>#include "stdafx.h"
#include "LogQueryImpl.h"
#include "LogItem.h"
#include "LogQueryResult.h"
#include "FilterParser.h"
#include "PatternServiceImpl.h"
using namespace mrl::utility;
LogQueryImpl::LogQueryImpl()
: taskWnd(new SimpleTaskMessageWindow())
, monitorThread(NULL)
, monitoring(false) {
}
LogQueryImpl::~LogQueryImpl() {
if (monitoring && monitorThread) {
monitoring = false;
monitorThread->join();
delete monitorThread;
}
reset();
delete taskWnd;
}
bool LogQueryImpl::load(const tstring& filePath) {
this->filePath = filePath;
startMonitor();
return true;
}
const tstring& LogQueryImpl::getFilePath() const {
return filePath;
}
void LogQueryImpl::setSelected(const LogItem* item) {
for (unsigned j = 0; j < logItems.size(); j++) {
LogItem* p = logItems[j];
p->selected = (item == p);
}
notifyGeneralDataChanged();
}
LogItem* LogQueryImpl::getSelected() const {
auto i = find_if(logItems.begin(), logItems.end(), [] (LogItem* p) {
return p->selected;
});
if (i != logItems.end()) {
return *i;
} else {
return NULL;
}
}
LogQueryResult* LogQueryImpl::query(const tstring& criteria, bool quiet) {
LogQueryResult* cachedResult = queryCache[criteria];
if (!cachedResult) {
cachedResult = queryImpl(criteria);
if (cachedResult) {
queryCache[criteria] = cachedResult;
}
}
if (!quiet) notifyQueryResultChanged(criteria, cachedResult);
return cachedResult;
}
LogQueryResult* LogQueryImpl::queryImpl(const tstring& criteria) {
// UNDONE: 把parser改为tstring兼容
#ifdef _UNICODE
string filter = mrl::utility::codeconv::unicodeToAscii(criteria);
#else
string filter& = criteria;
#endif
try {
FilterParser parser;
parser.compile(filter);
vector<LogItem*> queryResult;
for (auto i = logItems.begin(); i != logItems.end(); i++) {
LogItem* item = *i;
#ifdef _UNICODE
string line = mrl::utility::codeconv::unicodeToAscii(item->text);
#else
string line& = item->text;
#endif
if (parser.rootNode()->match(line)) {
queryResult.push_back(item);
}
}
return new LogQueryResult(queryResult);
} catch (...) {
return nullptr;
}
}
void LogQueryImpl::startMonitor() {
monitorThread = new boost::thread(([this] () {
monitoring = true;
while (monitoring) {
// UNDONE: 优化
::Sleep(500);
vector<LogItem*> logItems;
loadFile(logItems);
// UNDONE: 简单比较
if (this->logItems.size() != logItems.size()) {
DEBUG_INFO(_T("监测到文件变化"));
LogQueryImpl* that = this;
taskWnd->post(new SimpleTask([that, logItems] () {
that->reset(logItems);
}))->wait();
} else {
for_each(logItems.begin(), logItems.end(), [] (LogItem* p) {
delete p;
});
}
} // while monitoring
DEBUG_INFO(_T("监控线程退出!"));
}));
}
void LogQueryImpl::reset(const vector<LogItem*>& logItems) {
for_each(this->logItems.begin(), this->logItems.end(), [] (LogItem* p) {
delete p;
});
this->logItems = logItems;
for_each(this->queryCache.begin(), this->queryCache.end(), [] (const pair<tstring, LogQueryResult*>& p) {
delete p.second;
});
queryCache.clear();
notifyFileChanged();
}
void LogQueryImpl::reset() {
reset(vector<LogItem*>());
}
void LogQueryImpl::loadFile(vector<LogItem*>& logItems) {
HANDLE file = ::CreateFile(filePath.c_str(), GENERIC_READ, FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (file != INVALID_HANDLE_VALUE) {
DWORD fileSize = ::GetFileSize(file, NULL);
char* buffer = new char[fileSize + 1];
DWORD readSize = 0;
// 从头重新读取文件
::SetFilePointer(file, 0, NULL, FILE_BEGIN);
if (::ReadFile(file, buffer, fileSize + 1, &readSize, NULL)) {
buffer[readSize] = 0;
istringstream iss(buffer);
string line;
unsigned lineNum = 0;
while (iss.good()) {
std::getline(iss, line);
LogItem* item = new LogItem();
item->line = lineNum++;
#ifdef _UNICODE
item->text = mrl::utility::codeconv::asciiToUnicode(line);
#else
item->text = line;
#endif
item->selected = false;
logItems.push_back(item);
}
}
delete[] buffer;
::CloseHandle(file);
}
}<commit_msg>使用GetFileSize大幅提升监控性能<commit_after>#include "stdafx.h"
#include "LogQueryImpl.h"
#include "LogItem.h"
#include "LogQueryResult.h"
#include "FilterParser.h"
#include "PatternServiceImpl.h"
using namespace mrl::utility;
LogQueryImpl::LogQueryImpl()
: taskWnd(new SimpleTaskMessageWindow())
, monitorThread(NULL)
, monitoring(false) {
}
LogQueryImpl::~LogQueryImpl() {
if (monitoring && monitorThread) {
monitoring = false;
monitorThread->join();
delete monitorThread;
}
reset();
delete taskWnd;
}
bool LogQueryImpl::load(const tstring& filePath) {
this->filePath = filePath;
startMonitor();
return true;
}
const tstring& LogQueryImpl::getFilePath() const {
return filePath;
}
void LogQueryImpl::setSelected(const LogItem* item) {
for (unsigned j = 0; j < logItems.size(); j++) {
LogItem* p = logItems[j];
p->selected = (item == p);
}
notifyGeneralDataChanged();
}
LogItem* LogQueryImpl::getSelected() const {
auto i = find_if(logItems.begin(), logItems.end(), [] (LogItem* p) {
return p->selected;
});
if (i != logItems.end()) {
return *i;
} else {
return NULL;
}
}
LogQueryResult* LogQueryImpl::query(const tstring& criteria, bool quiet) {
LogQueryResult* cachedResult = queryCache[criteria];
if (!cachedResult) {
cachedResult = queryImpl(criteria);
if (cachedResult) {
queryCache[criteria] = cachedResult;
}
}
if (!quiet) notifyQueryResultChanged(criteria, cachedResult);
return cachedResult;
}
LogQueryResult* LogQueryImpl::queryImpl(const tstring& criteria) {
// UNDONE: 把parser改为tstring兼容
#ifdef _UNICODE
string filter = mrl::utility::codeconv::unicodeToAscii(criteria);
#else
string filter& = criteria;
#endif
try {
FilterParser parser;
parser.compile(filter);
vector<LogItem*> queryResult;
for (auto i = logItems.begin(); i != logItems.end(); i++) {
LogItem* item = *i;
#ifdef _UNICODE
string line = mrl::utility::codeconv::unicodeToAscii(item->text);
#else
string line& = item->text;
#endif
if (parser.rootNode()->match(line)) {
queryResult.push_back(item);
}
}
return new LogQueryResult(queryResult);
} catch (...) {
return nullptr;
}
}
unsigned getFileSize(const tstring& filePath) {
HANDLE file = ::CreateFile(filePath.c_str(), GENERIC_READ, FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
DWORD ret = ::GetFileSize(file, NULL);
::CloseHandle(file);
return ret;
}
void LogQueryImpl::startMonitor() {
monitorThread = new boost::thread(([this] () {
monitoring = true;
unsigned lastSize = 0;
while (monitoring) {
// UNDONE: 优化
::Sleep(500);
unsigned size = getFileSize(filePath);
if (size == lastSize) continue;
lastSize = size;
vector<LogItem*> logItems;
loadFile(logItems);
// UNDONE: 简单比较
if (this->logItems.size() != logItems.size()) {
DEBUG_INFO(_T("监测到文件变化"));
LogQueryImpl* that = this;
taskWnd->post(new SimpleTask([that, logItems] () {
that->reset(logItems);
}))->wait();
} else {
for_each(logItems.begin(), logItems.end(), [] (LogItem* p) {
delete p;
});
}
} // while monitoring
DEBUG_INFO(_T("监控线程退出!"));
}));
}
void LogQueryImpl::reset(const vector<LogItem*>& logItems) {
for_each(this->logItems.begin(), this->logItems.end(), [] (LogItem* p) {
delete p;
});
this->logItems = logItems;
for_each(this->queryCache.begin(), this->queryCache.end(), [] (const pair<tstring, LogQueryResult*>& p) {
delete p.second;
});
queryCache.clear();
notifyFileChanged();
}
void LogQueryImpl::reset() {
reset(vector<LogItem*>());
}
void LogQueryImpl::loadFile(vector<LogItem*>& logItems) {
HANDLE file = ::CreateFile(filePath.c_str(), GENERIC_READ, FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (file != INVALID_HANDLE_VALUE) {
DWORD fileSize = ::GetFileSize(file, NULL);
char* buffer = new char[fileSize + 1];
DWORD readSize = 0;
// 从头重新读取文件
::SetFilePointer(file, 0, NULL, FILE_BEGIN);
if (::ReadFile(file, buffer, fileSize + 1, &readSize, NULL)) {
buffer[readSize] = 0;
istringstream iss(buffer);
string line;
unsigned lineNum = 0;
while (iss.good()) {
std::getline(iss, line);
LogItem* item = new LogItem();
item->line = lineNum++;
#ifdef _UNICODE
item->text = mrl::utility::codeconv::asciiToUnicode(line);
#else
item->text = line;
#endif
item->selected = false;
logItems.push_back(item);
}
}
delete[] buffer;
::CloseHandle(file);
}
}<|endoftext|>
|
<commit_before>/*
* Copyright 2016 Adam Chyła, adam@chyla.org
* All rights reserved. Distributed under the terms of the MIT License.
*/
#include "network_trainer.h"
#include <patlms/util/run_partially.h>
#include <algorithm>
#include <vector>
#include <fstream>
#include <boost/log/trivial.hpp>
#include "src/bash/analyzer/detail/command_summary_divider/command_summary_divider.h"
#include "src/library/fann/fann_wrapper.h"
#include "src/library/fann/fann_guard.h"
namespace bash
{
namespace analyzer
{
namespace detail
{
namespace network_trainer
{
NetworkTrainerPtr NetworkTrainer::Create(::bash::database::detail::DatabaseFunctionsInterfacePtr database_functions,
::database::detail::GeneralDatabaseFunctionsInterfacePtr general_database_functions,
const std::string &neural_network_data_directory) {
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::Create: Function call";
auto fann_wrapper = ::library::fann::FannWrapper::Create();
return Create(database_functions, general_database_functions, neural_network_data_directory, fann_wrapper);
}
NetworkTrainerPtr NetworkTrainer::Create(::bash::database::detail::DatabaseFunctionsInterfacePtr database_functions,
::database::detail::GeneralDatabaseFunctionsInterfacePtr general_database_functions,
const std::string &neural_network_data_directory,
::library::fann::detail::FannWrapperInterfacePtr fann_wrapper) {
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::Create: Function call";
return NetworkTrainerPtr(new NetworkTrainer(database_functions, general_database_functions, neural_network_data_directory, fann_wrapper));
}
void NetworkTrainer::Train() {
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::Train: Function call";
auto configurations = database_functions_->GetAnomalyDetectionConfigurations();
for (const auto &c : configurations) {
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::Train: Is configuration changed for agent " << c.agent_name_id << "?: " << c.changed;
if (c.changed) {
CreateLearningSetFile(c);
CreateNetworkConfiguration(c);
}
}
}
NetworkTrainer::NetworkTrainer(::bash::database::detail::DatabaseFunctionsInterfacePtr database_functions,
::database::detail::GeneralDatabaseFunctionsInterfacePtr general_database_functions,
const std::string &neural_network_data_directory,
::library::fann::detail::FannWrapperInterfacePtr fann_wrapper) :
database_functions_(database_functions),
general_database_functions_(general_database_functions),
neural_network_data_directory_(neural_network_data_directory),
fann_wrapper_(fann_wrapper) {
}
void NetworkTrainer::CreateLearningSetFile(const ::bash::database::type::AnomalyDetectionConfiguration &configuration) {
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Function call";
auto users = database_functions_->GetUsersIdsFromSelectedDailyStatisticsInConfiguration(configuration.id);
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Found " << users.size() << " users";
constexpr::database::type::RowsCount MAX_ROWS_IN_MEMORY = 100;
constexpr unsigned int number_of_inputs = 100;
unsigned int number_of_outputs = users.size();
long long learning_set_size = database_functions_->CountSelectedDailyStatisticsWithoutUnknownClassificationInConfiguration(configuration.id);
std::string file_path = neural_network_data_directory_ + "/training-" + std::to_string(configuration.id) + ".data";
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Number of inputs: " << number_of_inputs;
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Number of outputs: " << number_of_outputs;
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Learning set size: " << learning_set_size;
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Training file path: " << file_path;
std::vector<double> input;
input.resize(number_of_inputs, 0);
std::vector<int> output;
output.resize(number_of_outputs, -1);
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Opening training file";
std::fstream file(file_path.c_str(), std::ios::out | std::ios::trunc);
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Writing training data";
file << learning_set_size << ' ' << number_of_inputs << ' ' << number_of_outputs << '\n';
auto selected_commands_ids = database_functions_->GetMarkedCommandsIds(configuration.id);
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Found " << selected_commands_ids.size() << " selected commands ids";
for (const auto &id : selected_commands_ids)
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: id: " << id;
command_summary_divider::CommandSummaryDivider divider;
unsigned selected_commands_position = 0;
unsigned commands_statistics_position = 0;
int user_output_position = 0;
for (const auto &user_id : users) {
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Writing data for user id (from database) " << user_id;
auto daily_user_statistics_count = database_functions_->CountSelectedDailyUserStatisticsWithoutUnknownClassificationFromConfigurationByUser(configuration.id, user_id);
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Found " << daily_user_statistics_count << " daily user statistics";
util::RunPartially(MAX_ROWS_IN_MEMORY, daily_user_statistics_count, [&](long long part_count, long long offset) {
auto daily_user_statistics = database_functions_->GetSelectedDailyUserStatisticsWithoutUnknownClassificationFromConfigurationByUser(configuration.id, user_id, part_count, offset);
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Found " << daily_user_statistics.size() << " statistics in part";
for (const auto &statistic : daily_user_statistics) {
std::fill(input.begin(), input.end(), 0);
auto commands_statistics = database_functions_->GetSelectedDailyUserCommandsStatistics(statistic.id);
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Found " << commands_statistics.size() << " selected daily user commands statistics with statistic id " << statistic.id;
selected_commands_position = 0;
commands_statistics_position = 0;
while (selected_commands_position < selected_commands_ids.size()
&& commands_statistics_position < commands_statistics.size()) {
const auto &command_statistic = commands_statistics.at(commands_statistics_position);
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Position " << selected_commands_position;
if (command_statistic.command_id == selected_commands_ids.at(selected_commands_position)) {
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Found command with id " << command_statistic.command_id;
input.at(selected_commands_position) = command_statistic.summary;
commands_statistics_position++;
}
selected_commands_position++;
}
std::transform(input.begin(), input.end(), input.begin(), divider);
if (statistic.classification == ::database::type::Classification::ANOMALY)
output.at(user_output_position) = -1;
else if (statistic.classification == ::database::type::Classification::NORMAL)
output.at(user_output_position) = 1;
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Classification set: " << output.at(user_output_position);
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Saving to file";
for (const auto &v : input)
file << v << " ";
file << '\n';
for (const auto &v : output)
file << v << " ";
file << '\n';
}
});
output.at(user_output_position) = -1;
user_output_position++;
}
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Closing training file";
file.close();
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Done";
}
void NetworkTrainer::CreateNetworkConfiguration(const ::bash::database::type::AnomalyDetectionConfiguration &configuration) {
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateNetworkConfiguration: Done";
auto users = database_functions_->GetUsersIdsFromSelectedDailyStatisticsInConfiguration(configuration.id);
constexpr::database::type::RowsCount MAX_ROWS_IN_MEMORY = 100;
constexpr unsigned int number_of_inputs = 100;
constexpr unsigned int number_of_layers = 3;
constexpr unsigned int number_of_hidden_neurons = 3;
const unsigned int number_of_outputs = users.size();
constexpr float desired_error = 0.001f;
constexpr unsigned int max_epochs = 100;
constexpr unsigned int epochs_between_reports = max_epochs;
const std::string file_path = neural_network_data_directory_ + "/training-" + std::to_string(configuration.id) + ".data";
const std::string network_configuration_file_path = neural_network_data_directory_ + "/network-" + std::to_string(configuration.id) + ".data";
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateNetworkConfiguration: Creating network";
struct fann *ann = fann_wrapper_->CreateStandard(number_of_layers, number_of_inputs, number_of_hidden_neurons, number_of_outputs);
::library::fann::FannGuard fann_guard(ann);
fann_wrapper_->SetActivationFunctionHidden(ann, FANN_SIGMOID);
fann_wrapper_->SetActivationFunctionOutput(ann, FANN_SIGMOID);
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateNetworkConfiguration: Training network";
fann_wrapper_->TrainOnFile(ann, file_path, max_epochs, epochs_between_reports, desired_error);
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateNetworkConfiguration: Saving network to file: " << network_configuration_file_path;
fann_wrapper_->Save(ann, network_configuration_file_path);
}
}
}
}
}
<commit_msg>Mark configuration as unchanged<commit_after>/*
* Copyright 2016 Adam Chyła, adam@chyla.org
* All rights reserved. Distributed under the terms of the MIT License.
*/
#include "network_trainer.h"
#include <patlms/util/run_partially.h>
#include <algorithm>
#include <vector>
#include <fstream>
#include <boost/log/trivial.hpp>
#include "src/bash/analyzer/detail/command_summary_divider/command_summary_divider.h"
#include "src/library/fann/fann_wrapper.h"
#include "src/library/fann/fann_guard.h"
namespace bash
{
namespace analyzer
{
namespace detail
{
namespace network_trainer
{
NetworkTrainerPtr NetworkTrainer::Create(::bash::database::detail::DatabaseFunctionsInterfacePtr database_functions,
::database::detail::GeneralDatabaseFunctionsInterfacePtr general_database_functions,
const std::string &neural_network_data_directory) {
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::Create: Function call";
auto fann_wrapper = ::library::fann::FannWrapper::Create();
return Create(database_functions, general_database_functions, neural_network_data_directory, fann_wrapper);
}
NetworkTrainerPtr NetworkTrainer::Create(::bash::database::detail::DatabaseFunctionsInterfacePtr database_functions,
::database::detail::GeneralDatabaseFunctionsInterfacePtr general_database_functions,
const std::string &neural_network_data_directory,
::library::fann::detail::FannWrapperInterfacePtr fann_wrapper) {
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::Create: Function call";
return NetworkTrainerPtr(new NetworkTrainer(database_functions, general_database_functions, neural_network_data_directory, fann_wrapper));
}
void NetworkTrainer::Train() {
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::Train: Function call";
auto configurations = database_functions_->GetAnomalyDetectionConfigurations();
for (const auto &c : configurations) {
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::Train: Is configuration changed for agent " << c.agent_name_id << "?: " << c.changed;
if (c.changed) {
CreateLearningSetFile(c);
CreateNetworkConfiguration(c);
database_functions_->MarkConfigurationAsUnchanged(c.id);
}
}
}
NetworkTrainer::NetworkTrainer(::bash::database::detail::DatabaseFunctionsInterfacePtr database_functions,
::database::detail::GeneralDatabaseFunctionsInterfacePtr general_database_functions,
const std::string &neural_network_data_directory,
::library::fann::detail::FannWrapperInterfacePtr fann_wrapper) :
database_functions_(database_functions),
general_database_functions_(general_database_functions),
neural_network_data_directory_(neural_network_data_directory),
fann_wrapper_(fann_wrapper) {
}
void NetworkTrainer::CreateLearningSetFile(const ::bash::database::type::AnomalyDetectionConfiguration &configuration) {
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Function call";
auto users = database_functions_->GetUsersIdsFromSelectedDailyStatisticsInConfiguration(configuration.id);
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Found " << users.size() << " users";
constexpr::database::type::RowsCount MAX_ROWS_IN_MEMORY = 100;
constexpr unsigned int number_of_inputs = 100;
unsigned int number_of_outputs = users.size();
long long learning_set_size = database_functions_->CountSelectedDailyStatisticsWithoutUnknownClassificationInConfiguration(configuration.id);
std::string file_path = neural_network_data_directory_ + "/training-" + std::to_string(configuration.id) + ".data";
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Number of inputs: " << number_of_inputs;
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Number of outputs: " << number_of_outputs;
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Learning set size: " << learning_set_size;
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Training file path: " << file_path;
std::vector<double> input;
input.resize(number_of_inputs, 0);
std::vector<int> output;
output.resize(number_of_outputs, -1);
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Opening training file";
std::fstream file(file_path.c_str(), std::ios::out | std::ios::trunc);
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Writing training data";
file << learning_set_size << ' ' << number_of_inputs << ' ' << number_of_outputs << '\n';
auto selected_commands_ids = database_functions_->GetMarkedCommandsIds(configuration.id);
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Found " << selected_commands_ids.size() << " selected commands ids";
for (const auto &id : selected_commands_ids)
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: id: " << id;
command_summary_divider::CommandSummaryDivider divider;
unsigned selected_commands_position = 0;
unsigned commands_statistics_position = 0;
int user_output_position = 0;
for (const auto &user_id : users) {
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Writing data for user id (from database) " << user_id;
auto daily_user_statistics_count = database_functions_->CountSelectedDailyUserStatisticsWithoutUnknownClassificationFromConfigurationByUser(configuration.id, user_id);
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Found " << daily_user_statistics_count << " daily user statistics";
util::RunPartially(MAX_ROWS_IN_MEMORY, daily_user_statistics_count, [&](long long part_count, long long offset) {
auto daily_user_statistics = database_functions_->GetSelectedDailyUserStatisticsWithoutUnknownClassificationFromConfigurationByUser(configuration.id, user_id, part_count, offset);
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Found " << daily_user_statistics.size() << " statistics in part";
for (const auto &statistic : daily_user_statistics) {
std::fill(input.begin(), input.end(), 0);
auto commands_statistics = database_functions_->GetSelectedDailyUserCommandsStatistics(statistic.id);
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Found " << commands_statistics.size() << " selected daily user commands statistics with statistic id " << statistic.id;
selected_commands_position = 0;
commands_statistics_position = 0;
while (selected_commands_position < selected_commands_ids.size()
&& commands_statistics_position < commands_statistics.size()) {
const auto &command_statistic = commands_statistics.at(commands_statistics_position);
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Position " << selected_commands_position;
if (command_statistic.command_id == selected_commands_ids.at(selected_commands_position)) {
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Found command with id " << command_statistic.command_id;
input.at(selected_commands_position) = command_statistic.summary;
commands_statistics_position++;
}
selected_commands_position++;
}
std::transform(input.begin(), input.end(), input.begin(), divider);
if (statistic.classification == ::database::type::Classification::ANOMALY)
output.at(user_output_position) = -1;
else if (statistic.classification == ::database::type::Classification::NORMAL)
output.at(user_output_position) = 1;
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Classification set: " << output.at(user_output_position);
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Saving to file";
for (const auto &v : input)
file << v << " ";
file << '\n';
for (const auto &v : output)
file << v << " ";
file << '\n';
}
});
output.at(user_output_position) = -1;
user_output_position++;
}
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Closing training file";
file.close();
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Done";
}
void NetworkTrainer::CreateNetworkConfiguration(const ::bash::database::type::AnomalyDetectionConfiguration &configuration) {
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateNetworkConfiguration: Done";
auto users = database_functions_->GetUsersIdsFromSelectedDailyStatisticsInConfiguration(configuration.id);
constexpr::database::type::RowsCount MAX_ROWS_IN_MEMORY = 100;
constexpr unsigned int number_of_inputs = 100;
constexpr unsigned int number_of_layers = 3;
constexpr unsigned int number_of_hidden_neurons = 3;
const unsigned int number_of_outputs = users.size();
constexpr float desired_error = 0.001f;
constexpr unsigned int max_epochs = 100;
constexpr unsigned int epochs_between_reports = max_epochs;
const std::string file_path = neural_network_data_directory_ + "/training-" + std::to_string(configuration.id) + ".data";
const std::string network_configuration_file_path = neural_network_data_directory_ + "/network-" + std::to_string(configuration.id) + ".data";
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateNetworkConfiguration: Creating network";
struct fann *ann = fann_wrapper_->CreateStandard(number_of_layers, number_of_inputs, number_of_hidden_neurons, number_of_outputs);
::library::fann::FannGuard fann_guard(ann);
fann_wrapper_->SetActivationFunctionHidden(ann, FANN_SIGMOID);
fann_wrapper_->SetActivationFunctionOutput(ann, FANN_SIGMOID);
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateNetworkConfiguration: Training network";
fann_wrapper_->TrainOnFile(ann, file_path, max_epochs, epochs_between_reports, desired_error);
BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateNetworkConfiguration: Saving network to file: " << network_configuration_file_path;
fann_wrapper_->Save(ann, network_configuration_file_path);
}
}
}
}
}
<|endoftext|>
|
<commit_before>#pragma once
#include "wrd-deps.hpp"
// World는 객체 안에서 다른 객체에 접근하는 접근자함수들에 경우에는 DelayingNullCorruption으로 인해 객체가 Null이라고 해도 Null을 반환할뿐 프로그램이 죽지는 않는다.
// 접근자 아닌 경우에는 "속도문제" 로 인해 수행하지 않는다.
// 또한 반환형이 객체에 대한 레퍼런스나 포인터가 아닌경우에도 정상적인 반환값과 겹칠 수있기 때문에 체크하지 않는다.
#define WRD_IS_NULL_2(VALUE, RET) \
if((VALUE.isNull())) { \
RET.warn(#VALUE); \
return RET; \
}
#define WRD_IS_NULL_1(VALUE) \
WRD_IS_NULL_2(VALUE, NullPtr)
#define WRD_IS_NULL(...) WRD_OVERLOAD(WRD_IS_NULL, __VA_ARGS__)
// multiple NULL check macro:
// if you need to check plenty arguments to be checked null
// and return value will be same, you can accomplish it conveniently
// with this macro.
//
// usage:
// WRD_IS_NULL(arg1, -1)
// WRD_IS_NULL(arg2, -1)
// WRD_IS_NULL(arg3, -1)
// or
// WRD_ARE_NULL(-1, arg1, arg2, arg3)
#define _ARE_NULL(VALUE, RET) WRD_IS_NULL(VALUE, RET)
#define WRD_ARE_NULL(RET, ...) NE_EACH_EXPAND(_ARE_NULL, RET, __VA_ARGS__)
#define WRD_IS_THIS_1(TYPE) WRD_IS_NULL(*this, Nuller<Type>::ref)
#define WRD_IS_THIS_0() WRD_IS_THIS_1(This)
#define WRD_IS_THIS(...) WRD_OVERLOAD(WRD_IS_THIS, __VA_ARGS__)
#define WRD_IS_SUPER_1(call) \
if(Super:: call ) return SuperFail;
#define WRD_IS_SUPER_2(res, call) \
Result& res = Super:: call ; \
if(res) return SuperFail;
#define WRD_IS_SUPER(...) WRD_OVERLOAD(WRD_IS_SUPER, __VA_ARGS__)
#define WRD_IS_CONST(RET) \
if((this->isConst())) { \
ConstCancel.warn(#RET); \
return RET; \
}
#define WRD_ASSERT_4(expr, ret, dump, msg) \
if( (expr) ) \
return ret.dump(msg);
#define WRD_ASSERT_3(expr, ret, msg) WRD_ASSERT_4(expr, ret, warn, msg)
#define WRD_ASSERT_2(expr, ret) WRD_ASSERT_4(expr, ret, warn, "")
#define WRD_ASSERT_1(expr) WRD_ASSERT_4(expr, Invalid, warn, "")
#define WRD_ASSERT(...) WRD_OVERLOAD(WRD_ASSERT, __VA_ARGS__)
#define WRD_IS_RES_5(expr, ret, chk, dump, msg) \
{ \
const Result& res = expr; \
WRD_ASSERT(res.chk, ret, dump, msg) \
}
#define WRD_IS_RES_4(expr, chk, dump, msg) WRD_IS_RES_5(expr, res, chk, dump, msg)
#define WRD_IS_RES_3(expr, chk, msg) WRD_IS_RES_5(expr, res, chk, warn, msg)
#define WRD_IS_RES_2(expr, chk) WRD_IS_RES_5(expr, res, chk, warn, #expr)
#define WRD_IS_RES(...) WRD_OVERLOAD(WRD_IS_RES, __VA_ARGS__)
#define WRD_IS_WARN_3(expr, ret, msg) WRD_IS_RES(expr, ret, isWarn(), warn, msg)
#define WRD_IS_WARN_2(expr, ret) WRD_IS_RES(expr, ret, isWarn(), warn, #expr)
#define WRD_IS_WARN_1(expr) WRD_IS_RES(expr, isWarn())
#define WRD_IS_WARN(...) WRD_OVERLOAD(WRD_IS_WARN, __VA_ARGS__)
#define WRD_IS_ERR_3(expr, ret, msg) WRD_IS_RES(expr, ret, isErr(), err, msg)
#define WRD_IS_ERR_2(expr, ret) WRD_IS_RES(expr, ret, isErr(), err, #expr)
#define WRD_IS_ERR_1(expr) WRD_IS_RES(expr, isErr())
#define WRD_IS_ERR(...) WRD_OVERLOAD(WRD_IS_ERR, __VA_ARGS__)
#define WRD_IS_GOOD_3(expr, ret, msg) WRD_IS_RES(expr, ret, isGood(), info, msg)
#define WRD_IS_GOOD_2(expr, ret) WRD_IS_RES(expr, ret, isGood(), info, #expr)
#define WRD_IS_GOOD_1(expr) WRD_IS_RES(expr, isGood())
#define WRD_IS_GOOD(...) WRD_OVERLOAD(WRD_IS_GOOD, __VA_ARGS__)
#define _CLASS_BASE \
public: \
virtual WRD_LAZY_METHOD(Class&, getClass, const, TClass<This>, WRD_VOID) \
TStrong<This> clone() const { return _clone(); } \
virtual TStrong<Instance> _clone() const { \
return new This(*this); \
}
#define WRD_CLASS_2(THIS, SUPER) \
WRD_INHERIT(THIS, SUPER) \
_CLASS_BASE
#define WRD_CLASS_1(THIS) \
WRD_INHERIT(THIS) \
_CLASS_BASE
#define WRD_CLASS(...) WRD_OVERLOAD(WRD_CLASS, __VA_ARGS__)
<commit_msg>- [wrd] fix macro has not been declared error.<commit_after>#pragma once
#include "wrd-deps.hpp"
// World는 객체 안에서 다른 객체에 접근하는 접근자함수들에 경우에는 DelayingNullCorruption으로 인해 객체가 Null이라고 해도 Null을 반환할뿐 프로그램이 죽지는 않는다.
// 접근자 아닌 경우에는 "속도문제" 로 인해 수행하지 않는다.
// 또한 반환형이 객체에 대한 레퍼런스나 포인터가 아닌경우에도 정상적인 반환값과 겹칠 수있기 때문에 체크하지 않는다.
#define WRD_IS_NULL_2(VALUE, RET) \
if((VALUE.isNull())) { \
RET.warn(#VALUE); \
return RET; \
}
#define WRD_IS_NULL_1(VALUE) \
WRD_IS_NULL_2(VALUE, NullPtr)
#define WRD_IS_NULL(...) WRD_OVERLOAD(WRD_IS_NULL, __VA_ARGS__)
// multiple NULL check macro:
// if you need to check plenty arguments to be checked null
// and return value will be same, you can accomplish it conveniently
// with this macro.
//
// usage:
// WRD_IS_NULL(arg1, -1)
// WRD_IS_NULL(arg2, -1)
// WRD_IS_NULL(arg3, -1)
// or
// WRD_ARE_NULL(-1, arg1, arg2, arg3)
#define _ARE_NULL(VALUE, RET) WRD_IS_NULL(VALUE, RET)
#define WRD_ARE_NULL(RET, ...) NE_EACH_EXPAND(_ARE_NULL, RET, __VA_ARGS__)
#define WRD_IS_THIS_1(TYPE) WRD_IS_NULL(*this, Nuller<Type>::ref)
#define WRD_IS_THIS_0() WRD_IS_THIS_1(This)
#define WRD_IS_THIS(...) WRD_OVERLOAD(WRD_IS_THIS, __VA_ARGS__)
#define WRD_IS_SUPER_1(call) \
if(Super:: call ) return SuperFail;
#define WRD_IS_SUPER_2(res, call) \
Result& res = Super:: call ; \
if(res) return SuperFail;
#define WRD_IS_SUPER(...) WRD_OVERLOAD(WRD_IS_SUPER, __VA_ARGS__)
#define WRD_IS_CONST(RET) \
if((this->isConst())) { \
ConstCancel.warn(#RET); \
return RET; \
}
#define WRD_ASSERT_4(expr, ret, dump, msg) \
if( (expr) ) \
return ret.dump(msg);
#define WRD_ASSERT_3(expr, ret, msg) WRD_ASSERT_4(expr, ret, warn, msg)
#define WRD_ASSERT_2(expr, ret) WRD_ASSERT_4(expr, ret, warn, "")
#define WRD_ASSERT_1(expr) WRD_ASSERT_4(expr, Invalid, warn, "")
#define WRD_ASSERT(...) WRD_OVERLOAD(WRD_ASSERT, __VA_ARGS__)
#define WRD_IS_RES_5(expr, ret, chk, dump, msg) \
{ \
const Result& res = expr; \
WRD_ASSERT(res.chk, ret, dump, msg) \
}
#define WRD_IS_RES_4(expr, chk, dump, msg) WRD_IS_RES_5(expr, res, chk, dump, msg)
#define WRD_IS_RES_3(expr, chk, msg) WRD_IS_RES_5(expr, res, chk, warn, msg)
#define WRD_IS_RES_2(expr, chk) WRD_IS_RES_5(expr, res, chk, warn, #expr)
#define WRD_IS_RES(...) WRD_OVERLOAD(WRD_IS_RES, __VA_ARGS__)
#define WRD_IS_WARN_3(expr, ret, msg) WRD_IS_RES(expr, ret, isWarn(), warn, msg)
#define WRD_IS_WARN_2(expr, ret) WRD_IS_RES(expr, ret, isWarn(), warn, #expr)
#define WRD_IS_WARN_1(expr) WRD_IS_RES(expr, isWarn())
#define WRD_IS_WARN(...) WRD_OVERLOAD(WRD_IS_WARN, __VA_ARGS__)
#define WRD_IS_ERR_3(expr, ret, msg) WRD_IS_RES(expr, ret, isErr(), err, msg)
#define WRD_IS_ERR_2(expr, ret) WRD_IS_RES(expr, ret, isErr(), err, #expr)
#define WRD_IS_ERR_1(expr) WRD_IS_RES(expr, isErr())
#define WRD_IS_ERR(...) WRD_OVERLOAD(WRD_IS_ERR, __VA_ARGS__)
#define WRD_IS_GOOD_3(expr, ret, msg) WRD_IS_RES(expr, ret, isGood(), info, msg)
#define WRD_IS_GOOD_2(expr, ret) WRD_IS_RES(expr, ret, isGood(), info, #expr)
#define WRD_IS_GOOD_1(expr) WRD_IS_RES(expr, isGood())
#define WRD_IS_GOOD(...) WRD_OVERLOAD(WRD_IS_GOOD, __VA_ARGS__)
#define _CLASS_BASE \
public: \
virtual WRD_LAZY_METHOD_5(Class&, getClass, const, TClass<This>, WRD_VOID) \
TStrong<This> clone() const { return _clone(); } \
virtual TStrong<Instance> _clone() const { \
return new This(*this); \
}
#define WRD_CLASS_2(THIS, SUPER) \
WRD_INHERIT_2(THIS, SUPER) \
_CLASS_BASE
#define WRD_CLASS_1(THIS) \
WRD_INHERIT_1(THIS) \
_CLASS_BASE
#define WRD_CLASS(...) WRD_OVERLOAD(WRD_CLASS, __VA_ARGS__)
<|endoftext|>
|
<commit_before>#pragma once
#include <xyz/openbmc_project/Sensor/Value/server.hpp>
#include <xyz/openbmc_project/Sensor/Threshold/Warning/server.hpp>
#include <xyz/openbmc_project/Sensor/Threshold/Critical/server.hpp>
#include <sdbusplus/server.hpp>
template <typename T>
using ServerObject = typename sdbusplus::server::object::object<T>;
using ValueInterface = sdbusplus::xyz::openbmc_project::Sensor::server::Value;
using ValueObject = ServerObject<ValueInterface>;
using WarningInterface =
sdbusplus::xyz::openbmc_project::Sensor::Threshold::server::Warning;
using WarningObject = ServerObject<WarningInterface>;
using CriticalInterface =
sdbusplus::xyz::openbmc_project::Sensor::Threshold::server::Critical;
using CriticalObject = ServerObject<CriticalInterface>;
enum class InterfaceType
{
VALUE,
WARN,
CRIT,
};
// vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
<commit_msg>Fix sdbusplus::server::object template wrapper<commit_after>#pragma once
#include <xyz/openbmc_project/Sensor/Value/server.hpp>
#include <xyz/openbmc_project/Sensor/Threshold/Warning/server.hpp>
#include <xyz/openbmc_project/Sensor/Threshold/Critical/server.hpp>
#include <sdbusplus/server.hpp>
template <typename... T>
using ServerObject = typename sdbusplus::server::object::object<T...>;
using ValueInterface = sdbusplus::xyz::openbmc_project::Sensor::server::Value;
using ValueObject = ServerObject<ValueInterface>;
using WarningInterface =
sdbusplus::xyz::openbmc_project::Sensor::Threshold::server::Warning;
using WarningObject = ServerObject<WarningInterface>;
using CriticalInterface =
sdbusplus::xyz::openbmc_project::Sensor::Threshold::server::Critical;
using CriticalObject = ServerObject<CriticalInterface>;
enum class InterfaceType
{
VALUE,
WARN,
CRIT,
};
// vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
<|endoftext|>
|
<commit_before>/*
* CommunityDetectionBenchmark.h
*
* Created on: 16.05.2014
* Author: Klara Reichard (klara.reichard@gmail.com), Marvin Ritter (marvin.ritter@gmail.com)
*/
#ifndef NOGTEST
#include <map>
#include "CommunityDetectionBenchmark.h"
#include "../PLP.h"
#include "../PLM.h"
#include "../Modularity.h"
#include "../../centrality/Betweenness.h"
#include "../../centrality/PageRank.h"
#include "../../auxiliary/Timer.h"
#include "../../structures/Partition.h"
namespace NetworKit {
void CommunityDetectionBenchmark::SetUp() {
}
TEST_F(CommunityDetectionBenchmark, timeClusteringAlgos) {
Aux::Timer timer;
Modularity mod;
// std::string graph = "../graphs/uk-2002.graph";
std::string graph = "../graphs/uk-2007-05.graph";
printf("Reading graph file %s ...\n", graph.c_str());
timer.start();
const Graph G = this->metisReader.read(graph);
timer.stop();
printf("Reading graph took %.1f s\n", timer.elapsedMilliseconds() / 1000.0);
std::map<std::string, CommunityDetectionAlgorithm*> algos = {
std::make_pair("Parallel Label Propagation", (CommunityDetectionAlgorithm*) new PLP),
std::make_pair("Parallel Louvain", (CommunityDetectionAlgorithm*) new PLM)
};
for (auto it = algos.begin(); it != algos.end(); it++) {
Graph Gcopy = G;
printf("Timing %s ...\n", it->first.c_str());
timer.start();
Partition zeta = it->second->run(Gcopy);
timer.stop();
auto communitySizes = zeta.subsetSizes();
printf("%s on %s: %.1f s\n\t# communities: %llu\n\tmodularity: %f\n",
it->first.c_str(), graph.c_str(),
timer.elapsedMilliseconds() / 1000.0,
zeta.numberOfSubsets(),
mod.getQuality(zeta, G));
delete it->second;
}
}
TEST_F(CommunityDetectionBenchmark, timeCentralities) {
Aux::Timer timer;
std::string graph = "../graphs/cond-mat-2005.graph";
const Graph G = this->metisReader.read(graph);
Graph G1 = this->metisReader.read("../graphs/cond-mat.graph");
Graph G2 = this->metisReader.read("../graphs/uk-2002.graph");
std::map<std::string, Centrality*> cens = {
std::make_pair("Betweenness Centrality on cond-mat", (Centrality*) new Betweenness(G1)),
std::make_pair("Page Rank Centrality on uk-2002", (Centrality*) new PageRank(G2, 1e-6))
};
for (auto it = cens.begin(); it != cens.end(); it++) {
timer.start();
it->second->run();
timer.stop();
auto ranking = it->second->ranking();
printf("%s: %.1f s\n\tranking: [(%llu: %f), (%llu: %f), ...]\n",
it->first.c_str(),
timer.elapsedMilliseconds() / 1000.0,
ranking[0].first, ranking[0].second,
ranking[1].first, ranking[1].second);
}
}
} /* namespace NetworKit */
#endif /*NOGTEST */
<commit_msg>updated benchmark to make multiple runs<commit_after>/*
* CommunityDetectionBenchmark.h
*
* Created on: 16.05.2014
* Author: Klara Reichard (klara.reichard@gmail.com), Marvin Ritter (marvin.ritter@gmail.com)
*/
#ifndef NOGTEST
#include <map>
#include <functional>
#include "CommunityDetectionBenchmark.h"
#include "../PLP.h"
#include "../PLM.h"
#include "../Modularity.h"
#include "../../centrality/Betweenness.h"
#include "../../centrality/PageRank.h"
#include "../../auxiliary/Timer.h"
#include "../../structures/Partition.h"
namespace NetworKit {
constexpr int runs = 20;
void CommunityDetectionBenchmark::SetUp() {
}
TEST_F(CommunityDetectionBenchmark, timeClusteringAlgos) {
Aux::Timer timer;
Modularity mod;
// std::string graph = "../graphs/in-2004.graph";
// std::string graph = "../graphs/uk-2002.graph";
std::string graph = "../graphs/uk-2007-05.graph";
printf("Reading graph file %s ...\n", graph.c_str());
timer.start();
const Graph G = this->metisReader.read(graph);
timer.stop();
printf("Reading graph took %.1f s\n", timer.elapsedMilliseconds() / 1000.0);
for (int r = 0; r < runs; r++) {
Graph Gcopy = G;
PLP algo;
timer.start();
Partition zeta = algo.run(Gcopy);
timer.stop();
auto communitySizes = zeta.subsetSizes();
printf("%s on %s: %.1f s\n\t# communities: %lu\n\tmodularity: %f\n",
"Parallel Label Propagation", graph.c_str(),
timer.elapsedMilliseconds() / 1000.0,
zeta.numberOfSubsets(),
mod.getQuality(zeta, G));
}
for (int r = 0; r < runs; r++) {
Graph Gcopy = G;
PLM algo;
timer.start();
Partition zeta = algo.run(Gcopy);
timer.stop();
auto communitySizes = zeta.subsetSizes();
printf("%s on %s: %.1f s\n\t# communities: %lu\n\tmodularity: %f\n",
"Parallel Louvain", graph.c_str(),
timer.elapsedMilliseconds() / 1000.0,
zeta.numberOfSubsets(),
mod.getQuality(zeta, G));
}
}
TEST_F(CommunityDetectionBenchmark, timePageRankCentrality) {
Aux::Timer timer;
std::string graph = "../graphs/uk-2002.graph";
const Graph G = this->metisReader.read(graph);
for (int r = 0; r < runs; r++) {
PageRank cen(G, 1e-6);
timer.start();
cen.run();
timer.stop();
auto ranking = cen.ranking();
printf("%s on %s: %.1f s\n\tranking: [(%lu: %f), (%lu: %f), ...]\n",
"Page Rank Centrality", graph.c_str(),
timer.elapsedMilliseconds() / 1000.0,
ranking[0].first, ranking[0].second,
ranking[1].first, ranking[1].second,
ranking[2].first, ranking[2].second);
}
}
TEST_F(CommunityDetectionBenchmark, timeBetweennessCentrality) {
Aux::Timer timer;
std::string graph = "../graphs/cond-mat-2005.graph";
const Graph G = this->metisReader.read(graph);
for (int r = 0; r < runs; r++) {
Betweenness cen(G);
timer.start();
cen.run();
timer.stop();
auto ranking = cen.ranking();
printf("%s on %s: %.1f s\n\tranking: [(%lu: %f), (%lu: %f), ...]\n",
"Betweenness Centrality", graph.c_str(),
timer.elapsedMilliseconds() / 1000.0,
ranking[0].first, ranking[0].second,
ranking[1].first, ranking[1].second,
ranking[2].first, ranking[2].second);
}
}
} /* namespace NetworKit */
#endif /*NOGTEST */
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: testshl_test.cxx,v $
*
* $Revision: 1.1 $
*
* last change: $Author: lla $ $Date: 2003-01-09 11:06:19 $
*
* 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 <stdio.h>
#ifdef WNT
// #define UNDER_WINDOWS_DEBUGGING
// Nice feature, to debug under windows, install msdev locally and use DebugBreak() to stop a new process at a point you want.
#ifdef UNDER_WINDOWS_DEBUGGING
#include <tools/presys.h>
#include <windows.h>
#include <tools/postsys.h>
#define VCL_NEED_BASETSD
#endif /* UNDER_WINDOWS_DEBUGGING */
#endif /* WNT */
#include <vector>
#ifndef _SAL_TRES_H_
#include <rtl/tres.h>
#endif
#ifndef _TESTSHL_TSTMGR_H_
#include "tstmgr.h"
#endif
#ifndef _RTL_STRING_HXX_
#include <rtl/string.hxx>
#endif
#include <osl/time.h>
using namespace std;
/**
* create bitmap of comandline parameters
*/
sal_uInt32 createFlags( vector< sal_Char* > const& cmdln )
{
sal_uInt32 retflags = rtl_tres_Flag_OK;
vector< sal_Char* >::const_iterator iter = cmdln.begin();
while( iter != cmdln.end() )
{
fprintf( stderr, "%s\n", *iter );
if ( *iter[0] == '-' )
{
rtl::OString item( *iter );
if ( item == "-boom" )
retflags |= rtl_tres_Flag_BOOM;
if ( item == "-verbose" )
retflags |= rtl_tres_Flag_VERBOSE;
if ( item == "-skip" )
retflags |= rtl_tres_Flag_SKIP;
if ( item == "-log" )
retflags |= rtl_tres_Flag_LOG;
if ( item == "-his" )
retflags |= rtl_tres_Flag_HIS;
if ( item == "-time" )
retflags |= rtl_tres_Flag_TIME;
if ( item == "-msg" )
retflags |= rtl_tres_Flag_MSG;
}
iter++;
}
return retflags;
}
sal_uInt32 createFlags(int argc, char* argv[])
{
vector< sal_Char* > cmdln;
sal_Int32 i;
/* collect comandline */
for ( i = 1; i < argc; i++ )
cmdln.push_back( argv[i] );
return createFlags(cmdln);
}
// -----------------------------------------------------------------------------
/**
* display usage screen
*/
void usage()
{
fprintf( stdout,
"USAGE: testshl shlname scename [-boom][-verbose][-log][-his][-msg]\n" );
exit(0);
}
#include <fstream>
#include <cppunit/TestFixture.h>
#include <cppunit/TestCaller.h>
#include <cppunit/TestSuite.h>
#include <cppunit/TestResult.h>
#include <cppunit/TestResultCollector.h>
#include <cppunit/TestAssert.h>
#include <cppunit/TextTestResult.h>
namespace CppunitTest
{
class AStringTest : public CppUnit::TestCase
{
rtl::OString *m_pStr;
public:
AStringTest()
:m_pStr(NULL) {}
void setUp()
{
m_pStr = new rtl::OString("test1");
// throw std::exception("initialization failed.");
}
void tearDown()
{
delete m_pStr;
}
void testEquality()
{
CPPUNIT_ASSERT( *m_pStr == "test1" );
CPPUNIT_ASSERT( (*m_pStr).equalsIgnoreAsciiCase("Test1") );
CPPUNIT_ASSERT( (*m_pStr).equalsIgnoreAsciiCase("Test2") );
CPPUNIT_ASSERT( *m_pStr == "test1" );
CPPUNIT_ASSERT( *m_pStr == "must also fail" );
}
void testEquality2()
{
rtl::OString aStr("test2");
CPPUNIT_ASSERT( aStr == "test2" );
CPPUNIT_ASSERT_MESSAGE("ein vergleichstest", aStr == "test2");
CPPUNIT_ASSERT( aStr == "must also fail" );
}
void testThrow()
{
throw std::exception("an own exception!");
CPPUNIT_ASSERT( *m_pStr == "test2" );
}
};
CppUnit::TestSuite *suite1()
{
CppUnit::TestSuite *suite = new CppUnit::TestSuite( "AStringTest" );
// CppUnit::TestSuite suite;
// CppUnit::TextTestResult result;
suite->addTest( new CppUnit::TestCaller<AStringTest>( "throw test", &AStringTest::testThrow ));
// suite->addTest( new CppUnit::TestCaller<AStringTest>( "test op eq", &AStringTest::testEquality ));
// suite->addTest( new CppUnit::TestCaller<AStringTest>( "test op eq", &AStringTest::testEquality2 ));
return suite;
}
// -----------------------------------------------------------------------------
class ASimpleTest : public CppUnit::TestCase
{
public:
void testEqual()
{
CPPUNIT_ASSERT( 1 == 1 );
}
};
CppUnit::TestSuite *suite2()
{
CppUnit::TestSuite *suite = new CppUnit::TestSuite( "A simple test" );
// CppUnit::TestSuite suite;
// CppUnit::TextTestResult result;
suite->addTest( new CppUnit::TestCaller<ASimpleTest>( "1 == 1", &ASimpleTest::testEqual ));
return suite;
}
// -----------------------------------------------------------------------------
CppUnit::TestSuite *suite()
{
CppUnit::TestSuite *suite = new CppUnit::TestSuite( "A simple test" );
// CppUnit::TestSuite suite;
// CppUnit::TextTestResult result;
suite->addTest( suite1() );
// suite->addTest( suite2() );
return suite;
}
}
void cppunitbased_test()
{
{
// ofstream out("c:\\temp\\output.txt", ios::out);
CppUnit::TextTestResult aResult;
CppUnit::TestSuite* pSuite = CppunitTest::suite();
int nTests = pSuite->countTestCases();
pSuite->run(&aResult);
// aResult.print(out);
cout << aResult;
delete pSuite;
}
exit(1);
}
// ----------------------------------- Main -----------------------------------
#if (defined UNX) || (defined OS2)
int main( int argc, char* argv[] )
#else
int _cdecl main( int argc, char* argv[] )
#endif
{
cppunitbased_test();
tslTestManager hMgr = 0;
/* show usage screen if too less parameters */
if ( argc < 3 )
usage();
#ifdef UNDER_WINDOWS_DEBUGGING
DebugBreak();
#endif
sal_uInt32 nCmdlinebitflags = createFlags( argc, argv );
hMgr = tsl_TestManager_create( argv, argc, nCmdlinebitflags );
tsl_TestManager_run( hMgr );
tsl_TestManager_destroy( hMgr );
return 0;
}
<commit_msg>INTEGRATION: CWS qadev16 (1.1.54); FILE MERGED 2004/02/10 15:06:52 lla 1.1.54.1: #114786# changes to internal tests.<commit_after>/*************************************************************************
*
* $RCSfile: testshl_test.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: obo $ $Date: 2004-03-19 14:43:41 $
*
* 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 <stdio.h>
#ifdef WNT
// #define UNDER_WINDOWS_DEBUGGING
// Nice feature, to debug under windows, install msdev locally and use DebugBreak() to stop a new process at a point you want.
#ifdef UNDER_WINDOWS_DEBUGGING
#include <tools/presys.h>
#include <windows.h>
#include <tools/postsys.h>
#define VCL_NEED_BASETSD
#endif /* UNDER_WINDOWS_DEBUGGING */
#endif /* WNT */
#include <vector>
#ifndef _SAL_TRES_H_
#include <rtl/tres.h>
#endif
#ifndef _TESTSHL_TSTMGR_H_
#include "tstmgr.h"
#endif
#ifndef _RTL_STRING_HXX_
#include <rtl/string.hxx>
#endif
#include <osl/time.h>
using namespace std;
/**
* create bitmap of comandline parameters
*/
sal_uInt32 createFlags( vector< sal_Char* > const& cmdln )
{
sal_uInt32 retflags = rtl_tres_Flag_OK;
vector< sal_Char* >::const_iterator iter = cmdln.begin();
while( iter != cmdln.end() )
{
fprintf( stderr, "%s\n", *iter );
if ( *iter[0] == '-' )
{
rtl::OString item( *iter );
if ( item == "-boom" )
retflags |= rtl_tres_Flag_BOOM;
if ( item == "-verbose" )
retflags |= rtl_tres_Flag_VERBOSE;
if ( item == "-skip" )
retflags |= rtl_tres_Flag_SKIP;
if ( item == "-log" )
retflags |= rtl_tres_Flag_LOG;
if ( item == "-his" )
retflags |= rtl_tres_Flag_HIS;
if ( item == "-time" )
retflags |= rtl_tres_Flag_TIME;
if ( item == "-msg" )
retflags |= rtl_tres_Flag_MSG;
if ( item == "-quiet" )
retflags |= rtl_tres_Flag_QUIET;
}
iter++;
}
return retflags;
}
sal_uInt32 createFlags(int argc, char* argv[])
{
vector< sal_Char* > cmdln;
sal_Int32 i;
/* collect comandline */
for ( i = 1; i < argc; i++ )
cmdln.push_back( argv[i] );
return createFlags(cmdln);
}
// -----------------------------------------------------------------------------
/**
* display usage screen
*/
void usage()
{
fprintf( stdout,
"USAGE: testshl shlname scename [-boom][-verbose][-log][-his][-msg]\n" );
exit(0);
}
#include <fstream>
#include <cppunit/TestFixture.h>
#include <cppunit/TestCaller.h>
#include <cppunit/TestSuite.h>
#include <cppunit/TestResult.h>
#include <cppunit/TestResultCollector.h>
#include <cppunit/TestAssert.h>
#include <cppunit/TextTestResult.h>
namespace CppunitTest
{
class AStringTest : public CppUnit::TestCase
{
rtl::OString *m_pStr;
public:
AStringTest()
:m_pStr(NULL) {}
void setUp()
{
m_pStr = new rtl::OString("test1");
// throw std::exception("initialization failed.");
}
void tearDown()
{
delete m_pStr;
}
void testEquality()
{
CPPUNIT_ASSERT( *m_pStr == "test1" );
CPPUNIT_ASSERT( (*m_pStr).equalsIgnoreAsciiCase("Test1") );
CPPUNIT_ASSERT( (*m_pStr).equalsIgnoreAsciiCase("Test2") );
CPPUNIT_ASSERT( *m_pStr == "test1" );
CPPUNIT_ASSERT( *m_pStr == "must also fail" );
}
void testEquality2()
{
rtl::OString aStr("test2");
CPPUNIT_ASSERT( aStr == "test2" );
CPPUNIT_ASSERT_MESSAGE("ein vergleichstest", aStr == "test2");
CPPUNIT_ASSERT( aStr == "must also fail" );
}
void testThrow()
{
throw std::exception("an own exception!");
CPPUNIT_ASSERT( *m_pStr == "test2" );
}
};
CppUnit::TestSuite *suite1()
{
CppUnit::TestSuite *suite = new CppUnit::TestSuite( "AStringTest" );
// CppUnit::TestSuite suite;
// CppUnit::TextTestResult result;
suite->addTest( new CppUnit::TestCaller<AStringTest>( "throw test", &AStringTest::testThrow ));
// suite->addTest( new CppUnit::TestCaller<AStringTest>( "test op eq", &AStringTest::testEquality ));
// suite->addTest( new CppUnit::TestCaller<AStringTest>( "test op eq", &AStringTest::testEquality2 ));
return suite;
}
// -----------------------------------------------------------------------------
class ASimpleTest : public CppUnit::TestCase
{
public:
void testEqual()
{
CPPUNIT_ASSERT( 1 == 1 );
}
};
CppUnit::TestSuite *suite2()
{
CppUnit::TestSuite *suite = new CppUnit::TestSuite( "A simple test" );
// CppUnit::TestSuite suite;
// CppUnit::TextTestResult result;
suite->addTest( new CppUnit::TestCaller<ASimpleTest>( "1 == 1", &ASimpleTest::testEqual ));
return suite;
}
// -----------------------------------------------------------------------------
CppUnit::TestSuite *suite()
{
CppUnit::TestSuite *suite = new CppUnit::TestSuite( "A simple test" );
// CppUnit::TestSuite suite;
// CppUnit::TextTestResult result;
suite->addTest( suite1() );
// suite->addTest( suite2() );
return suite;
}
}
void cppunitbased_test()
{
{
// ofstream out("c:\\temp\\output.txt", ios::out);
CppUnit::TextTestResult aResult;
CppUnit::TestSuite* pSuite = CppunitTest::suite();
int nTests = pSuite->countTestCases();
pSuite->run(&aResult);
// aResult.print(out);
cout << aResult;
delete pSuite;
}
exit(1);
}
// ----------------------------------- Main -----------------------------------
#if (defined UNX) || (defined OS2)
int main( int argc, char* argv[] )
#else
int _cdecl main( int argc, char* argv[] )
#endif
{
cppunitbased_test();
tslTestManager hMgr = 0;
/* show usage screen if too less parameters */
if ( argc < 3 )
usage();
#ifdef UNDER_WINDOWS_DEBUGGING
DebugBreak();
#endif
sal_uInt32 nCmdlinebitflags = createFlags( argc, argv );
hMgr = tsl_TestManager_create( argv, argc, nCmdlinebitflags );
tsl_TestManager_run( hMgr );
tsl_TestManager_destroy( hMgr );
return 0;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: helpagentdispatcher.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: rt $ $Date: 2005-09-09 01:19:38 $
*
* 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 __FRAMEWORK_DISPATCH_HELPAGENTDISPATCHER_HXX_
#include <dispatch/helpagentdispatcher.hxx>
#endif
#ifndef __FRAMEWORK_THREADHELP_RESETABLEGUARD_HXX_
#include <threadhelp/resetableguard.hxx>
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _TOOLKIT_HELPER_VCLUNOHELPER_HXX_
#include <toolkit/helper/vclunohelper.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _SV_HELP_HXX
#include <vcl/help.hxx>
#endif
#ifndef _COMPHELPER_GUARDING_HXX_
#include <comphelper/guarding.hxx>
#endif
#ifndef INCLUDED_SVTOOLS_HELPOPT_HXX
#include <svtools/helpopt.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
//........................................................................
namespace framework
{
//........................................................................
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::frame;
using namespace ::com::sun::star::util;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::awt;
using namespace ::com::sun::star::lang;
//====================================================================
//= HelpAgentDispatcher
//====================================================================
//--------------------------------------------------------------------
HelpAgentDispatcher::HelpAgentDispatcher( const Reference< XFrame >& _rxParentFrame )
:ThreadHelpBase(&Application::GetSolarMutex())
,m_pContainerWindow(NULL)
,m_pAgentWindow(NULL)
,m_xParentFrame(_rxParentFrame)
{
OSL_ENSURE(m_xParentFrame.is(), "HelpAgentDispatcher::HelpAgentDispatcher: invalid parent frame!");
}
//--------------------------------------------------------------------
HelpAgentDispatcher::~HelpAgentDispatcher()
{
osl_incrementInterlockedCount( &m_refCount );
// we may create new references to ourself below, so ensure the dtor is not called twice ....
closeAgentWindow();
if(m_xAutoCloseTimer.isValid())
m_xAutoCloseTimer->setListener(NULL);
}
//--------------------------------------------------------------------
sal_Bool HelpAgentDispatcher::ensureContainerWindow()
{
if (m_pContainerWindow)
return sal_True;
if (!m_xParentFrame.is())
{
OSL_ENSURE(sal_False, "HelpAgentDispatcher::ensureContainerWindow: have no explicit container window and no frame to obtain an implicit one!");
// error condition, already asserted in the ctor
return sal_False;
}
Reference< XWindow > xContainer = m_xParentFrame->getContainerWindow();
implConstruct(xContainer);
return (NULL != m_pContainerWindow);
}
//--------------------------------------------------------------------
void HelpAgentDispatcher::implConstruct( const Reference< XWindow >& _rxContainer )
{
OSL_ENSURE(!m_pContainerWindow, "HelpAgentDispatcher::implConstruct: not to be called twice!");
OSL_ENSURE(_rxContainer.is(), "HelpAgentDispatcher::implConstruct: invalid container window given!");
m_pContainerWindow = VCLUnoHelper::GetWindow(_rxContainer);
OSL_ENSURE(!_rxContainer.is() || (NULL != m_pContainerWindow), "HelpAgentDispatcher::implConstruct: could not get the implementation of the container!");
}
//--------------------------------------------------------------------
void SAL_CALL HelpAgentDispatcher::dispatch( const URL& _rURL, const Sequence< PropertyValue >& _rArgs ) throw (RuntimeException)
{
ResetableGuard aGuard(m_aLock);
switchURL(_rURL);
}
//--------------------------------------------------------------------
void SAL_CALL HelpAgentDispatcher::addStatusListener( const Reference< XStatusListener >& _rxListener, const URL& _rURL ) throw (RuntimeException)
{
// this is pretty simple: we accept _all_ URLs, and we accept them _always_. So simply notify the listener
// of the initial "available" state and then do nothing.
if (_rxListener.is())
{
FeatureStateEvent aEvent;
aEvent.FeatureURL = _rURL;
aEvent.IsEnabled = sal_True;
aEvent.Requery = sal_False;
_rxListener->statusChanged(aEvent);
}
}
//--------------------------------------------------------------------
void SAL_CALL HelpAgentDispatcher::removeStatusListener( const Reference< XStatusListener >& _rxListener, const URL& _rURL ) throw (RuntimeException)
{
// nothing to do. see addStatusListener
}
//--------------------------------------------------------------------
void SAL_CALL HelpAgentDispatcher::windowResized( const WindowEvent& _rSource ) throw (RuntimeException)
{
positionAgentWindow();
}
//--------------------------------------------------------------------
void SAL_CALL HelpAgentDispatcher::windowMoved( const WindowEvent& _rSource ) throw (RuntimeException)
{
// not interested in
}
//--------------------------------------------------------------------
void SAL_CALL HelpAgentDispatcher::windowShown( const EventObject& _rSource ) throw (RuntimeException)
{
// not interested in
}
//--------------------------------------------------------------------
void SAL_CALL HelpAgentDispatcher::windowHidden( const EventObject& _rSource ) throw (RuntimeException)
{
// not interested in
}
//--------------------------------------------------------------------
void SAL_CALL HelpAgentDispatcher::disposing( const EventObject& _rSource ) throw (RuntimeException)
{
::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > xSelfHold( static_cast< ::com::sun::star::frame::XDispatch* >(this), ::com::sun::star::uno::UNO_QUERY );
// not interested in case the container window is closed (this should be handled by our owner)
// interested in case our agent window is closed (we're the only instance allowed to close it)
if (m_pAgentWindow)
{
Reference< XWindow > xSource(_rSource.Source, UNO_QUERY);
Reference< XWindow > xAgentWindow = VCLUnoHelper::GetInterface(m_pAgentWindow);
if (xSource.get() == xAgentWindow.get())
{ // somebody closed my agent window, but it was not me
agentClosedExternally();
}
}
}
//--------------------------------------------------------------------
void HelpAgentDispatcher::agentClosedExternally()
{
ResetableGuard aGuard(m_aLock);
stopAutoCloseTimer();
m_pAgentWindow = NULL;
}
//--------------------------------------------------------------------
sal_Bool HelpAgentDispatcher::approveURLRequest(const URL& _rURL)
{
SvtHelpOptions aHelpOptions;
sal_Int32 nAllowedToIgnore = aHelpOptions.getAgentIgnoreURLCounter(_rURL.Complete);
return nAllowedToIgnore > 0;
}
//--------------------------------------------------------------------
void HelpAgentDispatcher::switchURL(const URL& _rURL)
{
if (!approveURLRequest(_rURL))
// silently drop the request
return;
// show our agent window
ensureAgentWindow();
// stop the expiration timer for the old URL
stopAutoCloseTimer();
// save the URL
m_sCurrentURL = _rURL.Complete;
// start the expiration timer for the new URL
startAutoCloseTimer();
}
//--------------------------------------------------------------------
void HelpAgentDispatcher::stopAutoCloseTimer()
{
if (!m_xAutoCloseTimer.isValid())
return;
m_xAutoCloseTimer->stop();
}
//--------------------------------------------------------------------
void HelpAgentDispatcher::startAutoCloseTimer()
{
::vos::TTimeValue aAutoCloseTimeout( SvtHelpOptions().GetHelpAgentTimeoutPeriod(), 0 );
if (!m_xAutoCloseTimer.isValid())
{
m_xAutoCloseTimer = new OTimerHelper(aAutoCloseTimeout);
m_xAutoCloseTimer->setListener(this);
}
m_xAutoCloseTimer->setRemainingTime(aAutoCloseTimeout);
m_xAutoCloseTimer->start();
}
//--------------------------------------------------------------------
void HelpAgentDispatcher::helpRequested()
{
ResetableGuard aGuard(m_aLock);
// FIRST stop the timer
stopAutoCloseTimer();
// reset the ignore counter for this URL
SvtHelpOptions().resetAgentIgnoreURLCounter(m_sCurrentURL);
Help* pApplicationHelp = Application::GetHelp();
OSL_ENSURE(pApplicationHelp, "HelpAgentDispatcher::helpRequested: no help system available!");
if (pApplicationHelp)
pApplicationHelp->Start( m_sCurrentURL, NULL );
aGuard.unlock();
closeAgentWindow();
}
//--------------------------------------------------------------------
void HelpAgentDispatcher::closeAgent()
{
// the hint has been ignored by the user (click the closer)
markURLIgnored(m_sCurrentURL);
// close the window
closeAgentWindow();
}
//--------------------------------------------------------------------
void HelpAgentDispatcher::timerExpired()
{
// the hint has been ignored by the user
markURLIgnored(m_sCurrentURL);
// close the window
closeAgentWindow();
}
//--------------------------------------------------------------------
void HelpAgentDispatcher::markURLIgnored( const ::rtl::OUString& _rURL )
{
SvtHelpOptions().decAgentIgnoreURLCounter(_rURL);
}
//--------------------------------------------------------------------
void HelpAgentDispatcher::closeAgentWindow()
{
::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > xSelfHold( static_cast< ::com::sun::star::frame::XDispatch* >(this), ::com::sun::star::uno::UNO_QUERY );
// now acquire the SolarMutex ...
::vos::OGuard aSolarGuard(Application::GetSolarMutex());
// ... and our own mutex
ResetableGuard aGuard(m_aLock);
stopAutoCloseTimer();
if (!m_pAgentWindow)
return;
if (m_pContainerWindow)
{
Reference< XWindow > xContainer = VCLUnoHelper::GetInterface(m_pContainerWindow);
OSL_ENSURE(xContainer.is(), "HelpAgentDispatcher::closeAgentWindow: no UNO interface for the container window!");
if (xContainer.is())
xContainer->removeWindowListener(this);
}
if (m_pAgentWindow)
{
Reference< XWindow > xAgentWindow = VCLUnoHelper::GetInterface(m_pAgentWindow);
OSL_ENSURE(xAgentWindow.is(), "HelpAgentDispatcher::closeAgentWindow: no UNO interface for the agent window!");
if (xAgentWindow.is())
xAgentWindow->removeWindowListener(this);
}
delete m_pAgentWindow;
m_pAgentWindow = NULL;
}
//--------------------------------------------------------------------
void HelpAgentDispatcher::positionAgentWindow()
{
OSL_ENSURE(m_pContainerWindow, "HelpAgentDispatcher::positionAgentWindow: please use ensureContainerWindow!");
OSL_ENSURE(m_pAgentWindow, "HelpAgentDispatcher::positionAgentWindow: to be called with an existing agent window only!");
OSL_ENSURE(m_pAgentWindow->GetParent() == m_pContainerWindow, "HelpAgentDispatcher::positionAgentWindow: invalid window hierarchy!");
const Size aContainerSize = m_pContainerWindow->GetSizePixel();
const Size aAgentSize = m_pAgentWindow->getPreferredSizePixel();
const Point aAgentPos ( aContainerSize.Width() - aAgentSize.Width()
, aContainerSize.Height() - aAgentSize.Height() );
// TODO: use a surrogate if the container window is too small to contain the full-sized agent window
m_pAgentWindow->SetPosSizePixel(aAgentPos, aAgentSize);
}
//--------------------------------------------------------------------
sal_Bool HelpAgentDispatcher::ensureAgentWindow()
{
if (m_pAgentWindow)
return sal_True;
::vos::OGuard aSolarGuard(Application::GetSolarMutex());
if (!ensureContainerWindow())
return sal_False;
// create it
m_pAgentWindow = new ::svt::HelpAgentWindow(m_pContainerWindow);
m_pAgentWindow->setCallback(this);
// add as listener at the agent window in case it is closed by the user (and not by us ourself)
Reference< XWindow > xAgentWindow = VCLUnoHelper::GetInterface(m_pAgentWindow);
OSL_ENSURE(xAgentWindow.is(), "HelpAgentDispatcher::ensureAgentWindow: no UNO interface for the agent window!");
if (xAgentWindow.is())
xAgentWindow->addWindowListener(this);
// add as window listener to the container window so we can maintain the property position of the agent window
Reference< XWindow > xContainer = VCLUnoHelper::GetInterface(m_pContainerWindow);
OSL_ENSURE(xContainer.is(), "HelpAgentDispatcher::ensureAgentWindow: no container window interface!");
if (xContainer.is())
xContainer->addWindowListener(this);
// position it
positionAgentWindow();
// show it
if (m_pContainerWindow->IsVisible())
m_pAgentWindow->Show();
return sal_True;
}
//........................................................................
} // namespace framework
//........................................................................
<commit_msg>INTEGRATION: CWS stacks01 (1.7.44); FILE MERGED 2005/11/03 08:08:36 as 1.7.44.1: #114142# HelpAgentDispatcher use ref counted objects instead pointer; it uses vcl timer instead of osl-threaded timer; remove status listener support (not needed)<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: helpagentdispatcher.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: rt $ $Date: 2005-11-10 16:11:57 $
*
* 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 __FRAMEWORK_DISPATCH_HELPAGENTDISPATCHER_HXX_
#include <dispatch/helpagentdispatcher.hxx>
#endif
#ifndef __FRAMEWORK_THREADHELP_READGUARD_HXX_
#include <threadhelp/readguard.hxx>
#endif
#ifndef __FRAMEWORK_THREADHELP_WRITEGUARD_HXX_
#include <threadhelp/writeguard.hxx>
#endif
#ifndef _COM_SUN_STAR_AWT_XWINDOW2_HPP_
#include <com/sun/star/awt/XWindow2.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_POSSIZE_HPP_
#include <com/sun/star/awt/PosSize.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_SIZE_HPP_
#include <com/sun/star/awt/Size.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_RECTANGLE_HPP_
#include <com/sun/star/awt/Rectangle.hpp>
#endif
#ifndef _TOOLKIT_HELPER_VCLUNOHELPER_HXX_
#include <toolkit/helper/vclunohelper.hxx>
#endif
#ifndef INCLUDED_SVTOOLS_HELPOPT_HXX
#include <svtools/helpopt.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _SV_HELP_HXX
#include <vcl/help.hxx>
#endif
namespace css = ::com::sun::star;
//........................................................................
namespace framework
{
//-----------------------------------------------
DEFINE_XINTERFACE_4(HelpAgentDispatcher ,
OWeakObject ,
DIRECT_INTERFACE (css::lang::XTypeProvider ),
DIRECT_INTERFACE (css::frame::XDispatch ),
DIRECT_INTERFACE (css::awt::XWindowListener),
DIRECT_INTERFACE (css::lang::XEventListener))
//-----------------------------------------------
DEFINE_XTYPEPROVIDER_2(HelpAgentDispatcher ,
css::lang::XTypeProvider,
css::frame::XDispatch )
//--------------------------------------------------------------------
HelpAgentDispatcher::HelpAgentDispatcher( const css::uno::Reference< css::frame::XFrame >& xParentFrame)
: ThreadHelpBase (&Application::GetSolarMutex())
, m_sCurrentURL ( )
, m_xContainerWindow( )
, m_xAgentWindow ( )
, m_aTimer ( )
, m_xSelfHold ( )
{
// It's required that this class has to be contructed with a valid frame.
// And "valid" means: the frame must already bound to a valid container window.
m_xContainerWindow = xParentFrame->getContainerWindow();
}
//--------------------------------------------------------------------
HelpAgentDispatcher::~HelpAgentDispatcher()
{
implts_stopTimer();
implts_ignoreCurrentURL();
// Needed ... because it was create as "new VCLWindow()" ! Such windows must be disposed explicitly.
css::uno::Reference< css::lang::XComponent > xAgentWindow(m_xAgentWindow, css::uno::UNO_QUERY);
if (xAgentWindow.is())
xAgentWindow->dispose();
}
//--------------------------------------------------------------------
void SAL_CALL HelpAgentDispatcher::dispatch(const css::util::URL& aURL ,
const css::uno::Sequence< css::beans::PropertyValue >& lArgs)
throw(css::uno::RuntimeException)
{
// silently drop the request if the new URL was marked to be ignored next time.
sal_Int32 nAllowedToIgnore = SvtHelpOptions().getAgentIgnoreURLCounter(aURL.Complete);
if (nAllowedToIgnore < 1)
return;
// stop the expiration timer for the old URL
// The timer will add the old URL to the list of ignorable URLs.
// So m_sCurrentURL must be set AFTER the timer was stopped !!!
implts_stopTimer();
// SAFE ->
WriteGuard aWriteLock(m_aLock);
m_sCurrentURL = aURL.Complete;
aWriteLock.unlock();
// <- SAFE
// start the expiration timer for the new URL
implts_startTimer();
// make sure the agent window is shown
implts_showAgentWindow();
}
//--------------------------------------------------------------------
void SAL_CALL HelpAgentDispatcher::addStatusListener(const css::uno::Reference< css::frame::XStatusListener >& xListener,
const css::util::URL& aURL )
throw(css::uno::RuntimeException)
{
// no status available
}
//--------------------------------------------------------------------
void SAL_CALL HelpAgentDispatcher::removeStatusListener(const css::uno::Reference< css::frame::XStatusListener >& xListener,
const css::util::URL& aURL )
throw(css::uno::RuntimeException)
{
// no status available
}
//--------------------------------------------------------------------
void SAL_CALL HelpAgentDispatcher::windowResized(const css::awt::WindowEvent& aEvent)
throw(css::uno::RuntimeException)
{
implts_positionAgentWindow();
}
//--------------------------------------------------------------------
void SAL_CALL HelpAgentDispatcher::windowMoved(const css::awt::WindowEvent& aEvent)
throw(css::uno::RuntimeException)
{
implts_positionAgentWindow();
}
//--------------------------------------------------------------------
void SAL_CALL HelpAgentDispatcher::windowShown(const css::lang::EventObject& aEvent)
throw(css::uno::RuntimeException)
{
implts_showAgentWindow();
}
//--------------------------------------------------------------------
void SAL_CALL HelpAgentDispatcher::windowHidden(const css::lang::EventObject& aEvent)
throw(css::uno::RuntimeException)
{
implts_hideAgentWindow();
}
//--------------------------------------------------------------------
void SAL_CALL HelpAgentDispatcher::disposing(const css::lang::EventObject& aEvent)
throw(css::uno::RuntimeException)
{
// SAFE ->
WriteGuard aWriteLock(m_aLock);
// Already disposed ?!
if (! m_xContainerWindow.is())
return;
// Wrong broadcaster ?!
if (aEvent.Source != m_xContainerWindow)
return;
css::uno::Reference< css::uno::XInterface > xSelfHoldUntilMethodEnds(static_cast< css::frame::XDispatch* >(this), css::uno::UNO_QUERY_THROW);
m_xSelfHold.clear();
aWriteLock.unlock();
// <- SAFE
implts_stopTimer();
implts_hideAgentWindow();
implts_ignoreCurrentURL();
// SAFE ->
aWriteLock.lock();
m_xContainerWindow.clear();
css::uno::Reference< css::lang::XComponent > xAgentWindow(m_xAgentWindow, css::uno::UNO_QUERY);
m_xAgentWindow.clear();
aWriteLock.unlock();
// <- SAFE
// Needed ... because it was create as "new VCLWindow()" ! Such windows must be disposed explicitly.
if (xAgentWindow.is())
xAgentWindow->dispose();
}
//--------------------------------------------------------------------
void HelpAgentDispatcher::helpRequested()
{
implts_stopTimer();
implts_hideAgentWindow();
implts_acceptCurrentURL();
}
//-----------------------------------------------
void HelpAgentDispatcher::closeAgent()
{
implts_stopTimer();
implts_hideAgentWindow();
implts_ignoreCurrentURL();
}
//--------------------------------------------------------------------
void HelpAgentDispatcher::implts_acceptCurrentURL()
{
// SAFE ->
WriteGuard aWriteLock(m_aLock);
::rtl::OUString sAcceptedURL = m_sCurrentURL;
m_sCurrentURL = ::rtl::OUString();
aWriteLock.unlock();
// <- SAFE
// We must make sure that this URL isnt marked as ignored by the user.
// Otherwhise the user wont see the corresponding help content in the future.
SvtHelpOptions().resetAgentIgnoreURLCounter(sAcceptedURL);
// show the right help content
// SOLAR SAFE ->
{
::vos::OGuard aSolarLock(Application::GetSolarMutex());
Help* pHelp = Application::GetHelp();
if (pHelp)
pHelp->Start(sAcceptedURL, NULL);
}
// <- SOLAR SAFE
}
//--------------------------------------------------------------------
void HelpAgentDispatcher::implts_ignoreCurrentURL()
{
// SAFE ->
WriteGuard aWriteLock(m_aLock);
::rtl::OUString sIgnoredURL = m_sCurrentURL;
m_sCurrentURL = ::rtl::OUString();
aWriteLock.unlock();
// <- SAFE
if (sIgnoredURL.getLength())
SvtHelpOptions().decAgentIgnoreURLCounter(sIgnoredURL);
}
//--------------------------------------------------------------------
void HelpAgentDispatcher::implts_stopTimer()
{
// SAFE ->
WriteGuard aWriteLock(m_aLock);
m_xSelfHold.clear();
aWriteLock.unlock();
// <- SAFE
// SOLAR SAFE ->
// Timer access needs no "own lock" ! It lives if we live ...
// But it requires locking of the solar mutex ... because it's a vcl based timer.
{
::vos::OGuard aSolarLock(Application::GetSolarMutex());
if (! m_aTimer.IsActive())
return;
m_aTimer.Stop();
}
// <- SOLAR SAFE
}
//--------------------------------------------------------------------
void HelpAgentDispatcher::implts_startTimer()
{
// SOLAR SAFE ->
// Timer access needs no "own lock" ! It lives if we live ...
// But it requires locking of the solar mutex ... because it's a vcl based timer.
{
::vos::OGuard aSolarLock(Application::GetSolarMutex());
if (m_aTimer.IsActive())
return;
}
// <- SOLAR SAFE
// SAFE ->
// Timer uses pointer to this help agent dispatcher ...
// But normaly we are ref counted. So we must make sure that this
// dispatcher isnt killed during the timer runs .-)
WriteGuard aWriteLock(m_aLock);
m_xSelfHold = css::uno::Reference< css::uno::XInterface >(static_cast< css::frame::XDispatch* >(this), css::uno::UNO_QUERY_THROW);
aWriteLock.unlock();
// <- SAFE
sal_Int32 nTime = SvtHelpOptions().GetHelpAgentTimeoutPeriod();
// SOLAR SAFE ->
// Timer access needs no "own lock" ! It lives if we live ...
// But it requires locking of the solar mutex ... because it's a vcl based timer.
{
::vos::OGuard aSolarLock(Application::GetSolarMutex());
m_aTimer.SetTimeout(nTime*1000); // sec => ms !
m_aTimer.Start();
}
}
//-----------------------------------------------
IMPL_LINK(HelpAgentDispatcher, implts_timerExpired, void*, pVoid)
{
// This method is called by using a pointer to us.
// But we must be aware that we can be destroyed hardly
// if our uno reference will be gone!
// => Hold this object alive till this method finish its work.
// SAFE ->
WriteGuard aWriteLock(m_aLock);
css::uno::Reference< css::uno::XInterface > xSelfHoldUntilMethodEnds(static_cast< css::frame::XDispatch* >(this), css::uno::UNO_QUERY_THROW);
m_xSelfHold.clear();
aWriteLock.unlock();
// <- SAFE
implts_hideAgentWindow();
implts_ignoreCurrentURL();
return 0;
}
//--------------------------------------------------------------------
void HelpAgentDispatcher::implts_showAgentWindow()
{
// SAFE ->
ReadGuard aReadLock(m_aLock);
css::uno::Reference< css::awt::XWindow2 > xContainerWindow(m_xContainerWindow, css::uno::UNO_QUERY_THROW);
aReadLock.unlock();
// <- SAFE
css::uno::Reference< css::awt::XWindow > xAgentWindow = implts_ensureAgentWindow();
if (
(xContainerWindow.is() ) &&
(xAgentWindow.is() ) &&
(xContainerWindow->isVisible())
)
{
// make sure that agent window resists at the right place .-)
implts_positionAgentWindow();
xAgentWindow->setVisible(sal_True);
}
}
//--------------------------------------------------------------------
void HelpAgentDispatcher::implts_hideAgentWindow()
{
css::uno::Reference< css::awt::XWindow > xAgentWindow = implts_ensureAgentWindow();
if (xAgentWindow.is())
xAgentWindow->setVisible(sal_False);
}
//--------------------------------------------------------------------
void HelpAgentDispatcher::implts_positionAgentWindow()
{
// SAFE ->
ReadGuard aReadLock(m_aLock);
css::uno::Reference< css::awt::XWindow > xContainerWindow = m_xContainerWindow;
aReadLock.unlock();
// <- SAFE
css::uno::Reference< css::awt::XWindow > xAgentWindow = implts_ensureAgentWindow();
if (
(! xContainerWindow.is()) ||
(! xAgentWindow.is() )
)
return;
::svt::HelpAgentWindow* pAgentWindow = (::svt::HelpAgentWindow*)VCLUnoHelper::GetWindow(xAgentWindow);
const css::awt::Rectangle aContainerSize = xContainerWindow->getPosSize();
const Size aAgentSize = pAgentWindow->getPreferredSizePixel();
sal_Int32 nW = aAgentSize.Width() ;
sal_Int32 nH = aAgentSize.Height();
if (nW < 1)
nW = 100;
if (nH < 1)
nH = 100;
sal_Int32 nX = aContainerSize.Width - nW;
sal_Int32 nY = aContainerSize.Height - nH;
// TODO: use a surrogate if the container window is too small to contain the full-sized agent window
xAgentWindow->setPosSize(nX, nY, nW, nH, css::awt::PosSize::POSSIZE);
}
//--------------------------------------------------------------------
css::uno::Reference< css::awt::XWindow > HelpAgentDispatcher::implts_ensureAgentWindow()
{
// SAFE ->
ReadGuard aReadLock(m_aLock);
if (m_xAgentWindow.is())
return m_xAgentWindow;
css::uno::Reference< css::awt::XWindow > xContainerWindow = m_xContainerWindow;
aReadLock.unlock();
// <- SAFE
if (!xContainerWindow.is())
return css::uno::Reference< css::awt::XWindow >();
::svt::HelpAgentWindow* pAgentWindow = 0;
// SOLAR SAFE ->
{
::vos::OGuard aSolarLock(Application::GetSolarMutex());
// create the agent window
Window* pContainerWindow = VCLUnoHelper::GetWindow(xContainerWindow);
pAgentWindow = new ::svt::HelpAgentWindow(pContainerWindow);
pAgentWindow->setCallback(this);
}
// <- SOLAR SAFE
// SAFE ->
WriteGuard aWriteLock(m_aLock);
m_xAgentWindow = VCLUnoHelper::GetInterface(pAgentWindow);
css::uno::Reference< css::awt::XWindow > xAgentWindow = m_xAgentWindow;
aWriteLock.unlock();
// <- SAFE
// add as window listener to the container window so we can maintain the property position of the agent window
xContainerWindow->addWindowListener(this);
// SOLAR SAFE ->
{
::vos::OGuard aSolarLock(Application::GetSolarMutex());
// establish callback for our internal used timer.
// Note: Its only active, if the timer will be started ...
m_aTimer.SetTimeoutHdl(LINK(this, HelpAgentDispatcher, implts_timerExpired));
}
// <- SOLAR SAFE
return xAgentWindow;
}
} // namespace framework
<|endoftext|>
|
<commit_before>#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include "Models/StateSpace/Multivariate/MultivariateStateSpaceRegressionModel.hpp"
#include "Models/StateSpace/Multivariate/PosteriorSamplers/MultivariateStateSpaceModelSampler.hpp"
#include "cpputil/math_utils.hpp"
#include "cpputil/Ptr.hpp"
namespace py = pybind11;
PYBIND11_DECLARE_HOLDER_TYPE(T, BOOM::Ptr<T>, true);
namespace BayesBoom {
using namespace BOOM;
void MultivariateStateSpaceModel_def(py::module &boom) {
py::class_<MultivariateStateSpaceModelBase,
Model,
BOOM::Ptr<MultivariateStateSpaceModelBase>>(
boom,
"MultivariateStateSpaceModelBase",
py::multiple_inheritance())
.def_property_readonly(
"nseries",
[](const MultivariateStateSpaceModelBase &model) {
return model.nseries();
},
"The number of time series described by the model.")
.def_property_readonly(
"time_dimension",
[](const MultivariateStateSpaceModelBase &model) {
return model.time_dimension();
},
"The number of time points in the model training data.")
.def_property_readonly(
"state_dimension",
[](const MultivariateStateSpaceModelBase &model) {
return model.state_dimension();
},
"The dimension of the state vector shared across all time series.")
.def_property_readonly(
"number_of_state_models",
[](const MultivariateStateSpaceModelBase &model) {
return model.number_of_state_models();
},
"The number state models defining the shared state vector.")
.def_property_readonly(
"log_likelihood",
[](MultivariateStateSpaceModelBase &model) {
return model.log_likelihood();
},
"The log likelihood under the current set of model parameters.")
.def("state_contributions",
[](const MultivariateStateSpaceModelBase &model, int which_state_model) {
return model.state_contributions(which_state_model);
},
py::arg("which_state_model"),
"Args:\n"
" which_state_model: The state model whose contribution is desired.\n"
"\n"
"Returns:\n"
" A Matrix. Element (t, d) is the contrubtion of the specified "
"state model to series d at time t.")
;
py::class_<ConditionallyIndependentMultivariateStateSpaceModelBase,
MultivariateStateSpaceModelBase,
BOOM::Ptr<ConditionallyIndependentMultivariateStateSpaceModelBase>>(
boom,
"ConditionallyIndependentMultivariateStateSpaceModelBase",
py::multiple_inheritance())
;
py::class_<MultivariateTimeSeriesRegressionData,
RegressionData,
BOOM::Ptr<MultivariateTimeSeriesRegressionData>>(
boom,
"MultivariateTimeSeriesRegressionData")
.def(py::init(
[](double y, const Vector &x, int series, int timestamp) {
return new MultivariateTimeSeriesRegressionData(
y, x, series, timestamp);
}),
py::arg("y"),
py::arg("x"),
py::arg("series"),
py::arg("timestamp"),
"Args:\n"
" y: The response variable.\n"
" x: A vector of predictors.\n"
" series: The identifier of the time series (0.. number of series - 1) to\n"
" which this observation belongs.\n"
" timestamp: The time-index of the time series (0.. sample_size - 1)\n"
" containing this observation.\n")
;
py::class_<MultivariateStateSpaceRegressionModel,
ConditionallyIndependentMultivariateStateSpaceModelBase,
PriorPolicy,
BOOM::Ptr<MultivariateStateSpaceRegressionModel>>(
boom,
"MultivariateStateSpaceRegressionModel",
py::multiple_inheritance())
.def(py::init(
[](int xdim, int nseries) {
return new BOOM::MultivariateStateSpaceRegressionModel(
xdim, nseries);
}),
py::arg("xdim"),
py::arg("nseries"),
"Args:\n"
" xdim: The dimension of the predictor variables.\n"
" nseries: The number of time series being modeled.\n")
.def_property_readonly(
"xdim",
[](const MultivariateStateSpaceRegressionModel &model) {
return model.xdim();
},
"Dimension of the vector of predictor variables.")
.def("add_data",
[](MultivariateStateSpaceRegressionModel &model,
const Ptr<MultivariateTimeSeriesRegressionData> &data_point) {
model.add_data(data_point);
},
py::arg("data_point"),
"Args:\n"
" data_point: A MultivariateTimeSeriesRegressionData object\n"
" containing information for a single data point.\n")
.def("add_state",
[](MultivariateStateSpaceRegressionModel &model,
SharedStateModel &state_model) {
model.add_state(Ptr<SharedStateModel>(&state_model));
},
"Args:\n"
" state_model: A SharedStateModel object defining an element of"
" state.\n")
.def("set_method",
[](MultivariateStateSpaceRegressionModel &model,
PosteriorSampler *sampler) {
model.set_method(Ptr<PosteriorSampler>(sampler));
})
.def("set_regression_coefficients",
[](MultivariateStateSpaceRegressionModel &model,
const Matrix &coefficients) {
if (coefficients.nrow() != model.nseries()) {
std::ostringstream err;
err << "The model describes " << model.nseries()
<< " series but the input matrix has "
<< coefficients.nrow() << " rows.";
report_error(err.str());
}
if (coefficients.ncol() != model.xdim()) {
std::ostringstream err;
err << "The model has predictor dimension "
<< model.xdim() << " but the input matrix has "
<< coefficients.ncol() << "columns.";
report_error(err.str());
}
for (int i = 0; i < coefficients.nrow(); ++i) {
model.observation_model()->model(i)->set_Beta(
coefficients.row(i));
}
},
"Args:\n\n"
" coefficients: A boom.Matrix with model.nseries rows and "
"model.xdim columns. Each row contains the regression "
"coefficients for a specific series.\n")
.def("set_regression_coefficients",
[](MultivariateStateSpaceRegressionModel &model,
const Vector &coefficients,
int which_model) {
model.observation_model()->model(which_model)->set_Beta(coefficients);
},
"Args:\n\n"
" coefficients: The boom.Vector of regression coefficients for "
"the regression model describing a single series.\n"
" which_model: The (integer) index of the model to update.\n")
.def("set_residual_sd",
[](MultivariateStateSpaceRegressionModel &model,
const Vector &residual_sd) {
if (residual_sd.size() != model.nseries()) {
std::ostringstream err;
err << "The model describes " << model.nseries()
<< " series but the input vector has "
<< residual_sd.size() << " entries.";
report_error(err.str());
}
for (int i = 0; i < model.nseries(); ++i) {
model.observation_model()->model(i)->set_sigsq(
square(residual_sd[i]));
}
},
"Args:\n\n"
" residual_sd: A boom.Vector containing the residual standard "
"deviation for each series.\n")
.def("set_residual_sd",
[](MultivariateStateSpaceRegressionModel &model,
double residual_sd,
int which_model) {
model.observation_model()->model(which_model)->set_sigsq(
square(residual_sd));
},
"Args:\n\n"
" residual_sd: The scalar valued residual standard deviation "
"for a single model.\n"
" which_model: The (integer) index of the model to update.\n")
.def("mle",
[](MultivariateStateSpaceRegressionModel &model,
double epsilon,
int max_tries) {
return model.mle(epsilon, max_tries);
},
py::arg("epsilon"),
py::arg("max_tries") = 500,
"Set model parameters to their maximum likelihood estimates.\n"
"\n"
"Args:\n"
" epsilon: A small positive number. Absolute changes to log likelihood\n"
" less than this value indicate that the algorithm has converged.\n"
" max_tries: Stop trying to optimzize after this many iterations.\n"
"\n"
"Returns:\n"
" The log likelihood value at the maximum.\n"
"\n"
"Effects:\n"
" Model parameters are set to the maximum likelihood estimates.\n")
;
py::class_<MultivariateStateSpaceModelSampler,
PosteriorSampler,
Ptr<MultivariateStateSpaceModelSampler>>(
boom,
"MultivariateStateSpaceModelSampler")
.def(py::init(
[](MultivariateStateSpaceModelBase *model,
RNG &seeding_rng = BOOM::GlobalRng::rng) {
return new MultivariateStateSpaceModelSampler(model, seeding_rng);
}))
;
}
} // namespace BayesBoom
<commit_msg>Expose shared_state to the python interface.<commit_after>#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include "Models/StateSpace/Multivariate/MultivariateStateSpaceRegressionModel.hpp"
#include "Models/StateSpace/Multivariate/PosteriorSamplers/MultivariateStateSpaceModelSampler.hpp"
#include "cpputil/math_utils.hpp"
#include "cpputil/Ptr.hpp"
namespace py = pybind11;
PYBIND11_DECLARE_HOLDER_TYPE(T, BOOM::Ptr<T>, true);
namespace BayesBoom {
using namespace BOOM;
void MultivariateStateSpaceModel_def(py::module &boom) {
py::class_<MultivariateStateSpaceModelBase,
Model,
BOOM::Ptr<MultivariateStateSpaceModelBase>>(
boom,
"MultivariateStateSpaceModelBase",
py::multiple_inheritance())
.def_property_readonly(
"nseries",
[](const MultivariateStateSpaceModelBase &model) {
return model.nseries();
},
"The number of time series described by the model.")
.def_property_readonly(
"time_dimension",
[](const MultivariateStateSpaceModelBase &model) {
return model.time_dimension();
},
"The number of time points in the model training data.")
.def_property_readonly(
"state_dimension",
[](const MultivariateStateSpaceModelBase &model) {
return model.state_dimension();
},
"The dimension of the state vector shared across all time series.")
.def_property_readonly(
"number_of_state_models",
[](const MultivariateStateSpaceModelBase &model) {
return model.number_of_state_models();
},
"The number state models defining the shared state vector.")
.def_property_readonly(
"log_likelihood",
[](MultivariateStateSpaceModelBase &model) {
return model.log_likelihood();
},
"The log likelihood under the current set of model parameters.")
.def("state_contributions",
[](const MultivariateStateSpaceModelBase &model, int which_state_model) {
return model.state_contributions(which_state_model);
},
py::arg("which_state_model"),
"Args:\n"
" which_state_model: The state model whose contribution is desired.\n"
"\n"
"Returns:\n"
" A Matrix. Element (t, d) is the contrubtion of the specified "
"state model to series d at time t.")
.def_property_readonly(
"shared_state",
[](const MultivariateStateSpaceModelBase &model) {return model.shared_state();},
"The full state matrix for the model")
;
py::class_<ConditionallyIndependentMultivariateStateSpaceModelBase,
MultivariateStateSpaceModelBase,
BOOM::Ptr<ConditionallyIndependentMultivariateStateSpaceModelBase>>(
boom,
"ConditionallyIndependentMultivariateStateSpaceModelBase",
py::multiple_inheritance())
;
py::class_<MultivariateTimeSeriesRegressionData,
RegressionData,
BOOM::Ptr<MultivariateTimeSeriesRegressionData>>(
boom,
"MultivariateTimeSeriesRegressionData")
.def(py::init(
[](double y, const Vector &x, int series, int timestamp) {
return new MultivariateTimeSeriesRegressionData(
y, x, series, timestamp);
}),
py::arg("y"),
py::arg("x"),
py::arg("series"),
py::arg("timestamp"),
"Args:\n"
" y: The response variable.\n"
" x: A vector of predictors.\n"
" series: The identifier of the time series (0.. number of series - 1) to\n"
" which this observation belongs.\n"
" timestamp: The time-index of the time series (0.. sample_size - 1)\n"
" containing this observation.\n")
;
py::class_<MultivariateStateSpaceRegressionModel,
ConditionallyIndependentMultivariateStateSpaceModelBase,
PriorPolicy,
BOOM::Ptr<MultivariateStateSpaceRegressionModel>>(
boom,
"MultivariateStateSpaceRegressionModel",
py::multiple_inheritance())
.def(py::init(
[](int xdim, int nseries) {
return new BOOM::MultivariateStateSpaceRegressionModel(
xdim, nseries);
}),
py::arg("xdim"),
py::arg("nseries"),
"Args:\n"
" xdim: The dimension of the predictor variables.\n"
" nseries: The number of time series being modeled.\n")
.def_property_readonly(
"xdim",
[](const MultivariateStateSpaceRegressionModel &model) {
return model.xdim();
},
"Dimension of the vector of predictor variables.")
.def("add_data",
[](MultivariateStateSpaceRegressionModel &model,
const Ptr<MultivariateTimeSeriesRegressionData> &data_point) {
model.add_data(data_point);
},
py::arg("data_point"),
"Add a single data point to the model.\n\n"
"Args:\n"
" data_point: A MultivariateTimeSeriesRegressionData object\n"
" containing information for a single data point.\n")
.def("add_data",
[](MultivariateStateSpaceRegressionModel &model,
const std::vector<int> &time_index,
const std::vector<int> &series_index,
const Vector &response,
const Matrix &predictors) {
size_t nobs = time_index.size();
if (series_index.size() != nobs) {
report_error("The series_index and time_index must have "
"the same number of elements.");
}
if (response.size() != nobs) {
report_error("The response must have the same number of "
"elements as the time_index.");
}
if (predictors.nrow() != nobs) {
report_error("The matrix of predictors must have the same "
"number of rows as the time_index.");
}
for (size_t i = 0; i < nobs; ++i) {
NEW(MultivariateTimeSeriesRegressionData, data_point)(
response[i],
predictors.row(i),
series_index[i],
time_index[i]);
model.add_data(data_point);
}
},
py::arg("time_index"),
py::arg("series_index"),
py::arg("response"),
py::arg("predictors"),
"Add a full data set to the model.\n\n"
"Args:\n"
" time_index: A list of integers indicating the time stamp "
"(0, 1, 2...) associated with the observation.\n"
" series_index: A list of integers indicating which series the "
"observation describes.\n"
" response: A boom.Vector giving the values of each series at "
"the specified times.\n"
" predictors: A boom.Matrix giving the row of predictor "
"variables to use for each observation.\n\n"
"Effect:\n"
" The model object is populated with the supplied data.\n")
.def("add_state",
[](MultivariateStateSpaceRegressionModel &model,
SharedStateModel &state_model) {
model.add_state(Ptr<SharedStateModel>(&state_model));
},
"Args:\n"
" state_model: A SharedStateModel object defining an element of"
" state.\n")
.def("set_method",
[](MultivariateStateSpaceRegressionModel &model,
PosteriorSampler *sampler) {
model.set_method(Ptr<PosteriorSampler>(sampler));
})
.def("set_regression_coefficients",
[](MultivariateStateSpaceRegressionModel &model,
const Matrix &coefficients) {
if (coefficients.nrow() != model.nseries()) {
std::ostringstream err;
err << "The model describes " << model.nseries()
<< " series but the input matrix has "
<< coefficients.nrow() << " rows.";
report_error(err.str());
}
if (coefficients.ncol() != model.xdim()) {
std::ostringstream err;
err << "The model has predictor dimension "
<< model.xdim() << " but the input matrix has "
<< coefficients.ncol() << "columns.";
report_error(err.str());
}
for (int i = 0; i < coefficients.nrow(); ++i) {
model.observation_model()->model(i)->set_Beta(
coefficients.row(i));
}
},
"Args:\n\n"
" coefficients: A boom.Matrix with model.nseries rows and "
"model.xdim columns. Each row contains the regression "
"coefficients for a specific series.\n")
.def("set_regression_coefficients",
[](MultivariateStateSpaceRegressionModel &model,
const Vector &coefficients,
int which_model) {
model.observation_model()->model(which_model)->set_Beta(coefficients);
},
"Args:\n\n"
" coefficients: The boom.Vector of regression coefficients for "
"the regression model describing a single series.\n"
" which_model: The (integer) index of the model to update.\n")
.def("set_residual_sd",
[](MultivariateStateSpaceRegressionModel &model,
const Vector &residual_sd) {
if (residual_sd.size() != model.nseries()) {
std::ostringstream err;
err << "The model describes " << model.nseries()
<< " series but the input vector has "
<< residual_sd.size() << " entries.";
report_error(err.str());
}
for (int i = 0; i < model.nseries(); ++i) {
model.observation_model()->model(i)->set_sigsq(
square(residual_sd[i]));
}
},
"Args:\n\n"
" residual_sd: A boom.Vector containing the residual standard "
"deviation for each series.\n")
.def("set_residual_sd",
[](MultivariateStateSpaceRegressionModel &model,
double residual_sd,
int which_model) {
model.observation_model()->model(which_model)->set_sigsq(
square(residual_sd));
},
"Args:\n\n"
" residual_sd: The scalar valued residual standard deviation "
"for a single model.\n"
" which_model: The (integer) index of the model to update.\n")
.def("mle",
[](MultivariateStateSpaceRegressionModel &model,
double epsilon,
int max_tries) {
return model.mle(epsilon, max_tries);
},
py::arg("epsilon"),
py::arg("max_tries") = 500,
"Set model parameters to their maximum likelihood estimates.\n"
"\n"
"Args:\n"
" epsilon: A small positive number. Absolute changes to log likelihood\n"
" less than this value indicate that the algorithm has converged.\n"
" max_tries: Stop trying to optimzize after this many iterations.\n"
"\n"
"Returns:\n"
" The log likelihood value at the maximum.\n"
"\n"
"Effects:\n"
" Model parameters are set to the maximum likelihood estimates.\n")
;
py::class_<MultivariateStateSpaceModelSampler,
PosteriorSampler,
Ptr<MultivariateStateSpaceModelSampler>>(
boom,
"MultivariateStateSpaceModelSampler")
.def(py::init(
[](MultivariateStateSpaceModelBase *model,
RNG &seeding_rng = BOOM::GlobalRng::rng) {
return new MultivariateStateSpaceModelSampler(model, seeding_rng);
}))
;
}
} // namespace BayesBoom
<|endoftext|>
|
<commit_before>#include "GameNetworkWorker.h"
#include "easylogging++.h"
#include "src/common/net/EventId.h"
#include "src/common/net/Deserializer.h"
#include <cassert>
namespace net {
GameNetworkWorker::GameNetworkWorker(quint16 port, std::shared_ptr<GameTimer> game_timer, std::weak_ptr<World> world, std::vector<Client> clients)
: port_(port),
game_timer_(game_timer),
last_packet_id_(1),
world_ptr_(world),
send_entities_timer_(),
detect_disconnect_timer_() {
QObject::connect(&socket_, SIGNAL(readyRead()), this, SLOT(ReadPendingDatagrams()));
QObject::connect(&socket_, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(SocketError(QAbstractSocket::SocketError)));
socket_.bind( port_);
for(Client client : clients) {
clients_.insert(std::pair<int, Client>(client.GetId(), client));
last_event_ids_[client.GetId()] = 0; // not event has been ACKed yet for this client (the first event ID will be 1)
last_received_pings_[client.GetId()] = game_timer_->GetTimestamp();
}
QObject::connect(&send_entities_timer_, &QTimer::timeout, this, &GameNetworkWorker::BroadcastWorld);
send_entities_timer_.start(100);
QObject::connect(&detect_disconnect_timer_, &QTimer::timeout, this, &GameNetworkWorker::DetectConnectionLost);
detect_disconnect_timer_.start(10000);
LOG(DEBUG) << "In game network worker initialized and ready on port " << port_;
}
void GameNetworkWorker::ReadPendingDatagrams() {
VLOG(9) << "Reading pending datagrams...";
while(socket_.hasPendingDatagrams()) {
QByteArray datagram;
datagram.resize(socket_.pendingDatagramSize());
QHostAddress sender;
quint16 sender_port;
socket_.readDatagram(datagram.data(), datagram.size(), &sender, &sender_port);
ProcessDatagram(datagram);
}
}
void GameNetworkWorker::SocketError(QAbstractSocket::SocketError error) {
LOG(ERROR) << "Error on socket: " << socket_.errorString().toStdWString();
(void) error;
}
void GameNetworkWorker::ProcessDatagram(const QByteArray& datagram) {
QDataStream stream(datagram);
if(!CheckProtocolAndVersion(stream)) {
LOG(WARNING) << "Protocol or version ID mismatch, dropping datagram.";
return;
}
quint8 client_id = GetClientId(stream);
if(!CheckStreamStatus(stream)) {
LOG(WARNING) << "Could not deserialize the client id.";
return;
}
auto it = clients_.find(client_id);
if(it == clients_.end()) {
LOG(WARNING) << "Got a datagram with client id " << (int) client_id << " that does not match a registered client, dropping it.";
return;
}
Client client = it->second;
if(!client.IsConnected()) {
LOG(WARNING) << "Received a datagram from a previously disconnected client. This server does not support client reconnection ; dropping the datagram";
}
VLOG(5) << "Datagram comes from client " << client.GetId();
quint32 packet_id = GetPacketId(stream);
if(!CheckStreamStatus(stream)) {
LOG(WARNING) << "Could not deserialize the packet id.";
return;
}
VLOG(5) << "Received datagram packet id: " << packet_id;
quint8 packet_type = GetPacketType(stream);
if(!CheckStreamStatus(stream)) {
LOG(WARNING) << "Could not deserialize the packet type.";
return;
}
switch(packet_type) {
case kPingPacketId:
VLOG(5) << "The datagram is a ping packet.";
ProcessPingPacket(stream, client, packet_id);
break;
case kEventPacketId:
VLOG(5) << "The datagram is an event packet.";
ProcessEventPacket(stream, client, packet_id);
break;
default:
LOG(WARNING) << "Received unknown packet type " << packet_type << ", dropping datagram.";
break;
}
}
bool GameNetworkWorker::CheckProtocolAndVersion(QDataStream &stream) {
assert(stream.status() == QDataStream::Ok);
quint8 protocol_id;
quint8 server_version;
stream >> protocol_id;
stream >> server_version;
if(!CheckStreamStatus(stream)) {
LOG(WARNING) << "Could not deserialize the protocol and version.";
return false;
}
quint8 accepted_version = GameNetworkWorker::kServerVersion;
quint8 accepted_protocol_id = GameNetworkWorker::kProtocolId;
if(protocol_id != accepted_protocol_id) {
LOG(WARNING) << "Received unexpected protocol ID: got " << protocol_id << ", expected " << accepted_protocol_id;
return false;
}
if(server_version != accepted_version) {
LOG(WARNING) << "Received unsupported server version: got " << server_version << ", but only version " << accepted_version << " is supported by this client";
return false;
}
return true;
}
quint8 GameNetworkWorker::GetPacketType(QDataStream& stream) {
assert(stream.status() == QDataStream::Ok);
quint8 packet_id;
stream >> packet_id;
return packet_id;
}
quint32 GameNetworkWorker::GetPacketId(QDataStream& stream) {
assert(stream.status() == QDataStream::Ok);
quint32 packet_id;
stream >> packet_id;
return packet_id;
}
quint8 GameNetworkWorker::GetClientId(QDataStream& stream) {
assert(stream.status() == QDataStream::Ok);
quint8 client_id;
stream >> client_id;
return client_id;
}
void GameNetworkWorker::ProcessPingPacket(QDataStream& stream, const Client& client, quint32 packet_id) {
(void) stream; // unused for now, the ping content does not matter
last_received_pings_[client.GetId()] = game_timer_->GetTimestamp();
SendPongPacket(client, packet_id);
}
void GameNetworkWorker::ProcessEventPacket(QDataStream& stream, const Client& client, quint32 packet_id) {
assert(stream.status() == QDataStream::Ok);
(void) packet_id;
quint8 events_size;
stream >> events_size;
if(!CheckStreamStatus(stream)) {
LOG(WARNING) << "Could not deserialize the number of events.";
return;
}
for(int i = 0; i < events_size; i++) {
std::unique_ptr<InGameEvent> event = Deserializer::DeserializeInGameEvent(stream);
if(stream.status() != QDataStream::Ok) {
LOG(WARNING) << "Stream is in an invalid state after having deserialized the event. Continuing anyway.";
}
if(event.get() == nullptr) {
LOG(WARNING) << "Could not deserialize the received event. Dropping remaining data.";
return;
}
VLOG(9) << "Deserialized event has ID " << event->GetId();
if(event->GetId() <= last_event_ids_[client.GetId()]) {
VLOG(8) << "The client has sent an event that has already been processed (according to its ID).";
continue;
}
auto client_event = std::unique_ptr<BaseClientEvent>(new BaseClientEvent(std::move(event), client, game_timer_->GetTimestamp()));
HandlePendingEvent(std::move(client_event));
}
EmitReadyEvents(client);
}
// TODO: defends against a client attacking the server by sending bad events id
void GameNetworkWorker::HandlePendingEvent(std::unique_ptr<BaseClientEvent> event) {
Client client = event->GetClient();
auto pair = std::pair<const quint32, std::unique_ptr<BaseClientEvent>>(event->GetEvent()->GetId(), std::move(event));
event_cache_[client.GetId()].insert(std::move(pair));
}
void GameNetworkWorker::EmitReadyEvents(Client client) {
quint8 client_id = client.GetId();
// look if the next event from this client (ordered by id) has been received
auto it = event_cache_[client_id].find(last_event_ids_[client_id] + 1);
bool send_ack = false;
while(it != event_cache_[client_id].end()) {
// if yes, send it to the application
EmitterVisitor visitor(this, it->second.get());
it->second->GetEvent()->Accept(visitor);
event_cache_[client_id].erase(it);
// this event will be ACKed
last_event_ids_[client_id]++;
send_ack = true;
// update iterator
it = event_cache_[client_id].find(last_event_ids_[client_id] + 1);
}
if(send_ack) {
SendAckPacket(client, last_event_ids_[client_id]);
}
}
void GameNetworkWorker::SendAckPacket(const Client& client, quint32 event_id) {
QByteArray buffer;
QDataStream stream(&buffer, QIODevice::OpenModeFlag::WriteOnly);
PrepareHeader(stream, kEventAckPacketId);
stream << event_id;
assert(stream.status() == QDataStream::Ok);
socket_.writeDatagram(buffer, client.GetAddress(), client.GetPort());
VLOG(9) << "Sent ACK packet for ids <= " << (int) event_id << " to client ID " << (int) client.GetId();
}
void GameNetworkWorker::SendPongPacket(const Client& client, quint32 packet_id) {
QByteArray buffer;
QDataStream stream(&buffer, QIODevice::OpenModeFlag::WriteOnly);
PrepareHeader(stream, kPingPacketId);
stream << packet_id;
quint32 timestamp = game_timer_->GetTimestamp();
stream << timestamp;
assert(stream.status() == QDataStream::Ok);
socket_.writeDatagram(buffer, client.GetAddress(), client.GetPort());
VLOG(9) << "Answered pong with timestamp " << timestamp << " to the ping with id " << packet_id;
VLOG(9) << "Client was at address " << client.GetAddress().toString().toStdWString() << ":" << client.GetPort();
}
quint32 GameNetworkWorker::PrepareHeader(QDataStream& stream, quint8 packet_type) {
assert(stream.status() == QDataStream::Ok);
quint32 packet_id = GetNextPacketId();
stream << kProtocolId;
stream << kServerVersion;
stream << packet_id;
stream << packet_type;
return packet_id;
}
quint32 GameNetworkWorker::GetNextPacketId() {
last_packet_id_ += 1;
return last_packet_id_;
}
void GameNetworkWorker::EmitEvent(ClientEvent<BombEvent> event) {
VLOG(EVENT_READY_LOG_LEVEL) << "Network worker: bomb event ready / client id: " << (int) event.GetClientId() << " / id: " << event.GetEventData().GetId();
emit BombEventReceived(event);
}
void GameNetworkWorker::EmitEvent(ClientEvent<MoveEvent> event) {
VLOG(EVENT_READY_LOG_LEVEL) << "Network worker: move event ready / client id: " << (int) event.GetClientId() << " / id: " << event.GetEventData().GetId();
emit MoveEventReceived(event);
}
void GameNetworkWorker::EmitEvent(ClientEvent<PlayerLeftEvent> event) {
VLOG(EVENT_READY_LOG_LEVEL) << "Network worker: player left event ready / client id: " << (int) event.GetClientId() << " / id: " << event.GetEventData().GetId();
emit PlayerLeftEventReceived(event);
}
void GameNetworkWorker::BroadcastWorld() {
quint32 timestamp = game_timer_->GetTimestamp();
VLOG(9) << "Broadcasting the world state to clients, timestamp is " << timestamp;
auto world = world_ptr_.lock();
if(world.get() == nullptr) {
LOG(WARNING) << "The World has gone out of scope, can not send it to clients!";
return;
}
std::vector<Entity*> to_send;
// do not put to many entites in the same packet to prevent the packet from
// being cut by the network layer
for(int i = 0; i < world->GetWidth(); i++) {
for(int j = 0; j < world->GetHeight(); j++) {
QPoint point(i, j);// TODO check indices
for(auto it = world->IteratorAtBegin(point); it != world->IteratorAtEnd(point); ++it) {
to_send.push_back(it->get());
}
}
}
for(auto it = world->CharacterIteratorBegin(); it != world->CharacterIteratorEnd(); ++it) {
to_send.push_back(it->get());
}
auto it = to_send.begin();
while(it != to_send.end()) {
QByteArray buffer;
QDataStream stream(&buffer, QIODevice::OpenModeFlag::WriteOnly);
quint32 packet_id = PrepareHeader(stream, kEntitiesPacketId);
stream << timestamp;
std::vector<Entity*> packet;
for(int i = 0; i < 10 && it != to_send.end(); ++i) {
packet.push_back(*it);
++it;
}
stream << (quint8) packet.size();
for(Entity* entity: packet) {
stream << *entity;
}
for(auto p: clients_) {
socket_.writeDatagram(buffer, buffer.size(), p.second.GetAddress(), p.second.GetPort());
}
VLOG(9) << "Sent the entities packet with ID: " << packet_id << " to all the clients";
}
}
void GameNetworkWorker::DetectConnectionLost() {
for(auto it = last_received_pings_.begin(); it != last_received_pings_.end(); ++it) {
if(game_timer_->GetTimestamp() > it->second + kDisconnectTimeout) {
auto itt = clients_.find(it->first);
assert(itt != clients_.end());
Client client = itt->second;
client.SetConnected(false);
LOG(INFO) << "The client " << (int) client.GetId() << " did not send a ping for at least " << (int) kDisconnectTimeout << " seconds ; marking it as disconnected.";
emit ConnectionLost(client);
last_received_pings_.erase(it);
}
}
}
bool GameNetworkWorker::CheckStreamStatus(const QDataStream& stream) const {
if(stream.status() != QDataStream::Ok) {
LOG(WARNING) << "Deserialization stream status is not OK (code is: " << (int) stream.status() << "), the current message will be lost.";
return false;
}
return true;
}
}
<commit_msg>Do not hardcode the frequency of disconnection checks.<commit_after>#include "GameNetworkWorker.h"
#include "easylogging++.h"
#include "src/common/net/EventId.h"
#include "src/common/net/Deserializer.h"
#include <cassert>
namespace net {
GameNetworkWorker::GameNetworkWorker(quint16 port, std::shared_ptr<GameTimer> game_timer, std::weak_ptr<World> world, std::vector<Client> clients)
: port_(port),
game_timer_(game_timer),
last_packet_id_(1),
world_ptr_(world),
send_entities_timer_(),
detect_disconnect_timer_() {
QObject::connect(&socket_, SIGNAL(readyRead()), this, SLOT(ReadPendingDatagrams()));
QObject::connect(&socket_, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(SocketError(QAbstractSocket::SocketError)));
socket_.bind( port_);
for(Client client : clients) {
clients_.insert(std::pair<int, Client>(client.GetId(), client));
last_event_ids_[client.GetId()] = 0; // not event has been ACKed yet for this client (the first event ID will be 1)
last_received_pings_[client.GetId()] = game_timer_->GetTimestamp();
}
QObject::connect(&send_entities_timer_, &QTimer::timeout, this, &GameNetworkWorker::BroadcastWorld);
send_entities_timer_.start(100);
QObject::connect(&detect_disconnect_timer_, &QTimer::timeout, this, &GameNetworkWorker::DetectConnectionLost);
detect_disconnect_timer_.start(kDisconnectTimeout / 3);
LOG(DEBUG) << "In game network worker initialized and ready on port " << port_;
}
void GameNetworkWorker::ReadPendingDatagrams() {
VLOG(9) << "Reading pending datagrams...";
while(socket_.hasPendingDatagrams()) {
QByteArray datagram;
datagram.resize(socket_.pendingDatagramSize());
QHostAddress sender;
quint16 sender_port;
socket_.readDatagram(datagram.data(), datagram.size(), &sender, &sender_port);
ProcessDatagram(datagram);
}
}
void GameNetworkWorker::SocketError(QAbstractSocket::SocketError error) {
LOG(ERROR) << "Error on socket: " << socket_.errorString().toStdWString();
(void) error;
}
void GameNetworkWorker::ProcessDatagram(const QByteArray& datagram) {
QDataStream stream(datagram);
if(!CheckProtocolAndVersion(stream)) {
LOG(WARNING) << "Protocol or version ID mismatch, dropping datagram.";
return;
}
quint8 client_id = GetClientId(stream);
if(!CheckStreamStatus(stream)) {
LOG(WARNING) << "Could not deserialize the client id.";
return;
}
auto it = clients_.find(client_id);
if(it == clients_.end()) {
LOG(WARNING) << "Got a datagram with client id " << (int) client_id << " that does not match a registered client, dropping it.";
return;
}
Client client = it->second;
if(!client.IsConnected()) {
LOG(WARNING) << "Received a datagram from a previously disconnected client. This server does not support client reconnection ; dropping the datagram";
}
VLOG(5) << "Datagram comes from client " << client.GetId();
quint32 packet_id = GetPacketId(stream);
if(!CheckStreamStatus(stream)) {
LOG(WARNING) << "Could not deserialize the packet id.";
return;
}
VLOG(5) << "Received datagram packet id: " << packet_id;
quint8 packet_type = GetPacketType(stream);
if(!CheckStreamStatus(stream)) {
LOG(WARNING) << "Could not deserialize the packet type.";
return;
}
switch(packet_type) {
case kPingPacketId:
VLOG(5) << "The datagram is a ping packet.";
ProcessPingPacket(stream, client, packet_id);
break;
case kEventPacketId:
VLOG(5) << "The datagram is an event packet.";
ProcessEventPacket(stream, client, packet_id);
break;
default:
LOG(WARNING) << "Received unknown packet type " << packet_type << ", dropping datagram.";
break;
}
}
bool GameNetworkWorker::CheckProtocolAndVersion(QDataStream &stream) {
assert(stream.status() == QDataStream::Ok);
quint8 protocol_id;
quint8 server_version;
stream >> protocol_id;
stream >> server_version;
if(!CheckStreamStatus(stream)) {
LOG(WARNING) << "Could not deserialize the protocol and version.";
return false;
}
quint8 accepted_version = GameNetworkWorker::kServerVersion;
quint8 accepted_protocol_id = GameNetworkWorker::kProtocolId;
if(protocol_id != accepted_protocol_id) {
LOG(WARNING) << "Received unexpected protocol ID: got " << protocol_id << ", expected " << accepted_protocol_id;
return false;
}
if(server_version != accepted_version) {
LOG(WARNING) << "Received unsupported server version: got " << server_version << ", but only version " << accepted_version << " is supported by this client";
return false;
}
return true;
}
quint8 GameNetworkWorker::GetPacketType(QDataStream& stream) {
assert(stream.status() == QDataStream::Ok);
quint8 packet_id;
stream >> packet_id;
return packet_id;
}
quint32 GameNetworkWorker::GetPacketId(QDataStream& stream) {
assert(stream.status() == QDataStream::Ok);
quint32 packet_id;
stream >> packet_id;
return packet_id;
}
quint8 GameNetworkWorker::GetClientId(QDataStream& stream) {
assert(stream.status() == QDataStream::Ok);
quint8 client_id;
stream >> client_id;
return client_id;
}
void GameNetworkWorker::ProcessPingPacket(QDataStream& stream, const Client& client, quint32 packet_id) {
(void) stream; // unused for now, the ping content does not matter
last_received_pings_[client.GetId()] = game_timer_->GetTimestamp();
SendPongPacket(client, packet_id);
}
void GameNetworkWorker::ProcessEventPacket(QDataStream& stream, const Client& client, quint32 packet_id) {
assert(stream.status() == QDataStream::Ok);
(void) packet_id;
quint8 events_size;
stream >> events_size;
if(!CheckStreamStatus(stream)) {
LOG(WARNING) << "Could not deserialize the number of events.";
return;
}
for(int i = 0; i < events_size; i++) {
std::unique_ptr<InGameEvent> event = Deserializer::DeserializeInGameEvent(stream);
if(stream.status() != QDataStream::Ok) {
LOG(WARNING) << "Stream is in an invalid state after having deserialized the event. Continuing anyway.";
}
if(event.get() == nullptr) {
LOG(WARNING) << "Could not deserialize the received event. Dropping remaining data.";
return;
}
VLOG(9) << "Deserialized event has ID " << event->GetId();
if(event->GetId() <= last_event_ids_[client.GetId()]) {
VLOG(8) << "The client has sent an event that has already been processed (according to its ID).";
continue;
}
auto client_event = std::unique_ptr<BaseClientEvent>(new BaseClientEvent(std::move(event), client, game_timer_->GetTimestamp()));
HandlePendingEvent(std::move(client_event));
}
EmitReadyEvents(client);
}
// TODO: defends against a client attacking the server by sending bad events id
void GameNetworkWorker::HandlePendingEvent(std::unique_ptr<BaseClientEvent> event) {
Client client = event->GetClient();
auto pair = std::pair<const quint32, std::unique_ptr<BaseClientEvent>>(event->GetEvent()->GetId(), std::move(event));
event_cache_[client.GetId()].insert(std::move(pair));
}
void GameNetworkWorker::EmitReadyEvents(Client client) {
quint8 client_id = client.GetId();
// look if the next event from this client (ordered by id) has been received
auto it = event_cache_[client_id].find(last_event_ids_[client_id] + 1);
bool send_ack = false;
while(it != event_cache_[client_id].end()) {
// if yes, send it to the application
EmitterVisitor visitor(this, it->second.get());
it->second->GetEvent()->Accept(visitor);
event_cache_[client_id].erase(it);
// this event will be ACKed
last_event_ids_[client_id]++;
send_ack = true;
// update iterator
it = event_cache_[client_id].find(last_event_ids_[client_id] + 1);
}
if(send_ack) {
SendAckPacket(client, last_event_ids_[client_id]);
}
}
void GameNetworkWorker::SendAckPacket(const Client& client, quint32 event_id) {
QByteArray buffer;
QDataStream stream(&buffer, QIODevice::OpenModeFlag::WriteOnly);
PrepareHeader(stream, kEventAckPacketId);
stream << event_id;
assert(stream.status() == QDataStream::Ok);
socket_.writeDatagram(buffer, client.GetAddress(), client.GetPort());
VLOG(9) << "Sent ACK packet for ids <= " << (int) event_id << " to client ID " << (int) client.GetId();
}
void GameNetworkWorker::SendPongPacket(const Client& client, quint32 packet_id) {
QByteArray buffer;
QDataStream stream(&buffer, QIODevice::OpenModeFlag::WriteOnly);
PrepareHeader(stream, kPingPacketId);
stream << packet_id;
quint32 timestamp = game_timer_->GetTimestamp();
stream << timestamp;
assert(stream.status() == QDataStream::Ok);
socket_.writeDatagram(buffer, client.GetAddress(), client.GetPort());
VLOG(9) << "Answered pong with timestamp " << timestamp << " to the ping with id " << packet_id;
VLOG(9) << "Client was at address " << client.GetAddress().toString().toStdWString() << ":" << client.GetPort();
}
quint32 GameNetworkWorker::PrepareHeader(QDataStream& stream, quint8 packet_type) {
assert(stream.status() == QDataStream::Ok);
quint32 packet_id = GetNextPacketId();
stream << kProtocolId;
stream << kServerVersion;
stream << packet_id;
stream << packet_type;
return packet_id;
}
quint32 GameNetworkWorker::GetNextPacketId() {
last_packet_id_ += 1;
return last_packet_id_;
}
void GameNetworkWorker::EmitEvent(ClientEvent<BombEvent> event) {
VLOG(EVENT_READY_LOG_LEVEL) << "Network worker: bomb event ready / client id: " << (int) event.GetClientId() << " / id: " << event.GetEventData().GetId();
emit BombEventReceived(event);
}
void GameNetworkWorker::EmitEvent(ClientEvent<MoveEvent> event) {
VLOG(EVENT_READY_LOG_LEVEL) << "Network worker: move event ready / client id: " << (int) event.GetClientId() << " / id: " << event.GetEventData().GetId();
emit MoveEventReceived(event);
}
void GameNetworkWorker::EmitEvent(ClientEvent<PlayerLeftEvent> event) {
VLOG(EVENT_READY_LOG_LEVEL) << "Network worker: player left event ready / client id: " << (int) event.GetClientId() << " / id: " << event.GetEventData().GetId();
emit PlayerLeftEventReceived(event);
}
void GameNetworkWorker::BroadcastWorld() {
quint32 timestamp = game_timer_->GetTimestamp();
VLOG(9) << "Broadcasting the world state to clients, timestamp is " << timestamp;
auto world = world_ptr_.lock();
if(world.get() == nullptr) {
LOG(WARNING) << "The World has gone out of scope, can not send it to clients!";
return;
}
std::vector<Entity*> to_send;
// do not put to many entites in the same packet to prevent the packet from
// being cut by the network layer
for(int i = 0; i < world->GetWidth(); i++) {
for(int j = 0; j < world->GetHeight(); j++) {
QPoint point(i, j);// TODO check indices
for(auto it = world->IteratorAtBegin(point); it != world->IteratorAtEnd(point); ++it) {
to_send.push_back(it->get());
}
}
}
for(auto it = world->CharacterIteratorBegin(); it != world->CharacterIteratorEnd(); ++it) {
to_send.push_back(it->get());
}
auto it = to_send.begin();
while(it != to_send.end()) {
QByteArray buffer;
QDataStream stream(&buffer, QIODevice::OpenModeFlag::WriteOnly);
quint32 packet_id = PrepareHeader(stream, kEntitiesPacketId);
stream << timestamp;
std::vector<Entity*> packet;
for(int i = 0; i < 10 && it != to_send.end(); ++i) {
packet.push_back(*it);
++it;
}
stream << (quint8) packet.size();
for(Entity* entity: packet) {
stream << *entity;
}
for(auto p: clients_) {
socket_.writeDatagram(buffer, buffer.size(), p.second.GetAddress(), p.second.GetPort());
}
VLOG(9) << "Sent the entities packet with ID: " << packet_id << " to all the clients";
}
}
void GameNetworkWorker::DetectConnectionLost() {
for(auto it = last_received_pings_.begin(); it != last_received_pings_.end(); ++it) {
if(game_timer_->GetTimestamp() > it->second + kDisconnectTimeout) {
auto itt = clients_.find(it->first);
assert(itt != clients_.end());
Client client = itt->second;
client.SetConnected(false);
LOG(INFO) << "The client " << (int) client.GetId() << " did not send a ping for at least " << (int) kDisconnectTimeout << " seconds ; marking it as disconnected.";
emit ConnectionLost(client);
last_received_pings_.erase(it);
}
}
}
bool GameNetworkWorker::CheckStreamStatus(const QDataStream& stream) const {
if(stream.status() != QDataStream::Ok) {
LOG(WARNING) << "Deserialization stream status is not OK (code is: " << (int) stream.status() << "), the current message will be lost.";
return false;
}
return true;
}
}
<|endoftext|>
|
<commit_before>/****************************************************************************
*
* Copyright (c) 2017 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @file FlightTaskManualPosition.cpp
*/
#include "FlightTaskManualPosition.hpp"
#include <mathlib/mathlib.h>
#include <float.h>
using namespace matrix;
FlightTaskManualPosition::FlightTaskManualPosition(control::SuperBlock *parent, const char *name) :
FlightTaskManualAltitude(parent, name),
_vel_xy_manual_max(parent, "MPC_VEL_MANUAL", false),
_acc_xy_max(parent, "MPC_ACC_HOR_MAX", false),
_vel_hold_thr_xy(parent, "MPC_HOLD_MAX_XY", false)
{}
bool FlightTaskManualPosition::activate()
{
_pos_sp_xy = matrix::Vector2f(NAN, NAN);
_vel_sp_xy = matrix::Vector2f(0.0f, 0.0f);
return FlightTaskManualAltitude::activate();
}
void FlightTaskManualPosition::_scaleSticks()
{
/* Use same scaling as for FlightTaskManualAltitude to
* get yaw and z */
FlightTaskManualAltitude::_scaleSticks();
/* Constrain length of stick inputs to 1 for xy*/
matrix::Vector2f stick_xy(_sticks_expo(0), _sticks_expo(1));
float mag = math::constrain(stick_xy.length(), 0.0f, 1.0f);
if (mag > FLT_EPSILON) {
stick_xy = stick_xy.normalized() * mag;
}
/* Scale to velocity.*/
_vel_sp_xy = stick_xy * _vel_xy_manual_max.get();
/* Rotate setpoint into local frame. */
matrix::Vector3f vel_sp{_vel_sp_xy(0), _vel_sp_xy(1), 0.0f};
vel_sp = (matrix::Dcmf(matrix::Eulerf(0.0f, 0.0f, _yaw)) * vel_sp);
_vel_sp_xy = matrix::Vector2f(vel_sp(0), vel_sp(1));
}
void FlightTaskManualPosition::_updateXYlock()
{
/* If position lock is not active, position setpoint is set to NAN.*/
const float vel_xy_norm = Vector2f(&_velocity(0)).length();
const bool apply_brake = _vel_sp_xy.length() < FLT_EPSILON;
const bool stopped = (_vel_hold_thr_xy.get() < FLT_EPSILON || vel_xy_norm < _vel_hold_thr_xy.get());
if (apply_brake && stopped && !PX4_ISFINITE(_pos_sp_xy(0))) {
_pos_sp_xy = matrix::Vector2f(&_position(0));
} else if (!apply_brake) {
_pos_sp_xy = _pos_sp_xy * NAN;
}
}
void FlightTaskManualPosition::_updateSetpoints()
{
FlightTaskManualAltitude::_updateSetpoints(); // get yaw and z setpoints
_updateXYlock(); // check for position lock
}
bool FlightTaskManualPosition::update()
{
_scaleSticks();
_updateSetpoints();
_setPositionSetpoint(Vector3f(_pos_sp_xy(0), _pos_sp_xy(1), _pos_sp_z));
_setVelocitySetpoint(Vector3f(_vel_sp_xy(0), _vel_sp_xy(1), _vel_sp_z));
_setYawSetpoint(_yaw_sp);
_setYawspeedSetpoint(_yaw_rate_sp);
_setThrustSetpoint(Vector3f(NAN, NAN, NAN));
return true;
}
<commit_msg>FlightTaskManualPosition: use axis angle to rotate into world frame<commit_after>/****************************************************************************
*
* Copyright (c) 2017 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @file FlightTaskManualPosition.cpp
*/
#include "FlightTaskManualPosition.hpp"
#include <mathlib/mathlib.h>
#include <float.h>
using namespace matrix;
FlightTaskManualPosition::FlightTaskManualPosition(control::SuperBlock *parent, const char *name) :
FlightTaskManualAltitude(parent, name),
_vel_xy_manual_max(parent, "MPC_VEL_MANUAL", false),
_acc_xy_max(parent, "MPC_ACC_HOR_MAX", false),
_vel_hold_thr_xy(parent, "MPC_HOLD_MAX_XY", false)
{}
bool FlightTaskManualPosition::activate()
{
_pos_sp_xy = matrix::Vector2f(NAN, NAN);
_vel_sp_xy = matrix::Vector2f(0.0f, 0.0f);
return FlightTaskManualAltitude::activate();
}
void FlightTaskManualPosition::_scaleSticks()
{
/* Use same scaling as for FlightTaskManualAltitude to
* get yaw and z */
FlightTaskManualAltitude::_scaleSticks();
/* Constrain length of stick inputs to 1 for xy*/
matrix::Vector2f stick_xy(_sticks_expo(0), _sticks_expo(1));
float mag = math::constrain(stick_xy.length(), 0.0f, 1.0f);
if (mag > FLT_EPSILON) {
stick_xy = stick_xy.normalized() * mag;
}
/* Scale to velocity.*/
_vel_sp_xy = stick_xy * _vel_xy_manual_max.get();
/* Rotate setpoint into local frame. */
matrix::Quatf q_yaw = matrix::AxisAnglef(matrix::Vector3f(0.0f, 0.0f, 1.0f), _yaw);
matrix::Vector3f vel_world = q_yaw.conjugate(matrix::Vector3f(_vel_sp_xy(0), _vel_sp_xy(1), 0.0f));
_vel_sp_xy = matrix::Vector2f(vel_world(0), vel_world(1));
}
void FlightTaskManualPosition::_updateXYlock()
{
/* If position lock is not active, position setpoint is set to NAN.*/
const float vel_xy_norm = Vector2f(&_velocity(0)).length();
const bool apply_brake = _vel_sp_xy.length() < FLT_EPSILON;
const bool stopped = (_vel_hold_thr_xy.get() < FLT_EPSILON || vel_xy_norm < _vel_hold_thr_xy.get());
if (apply_brake && stopped && !PX4_ISFINITE(_pos_sp_xy(0))) {
_pos_sp_xy = matrix::Vector2f(&_position(0));
} else if (!apply_brake) {
/* Don't use position setpoint */
_pos_sp_xy = _pos_sp_xy * NAN;
}
}
void FlightTaskManualPosition::_updateSetpoints()
{
FlightTaskManualAltitude::_updateSetpoints(); // get yaw and z setpoints
_updateXYlock(); // check for position lock
}
bool FlightTaskManualPosition::update()
{
_scaleSticks();
_updateSetpoints();
_setPositionSetpoint(Vector3f(_pos_sp_xy(0), _pos_sp_xy(1), _pos_sp_z));
_setVelocitySetpoint(Vector3f(_vel_sp_xy(0), _vel_sp_xy(1), _vel_sp_z));
_setYawSetpoint(_yaw_sp);
_setYawspeedSetpoint(_yaw_rate_sp);
_setThrustSetpoint(Vector3f(NAN, NAN, NAN));
return true;
}
<|endoftext|>
|
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2017. All rights reserved
*/
#include "../../StroikaPreComp.h"
#include "../../Characters/CString/Utilities.h"
#include "../../Characters/String.h"
#include "../../Characters/StringBuilder.h"
#include "../../Characters/String_Constant.h"
#include "../../DataExchange/Variant/CharacterDelimitedLines/Reader.h"
#include "../../Execution/Finally.h"
#include "../../Memory/SmallStackBuffer.h"
#include "FileInputStream.h"
#include "MountedFilesystem.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Characters;
using namespace Stroika::Foundation::Containers;
using namespace Stroika::Foundation::IO;
using namespace Stroika::Foundation::IO::FileSystem;
// Comment this in to turn on aggressive noisy DbgTrace in this module
//#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1
#if qPlatform_Linux
namespace {
Collection<MountedFilesystemType> ReadMountInfo_FromProcFSMounts_ ()
{
/*
* I haven't found this clearly documented yet, but it appears that a filesystem can be over-mounted.
* See https://www.kernel.org/doc/Documentation/filesystems/ramfs-rootfs-initramfs.txt
*
* So the last one with a given mount point in the file wins.
*/
Collection<MountedFilesystemType> results;
DataExchange::Variant::CharacterDelimitedLines::Reader reader{{' ', '\t'}};
// Note - /procfs files always unseekable
static const String_Constant kProcMountsFileName_{L"/proc/mounts"};
for (Sequence<String> line : reader.ReadMatrix (FileInputStream::mk (kProcMountsFileName_, FileInputStream::eNotSeekable))) {
#if USE_NOISY_TRACE_IN_THIS_MODULE_
DbgTrace (L"in IO::FileSystem::{}::ReadMountInfo_FromProcFSMounts_ linesize=%d, line[0]=%s", line.size (), line.empty () ? L"" : line[0].c_str ());
#endif
//
// https://www.centos.org/docs/5/html/5.2/Deployment_Guide/s2-proc-mounts.html
//
// 1 - device name
// 2 - mounted on
// 3 - fstype
//
if (line.size () >= 3) {
String devName = line[0];
// procfs/mounts often contains symbolic links to device files
// e.g. /dev/disk/by-uuid/e1d70192-1bb0-461d-b89f-b054e45bfa00
if (devName.StartsWith (L"/")) {
IgnoreExceptionsExceptThreadAbortForCall (devName = IO::FileSystem::FileSystem::Default ().CanonicalizeName (devName));
}
String mountedAt = line[1];
String fstype = line[2];
result.Add (MountedFilesystemType{mountedAt, devName, fstype});
}
}
return results;
}
}
#elif qPlatform_Windows
namespace {
Collection<MountedFilesystemType> GetMountedFilesystems_Windows_ ()
{
Collection<MountedFilesystemType> results{};
TCHAR volumeNameBuf[1024];
HANDLE hVol = INVALID_HANDLE_VALUE;
auto&& cleanup = Execution::Finally ([&]() noexcept { if (hVol != INVALID_HANDLE_VALUE) { ::CloseHandle (hVol); } });
for (HANDLE hVol = ::FindFirstVolume (volumeNameBuf, static_cast<DWORD> (NEltsOf (volumeNameBuf))); hVol != INVALID_HANDLE_VALUE;) {
DWORD lpMaximumComponentLength;
DWORD dwSysFlags;
TCHAR fileSysNameBuf[1024];
if (::GetVolumeInformation (volumeNameBuf, nullptr, static_cast<DWORD> (NEltsOf (volumeNameBuf)), nullptr, &lpMaximumComponentLength, &dwSysFlags, fileSysNameBuf, static_cast<DWORD> (NEltsOf (fileSysNameBuf)))) {
MountedFilesystemType v;
v.fFileSystemType = String::FromSDKString (fileSysNameBuf);
v.fVolumeID = String::FromSDKString (volumeNameBuf);
///
TCHAR volPathsBuf[10 * 1024];
DWORD retLen = 0;
DWORD x = ::GetVolumePathNamesForVolumeName (volumeNameBuf, volPathsBuf, static_cast<DWORD> (NEltsOf (volPathsBuf)), &retLen);
if (x == 0) {
DbgTrace (SDKSTR ("Ignoring error getting paths (volume='%s')"), volumeNameBuf);
}
else if (volPathsBuf[0] == 0) {
// Ignore - unmounted!
DbgTrace (SDKSTR ("Ignoring unmounted filesystem (volume='%s')"), volumeNameBuf);
}
else {
for (const TCHAR* NameIdx = volPathsBuf; NameIdx[0] != L'\0'; NameIdx += Characters::CString::Length (NameIdx) + 1) {
v.fMountedOn = String::FromSDKString (NameIdx);
results.Add (v);
}
}
}
// find next
if (not::FindNextVolume (hVol, volumeNameBuf, static_cast<DWORD> (NEltsOf (volumeNameBuf)))) {
::FindVolumeClose (hVol);
hVol = INVALID_HANDLE_VALUE;
}
}
return results;
}
}
#endif
/*
********************************************************************************
******************** IO::FileSystem::MountedFilesystemType *********************
********************************************************************************
*/
String MountedFilesystemType::ToString () const
{
StringBuilder sb;
sb += L"{";
sb += L"Mounted-On: '" + fMountedOn + L"', ";
sb += L"Device-Path: '" + fDevicePath + L"', ";
if (fFileSystemType) {
sb += L"FileSystem-Type: '" + *fFileSystemType + L"', ";
}
if (fVolumeID) {
sb += L"Volume-ID: '" + *fVolumeID + L"', ";
}
sb += L"}";
return sb.str ();
}
/*
********************************************************************************
******************** IO::FileSystem::GetMountedFilesystems *********************
********************************************************************************
*/
Containers::Collection<MountedFilesystemType> FileSystem::GetMountedFilesystems ()
{
#if qPlatform_Linux
return ReadMountInfo_FromProcFSMounts_ ();
#elif qPlatform_Windows
return GetMountedFilesystems_Windows_ ();
#else
AssertNotImplemented ();
return {};
#endif
}
<commit_msg>improved IO::FileSystem::GetMountedFilesystems<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2017. All rights reserved
*/
#include "../../StroikaPreComp.h"
#include "../../Characters/CString/Utilities.h"
#include "../../Characters/String.h"
#include "../../Characters/StringBuilder.h"
#include "../../Characters/String_Constant.h"
#include "../../DataExchange/Variant/CharacterDelimitedLines/Reader.h"
#include "../../Execution/Finally.h"
#include "../../Memory/SmallStackBuffer.h"
#include "FileInputStream.h"
#include "FileSystem.h"
#include "MountedFilesystem.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Characters;
using namespace Stroika::Foundation::Containers;
using namespace Stroika::Foundation::IO;
using namespace Stroika::Foundation::IO::FileSystem;
// Comment this in to turn on aggressive noisy DbgTrace in this module
//#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1
namespace {
/*
* Something like this is used on many unix systems.
*/
Collection<MountedFilesystemType> ReadMountInfo_MTabLikeFile_ (const String& filename)
{
/*
* I haven't found this clearly documented yet, but it appears that a filesystem can be over-mounted.
* See https://www.kernel.org/doc/Documentation/filesystems/ramfs-rootfs-initramfs.txt
*
* So the last one with a given mount point in the file wins.
*/
Collection<MountedFilesystemType> results;
DataExchange::Variant::CharacterDelimitedLines::Reader reader{{' ', '\t'}};
// Note - /procfs files always unseekable
for (Sequence<String> line : reader.ReadMatrix (FileInputStream::mk (filename, FileInputStream::eNotSeekable))) {
#if USE_NOISY_TRACE_IN_THIS_MODULE_
DbgTrace (L"in IO::FileSystem::{}::ReadMountInfo_MTabLikeFile_ linesize=%d, line[0]=%s", line.size (), line.empty () ? L"" : line[0].c_str ());
#endif
//
// https://www.centos.org/docs/5/html/5.2/Deployment_Guide/s2-proc-mounts.html
//
// 1 - device name
// 2 - mounted on
// 3 - fstype
//
if (line.size () >= 3) {
String devName = line[0];
// procfs/mounts often contains symbolic links to device files
// e.g. /dev/disk/by-uuid/e1d70192-1bb0-461d-b89f-b054e45bfa00
if (devName.StartsWith (L"/")) {
IgnoreExceptionsExceptThreadAbortForCall (devName = IO::FileSystem::FileSystem::Default ().CanonicalizeName (devName));
}
String mountedAt = line[1];
String fstype = line[2];
results.Add (MountedFilesystemType{mountedAt, devName, fstype});
}
}
return results;
}
}
#if qPlatform_Linux
namespace {
Collection<MountedFilesystemType> ReadMountInfo_FromProcFSMounts_ ()
{
static const String_Constant kProcMountsFileName_{L"/proc/mounts"};
return ReadMountInfo_MTabLikeFile_ (ReadMountInfo_FromProcFSMounts_);
}
}
#endif
#if qPlatform_Linux or qPlatform_MacOS
namespace {
Collection<MountedFilesystemType> ReadMountInfo_ETC_MTAB_ ()
{
static const String_Constant kProcMountsFileName_{L"/etc/mtab"};
return ReadMountInfo_MTabLikeFile_ (kProcMountsFileName_);
}
}
#endif
#if qPlatform_Windows
namespace {
Collection<MountedFilesystemType> GetMountedFilesystems_Windows_ ()
{
Collection<MountedFilesystemType> results{};
TCHAR volumeNameBuf[1024];
HANDLE hVol = INVALID_HANDLE_VALUE;
auto&& cleanup = Execution::Finally ([&]() noexcept { if (hVol != INVALID_HANDLE_VALUE) { ::CloseHandle (hVol); } });
for (HANDLE hVol = ::FindFirstVolume (volumeNameBuf, static_cast<DWORD> (NEltsOf (volumeNameBuf))); hVol != INVALID_HANDLE_VALUE;) {
DWORD lpMaximumComponentLength;
DWORD dwSysFlags;
TCHAR fileSysNameBuf[1024];
if (::GetVolumeInformation (volumeNameBuf, nullptr, static_cast<DWORD> (NEltsOf (volumeNameBuf)), nullptr, &lpMaximumComponentLength, &dwSysFlags, fileSysNameBuf, static_cast<DWORD> (NEltsOf (fileSysNameBuf)))) {
MountedFilesystemType v;
v.fFileSystemType = String::FromSDKString (fileSysNameBuf);
v.fVolumeID = String::FromSDKString (volumeNameBuf);
///
TCHAR volPathsBuf[10 * 1024];
DWORD retLen = 0;
DWORD x = ::GetVolumePathNamesForVolumeName (volumeNameBuf, volPathsBuf, static_cast<DWORD> (NEltsOf (volPathsBuf)), &retLen);
if (x == 0) {
DbgTrace (SDKSTR ("Ignoring error getting paths (volume='%s')"), volumeNameBuf);
}
else if (volPathsBuf[0] == 0) {
// Ignore - unmounted!
DbgTrace (SDKSTR ("Ignoring unmounted filesystem (volume='%s')"), volumeNameBuf);
}
else {
for (const TCHAR* NameIdx = volPathsBuf; NameIdx[0] != L'\0'; NameIdx += Characters::CString::Length (NameIdx) + 1) {
v.fMountedOn = String::FromSDKString (NameIdx);
results.Add (v);
}
}
}
// find next
if (not::FindNextVolume (hVol, volumeNameBuf, static_cast<DWORD> (NEltsOf (volumeNameBuf)))) {
::FindVolumeClose (hVol);
hVol = INVALID_HANDLE_VALUE;
}
}
return results;
}
}
#endif
/*
********************************************************************************
******************** IO::FileSystem::MountedFilesystemType *********************
********************************************************************************
*/
String MountedFilesystemType::ToString () const
{
StringBuilder sb;
sb += L"{";
sb += L"Mounted-On: '" + fMountedOn + L"', ";
sb += L"Device-Path: '" + fDevicePath + L"', ";
if (fFileSystemType) {
sb += L"FileSystem-Type: '" + *fFileSystemType + L"', ";
}
if (fVolumeID) {
sb += L"Volume-ID: '" + *fVolumeID + L"', ";
}
sb += L"}";
return sb.str ();
}
/*
********************************************************************************
******************** IO::FileSystem::GetMountedFilesystems *********************
********************************************************************************
*/
Containers::Collection<MountedFilesystemType> IO::FileSystem::GetMountedFilesystems ()
{
#if qPlatform_Linux
return ReadMountInfo_FromProcFSMounts_ ();
#elif qPlatform_MacOS
return ReadMountInfo_ETC_MTAB_ ();
#elif qPlatform_Windows
return GetMountedFilesystems_Windows_ ();
#else
AssertNotImplemented ();
return {};
#endif
}
<|endoftext|>
|
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2017. All rights reserved
*/
#include "../../StroikaPreComp.h"
#if qPlatform_Linux
#include <poll.h>
#elif qPlatform_Windows
#include <Windows.h>
#include <winioctl.h>
#endif
#include "../../Characters/CString/Utilities.h"
#include "../../Characters/Format.h"
#include "../../Characters/String.h"
#include "../../Characters/StringBuilder.h"
#include "../../Characters/String_Constant.h"
#include "../../Characters/ToString.h"
#include "../../DataExchange/Variant/CharacterDelimitedLines/Reader.h"
#include "../../Execution/Finally.h"
#include "../../Execution/Synchronized.h"
#include "../../Memory/SmallStackBuffer.h"
#include "FileInputStream.h"
#include "FileSystem.h"
#include "MountedFilesystem.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Characters;
using namespace Stroika::Foundation::Containers;
using namespace Stroika::Foundation::IO;
using namespace Stroika::Foundation::IO::FileSystem;
// Comment this in to turn on aggressive noisy DbgTrace in this module
//#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1
//#define qUseWATCHER_ 1
#ifndef qUseWATCHER_
#define qUseWATCHER_ qPlatform_POSIX
#endif
#if qUseWATCHER_
namespace {
// experimental basis for file watcher
struct Watcher_ {
int mfd;
Watcher_ (const String& fn)
: mfd (::open (fn.AsNarrowSDKString ().c_str (), O_RDONLY, 0))
{
}
~Watcher_ ()
{
::close (mfd);
}
bool IsNewAvail () const
{
struct pollfd pfd;
int rv;
int changes = 0;
pfd.fd = mfd;
pfd.events = POLLERR | POLLPRI;
pfd.revents = 0;
if ((rv = poll (&pfd, 1, 5)) >= 0) {
if (pfd.revents & POLLERR) {
return true;
}
}
}
};
}
#endif
namespace {
/*
* Something like this is used on many unix systems.
*/
Collection<MountedFilesystemType> ReadMountInfo_MTabLikeFile_ (const Streams::InputStream<Memory::Byte>& readStream)
{
/*
* I haven't found this clearly documented yet, but it appears that a filesystem can be over-mounted.
* See https://www.kernel.org/doc/Documentation/filesystems/ramfs-rootfs-initramfs.txt
*
* So the last one with a given mount point in the file wins.
*/
Collection<MountedFilesystemType> results;
DataExchange::Variant::CharacterDelimitedLines::Reader reader{{' ', '\t'}};
for (Sequence<String> line : reader.ReadMatrix (readStream)) {
#if USE_NOISY_TRACE_IN_THIS_MODULE_
DbgTrace (L"in IO::FileSystem::{}::ReadMountInfo_MTabLikeFile_ linesize=%d, line[0]=%s", line.size (), line.empty () ? L"" : line[0].c_str ());
#endif
//
// https://www.centos.org/docs/5/html/5.2/Deployment_Guide/s2-proc-mounts.html
//
// 1 - device name
// 2 - mounted on
// 3 - fstype
//
if (line.size () >= 3) {
String devName = line[0];
// procfs/mounts often contains symbolic links to device files
// e.g. /dev/disk/by-uuid/e1d70192-1bb0-461d-b89f-b054e45bfa00
if (devName.StartsWith (L"/")) {
IgnoreExceptionsExceptThreadAbortForCall (devName = IO::FileSystem::FileSystem::Default ().CanonicalizeName (devName));
}
String mountedAt = line[1];
String fstype = line[2];
results.Add (MountedFilesystemType{mountedAt, Set<String>{devName}, fstype});
}
}
return results;
}
}
#if qPlatform_Linux
namespace {
Collection<MountedFilesystemType> ReadMountInfo_FromProcFSMounts_ ()
{
// Note - /procfs files always unseekable
static const String_Constant kUseFile2List_{L"/proc/mounts"};
#if qUseWATCHER_
static const Watcher_ sWatcher_{kUseFile2List_};
static Execution::Syncrhonized<Collection<MountedFilesystemType>> sLastResult_;
static bool sFirstTime_{true};
if (sFirstTime_ or sWatcher_.IsNewAvail ()) {
sLastResult_ = ReadMountInfo_MTabLikeFile_ (FileInputStream::mk (kUseFile2List_, FileInputStream::eNotSeekable));
}
return sLastResult_;
#else
return ReadMountInfo_MTabLikeFile_ (FileInputStream::mk (kUseFile2List_, FileInputStream::eNotSeekable));
#endif
}
}
#endif
#if qPlatform_Linux
namespace {
Collection<MountedFilesystemType> ReadMountInfo_ETC_MTAB_ ()
{
// Note - /procfs files always unseekable and this is sklink to /procfs
static const String_Constant kUseFile2List_{L"/etc/mtab"};
return ReadMountInfo_MTabLikeFile_ (FileInputStream::mk (kUseFile2List_, FileInputStream::eNotSeekable));
}
}
#endif
#if qPlatform_Windows
namespace {
using DynamicDiskIDType = String;
static String GetPhysNameForDriveNumber_ (unsigned int i)
{
// This format is NOT super well documented, and was mostly derived from reading the remarks section
// of https://msdn.microsoft.com/en-us/library/windows/desktop/aa363216%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396
// (DeviceIoControl function)
return Characters::Format (L"\\\\.\\PhysicalDrive%d", i);
}
Optional<Set<DynamicDiskIDType>> GetDisksForVolume_ (String volumeName)
{
wchar_t volPathsBuf[10 * 1024] = {0};
DWORD retLen = 0;
DWORD x = ::GetVolumePathNamesForVolumeNameW (volumeName.c_str (), volPathsBuf, static_cast<DWORD> (NEltsOf (volPathsBuf)), &retLen);
if (x == 0 or retLen <= 1) {
return Set<String> ();
}
Assert (1 <= Characters::CString::Length (volPathsBuf) and Characters::CString::Length (volPathsBuf) < NEltsOf (volPathsBuf));
volumeName = L"\\\\.\\" + String::FromSDKString (volPathsBuf).CircularSubString (0, -1);
// @todo - rewrite this - must somehow otherwise callocate this to be large enuf (dynamic alloc) - if we want more disk exents, but not sure when that happens...
VOLUME_DISK_EXTENTS volumeDiskExtents;
{
/*
* For reasons I don't understand (maybe a hit at http://superuser.com/questions/733687/give-regular-user-permission-to-access-physical-drive-on-windows)
* this only works with admin privilges
*/
HANDLE hHandle = ::CreateFileW (volumeName.c_str (), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hHandle == INVALID_HANDLE_VALUE) {
return {};
}
DWORD dwBytesReturned = 0;
BOOL bResult = ::DeviceIoControl (hHandle, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, NULL, 0, &volumeDiskExtents, sizeof (volumeDiskExtents), &dwBytesReturned, NULL);
::CloseHandle (hHandle);
if (not bResult) {
return {};
}
}
Set<DynamicDiskIDType> result;
for (DWORD n = 0; n < volumeDiskExtents.NumberOfDiskExtents; ++n) {
PDISK_EXTENT pDiskExtent = &volumeDiskExtents.Extents[n];
result.Add (GetPhysNameForDriveNumber_ (pDiskExtent->DiskNumber));
}
return result;
}
Collection<MountedFilesystemType> GetMountedFilesystems_Windows_ ()
{
Collection<MountedFilesystemType> results{};
TCHAR volumeNameBuf[1024];
HANDLE hVol = INVALID_HANDLE_VALUE;
auto&& cleanup = Execution::Finally ([&]() noexcept { if (hVol != INVALID_HANDLE_VALUE) { ::CloseHandle (hVol); } });
for (HANDLE hVol = ::FindFirstVolume (volumeNameBuf, static_cast<DWORD> (NEltsOf (volumeNameBuf))); hVol != INVALID_HANDLE_VALUE;) {
DWORD lpMaximumComponentLength;
DWORD dwSysFlags;
TCHAR fileSysNameBuf[1024];
if (::GetVolumeInformation (volumeNameBuf, nullptr, static_cast<DWORD> (NEltsOf (volumeNameBuf)), nullptr, &lpMaximumComponentLength, &dwSysFlags, fileSysNameBuf, static_cast<DWORD> (NEltsOf (fileSysNameBuf)))) {
MountedFilesystemType v;
v.fFileSystemType = String::FromSDKString (fileSysNameBuf);
v.fVolumeID = String::FromSDKString (volumeNameBuf);
v.fDevicePaths = GetDisksForVolume_ (volumeNameBuf);
///
TCHAR volPathsBuf[10 * 1024];
DWORD retLen = 0;
DWORD x = ::GetVolumePathNamesForVolumeName (volumeNameBuf, volPathsBuf, static_cast<DWORD> (NEltsOf (volPathsBuf)), &retLen);
if (x == 0) {
DbgTrace (SDKSTR ("Ignoring error getting paths (volume='%s')"), volumeNameBuf);
}
else if (volPathsBuf[0] == 0) {
// Ignore - unmounted!
DbgTrace (SDKSTR ("Ignoring unmounted filesystem (volume='%s')"), volumeNameBuf);
}
else {
for (const TCHAR* NameIdx = volPathsBuf; NameIdx[0] != L'\0'; NameIdx += Characters::CString::Length (NameIdx) + 1) {
v.fMountedOn = String::FromSDKString (NameIdx);
results.Add (v);
}
}
}
// find next
if (not::FindNextVolume (hVol, volumeNameBuf, static_cast<DWORD> (NEltsOf (volumeNameBuf)))) {
::FindVolumeClose (hVol);
hVol = INVALID_HANDLE_VALUE;
}
}
return results;
}
}
#endif
/*
********************************************************************************
******************** IO::FileSystem::MountedFilesystemType *********************
********************************************************************************
*/
String MountedFilesystemType::ToString () const
{
StringBuilder sb;
sb += L"{";
sb += L"Mounted-On: '" + fMountedOn + L"', ";
if (fDevicePaths) {
sb += L"Device-Paths: " + Characters::ToString (*fDevicePaths) + L", ";
}
if (fFileSystemType) {
sb += L"FileSystem-Type: '" + *fFileSystemType + L"', ";
}
if (fVolumeID) {
sb += L"Volume-ID: '" + *fVolumeID + L"', ";
}
sb += L"}";
return sb.str ();
}
/*
********************************************************************************
******************** IO::FileSystem::GetMountedFilesystems *********************
********************************************************************************
*/
Containers::Collection<MountedFilesystemType> IO::FileSystem::GetMountedFilesystems ()
{
#if qPlatform_Linux
return ReadMountInfo_FromProcFSMounts_ ();
#elif qPlatform_Windows
return GetMountedFilesystems_Windows_ ();
#else
AssertNotImplemented ();
return {};
#endif
}
<commit_msg>enable/tweak/fix new faster watcher code for mounted filesystems for Linux<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2017. All rights reserved
*/
#include "../../StroikaPreComp.h"
#if qPlatform_Linux
#include <fcntl.h>
#include <poll.h>
#include <unistd.h>
#elif qPlatform_Windows
#include <Windows.h>
#include <winioctl.h>
#endif
#include "../../Characters/CString/Utilities.h"
#include "../../Characters/Format.h"
#include "../../Characters/String.h"
#include "../../Characters/StringBuilder.h"
#include "../../Characters/String_Constant.h"
#include "../../Characters/ToString.h"
#include "../../DataExchange/Variant/CharacterDelimitedLines/Reader.h"
#include "../../Execution/Finally.h"
#include "../../Execution/Synchronized.h"
#include "../../Memory/SmallStackBuffer.h"
#include "FileInputStream.h"
#include "FileSystem.h"
#include "MountedFilesystem.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Characters;
using namespace Stroika::Foundation::Containers;
using namespace Stroika::Foundation::IO;
using namespace Stroika::Foundation::IO::FileSystem;
// Comment this in to turn on aggressive noisy DbgTrace in this module
//#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1
#ifndef qUseWATCHER_
#define qUseWATCHER_ qPlatform_POSIX
#endif
#if qUseWATCHER_
namespace {
// experimental basis for file watcher
struct Watcher_ {
int mfd;
Watcher_ (const String& fn)
: mfd (::open (fn.AsNarrowSDKString ().c_str (), O_RDONLY, 0))
{
}
~Watcher_ ()
{
::close (mfd);
}
bool IsNewAvail () const
{
// according to http://stackoverflow.com/questions/5070801/monitoring-mount-point-changes-via-proc-mounts
// have to use poll with POLLPRI | POLLERR flags
struct pollfd pfd;
int rv;
int changes = 0;
pfd.fd = mfd;
pfd.events = POLLERR | POLLPRI;
pfd.revents = 0;
if ((rv = poll (&pfd, 1, 0)) >= 0) {
if (pfd.revents & POLLERR) {
return true;
}
}
return false;
}
};
}
#endif
namespace {
/*
* Something like this is used on many unix systems.
*/
Collection<MountedFilesystemType> ReadMountInfo_MTabLikeFile_ (const Streams::InputStream<Memory::Byte>& readStream)
{
/*
* I haven't found this clearly documented yet, but it appears that a filesystem can be over-mounted.
* See https://www.kernel.org/doc/Documentation/filesystems/ramfs-rootfs-initramfs.txt
*
* So the last one with a given mount point in the file wins.
*/
Collection<MountedFilesystemType> results;
DataExchange::Variant::CharacterDelimitedLines::Reader reader{{' ', '\t'}};
for (Sequence<String> line : reader.ReadMatrix (readStream)) {
#if USE_NOISY_TRACE_IN_THIS_MODULE_
DbgTrace (L"in IO::FileSystem::{}::ReadMountInfo_MTabLikeFile_ linesize=%d, line[0]=%s", line.size (), line.empty () ? L"" : line[0].c_str ());
#endif
//
// https://www.centos.org/docs/5/html/5.2/Deployment_Guide/s2-proc-mounts.html
//
// 1 - device name
// 2 - mounted on
// 3 - fstype
//
if (line.size () >= 3) {
String devName = line[0];
// procfs/mounts often contains symbolic links to device files
// e.g. /dev/disk/by-uuid/e1d70192-1bb0-461d-b89f-b054e45bfa00
if (devName.StartsWith (L"/")) {
IgnoreExceptionsExceptThreadAbortForCall (devName = IO::FileSystem::FileSystem::Default ().CanonicalizeName (devName));
}
String mountedAt = line[1];
String fstype = line[2];
results.Add (MountedFilesystemType{mountedAt, Set<String>{devName}, fstype});
}
}
return results;
}
}
#if qPlatform_Linux
namespace {
Collection<MountedFilesystemType> ReadMountInfo_FromProcFSMounts_ ()
{
// Note - /procfs files always unseekable
static const String_Constant kUseFile2List_{L"/proc/mounts"};
#if qUseWATCHER_
static const Watcher_ sWatcher_{kUseFile2List_};
static Execution::Synchronized<Collection<MountedFilesystemType>> sLastResult_;
static bool sFirstTime_{true};
if (sFirstTime_ or sWatcher_.IsNewAvail ()) {
sLastResult_ = ReadMountInfo_MTabLikeFile_ (FileInputStream::mk (kUseFile2List_, FileInputStream::eNotSeekable));
sFirstTime_ = false;
}
return sLastResult_;
#else
return ReadMountInfo_MTabLikeFile_ (FileInputStream::mk (kUseFile2List_, FileInputStream::eNotSeekable));
#endif
}
}
#endif
#if qPlatform_Linux
namespace {
Collection<MountedFilesystemType> ReadMountInfo_ETC_MTAB_ ()
{
// Note - /procfs files always unseekable and this is sklink to /procfs
static const String_Constant kUseFile2List_{L"/etc/mtab"};
return ReadMountInfo_MTabLikeFile_ (FileInputStream::mk (kUseFile2List_, FileInputStream::eNotSeekable));
}
}
#endif
#if qPlatform_Windows
namespace {
using DynamicDiskIDType = String;
static String GetPhysNameForDriveNumber_ (unsigned int i)
{
// This format is NOT super well documented, and was mostly derived from reading the remarks section
// of https://msdn.microsoft.com/en-us/library/windows/desktop/aa363216%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396
// (DeviceIoControl function)
return Characters::Format (L"\\\\.\\PhysicalDrive%d", i);
}
Optional<Set<DynamicDiskIDType>> GetDisksForVolume_ (String volumeName)
{
wchar_t volPathsBuf[10 * 1024] = {0};
DWORD retLen = 0;
DWORD x = ::GetVolumePathNamesForVolumeNameW (volumeName.c_str (), volPathsBuf, static_cast<DWORD> (NEltsOf (volPathsBuf)), &retLen);
if (x == 0 or retLen <= 1) {
return Set<String> ();
}
Assert (1 <= Characters::CString::Length (volPathsBuf) and Characters::CString::Length (volPathsBuf) < NEltsOf (volPathsBuf));
volumeName = L"\\\\.\\" + String::FromSDKString (volPathsBuf).CircularSubString (0, -1);
// @todo - rewrite this - must somehow otherwise callocate this to be large enuf (dynamic alloc) - if we want more disk exents, but not sure when that happens...
VOLUME_DISK_EXTENTS volumeDiskExtents;
{
/*
* For reasons I don't understand (maybe a hit at http://superuser.com/questions/733687/give-regular-user-permission-to-access-physical-drive-on-windows)
* this only works with admin privilges
*/
HANDLE hHandle = ::CreateFileW (volumeName.c_str (), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hHandle == INVALID_HANDLE_VALUE) {
return {};
}
DWORD dwBytesReturned = 0;
BOOL bResult = ::DeviceIoControl (hHandle, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, NULL, 0, &volumeDiskExtents, sizeof (volumeDiskExtents), &dwBytesReturned, NULL);
::CloseHandle (hHandle);
if (not bResult) {
return {};
}
}
Set<DynamicDiskIDType> result;
for (DWORD n = 0; n < volumeDiskExtents.NumberOfDiskExtents; ++n) {
PDISK_EXTENT pDiskExtent = &volumeDiskExtents.Extents[n];
result.Add (GetPhysNameForDriveNumber_ (pDiskExtent->DiskNumber));
}
return result;
}
Collection<MountedFilesystemType> GetMountedFilesystems_Windows_ ()
{
Collection<MountedFilesystemType> results{};
TCHAR volumeNameBuf[1024];
HANDLE hVol = INVALID_HANDLE_VALUE;
auto&& cleanup = Execution::Finally ([&]() noexcept { if (hVol != INVALID_HANDLE_VALUE) { ::CloseHandle (hVol); } });
for (HANDLE hVol = ::FindFirstVolume (volumeNameBuf, static_cast<DWORD> (NEltsOf (volumeNameBuf))); hVol != INVALID_HANDLE_VALUE;) {
DWORD lpMaximumComponentLength;
DWORD dwSysFlags;
TCHAR fileSysNameBuf[1024];
if (::GetVolumeInformation (volumeNameBuf, nullptr, static_cast<DWORD> (NEltsOf (volumeNameBuf)), nullptr, &lpMaximumComponentLength, &dwSysFlags, fileSysNameBuf, static_cast<DWORD> (NEltsOf (fileSysNameBuf)))) {
MountedFilesystemType v;
v.fFileSystemType = String::FromSDKString (fileSysNameBuf);
v.fVolumeID = String::FromSDKString (volumeNameBuf);
v.fDevicePaths = GetDisksForVolume_ (volumeNameBuf);
///
TCHAR volPathsBuf[10 * 1024];
DWORD retLen = 0;
DWORD x = ::GetVolumePathNamesForVolumeName (volumeNameBuf, volPathsBuf, static_cast<DWORD> (NEltsOf (volPathsBuf)), &retLen);
if (x == 0) {
DbgTrace (SDKSTR ("Ignoring error getting paths (volume='%s')"), volumeNameBuf);
}
else if (volPathsBuf[0] == 0) {
// Ignore - unmounted!
DbgTrace (SDKSTR ("Ignoring unmounted filesystem (volume='%s')"), volumeNameBuf);
}
else {
for (const TCHAR* NameIdx = volPathsBuf; NameIdx[0] != L'\0'; NameIdx += Characters::CString::Length (NameIdx) + 1) {
v.fMountedOn = String::FromSDKString (NameIdx);
results.Add (v);
}
}
}
// find next
if (not::FindNextVolume (hVol, volumeNameBuf, static_cast<DWORD> (NEltsOf (volumeNameBuf)))) {
::FindVolumeClose (hVol);
hVol = INVALID_HANDLE_VALUE;
}
}
return results;
}
}
#endif
/*
********************************************************************************
******************** IO::FileSystem::MountedFilesystemType *********************
********************************************************************************
*/
String MountedFilesystemType::ToString () const
{
StringBuilder sb;
sb += L"{";
sb += L"Mounted-On: '" + fMountedOn + L"', ";
if (fDevicePaths) {
sb += L"Device-Paths: " + Characters::ToString (*fDevicePaths) + L", ";
}
if (fFileSystemType) {
sb += L"FileSystem-Type: '" + *fFileSystemType + L"', ";
}
if (fVolumeID) {
sb += L"Volume-ID: '" + *fVolumeID + L"', ";
}
sb += L"}";
return sb.str ();
}
/*
********************************************************************************
******************** IO::FileSystem::GetMountedFilesystems *********************
********************************************************************************
*/
Containers::Collection<MountedFilesystemType> IO::FileSystem::GetMountedFilesystems ()
{
#if qPlatform_Linux
return ReadMountInfo_FromProcFSMounts_ ();
#elif qPlatform_Windows
return GetMountedFilesystems_Windows_ ();
#else
AssertNotImplemented ();
return {};
#endif
}
<|endoftext|>
|
<commit_before>/*
* LootManagerImplementation.cpp
*
* Created on: Jun 20, 2011
* Author: Kyle
*/
#include "engine/engine.h"
#include "LootManager.h"
#include "server/zone/objects/scene/SceneObject.h"
#include "server/zone/objects/creature/CreatureObject.h"
#include "server/zone/objects/creature/AiAgent.h"
#include "server/zone/managers/crafting/CraftingManager.h"
#include "server/zone/managers/templates/TemplateManager.h"
#include "server/zone/templates/LootItemTemplate.h"
#include "server/zone/ZoneServer.h"
#include "server/zone/managers/stringid/StringIdManager.h"
#include "LootGroupMap.h"
void LootManagerImplementation::initialize() {
lua = new Lua();
lua->init();
info("Loading configuration.");
if(!loadConfigData()) {
loadDefaultConfig();
info("***** ERROR in configuration, using default values");
}
lootGroupMap = LootGroupMap::instance();
lootGroupMap->initialize();
info("Loaded " + String::valueOf(lootGroupMap->getTotalItems()) + " loot items.", true);
info("Loaded " + String::valueOf(lootGroupMap->getTotalGroups()) + " loot groups.", true);
info("Initialized.");
}
bool LootManagerImplementation::loadConfigFile() {
return lua->runFile("scripts/managers/loot_manager.lua");
}
bool LootManagerImplementation::loadConfigData() {
if (!loadConfigFile())
return false;
exceptionalChance = lua->getGlobalFloat("exceptionalChance");
exceptionalModifier = lua->getGlobalFloat("exceptionalModifier");
legendaryChance = lua->getGlobalFloat("legendaryChance");
legendaryModifier = lua->getGlobalFloat("legendaryModifier");
LuaObject lootableModsTable = lua->getGlobalObject("lootableStatMods");
if (!lootableModsTable.isValidTable())
return false;
for (int i = 1; i <= lootableModsTable.getTableSize(); ++i) {
String mod = lootableModsTable.getStringAt(i);
lootableMods.put(mod);
}
lootableModsTable.pop();
info("Loaded " + String::valueOf(lootableMods.size()) + " lootable stat mods.", true);
return true;
}
void LootManagerImplementation::loadDefaultConfig() {
}
void LootManagerImplementation::setInitialObjectStats(LootItemTemplate* templateObject, CraftingValues* craftingValues, TangibleObject* prototype) {
SharedTangibleObjectTemplate* tanoTemplate = dynamic_cast<SharedTangibleObjectTemplate*>(prototype->getObjectTemplate());
if (tanoTemplate != NULL) {
Vector<String>* props = tanoTemplate->getExperimentalSubGroupTitles();
Vector<int>* mins = tanoTemplate->getExperimentalMin();
Vector<int>* maxs = tanoTemplate->getExperimentalMax();
Vector<short>* prec = tanoTemplate->getExperimentalPrecision();
for (int i = 0; i < props->size(); ++i) {
String property = props->get(i);
if (craftingValues->hasProperty(property))
continue;
craftingValues->addExperimentalProperty(property, property, mins->get(i), maxs->get(i), prec->get(i), false);
}
}
Vector<String>* customizationData = templateObject->getCustomizationStringNames();
Vector<Vector<int> >* customizationValues = templateObject->getCustomizationValues();
for (int i = 0; i < customizationData->size(); ++i) {
String customizationString = customizationData->get(i);
Vector<int>* values = &customizationValues->get(i);
int idx = customizationString.lastIndexOf("/");
if (idx != -1)
customizationString = customizationString.subString(idx + 1);
if (values->size() > 0) {
int randomValue = values->get(System::random(values->size() - 1));
prototype->setCustomizationVariable(customizationString, randomValue, false);
}
}
}
void LootManagerImplementation::setCustomObjectName(TangibleObject* object, LootItemTemplate* templateObject) {
String customName = templateObject->getCustomObjectName();
if (!customName.isEmpty()) {
if (customName.charAt(0) == '@') {
StringId stringId(customName);
object->setObjectName(stringId);
} else {
object->setCustomObjectName(customName, false);
}
}
}
int LootManagerImplementation::calculateLootCredits(int level) {
int maxcredits = (int) round((.03f * level * level) + (3 * level) + 50);
int mincredits = (int) round((((float) maxcredits) * .5f) + (2.0f * level));
int credits = mincredits + System::random(maxcredits - mincredits);
return credits;
}
SceneObject* LootManagerImplementation::createLootObject(LootItemTemplate* templateObject, int level) {
String directTemplateObject = templateObject->getDirectObjectTemplate();
ManagedReference<TangibleObject*> prototype = dynamic_cast<TangibleObject*> (zoneServer->createObject(directTemplateObject.hashCode(), 2));
if (prototype == NULL)
return NULL;
prototype->createChildObjects();
CraftingValues craftingValues = templateObject->getCraftingValuesCopy();
setInitialObjectStats(templateObject, &craftingValues, prototype);
setCustomObjectName(prototype, templateObject);
float excMod = 1.0;
if (System::random(exceptionalChance) == exceptionalChance) {
UnicodeString objectName = prototype->getCustomObjectName();
uint32 bitmask = prototype->getOptionsBitmask() | 0x20;
if (objectName.isEmpty())
objectName = StringIdManager::instance()->getStringId(prototype->getObjectName()->getFullPath().hashCode());
UnicodeString newName = objectName + " (Exceptional)";
prototype->setCustomObjectName(newName, false);
excMod = exceptionalModifier;
prototype->setOptionsBitmask(bitmask, false);
} else if (System::random(legendaryChance) == legendaryChance) {
UnicodeString objectName = prototype->getCustomObjectName();
uint32 bitmask = prototype->getOptionsBitmask() | 0x20;
if (objectName.isEmpty())
objectName = StringIdManager::instance()->getStringId(prototype->getObjectName()->getFullPath().hashCode());
UnicodeString newName = objectName + " (Legendary)";
prototype->setCustomObjectName(newName, false);
excMod = legendaryModifier;
prototype->setOptionsBitmask(bitmask, false);
}
String subtitle;
float percentage = System::random(10000) / 10000.f; //Generate a base percentage. We will deviate slightly from this on each stat.
for (int i = 0; i < craftingValues.getExperimentalPropertySubtitleSize(); ++i) {
subtitle = craftingValues.getExperimentalPropertySubtitle(i);
if (subtitle == "hitpoints")
continue;
float min = craftingValues.getMinValue(subtitle);
float max = craftingValues.getMaxValue(subtitle);
float minMod = (max >= min) ? 2000.f : -2000.f;
float maxMod = (max >= min) ? 500.f : -500.f;
min = (min * level / minMod) + min;
max = (max * level / maxMod) + max;
if (max >= min) {
min *= excMod;
max *= excMod;
} else {
min /= excMod;
max /= excMod;
}
craftingValues.setMinValue(subtitle, min);
craftingValues.setMaxValue(subtitle, max);
float deviation = (((float) System::random(400)) - 200) / 1000.f; //Deviate up to 2%
craftingValues.setCurrentPercentage(subtitle, percentage + deviation);
}
// Use percentages to recalculate the values
craftingValues.recalculateValues(false);
craftingValues.addExperimentalProperty("creatureLevel", "creatureLevel", level, level, 0, false);
// Update the Tano with new values
prototype->updateCraftingValues(&craftingValues, false);
return prototype;
}
void LootManagerImplementation::createLoot(SceneObject* container, AiAgent* creature) {
LootGroupCollection* lootGroups = creature->getLootGroups();
int lootChance = creature->getLootChance();
if (lootGroups == NULL || lootChance <= 0)
return;
//First roll is on what loot group, if any, to use.
int roll = System::random(10000000); //100.00000% with 5 decimal precision
if (roll > lootChance) {
//The creature isn't dropping loot because the roll was in the "no drop" zone of the percentage.
return;
}
int tempChance = 0; //Start at 0.
//Now loop through the lootgroups to figure out which lootgroup to use.
for (int i = 0; i < lootGroups->size(); ++i) {
LootGroupEntry entry = lootGroups->get(i);
tempChance += entry.getWeight();
//Is this entry lower than the roll? If yes, then we want to try the next entry.
if (tempChance < roll)
continue;
createLoot(container, entry.getItemTemplate(), creature->getLevel());
return; //If we got here, then we found the entry we were looking for.
}
}
void LootManagerImplementation::createLoot(SceneObject* container, const String& lootGroup, int level) {
if (container->hasFullContainerObjects())
return;
Reference<LootGroup*> group = lootGroupMap->get(lootGroup);
if (group == NULL)
return;
//Now we do the second roll for the item out of the group.
int roll = System::random(10000000);
int tempChance = 0;
for (int i = 0; i < group->size(); ++i) {
if (container->hasFullContainerObjects())
return;
LootGroupEntry entry = group->get(i);
tempChance += entry.getWeight();
if (tempChance < roll)
continue; //If the roll is greater than this item, move on to the next one.
String item = entry.getItemTemplate();
LootItemTemplate* itemTemplate = lootGroupMap->getLootItem(item);
if (itemTemplate != NULL) {
//int minLevel = itemTemplate->getMinimumLevel();
//int maxLevel = itemTemplate->getMaximumLevel();
//if (level != -1) {
//if (minLevel != -1 && level < minLevel)
//continue;
//if (maxLevel != -1 && level > maxLevel)
//continue;
//}
SceneObject* obj = createLootObject(itemTemplate, level);
if (obj != NULL) {
if (container->transferObject(obj, -1, false))
container->broadcastObject(obj, true);
}
} else {
error(item + " loot item template not found");
}
return;
}
}
<commit_msg>[fixed] Using optionbitmask class for yellow name.<commit_after>/*
* LootManagerImplementation.cpp
*
* Created on: Jun 20, 2011
* Author: Kyle
*/
#include "engine/engine.h"
#include "LootManager.h"
#include "server/zone/objects/scene/SceneObject.h"
#include "server/zone/objects/creature/CreatureObject.h"
#include "server/zone/objects/creature/AiAgent.h"
#include "server/zone/managers/crafting/CraftingManager.h"
#include "server/zone/managers/templates/TemplateManager.h"
#include "server/zone/templates/LootItemTemplate.h"
#include "server/zone/ZoneServer.h"
#include "server/zone/managers/stringid/StringIdManager.h"
#include "LootGroupMap.h"
void LootManagerImplementation::initialize() {
lua = new Lua();
lua->init();
info("Loading configuration.");
if(!loadConfigData()) {
loadDefaultConfig();
info("***** ERROR in configuration, using default values");
}
lootGroupMap = LootGroupMap::instance();
lootGroupMap->initialize();
info("Loaded " + String::valueOf(lootGroupMap->getTotalItems()) + " loot items.", true);
info("Loaded " + String::valueOf(lootGroupMap->getTotalGroups()) + " loot groups.", true);
info("Initialized.");
}
bool LootManagerImplementation::loadConfigFile() {
return lua->runFile("scripts/managers/loot_manager.lua");
}
bool LootManagerImplementation::loadConfigData() {
if (!loadConfigFile())
return false;
exceptionalChance = lua->getGlobalFloat("exceptionalChance");
exceptionalModifier = lua->getGlobalFloat("exceptionalModifier");
legendaryChance = lua->getGlobalFloat("legendaryChance");
legendaryModifier = lua->getGlobalFloat("legendaryModifier");
LuaObject lootableModsTable = lua->getGlobalObject("lootableStatMods");
if (!lootableModsTable.isValidTable())
return false;
for (int i = 1; i <= lootableModsTable.getTableSize(); ++i) {
String mod = lootableModsTable.getStringAt(i);
lootableMods.put(mod);
}
lootableModsTable.pop();
info("Loaded " + String::valueOf(lootableMods.size()) + " lootable stat mods.", true);
return true;
}
void LootManagerImplementation::loadDefaultConfig() {
}
void LootManagerImplementation::setInitialObjectStats(LootItemTemplate* templateObject, CraftingValues* craftingValues, TangibleObject* prototype) {
SharedTangibleObjectTemplate* tanoTemplate = dynamic_cast<SharedTangibleObjectTemplate*>(prototype->getObjectTemplate());
if (tanoTemplate != NULL) {
Vector<String>* props = tanoTemplate->getExperimentalSubGroupTitles();
Vector<int>* mins = tanoTemplate->getExperimentalMin();
Vector<int>* maxs = tanoTemplate->getExperimentalMax();
Vector<short>* prec = tanoTemplate->getExperimentalPrecision();
for (int i = 0; i < props->size(); ++i) {
String property = props->get(i);
if (craftingValues->hasProperty(property))
continue;
craftingValues->addExperimentalProperty(property, property, mins->get(i), maxs->get(i), prec->get(i), false);
}
}
Vector<String>* customizationData = templateObject->getCustomizationStringNames();
Vector<Vector<int> >* customizationValues = templateObject->getCustomizationValues();
for (int i = 0; i < customizationData->size(); ++i) {
String customizationString = customizationData->get(i);
Vector<int>* values = &customizationValues->get(i);
int idx = customizationString.lastIndexOf("/");
if (idx != -1)
customizationString = customizationString.subString(idx + 1);
if (values->size() > 0) {
int randomValue = values->get(System::random(values->size() - 1));
prototype->setCustomizationVariable(customizationString, randomValue, false);
}
}
}
void LootManagerImplementation::setCustomObjectName(TangibleObject* object, LootItemTemplate* templateObject) {
String customName = templateObject->getCustomObjectName();
if (!customName.isEmpty()) {
if (customName.charAt(0) == '@') {
StringId stringId(customName);
object->setObjectName(stringId);
} else {
object->setCustomObjectName(customName, false);
}
}
}
int LootManagerImplementation::calculateLootCredits(int level) {
int maxcredits = (int) round((.03f * level * level) + (3 * level) + 50);
int mincredits = (int) round((((float) maxcredits) * .5f) + (2.0f * level));
int credits = mincredits + System::random(maxcredits - mincredits);
return credits;
}
SceneObject* LootManagerImplementation::createLootObject(LootItemTemplate* templateObject, int level) {
String directTemplateObject = templateObject->getDirectObjectTemplate();
ManagedReference<TangibleObject*> prototype = dynamic_cast<TangibleObject*> (zoneServer->createObject(directTemplateObject.hashCode(), 2));
if (prototype == NULL)
return NULL;
prototype->createChildObjects();
CraftingValues craftingValues = templateObject->getCraftingValuesCopy();
setInitialObjectStats(templateObject, &craftingValues, prototype);
setCustomObjectName(prototype, templateObject);
float excMod = 1.0;
if (System::random(exceptionalChance) == exceptionalChance) {
UnicodeString objectName = prototype->getCustomObjectName();
uint32 bitmask = prototype->getOptionsBitmask() | OptionBitmask::YELLOW;
if (objectName.isEmpty())
objectName = StringIdManager::instance()->getStringId(prototype->getObjectName()->getFullPath().hashCode());
UnicodeString newName = objectName + " (Exceptional)";
prototype->setCustomObjectName(newName, false);
excMod = exceptionalModifier;
prototype->setOptionsBitmask(bitmask, false);
} else if (System::random(legendaryChance) == legendaryChance) {
UnicodeString objectName = prototype->getCustomObjectName();
uint32 bitmask = prototype->getOptionsBitmask() | OptionBitmask::YELLOW;
if (objectName.isEmpty())
objectName = StringIdManager::instance()->getStringId(prototype->getObjectName()->getFullPath().hashCode());
UnicodeString newName = objectName + " (Legendary)";
prototype->setCustomObjectName(newName, false);
excMod = legendaryModifier;
prototype->setOptionsBitmask(bitmask, false);
}
String subtitle;
float percentage = System::random(10000) / 10000.f; //Generate a base percentage. We will deviate slightly from this on each stat.
for (int i = 0; i < craftingValues.getExperimentalPropertySubtitleSize(); ++i) {
subtitle = craftingValues.getExperimentalPropertySubtitle(i);
if (subtitle == "hitpoints")
continue;
float min = craftingValues.getMinValue(subtitle);
float max = craftingValues.getMaxValue(subtitle);
float minMod = (max >= min) ? 2000.f : -2000.f;
float maxMod = (max >= min) ? 500.f : -500.f;
min = (min * level / minMod) + min;
max = (max * level / maxMod) + max;
if (max >= min) {
min *= excMod;
max *= excMod;
} else {
min /= excMod;
max /= excMod;
}
craftingValues.setMinValue(subtitle, min);
craftingValues.setMaxValue(subtitle, max);
float deviation = (((float) System::random(400)) - 200) / 1000.f; //Deviate up to 2%
craftingValues.setCurrentPercentage(subtitle, percentage + deviation);
}
// Use percentages to recalculate the values
craftingValues.recalculateValues(false);
craftingValues.addExperimentalProperty("creatureLevel", "creatureLevel", level, level, 0, false);
// Update the Tano with new values
prototype->updateCraftingValues(&craftingValues, false);
return prototype;
}
void LootManagerImplementation::createLoot(SceneObject* container, AiAgent* creature) {
LootGroupCollection* lootGroups = creature->getLootGroups();
int lootChance = creature->getLootChance();
if (lootGroups == NULL || lootChance <= 0)
return;
//First roll is on what loot group, if any, to use.
int roll = System::random(10000000); //100.00000% with 5 decimal precision
if (roll > lootChance) {
//The creature isn't dropping loot because the roll was in the "no drop" zone of the percentage.
return;
}
int tempChance = 0; //Start at 0.
//Now loop through the lootgroups to figure out which lootgroup to use.
for (int i = 0; i < lootGroups->size(); ++i) {
LootGroupEntry entry = lootGroups->get(i);
tempChance += entry.getWeight();
//Is this entry lower than the roll? If yes, then we want to try the next entry.
if (tempChance < roll)
continue;
createLoot(container, entry.getItemTemplate(), creature->getLevel());
return; //If we got here, then we found the entry we were looking for.
}
}
void LootManagerImplementation::createLoot(SceneObject* container, const String& lootGroup, int level) {
if (container->hasFullContainerObjects())
return;
Reference<LootGroup*> group = lootGroupMap->get(lootGroup);
if (group == NULL)
return;
//Now we do the second roll for the item out of the group.
int roll = System::random(10000000);
int tempChance = 0;
for (int i = 0; i < group->size(); ++i) {
if (container->hasFullContainerObjects())
return;
LootGroupEntry entry = group->get(i);
tempChance += entry.getWeight();
if (tempChance < roll)
continue; //If the roll is greater than this item, move on to the next one.
String item = entry.getItemTemplate();
LootItemTemplate* itemTemplate = lootGroupMap->getLootItem(item);
if (itemTemplate != NULL) {
//int minLevel = itemTemplate->getMinimumLevel();
//int maxLevel = itemTemplate->getMaximumLevel();
//if (level != -1) {
//if (minLevel != -1 && level < minLevel)
//continue;
//if (maxLevel != -1 && level > maxLevel)
//continue;
//}
SceneObject* obj = createLootObject(itemTemplate, level);
if (obj != NULL) {
if (container->transferObject(obj, -1, false))
container->broadcastObject(obj, true);
}
} else {
error(item + " loot item template not found");
}
return;
}
}
<|endoftext|>
|
<commit_before>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/api/notification_provider/notification_provider_api.h"
#include "chrome/browser/extensions/chrome_extension_function.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/extensions/api/notification_provider.h"
typedef ExtensionApiTest NotificationProviderApiTest;
IN_PROC_BROWSER_TEST_F(NotificationProviderApiTest, Events) {
std::string sender_id1 = "SenderId1";
std::string notification_id1 = "NotificationId1";
extensions::api::notifications::NotificationOptions options;
options.type = extensions::api::notifications::ParseTemplateType("basic");
options.icon_url = scoped_ptr<std::string>(new std::string("icon.png"));
options.title = scoped_ptr<std::string>(new std::string("Title"));
options.message =
scoped_ptr<std::string>(new std::string("Here goes the message"));
ResultCatcher catcher;
catcher.RestrictToProfile(browser()->profile());
// Test notification provider extension
const extensions::Extension* extension =
LoadExtension(test_data_dir_.AppendASCII("notification_provider/events"));
ASSERT_TRUE(extension);
extensions::NotificationProviderEventRouter* event_router =
new extensions::NotificationProviderEventRouter(browser()->profile());
event_router->CreateNotification(
extension->id(), sender_id1, notification_id1, options);
event_router->UpdateNotification(
extension->id(), sender_id1, notification_id1, options);
event_router->ClearNotification(
extension->id(), sender_id1, notification_id1);
EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}
<commit_msg>Fix memory leak in NotificationProviderApiTest.Events.<commit_after>// Copyright 2014 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/memory/scoped_ptr.h"
#include "chrome/browser/extensions/api/notification_provider/notification_provider_api.h"
#include "chrome/browser/extensions/chrome_extension_function.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/extensions/api/notification_provider.h"
typedef ExtensionApiTest NotificationProviderApiTest;
IN_PROC_BROWSER_TEST_F(NotificationProviderApiTest, Events) {
std::string sender_id1 = "SenderId1";
std::string notification_id1 = "NotificationId1";
extensions::api::notifications::NotificationOptions options;
options.type = extensions::api::notifications::ParseTemplateType("basic");
options.icon_url = scoped_ptr<std::string>(new std::string("icon.png"));
options.title = scoped_ptr<std::string>(new std::string("Title"));
options.message =
scoped_ptr<std::string>(new std::string("Here goes the message"));
ResultCatcher catcher;
catcher.RestrictToProfile(browser()->profile());
// Test notification provider extension
const extensions::Extension* extension =
LoadExtension(test_data_dir_.AppendASCII("notification_provider/events"));
ASSERT_TRUE(extension);
scoped_ptr<extensions::NotificationProviderEventRouter> event_router(
new extensions::NotificationProviderEventRouter(browser()->profile()));
event_router->CreateNotification(
extension->id(), sender_id1, notification_id1, options);
event_router->UpdateNotification(
extension->id(), sender_id1, notification_id1, options);
event_router->ClearNotification(
extension->id(), sender_id1, notification_id1);
EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}
<|endoftext|>
|
<commit_before>////////////////////////////////////////////////////////////////////////////
//
// Copyright 2016 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
#ifndef ERROR_HANDLING_HPP
#define ERROR_HANDLING_HPP
#include <string>
#include <realm.hpp>
#include "realm_error_type.hpp"
namespace realm {
struct NativeException {
RealmErrorType type;
std::string message;
struct Marshallable {
RealmErrorType type;
const char* messagesBytes;
size_t messageLength;
};
Marshallable for_marshalling() const {
auto messageCopy = new char[message.size()];
message.copy(messageCopy, message.length());
return {
type,
messageCopy,
message.size()
};
}
};
class RowDetachedException : public std::runtime_error {
public:
RowDetachedException() : std::runtime_error("Attempted to access detached row") {}
};
NativeException convert_exception();
void throw_managed_exception(const NativeException& exception);
template <class T>
struct Default {
static T default_value() {
return T{};
}
};
template <>
struct Default<void> {
static void default_value() {}
};
template <class F>
auto handle_errors(F&& func) -> decltype(func())
{
using RetVal = decltype(func());
try {
return func();
}
catch (...) {
throw_managed_exception(convert_exception());
return Default<RetVal>::default_value();
}
}
template <class F>
auto handle_errors_param(F&& func, NativeException::Marshallable& ex) -> decltype(func())
{
using RetVal = decltype(func());
ex.type = RealmErrorType::NoError;
try {
return func();
}
catch (...) {
ex = convert_exception().for_marshalling();
return Default<RetVal>::default_value();
}
}
} // namespace realm
#endif // ERROR_HANDLING_HPP
<commit_msg>Make NativeException::Marshallable::messageBytes a void* instead of a char*<commit_after>////////////////////////////////////////////////////////////////////////////
//
// Copyright 2016 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
#ifndef ERROR_HANDLING_HPP
#define ERROR_HANDLING_HPP
#include <string>
#include <new>
#include <realm.hpp>
#include "realm_error_type.hpp"
namespace realm {
struct NativeException {
RealmErrorType type;
std::string message;
struct Marshallable {
RealmErrorType type;
void* messagesBytes;
size_t messageLength;
};
Marshallable for_marshalling() const {
auto messageCopy = ::operator new (message.size());
message.copy(reinterpret_cast<char*>(messageCopy), message.length());
return {
type,
messageCopy,
message.size()
};
}
};
class RowDetachedException : public std::runtime_error {
public:
RowDetachedException() : std::runtime_error("Attempted to access detached row") {}
};
NativeException convert_exception();
void throw_managed_exception(const NativeException& exception);
template <class T>
struct Default {
static T default_value() {
return T{};
}
};
template <>
struct Default<void> {
static void default_value() {}
};
template <class F>
auto handle_errors(F&& func) -> decltype(func())
{
using RetVal = decltype(func());
try {
return func();
}
catch (...) {
throw_managed_exception(convert_exception());
return Default<RetVal>::default_value();
}
}
template <class F>
auto handle_errors_param(F&& func, NativeException::Marshallable& ex) -> decltype(func())
{
using RetVal = decltype(func());
ex.type = RealmErrorType::NoError;
try {
return func();
}
catch (...) {
ex = convert_exception().for_marshalling();
return Default<RetVal>::default_value();
}
}
} // namespace realm
#endif // ERROR_HANDLING_HPP
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: networkdomain.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: obo $ $Date: 2006-09-16 13:57:53 $
*
* 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_framework.hxx"
#ifndef __FRAMEWORK_HELPER_NETWORKDOMAIN_HXX_
#include <helper/networkdomain.hxx>
#endif
namespace framework
{
#ifdef WNT
//_________________________________________________________________________________________________________________
// Windows
//_________________________________________________________________________________________________________________
#define UNICODE
#include <windows.h>
//_________________________________________________________________________________________________________________
// Win NT, Win 2000, Win XP
//_________________________________________________________________________________________________________________
static DWORD WINAPI GetUserDomainW_NT( LPWSTR lpBuffer, DWORD nSize )
{
return GetEnvironmentVariable( TEXT("USERDOMAIN"), lpBuffer, nSize );
}
//_________________________________________________________________________________________________________________
// Win 9x,Win ME
//_________________________________________________________________________________________________________________
static DWORD WINAPI GetUserDomainW_WINDOWS( LPWSTR lpBuffer, DWORD nSize )
{
HKEY hkeyLogon;
HKEY hkeyWorkgroup;
DWORD dwResult = 0;
if ( ERROR_SUCCESS == RegOpenKeyEx(
HKEY_LOCAL_MACHINE,
TEXT("Network\\Logon"),
0, KEY_READ, &hkeyLogon ) )
{
DWORD dwLogon = 0;
DWORD dwLogonSize = sizeof(dwLogon);
LONG lResult = RegQueryValueEx( hkeyLogon, TEXT("LMLogon"), 0, NULL, (LPBYTE)&dwLogon, &dwLogonSize );
RegCloseKey( hkeyLogon );
if ( dwLogon )
{
HKEY hkeyNetworkProvider;
if ( ERROR_SUCCESS == RegOpenKeyEx(
HKEY_LOCAL_MACHINE,
TEXT("SYSTEM\\CurrentControlSet\\Services\\MSNP32\\NetworkProvider"),
0, KEY_READ, &hkeyNetworkProvider ) )
{
DWORD dwBufferSize = nSize;
LONG lResult = RegQueryValueEx( hkeyNetworkProvider, TEXT("AuthenticatingAgent"), 0, NULL, (LPBYTE)lpBuffer, &dwBufferSize );
if ( ERROR_SUCCESS == lResult || ERROR_MORE_DATA == lResult )
dwResult = dwBufferSize / sizeof(TCHAR);
RegCloseKey( hkeyNetworkProvider );
}
}
}
else if ( ERROR_SUCCESS == RegOpenKeyEx(
HKEY_LOCAL_MACHINE,
TEXT("SYSTEM\\CurrentControlSet\\Services\\VxD\\VNETSUP"),
0, KEY_READ, &hkeyWorkgroup ) )
{
DWORD dwBufferSize = nSize;
LONG lResult = RegQueryValueEx( hkeyWorkgroup, TEXT("Workgroup"), 0, NULL, (LPBYTE)lpBuffer, &dwBufferSize );
if ( ERROR_SUCCESS == lResult || ERROR_MORE_DATA == lResult )
dwResult = dwBufferSize / sizeof(TCHAR);
RegCloseKey( hkeyWorkgroup );
}
return dwResult;
}
static rtl::OUString GetUserDomain()
{
sal_Unicode aBuffer[256];
long nVersion = GetVersion();
DWORD nResult;
if ( nVersion < 0 )
nResult = GetUserDomainW_WINDOWS( aBuffer, sizeof( aBuffer ) );
else
nResult = GetUserDomainW_NT( aBuffer, sizeof( aBuffer ) );
if ( nResult > 0 )
return rtl::OUString( aBuffer );
else
return rtl::OUString();
}
//_________________________________________________________________________________________________________________
// Windows
//_________________________________________________________________________________________________________________
rtl::OUString NetworkDomain::GetYPDomainName()
{
return ::rtl::OUString();
}
rtl::OUString NetworkDomain::GetNTDomainName()
{
return GetUserDomain();
}
#elif defined( UNIX )
#include <rtl/ustring.h>
#include <stdlib.h>
#include <errno.h>
#include <osl/thread.h>
//_________________________________________________________________________________________________________________
// Unix
//_________________________________________________________________________________________________________________
#if defined( SOLARIS )
//_________________________________________________________________________________________________________________
// Solaris
//_________________________________________________________________________________________________________________
#include <sys/systeminfo.h>
#include <sal/alloca.h>
static rtl_uString *getDomainName()
{
/* Initialize and assume failure */
rtl_uString *ustrDomainName = NULL;
char szBuffer[256];
long nCopied = sizeof(szBuffer);
char *pBuffer = szBuffer;
long nBufSize;
do
{
nBufSize = nCopied;
nCopied = sysinfo( SI_SRPC_DOMAIN, pBuffer, nBufSize );
/* If nCopied is greater than buffersize we need to allocate
a buffer with suitable size */
if ( nCopied > nBufSize )
pBuffer = (char *)alloca( nCopied );
} while ( nCopied > nBufSize );
if ( -1 != nCopied )
{
rtl_string2UString(
&ustrDomainName,
pBuffer,
nCopied - 1,
osl_getThreadTextEncoding(),
OSTRING_TO_OUSTRING_CVTFLAGS );
}
return ustrDomainName;
}
#elif defined( LINUX ) /* endif SOLARIS */
//_________________________________________________________________________________________________________________
// Linux
//_________________________________________________________________________________________________________________
#include <unistd.h>
#include <string.h>
static rtl_uString *getDomainName()
{
/* Initialize and assume failure */
rtl_uString *ustrDomainName = NULL;
char *pBuffer;
int result;
size_t nBufSize = 0;
do
{
nBufSize += 256; /* Increase buffer size by steps of 256 bytes */
pBuffer = (char *)alloca( nBufSize );
result = getdomainname( pBuffer, nBufSize );
/* If buffersize in not large enough -1 is returned and errno
is set to EINVAL. This only applies to libc. With glibc the name
is truncated. */
} while ( -1 == result && EINVAL == errno );
if ( 0 == result )
{
rtl_string2UString(
&ustrDomainName,
pBuffer,
strlen( pBuffer ),
osl_getThreadTextEncoding(),
OSTRING_TO_OUSTRING_CVTFLAGS );
}
return ustrDomainName;
}
#else /* LINUX */
//_________________________________________________________________________________________________________________
// Other Unix
//_________________________________________________________________________________________________________________
static rtl_uString *getDomainName()
{
return NULL;
}
#endif
//_________________________________________________________________________________________________________________
// Unix
//_________________________________________________________________________________________________________________
rtl::OUString NetworkDomain::GetYPDomainName()
{
rtl_uString* pResult = getDomainName();
if ( pResult )
return rtl::OUString( pResult );
else
return rtl::OUString();
}
rtl::OUString NetworkDomain::GetNTDomainName()
{
return ::rtl::OUString();
}
#else /* UNIX */
//_________________________________________________________________________________________________________________
// Other operating systems (non-Windows and non-Unix)
//_________________________________________________________________________________________________________________
rtl::OUString NetworkDomain::GetYPDomainName()
{
return rtl::OUString();
}
rtl::OUString NetworkDomain::GetNTDomainName()
{
return rtl::OUString();
}
#endif
} // namespace framework
<commit_msg>INTEGRATION: CWS sb59 (1.5.142); FILE MERGED 2006/08/10 08:16:20 sb 1.5.142.1: #i67487# Made code warning-free (wntmsci10).<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: networkdomain.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: obo $ $Date: 2006-10-12 10:40:17 $
*
* 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_framework.hxx"
#ifndef __FRAMEWORK_HELPER_NETWORKDOMAIN_HXX_
#include <helper/networkdomain.hxx>
#endif
namespace framework
{
#ifdef WNT
//_________________________________________________________________________________________________________________
// Windows
//_________________________________________________________________________________________________________________
#define UNICODE
#if defined _MSC_VER
#pragma warning(push, 1)
#endif
#include <windows.h>
#if defined _MSC_VER
#pragma warning(pop)
#endif
//_________________________________________________________________________________________________________________
// Win NT, Win 2000, Win XP
//_________________________________________________________________________________________________________________
static DWORD WINAPI GetUserDomainW_NT( LPWSTR lpBuffer, DWORD nSize )
{
return GetEnvironmentVariable( TEXT("USERDOMAIN"), lpBuffer, nSize );
}
//_________________________________________________________________________________________________________________
// Win 9x,Win ME
//_________________________________________________________________________________________________________________
static DWORD WINAPI GetUserDomainW_WINDOWS( LPWSTR lpBuffer, DWORD nSize )
{
HKEY hkeyLogon;
HKEY hkeyWorkgroup;
DWORD dwResult = 0;
if ( ERROR_SUCCESS == RegOpenKeyEx(
HKEY_LOCAL_MACHINE,
TEXT("Network\\Logon"),
0, KEY_READ, &hkeyLogon ) )
{
DWORD dwLogon = 0;
DWORD dwLogonSize = sizeof(dwLogon);
RegQueryValueEx( hkeyLogon, TEXT("LMLogon"), 0, NULL, (LPBYTE)&dwLogon, &dwLogonSize );
RegCloseKey( hkeyLogon );
if ( dwLogon )
{
HKEY hkeyNetworkProvider;
if ( ERROR_SUCCESS == RegOpenKeyEx(
HKEY_LOCAL_MACHINE,
TEXT("SYSTEM\\CurrentControlSet\\Services\\MSNP32\\NetworkProvider"),
0, KEY_READ, &hkeyNetworkProvider ) )
{
DWORD dwBufferSize = nSize;
LONG lResult = RegQueryValueEx( hkeyNetworkProvider, TEXT("AuthenticatingAgent"), 0, NULL, (LPBYTE)lpBuffer, &dwBufferSize );
if ( ERROR_SUCCESS == lResult || ERROR_MORE_DATA == lResult )
dwResult = dwBufferSize / sizeof(TCHAR);
RegCloseKey( hkeyNetworkProvider );
}
}
}
else if ( ERROR_SUCCESS == RegOpenKeyEx(
HKEY_LOCAL_MACHINE,
TEXT("SYSTEM\\CurrentControlSet\\Services\\VxD\\VNETSUP"),
0, KEY_READ, &hkeyWorkgroup ) )
{
DWORD dwBufferSize = nSize;
LONG lResult = RegQueryValueEx( hkeyWorkgroup, TEXT("Workgroup"), 0, NULL, (LPBYTE)lpBuffer, &dwBufferSize );
if ( ERROR_SUCCESS == lResult || ERROR_MORE_DATA == lResult )
dwResult = dwBufferSize / sizeof(TCHAR);
RegCloseKey( hkeyWorkgroup );
}
return dwResult;
}
static rtl::OUString GetUserDomain()
{
sal_Unicode aBuffer[256];
long nVersion = GetVersion();
DWORD nResult;
if ( nVersion < 0 )
nResult = GetUserDomainW_WINDOWS( aBuffer, sizeof( aBuffer ) );
else
nResult = GetUserDomainW_NT( aBuffer, sizeof( aBuffer ) );
if ( nResult > 0 )
return rtl::OUString( aBuffer );
else
return rtl::OUString();
}
//_________________________________________________________________________________________________________________
// Windows
//_________________________________________________________________________________________________________________
rtl::OUString NetworkDomain::GetYPDomainName()
{
return ::rtl::OUString();
}
rtl::OUString NetworkDomain::GetNTDomainName()
{
return GetUserDomain();
}
#elif defined( UNIX )
#include <rtl/ustring.h>
#include <stdlib.h>
#include <errno.h>
#include <osl/thread.h>
//_________________________________________________________________________________________________________________
// Unix
//_________________________________________________________________________________________________________________
#if defined( SOLARIS )
//_________________________________________________________________________________________________________________
// Solaris
//_________________________________________________________________________________________________________________
#include <sys/systeminfo.h>
#include <sal/alloca.h>
static rtl_uString *getDomainName()
{
/* Initialize and assume failure */
rtl_uString *ustrDomainName = NULL;
char szBuffer[256];
long nCopied = sizeof(szBuffer);
char *pBuffer = szBuffer;
long nBufSize;
do
{
nBufSize = nCopied;
nCopied = sysinfo( SI_SRPC_DOMAIN, pBuffer, nBufSize );
/* If nCopied is greater than buffersize we need to allocate
a buffer with suitable size */
if ( nCopied > nBufSize )
pBuffer = (char *)alloca( nCopied );
} while ( nCopied > nBufSize );
if ( -1 != nCopied )
{
rtl_string2UString(
&ustrDomainName,
pBuffer,
nCopied - 1,
osl_getThreadTextEncoding(),
OSTRING_TO_OUSTRING_CVTFLAGS );
}
return ustrDomainName;
}
#elif defined( LINUX ) /* endif SOLARIS */
//_________________________________________________________________________________________________________________
// Linux
//_________________________________________________________________________________________________________________
#include <unistd.h>
#include <string.h>
static rtl_uString *getDomainName()
{
/* Initialize and assume failure */
rtl_uString *ustrDomainName = NULL;
char *pBuffer;
int result;
size_t nBufSize = 0;
do
{
nBufSize += 256; /* Increase buffer size by steps of 256 bytes */
pBuffer = (char *)alloca( nBufSize );
result = getdomainname( pBuffer, nBufSize );
/* If buffersize in not large enough -1 is returned and errno
is set to EINVAL. This only applies to libc. With glibc the name
is truncated. */
} while ( -1 == result && EINVAL == errno );
if ( 0 == result )
{
rtl_string2UString(
&ustrDomainName,
pBuffer,
strlen( pBuffer ),
osl_getThreadTextEncoding(),
OSTRING_TO_OUSTRING_CVTFLAGS );
}
return ustrDomainName;
}
#else /* LINUX */
//_________________________________________________________________________________________________________________
// Other Unix
//_________________________________________________________________________________________________________________
static rtl_uString *getDomainName()
{
return NULL;
}
#endif
//_________________________________________________________________________________________________________________
// Unix
//_________________________________________________________________________________________________________________
rtl::OUString NetworkDomain::GetYPDomainName()
{
rtl_uString* pResult = getDomainName();
if ( pResult )
return rtl::OUString( pResult );
else
return rtl::OUString();
}
rtl::OUString NetworkDomain::GetNTDomainName()
{
return ::rtl::OUString();
}
#else /* UNIX */
//_________________________________________________________________________________________________________________
// Other operating systems (non-Windows and non-Unix)
//_________________________________________________________________________________________________________________
rtl::OUString NetworkDomain::GetYPDomainName()
{
return rtl::OUString();
}
rtl::OUString NetworkDomain::GetNTDomainName()
{
return rtl::OUString();
}
#endif
} // namespace framework
<|endoftext|>
|
<commit_before>/****************************************************************************
*
* (c) 2009-2016 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
*
* QGroundControl is licensed according to the terms in the file
* COPYING.md in the root of the source code directory.
*
****************************************************************************/
#include "AirMapRulesetsManager.h"
#include "AirMapManager.h"
#include <QSettings>
using namespace airmap;
static const char* kAirMapFeatureGroup = "AirMapFeatureGroup";
//-----------------------------------------------------------------------------
AirMapRuleFeature::AirMapRuleFeature(QObject* parent)
: AirspaceRuleFeature(parent)
{
}
//-----------------------------------------------------------------------------
AirMapRuleFeature::AirMapRuleFeature(airmap::RuleSet::Feature feature, QObject* parent)
: AirspaceRuleFeature(parent)
, _feature(feature)
{
//-- Restore persisted value (if it exists)
QSettings settings;
settings.beginGroup(kAirMapFeatureGroup);
switch(_feature.type) {
case RuleSet::Feature::Type::boolean:
_value = settings.value(name(), false);
break;;
case RuleSet::Feature::Type::floating_point:
_value = settings.value(name(), 0.0f);
break;;
case RuleSet::Feature::Type::string:
_value = settings.value(name(), QString());
break;;
default:
break;
}
settings.endGroup();
}
//-----------------------------------------------------------------------------
AirspaceRuleFeature::Type
AirMapRuleFeature::type()
{
switch(_feature.type) {
case RuleSet::Feature::Type::boolean:
return AirspaceRuleFeature::Boolean;
case RuleSet::Feature::Type::floating_point:
return AirspaceRuleFeature::Float;
case RuleSet::Feature::Type::string:
return AirspaceRuleFeature::String;
default:
break;
}
return AirspaceRuleFeature::Unknown;
}
//-----------------------------------------------------------------------------
AirspaceRuleFeature::Unit
AirMapRuleFeature::unit()
{
switch(_feature.unit) {
case RuleSet::Feature::Unit::kilograms:
return AirspaceRuleFeature::Kilogram;
case RuleSet::Feature::Unit::meters:
return AirspaceRuleFeature::Meters;
case RuleSet::Feature::Unit::meters_per_sec:
return AirspaceRuleFeature::MetersPerSecond;
default:
break;
}
return AirspaceRuleFeature::UnknownUnit;
}
//-----------------------------------------------------------------------------
AirspaceRuleFeature::Measurement
AirMapRuleFeature::measurement()
{
switch(_feature.measurement) {
case RuleSet::Feature::Measurement::speed:
return AirspaceRuleFeature::Speed;
case RuleSet::Feature::Measurement::weight:
return AirspaceRuleFeature::Weight;
case RuleSet::Feature::Measurement::distance:
return AirspaceRuleFeature::Distance;
default:
break;
}
return AirspaceRuleFeature::UnknownMeasurement;
}
//-----------------------------------------------------------------------------
void
AirMapRuleFeature::setValue(const QVariant val)
{
_value = val;
//-- Make value persistent
QSettings settings;
settings.beginGroup(kAirMapFeatureGroup);
settings.setValue(name(), _value);
settings.endGroup();
emit valueChanged();
}
//-----------------------------------------------------------------------------
AirMapRule::AirMapRule(QObject* parent)
: AirspaceRule(parent)
{
}
//-----------------------------------------------------------------------------
AirMapRule::AirMapRule(const airmap::RuleSet::Rule& rule, QObject* parent)
: AirspaceRule(parent)
, _rule(rule)
{
}
//-----------------------------------------------------------------------------
AirMapRule::~AirMapRule()
{
_features.deleteListAndContents();
}
//-----------------------------------------------------------------------------
AirspaceRule::Status
AirMapRule::status()
{
switch(_rule.status) {
case RuleSet::Rule::Status::conflicting:
return AirspaceRule::Conflicting;
case RuleSet::Rule::Status::not_conflicting:
return AirspaceRule::NotConflicting;
case RuleSet::Rule::Status::missing_info:
return AirspaceRule::MissingInfo;
case RuleSet::Rule::Status::unknown:
default:
return AirspaceRule::Unknown;
}
}
//-----------------------------------------------------------------------------
AirMapRuleSet::AirMapRuleSet(QObject* parent)
: AirspaceRuleSet(parent)
, _isDefault(false)
, _selected(false)
, _selectionType(AirspaceRuleSet::Optional)
{
}
//-----------------------------------------------------------------------------
AirMapRuleSet::~AirMapRuleSet()
{
_rules.deleteListAndContents();
}
//-----------------------------------------------------------------------------
void
AirMapRuleSet::setSelected(bool sel)
{
if(_selectionType != AirspaceRuleSet::Required) {
_selected = sel;
} else {
_selected = true;
}
emit selectedChanged();
}
//-----------------------------------------------------------------------------
AirMapRulesetsManager::AirMapRulesetsManager(AirMapSharedState& shared)
: _shared(shared)
{
}
//-----------------------------------------------------------------------------
static bool
rules_sort(QObject* a, QObject* b)
{
AirMapRule* aa = qobject_cast<AirMapRule*>(a);
AirMapRule* bb = qobject_cast<AirMapRule*>(b);
if(!aa || !bb) return false;
return (int)aa->order() > (int)bb->order();
}
//-----------------------------------------------------------------------------
void AirMapRulesetsManager::setROI(const QGCGeoBoundingCube& roi)
{
if (!_shared.client()) {
qCDebug(AirMapManagerLog) << "No AirMap client instance. Not updating Airspace";
return;
}
if (_state != State::Idle) {
qCWarning(AirMapManagerLog) << "AirMapRulesetsManager::updateROI: state not idle";
return;
}
qCDebug(AirMapManagerLog) << "Rulesets Request (ROI Changed)";
_valid = false;
_ruleSets.clearAndDeleteContents();
_state = State::RetrieveItems;
RuleSets::Search::Parameters params;
//-- Geometry: Polygon
Geometry::Polygon polygon;
for (const auto& qcoord : roi.polygon2D()) {
Geometry::Coordinate coord;
coord.latitude = qcoord.latitude();
coord.longitude = qcoord.longitude();
polygon.outer_ring.coordinates.push_back(coord);
}
params.geometry = Geometry(polygon);
std::weak_ptr<LifetimeChecker> isAlive(_instance);
_shared.client()->rulesets().search(params,
[this, isAlive](const RuleSets::Search::Result& result) {
if (!isAlive.lock()) return;
if (_state != State::RetrieveItems) return;
if (result) {
const std::vector<RuleSet> rulesets = result.value();
qCDebug(AirMapManagerLog) << "Successful rulesets search. Items:" << rulesets.size();
for (const auto& ruleset : rulesets) {
AirMapRuleSet* pRuleSet = new AirMapRuleSet(this);
connect(pRuleSet, &AirspaceRuleSet::selectedChanged, this, &AirMapRulesetsManager::_selectedChanged);
pRuleSet->_id = QString::fromStdString(ruleset.id);
pRuleSet->_name = QString::fromStdString(ruleset.name);
pRuleSet->_shortName = QString::fromStdString(ruleset.short_name);
pRuleSet->_description = QString::fromStdString(ruleset.description);
pRuleSet->_isDefault = ruleset.is_default;
//-- TODO: This should be persistent and if the new incoming set has the
// same, previosuly selected rulesets, it should "remember".
if(pRuleSet->_isDefault) {
pRuleSet->_selected = true;
}
switch(ruleset.selection_type) {
case RuleSet::SelectionType::pickone:
pRuleSet->_selectionType = AirspaceRuleSet::Pickone;
break;
case RuleSet::SelectionType::required:
pRuleSet->_selectionType = AirspaceRuleSet::Required;
pRuleSet->_selected = true;
break;
default:
case RuleSet::SelectionType::optional:
pRuleSet->_selectionType = AirspaceRuleSet::Optional;
break;
}
//-- Iterate Rules
for (const auto& rule : ruleset.rules) {
AirMapRule* pRule = new AirMapRule(rule, this);
//-- Iterate Rule Features
for (const auto& feature : rule.features) {
AirMapRuleFeature* pFeature = new AirMapRuleFeature(feature, this);
pRule->_features.append(pFeature);
}
pRuleSet->_rules.append(pRule);
}
//-- Sort rules by display order
std::sort(pRuleSet->_rules.objectList()->begin(), pRuleSet->_rules.objectList()->end(), rules_sort);
_ruleSets.append(pRuleSet);
qCDebug(AirMapManagerLog) << "Adding ruleset" << pRuleSet->name();
/*
qDebug() << "------------------------------------------";
qDebug() << "Jurisdiction:" << ruleset.jurisdiction.name.data() << (int)ruleset.jurisdiction.region;
qDebug() << "Name: " << ruleset.name.data();
qDebug() << "Short Name: " << ruleset.short_name.data();
qDebug() << "Description: " << ruleset.description.data();
qDebug() << "Is default: " << ruleset.is_default;
qDebug() << "Applicable to these airspace types:";
for (const auto& airspaceType : ruleset.airspace_types) {
qDebug() << " " << airspaceType.data();
}
qDebug() << "Rules:";
for (const auto& rule : ruleset.rules) {
qDebug() << " --------------------------------------";
qDebug() << " short_text: " << rule.short_text.data();
qDebug() << " description: " << rule.description.data();
qDebug() << " display_order:" << rule.display_order;
qDebug() << " status: " << (int)rule.status;
qDebug() << " ------------------------------";
qDebug() << " Features:";
for (const auto& feature : rule.features) {
qDebug() << " name: " << feature.name.data();
qDebug() << " description:" << feature.description.data();
qDebug() << " status: " << (int)feature.status;
qDebug() << " type: " << (int)feature.type;
qDebug() << " measurement:" << (int)feature.measurement;
qDebug() << " unit: " << (int)feature.unit;
}
}
*/
}
_valid = true;
} else {
QString description = QString::fromStdString(result.error().description() ? result.error().description().get() : "");
emit error("Failed to retrieve RuleSets", QString::fromStdString(result.error().message()), description);
}
_state = State::Idle;
emit ruleSetsChanged();
emit selectedRuleSetsChanged();
});
}
//-----------------------------------------------------------------------------
QString
AirMapRulesetsManager::selectedRuleSets()
{
QString selection;
for(int i = 0; i < _ruleSets.count(); i++) {
AirMapRuleSet* rule = qobject_cast<AirMapRuleSet*>(_ruleSets.get(i));
if(rule && rule->selected()) {
selection += rule->shortName() + ", ";
}
}
int idx = selection.lastIndexOf(", ");
if(idx >= 0) {
selection = selection.left(idx);
}
return selection;
}
//-----------------------------------------------------------------------------
void
AirMapRulesetsManager::_selectedChanged()
{
emit selectedRuleSetsChanged();
//-- TODO: Do whatever it is you do to select a rule
}
<commit_msg>Make all numeric values default to 1 (as opposed to 0) for the time being.<commit_after>/****************************************************************************
*
* (c) 2009-2016 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
*
* QGroundControl is licensed according to the terms in the file
* COPYING.md in the root of the source code directory.
*
****************************************************************************/
#include "AirMapRulesetsManager.h"
#include "AirMapManager.h"
#include <QSettings>
using namespace airmap;
static const char* kAirMapFeatureGroup = "AirMapFeatureGroup";
//-----------------------------------------------------------------------------
AirMapRuleFeature::AirMapRuleFeature(QObject* parent)
: AirspaceRuleFeature(parent)
{
}
//-----------------------------------------------------------------------------
AirMapRuleFeature::AirMapRuleFeature(airmap::RuleSet::Feature feature, QObject* parent)
: AirspaceRuleFeature(parent)
, _feature(feature)
{
//-- Restore persisted value (if it exists)
QSettings settings;
settings.beginGroup(kAirMapFeatureGroup);
switch(_feature.type) {
case RuleSet::Feature::Type::boolean:
_value = settings.value(name(), false);
break;;
case RuleSet::Feature::Type::floating_point:
//_value = settings.value(name(), 0.0f);
//-- Default to 1 for now
_value = settings.value(name(), 1.0f);
break;;
case RuleSet::Feature::Type::string:
_value = settings.value(name(), QString());
break;;
default:
break;
}
settings.endGroup();
}
//-----------------------------------------------------------------------------
AirspaceRuleFeature::Type
AirMapRuleFeature::type()
{
switch(_feature.type) {
case RuleSet::Feature::Type::boolean:
return AirspaceRuleFeature::Boolean;
case RuleSet::Feature::Type::floating_point:
return AirspaceRuleFeature::Float;
case RuleSet::Feature::Type::string:
return AirspaceRuleFeature::String;
default:
break;
}
return AirspaceRuleFeature::Unknown;
}
//-----------------------------------------------------------------------------
AirspaceRuleFeature::Unit
AirMapRuleFeature::unit()
{
switch(_feature.unit) {
case RuleSet::Feature::Unit::kilograms:
return AirspaceRuleFeature::Kilogram;
case RuleSet::Feature::Unit::meters:
return AirspaceRuleFeature::Meters;
case RuleSet::Feature::Unit::meters_per_sec:
return AirspaceRuleFeature::MetersPerSecond;
default:
break;
}
return AirspaceRuleFeature::UnknownUnit;
}
//-----------------------------------------------------------------------------
AirspaceRuleFeature::Measurement
AirMapRuleFeature::measurement()
{
switch(_feature.measurement) {
case RuleSet::Feature::Measurement::speed:
return AirspaceRuleFeature::Speed;
case RuleSet::Feature::Measurement::weight:
return AirspaceRuleFeature::Weight;
case RuleSet::Feature::Measurement::distance:
return AirspaceRuleFeature::Distance;
default:
break;
}
return AirspaceRuleFeature::UnknownMeasurement;
}
//-----------------------------------------------------------------------------
void
AirMapRuleFeature::setValue(const QVariant val)
{
_value = val;
//-- Make value persistent
QSettings settings;
settings.beginGroup(kAirMapFeatureGroup);
settings.setValue(name(), _value);
settings.endGroup();
emit valueChanged();
}
//-----------------------------------------------------------------------------
AirMapRule::AirMapRule(QObject* parent)
: AirspaceRule(parent)
{
}
//-----------------------------------------------------------------------------
AirMapRule::AirMapRule(const airmap::RuleSet::Rule& rule, QObject* parent)
: AirspaceRule(parent)
, _rule(rule)
{
}
//-----------------------------------------------------------------------------
AirMapRule::~AirMapRule()
{
_features.deleteListAndContents();
}
//-----------------------------------------------------------------------------
AirspaceRule::Status
AirMapRule::status()
{
switch(_rule.status) {
case RuleSet::Rule::Status::conflicting:
return AirspaceRule::Conflicting;
case RuleSet::Rule::Status::not_conflicting:
return AirspaceRule::NotConflicting;
case RuleSet::Rule::Status::missing_info:
return AirspaceRule::MissingInfo;
case RuleSet::Rule::Status::unknown:
default:
return AirspaceRule::Unknown;
}
}
//-----------------------------------------------------------------------------
AirMapRuleSet::AirMapRuleSet(QObject* parent)
: AirspaceRuleSet(parent)
, _isDefault(false)
, _selected(false)
, _selectionType(AirspaceRuleSet::Optional)
{
}
//-----------------------------------------------------------------------------
AirMapRuleSet::~AirMapRuleSet()
{
_rules.deleteListAndContents();
}
//-----------------------------------------------------------------------------
void
AirMapRuleSet::setSelected(bool sel)
{
if(_selectionType != AirspaceRuleSet::Required) {
_selected = sel;
} else {
_selected = true;
}
emit selectedChanged();
}
//-----------------------------------------------------------------------------
AirMapRulesetsManager::AirMapRulesetsManager(AirMapSharedState& shared)
: _shared(shared)
{
}
//-----------------------------------------------------------------------------
static bool
rules_sort(QObject* a, QObject* b)
{
AirMapRule* aa = qobject_cast<AirMapRule*>(a);
AirMapRule* bb = qobject_cast<AirMapRule*>(b);
if(!aa || !bb) return false;
return (int)aa->order() > (int)bb->order();
}
//-----------------------------------------------------------------------------
void AirMapRulesetsManager::setROI(const QGCGeoBoundingCube& roi)
{
if (!_shared.client()) {
qCDebug(AirMapManagerLog) << "No AirMap client instance. Not updating Airspace";
return;
}
if (_state != State::Idle) {
qCWarning(AirMapManagerLog) << "AirMapRulesetsManager::updateROI: state not idle";
return;
}
qCDebug(AirMapManagerLog) << "Rulesets Request (ROI Changed)";
_valid = false;
_ruleSets.clearAndDeleteContents();
_state = State::RetrieveItems;
RuleSets::Search::Parameters params;
//-- Geometry: Polygon
Geometry::Polygon polygon;
for (const auto& qcoord : roi.polygon2D()) {
Geometry::Coordinate coord;
coord.latitude = qcoord.latitude();
coord.longitude = qcoord.longitude();
polygon.outer_ring.coordinates.push_back(coord);
}
params.geometry = Geometry(polygon);
std::weak_ptr<LifetimeChecker> isAlive(_instance);
_shared.client()->rulesets().search(params,
[this, isAlive](const RuleSets::Search::Result& result) {
if (!isAlive.lock()) return;
if (_state != State::RetrieveItems) return;
if (result) {
const std::vector<RuleSet> rulesets = result.value();
qCDebug(AirMapManagerLog) << "Successful rulesets search. Items:" << rulesets.size();
for (const auto& ruleset : rulesets) {
AirMapRuleSet* pRuleSet = new AirMapRuleSet(this);
connect(pRuleSet, &AirspaceRuleSet::selectedChanged, this, &AirMapRulesetsManager::_selectedChanged);
pRuleSet->_id = QString::fromStdString(ruleset.id);
pRuleSet->_name = QString::fromStdString(ruleset.name);
pRuleSet->_shortName = QString::fromStdString(ruleset.short_name);
pRuleSet->_description = QString::fromStdString(ruleset.description);
pRuleSet->_isDefault = ruleset.is_default;
//-- TODO: This should be persistent and if the new incoming set has the
// same, previosuly selected rulesets, it should "remember".
if(pRuleSet->_isDefault) {
pRuleSet->_selected = true;
}
switch(ruleset.selection_type) {
case RuleSet::SelectionType::pickone:
pRuleSet->_selectionType = AirspaceRuleSet::Pickone;
break;
case RuleSet::SelectionType::required:
pRuleSet->_selectionType = AirspaceRuleSet::Required;
pRuleSet->_selected = true;
break;
default:
case RuleSet::SelectionType::optional:
pRuleSet->_selectionType = AirspaceRuleSet::Optional;
break;
}
//-- Iterate Rules
for (const auto& rule : ruleset.rules) {
AirMapRule* pRule = new AirMapRule(rule, this);
//-- Iterate Rule Features
for (const auto& feature : rule.features) {
AirMapRuleFeature* pFeature = new AirMapRuleFeature(feature, this);
pRule->_features.append(pFeature);
}
pRuleSet->_rules.append(pRule);
}
//-- Sort rules by display order
std::sort(pRuleSet->_rules.objectList()->begin(), pRuleSet->_rules.objectList()->end(), rules_sort);
_ruleSets.append(pRuleSet);
qCDebug(AirMapManagerLog) << "Adding ruleset" << pRuleSet->name();
/*
qDebug() << "------------------------------------------";
qDebug() << "Jurisdiction:" << ruleset.jurisdiction.name.data() << (int)ruleset.jurisdiction.region;
qDebug() << "Name: " << ruleset.name.data();
qDebug() << "Short Name: " << ruleset.short_name.data();
qDebug() << "Description: " << ruleset.description.data();
qDebug() << "Is default: " << ruleset.is_default;
qDebug() << "Applicable to these airspace types:";
for (const auto& airspaceType : ruleset.airspace_types) {
qDebug() << " " << airspaceType.data();
}
qDebug() << "Rules:";
for (const auto& rule : ruleset.rules) {
qDebug() << " --------------------------------------";
qDebug() << " short_text: " << rule.short_text.data();
qDebug() << " description: " << rule.description.data();
qDebug() << " display_order:" << rule.display_order;
qDebug() << " status: " << (int)rule.status;
qDebug() << " ------------------------------";
qDebug() << " Features:";
for (const auto& feature : rule.features) {
qDebug() << " name: " << feature.name.data();
qDebug() << " description:" << feature.description.data();
qDebug() << " status: " << (int)feature.status;
qDebug() << " type: " << (int)feature.type;
qDebug() << " measurement:" << (int)feature.measurement;
qDebug() << " unit: " << (int)feature.unit;
}
}
*/
}
_valid = true;
} else {
QString description = QString::fromStdString(result.error().description() ? result.error().description().get() : "");
emit error("Failed to retrieve RuleSets", QString::fromStdString(result.error().message()), description);
}
_state = State::Idle;
emit ruleSetsChanged();
emit selectedRuleSetsChanged();
});
}
//-----------------------------------------------------------------------------
QString
AirMapRulesetsManager::selectedRuleSets()
{
QString selection;
for(int i = 0; i < _ruleSets.count(); i++) {
AirMapRuleSet* rule = qobject_cast<AirMapRuleSet*>(_ruleSets.get(i));
if(rule && rule->selected()) {
selection += rule->shortName() + ", ";
}
}
int idx = selection.lastIndexOf(", ");
if(idx >= 0) {
selection = selection.left(idx);
}
return selection;
}
//-----------------------------------------------------------------------------
void
AirMapRulesetsManager::_selectedChanged()
{
emit selectedRuleSetsChanged();
//-- TODO: Do whatever it is you do to select a rule
}
<|endoftext|>
|
<commit_before>#include <string.h>
#if defined(__SSE2__)
#include <emmintrin.h>
#endif
#if defined(__SSE4_1__)
#include <smmintrin.h>
#endif
#include "m_half.h"
#include "m_const.h"
namespace m {
static struct halfData {
halfData();
// 1536 bytes
uint32_t baseTable[512];
uint8_t shiftTable[512];
} gHalf;
halfData::halfData() {
for (int i = 0, e = 0; i < 256; ++i) {
e = i - 127;
if (e < -24) {
// When magnitude of the number is really small (2^-24 or smaller),
// there is no possible half-float representation for the number, so
// it must be mapped to zero (or negative zero). Setting the shift
// table entries to 24 will shift all mantissa bits, leaving just zero.
// Base tables store zero otherwise (0x8000 for negative zero case.)
baseTable[i|0x000] = 0x0000;
baseTable[i|0x100] = 0x8000;
shiftTable[i|0x000] = 24;
shiftTable[i|0x100] = 24;
} else if (e < -14) {
// When the number is small (< 2^-14), the value can only be
// represented using a subnormal half-float. This is the most
// complex case: first, the leading 1-bit, implicitly represented
// in the normalized representation, must be explicitly added, then
// the resulting mantissa must be shifted rightward, or over a number
// of bit-positions as determined by the exponent. Here we prefer to
// shift the original mantissa bits, and add the pre-shifted 1-bit to
// it.
//
// Note: Shifting by -e-14 will never be negative, thus ensuring
// proper conversion, an alternative method is to shift by 18-e, which
// depends on implementation-defined behavior of unsigned shift.
baseTable[i|0x000] = (0x0400 >> (-e-14));
baseTable[i|0x100] = (0x0400 >> (-e-14)) | 0x8000;
shiftTable[i|0x000] = -e-1;
shiftTable[i|0x100] = -e-1;
} else if (e <= 15) {
// Normal numbers (smaller than 2^15), can be represented using half
// floats, albeit with slightly less precision. The entries in the
// base table are simply set to the bias-adjust exponent value, shifted
// into the right position. A sign bit is added for the negative case.
baseTable[i|0x000] = ((e+15) << 10);
baseTable[i|0x100] = ((e+15) << 10) | 0x8000;
shiftTable[i|0x000] = 13;
shiftTable[i|0x100] = 13;
} else if (e < 128) {
// Large values (numbers less than 2^128) must be mapped to half-float
// Infinity, They are too large to be represented as half-floats. In
// this case the base table is set to 0x7C00 (with sign if negative)
// and the mantissa is zeroed out, which is accomplished by shifting
// out all mantissa bits.
baseTable[i|0x000] = 0x7C00;
baseTable[i|0x100] = 0xFC00;
shiftTable[i|0x000] = 24;
shiftTable[i|0x100] = 24;
} else {
// Remaining float numbers such as Infs and NaNs should stay Infs and
// NaNs after conversion. The base table entries are exactly the same
// as the previous case, except the mantissa-bits are to be preserved
// as much as possible.
baseTable[i|0x000] = 0x7C00;
baseTable[i|0x100] = 0xFC00;
shiftTable[i|0x000] = 13;
shiftTable[i|0x100] = 13;
}
}
}
half convertToHalf(float in) {
const floatShape shape = { in };
return gHalf.baseTable[(shape.asInt >> 23) & 0x1FF] +
((shape.asInt & 0x007FFFFF) >> gHalf.shiftTable[(shape.asInt >> 23) & 0x1FF]);
}
float convertToFloat(half in) {
static constexpr uint32_t kMagic = 113 << 23;
static constexpr uint32_t kShiftedExp = 0x7C00 << 13; // exponent mask after shift
static constexpr floatShape kMagicShape = { kMagic };
floatShape out = { uint32_t(in & 0x7FFF) << 13 }; // exponent/mantissa bits
const size_t exp = kShiftedExp & out.asInt; // exponent
out.asInt += (127 - 15) << 23; // adjust exponent
if (exp == kShiftedExp) {
// extra adjustment of exponent for Inf/Nan?
out.asInt += (128 - 16) << 23;
} else if (exp == 0) {
// extra adjustment of exponent for Zero/Denormal?
out.asInt += 1 << 23;
// renormalize
out.asFloat -= kMagicShape.asFloat;
}
// sign bit
out.asInt |= (in & 0x8000) << 16;
return out.asFloat;
}
#if defined(__SSE2__)
union vectorShape {
__m128i asVector;
alignas(16) uint32_t asInt[4];
};
template <unsigned int I>
static inline uint32_t extractScalar(__m128i v) {
#if defined(__SSE4_1__)
return _mm_extract_epi32(v, I);
#else
// Not pretty
vectorShape shape;
shape.asVector = v;
return shape.asInt[I];
#endif
}
static __m128i convertToHalfSSE2(__m128 f) {
// ~15 SSE2 ops
alignas(16) static const uint32_t kMaskAbsolute[4] = { 0x7fffffffu, 0x7fffffffu, 0x7fffffffu, 0x7fffffffu };
alignas(16) static const uint32_t kInf32[4] = { 255 << 23, 255 << 23, 255 << 23, 255 << 23 };
alignas(16) static const uint32_t kExpInf[4] = { (255 ^ 31) << 23, (255 ^ 31) << 23, (255 ^ 31) << 23, (255 ^ 31) << 23 };
alignas(16) static const uint32_t kMax[4] = { (127 + 16) << 23, (127 + 16) << 23, (127 + 16) << 23, (127 + 16) << 23 };
alignas(16) static const uint32_t kMagic[4] = { 15 << 23, 15 << 23, 15 << 23, 15 << 23 };
const __m128 maskAbsolute = *(const __m128 *const)&kMaskAbsolute;
const __m128 absolute = _mm_and_ps(maskAbsolute, f);
const __m128 justSign = _mm_xor_ps(f, absolute);
const __m128 max = *(const __m128 *const)&kMax;
const __m128 expInf = *(const __m128 *const)&kExpInf;
const __m128 infNanCase = _mm_xor_ps(expInf, absolute);
const __m128 clamped = _mm_min_ps(max, absolute);
const __m128 notNormal = _mm_cmpnlt_ps(absolute, *(const __m128 *const)&kInf32);
const __m128 scaled = _mm_mul_ps(clamped, *(const __m128 *const)&kMagic);
const __m128 merge1 = _mm_and_ps(infNanCase, notNormal);
const __m128 merge2 = _mm_andnot_ps(notNormal, scaled);
const __m128 merged = _mm_or_ps(merge1, merge2);
const __m128i shifted = _mm_srli_epi32(_mm_castps_si128(merged), 13);
const __m128i signShifted = _mm_srli_epi32(_mm_castps_si128(justSign), 16);
const __m128i value = _mm_or_si128(shifted, signShifted);
return value;
}
static __m128 convertToFloatSSE2(__m128i h) {
// ~19 SSE2 ops
alignas(16) static const uint32_t kMaskNoSign[4] = { 0x7fff, 0x7fff, 0x7fff, 0x7fff };
alignas(16) static const uint32_t kSmallestNormal[4] = { 0x0400, 0x0400, 0x0400, 0x0400 };
alignas(16) static const uint32_t kInfinity[4] = { 0x7c00, 0x7c00, 0x7c00, 0x7c00 };
alignas(16) static const uint32_t kExpAdjustNormal[4] = { (127 - 15) << 23, (127 - 15) << 23, (127 - 15) << 23, (127 - 15) << 23, };
alignas(16) static const uint32_t kMagicDenormal[4] = { 113 << 23, 113 << 23, 113 << 23, 113 << 23 };
const __m128i noSign = *(const __m128i *const)&kMaskNoSign;
const __m128i exponentAdjust = *(const __m128i *const)&kExpAdjustNormal;
const __m128i smallest = *(const __m128i *const)&kSmallestNormal;
const __m128i infinity = *(const __m128i *const)&kInfinity;
const __m128i expAnd = _mm_and_si128(noSign, h);
const __m128i justSign = _mm_xor_si128(h, expAnd);
const __m128i notInfNan = _mm_cmpgt_epi32(infinity, expAnd);
const __m128i isDenormal = _mm_cmpgt_epi32(smallest, expAnd);
const __m128i shifted = _mm_slli_epi32(expAnd, 13);
const __m128i adjustInfNan = _mm_andnot_si128(notInfNan, exponentAdjust);
const __m128i adjusted = _mm_add_epi32(exponentAdjust, shifted);
const __m128i denormal1 = _mm_add_epi32(shifted, *(const __m128i *const)&kMagicDenormal);
const __m128i adjusted2 = _mm_add_epi32(adjusted, adjustInfNan);
const __m128 denormal2 = _mm_sub_ps(_mm_castsi128_ps(denormal1), *(const __m128 *const)&kMagicDenormal);
const __m128 adjusted3 = _mm_and_ps(denormal2, _mm_castsi128_ps(isDenormal));
const __m128 adjusted4 = _mm_andnot_ps(_mm_castsi128_ps(isDenormal), _mm_castsi128_ps(adjusted2));
const __m128 adjusted5 = _mm_or_ps(adjusted3, adjusted4);
const __m128i sign = _mm_slli_epi32(justSign, 16);
const __m128 value = _mm_or_ps(adjusted5, _mm_castsi128_ps(sign));
return value;
}
#endif
u::vector<half> convertToHalf(const float *const input, size_t length) {
u::vector<half> result(length);
const float *in = input;
U_ASSERT(((uintptr_t)(const void *)in) % 16 == 0);
U_ASSUME_ALIGNED(in, 16);
#if defined(__SSE2__)
const int blocks = int(length) / 4;
const int remainder = int(length) % 4;
int where = 0;
for (int i = 0; i < blocks; i++) {
const __m128 value = _mm_load_ps(&in[where]);
const __m128i convert = convertToHalfSSE2(value);
result[where++] = extractScalar<0>(convert);
result[where++] = extractScalar<1>(convert);
result[where++] = extractScalar<2>(convert);
result[where++] = extractScalar<3>(convert);
}
for (int i = 0; i < remainder; i++)
result[where+i] = convertToHalf(in[where+i]);
#else
for (size_t i = 0; i < length; i++)
result[i] = convertToHalf(in[i]);
#endif
return result;
}
u::vector<float> convertToFloat(const half *const input, size_t length) {
u::vector<float> result(length);
#if defined(__SSE2__)
const half *in = input;
U_ASSUME_ALIGNED(in, 16);
const int blocks = int(length) / 4;
const int remainder = int(length) % 4;
int where = 0;
for (int i = 0; i < blocks; i++, where += 4) {
alignas(16) const __m128i value = _mm_set_epi32(in[where+0], in[where+1], in[where+2], in[where+3]);
const __m128 convert = convertToFloatSSE2(value);
memcpy(&result[where], &convert, sizeof convert);
}
for (int i = 0; i < remainder; i++)
result[where+i] = convertToFloat(in[where+i]);
#else
for (size_t i = 0; i < length; i++)
result[i] = convertToFloat(in[i]);
#endif
return result;
}
}
<commit_msg>Compiler flushes register to memory when extracting a lane - lets not do that.<commit_after>#include <string.h>
#if defined(__SSE2__)
#include <emmintrin.h>
#endif
#if defined(__SSE4_1__)
#include <smmintrin.h>
#endif
#include "m_half.h"
#include "m_const.h"
namespace m {
static struct halfData {
halfData();
// 1536 bytes
uint32_t baseTable[512];
uint8_t shiftTable[512];
} gHalf;
halfData::halfData() {
for (int i = 0, e = 0; i < 256; ++i) {
e = i - 127;
if (e < -24) {
// When magnitude of the number is really small (2^-24 or smaller),
// there is no possible half-float representation for the number, so
// it must be mapped to zero (or negative zero). Setting the shift
// table entries to 24 will shift all mantissa bits, leaving just zero.
// Base tables store zero otherwise (0x8000 for negative zero case.)
baseTable[i|0x000] = 0x0000;
baseTable[i|0x100] = 0x8000;
shiftTable[i|0x000] = 24;
shiftTable[i|0x100] = 24;
} else if (e < -14) {
// When the number is small (< 2^-14), the value can only be
// represented using a subnormal half-float. This is the most
// complex case: first, the leading 1-bit, implicitly represented
// in the normalized representation, must be explicitly added, then
// the resulting mantissa must be shifted rightward, or over a number
// of bit-positions as determined by the exponent. Here we prefer to
// shift the original mantissa bits, and add the pre-shifted 1-bit to
// it.
//
// Note: Shifting by -e-14 will never be negative, thus ensuring
// proper conversion, an alternative method is to shift by 18-e, which
// depends on implementation-defined behavior of unsigned shift.
baseTable[i|0x000] = (0x0400 >> (-e-14));
baseTable[i|0x100] = (0x0400 >> (-e-14)) | 0x8000;
shiftTable[i|0x000] = -e-1;
shiftTable[i|0x100] = -e-1;
} else if (e <= 15) {
// Normal numbers (smaller than 2^15), can be represented using half
// floats, albeit with slightly less precision. The entries in the
// base table are simply set to the bias-adjust exponent value, shifted
// into the right position. A sign bit is added for the negative case.
baseTable[i|0x000] = ((e+15) << 10);
baseTable[i|0x100] = ((e+15) << 10) | 0x8000;
shiftTable[i|0x000] = 13;
shiftTable[i|0x100] = 13;
} else if (e < 128) {
// Large values (numbers less than 2^128) must be mapped to half-float
// Infinity, They are too large to be represented as half-floats. In
// this case the base table is set to 0x7C00 (with sign if negative)
// and the mantissa is zeroed out, which is accomplished by shifting
// out all mantissa bits.
baseTable[i|0x000] = 0x7C00;
baseTable[i|0x100] = 0xFC00;
shiftTable[i|0x000] = 24;
shiftTable[i|0x100] = 24;
} else {
// Remaining float numbers such as Infs and NaNs should stay Infs and
// NaNs after conversion. The base table entries are exactly the same
// as the previous case, except the mantissa-bits are to be preserved
// as much as possible.
baseTable[i|0x000] = 0x7C00;
baseTable[i|0x100] = 0xFC00;
shiftTable[i|0x000] = 13;
shiftTable[i|0x100] = 13;
}
}
}
half convertToHalf(float in) {
const floatShape shape = { in };
return gHalf.baseTable[(shape.asInt >> 23) & 0x1FF] +
((shape.asInt & 0x007FFFFF) >> gHalf.shiftTable[(shape.asInt >> 23) & 0x1FF]);
}
float convertToFloat(half in) {
static constexpr uint32_t kMagic = 113 << 23;
static constexpr uint32_t kShiftedExp = 0x7C00 << 13; // exponent mask after shift
static constexpr floatShape kMagicShape = { kMagic };
floatShape out = { uint32_t(in & 0x7FFF) << 13 }; // exponent/mantissa bits
const size_t exp = kShiftedExp & out.asInt; // exponent
out.asInt += (127 - 15) << 23; // adjust exponent
if (exp == kShiftedExp) {
// extra adjustment of exponent for Inf/Nan?
out.asInt += (128 - 16) << 23;
} else if (exp == 0) {
// extra adjustment of exponent for Zero/Denormal?
out.asInt += 1 << 23;
// renormalize
out.asFloat -= kMagicShape.asFloat;
}
// sign bit
out.asInt |= (in & 0x8000) << 16;
return out.asFloat;
}
#if defined(__SSE2__)
union vectorShape {
__m128i asVector;
alignas(16) uint32_t asInt[4];
};
template <unsigned int I>
static inline uint32_t extractScalar(__m128i v) {
#if defined(__SSE4_1__)
return _mm_extract_epi32(v, I);
#else
return _mm_cvtsi128_si32(_mm_shuffle_epi32(v, _MM_SHUFFLE(I,I,I,I)));
#endif
}
static __m128i convertToHalfSSE2(__m128 f) {
// ~15 SSE2 ops
alignas(16) static const uint32_t kMaskAbsolute[4] = { 0x7fffffffu, 0x7fffffffu, 0x7fffffffu, 0x7fffffffu };
alignas(16) static const uint32_t kInf32[4] = { 255 << 23, 255 << 23, 255 << 23, 255 << 23 };
alignas(16) static const uint32_t kExpInf[4] = { (255 ^ 31) << 23, (255 ^ 31) << 23, (255 ^ 31) << 23, (255 ^ 31) << 23 };
alignas(16) static const uint32_t kMax[4] = { (127 + 16) << 23, (127 + 16) << 23, (127 + 16) << 23, (127 + 16) << 23 };
alignas(16) static const uint32_t kMagic[4] = { 15 << 23, 15 << 23, 15 << 23, 15 << 23 };
const __m128 maskAbsolute = *(const __m128 *const)&kMaskAbsolute;
const __m128 absolute = _mm_and_ps(maskAbsolute, f);
const __m128 justSign = _mm_xor_ps(f, absolute);
const __m128 max = *(const __m128 *const)&kMax;
const __m128 expInf = *(const __m128 *const)&kExpInf;
const __m128 infNanCase = _mm_xor_ps(expInf, absolute);
const __m128 clamped = _mm_min_ps(max, absolute);
const __m128 notNormal = _mm_cmpnlt_ps(absolute, *(const __m128 *const)&kInf32);
const __m128 scaled = _mm_mul_ps(clamped, *(const __m128 *const)&kMagic);
const __m128 merge1 = _mm_and_ps(infNanCase, notNormal);
const __m128 merge2 = _mm_andnot_ps(notNormal, scaled);
const __m128 merged = _mm_or_ps(merge1, merge2);
const __m128i shifted = _mm_srli_epi32(_mm_castps_si128(merged), 13);
const __m128i signShifted = _mm_srli_epi32(_mm_castps_si128(justSign), 16);
const __m128i value = _mm_or_si128(shifted, signShifted);
return value;
}
static __m128 convertToFloatSSE2(__m128i h) {
// ~19 SSE2 ops
alignas(16) static const uint32_t kMaskNoSign[4] = { 0x7fff, 0x7fff, 0x7fff, 0x7fff };
alignas(16) static const uint32_t kSmallestNormal[4] = { 0x0400, 0x0400, 0x0400, 0x0400 };
alignas(16) static const uint32_t kInfinity[4] = { 0x7c00, 0x7c00, 0x7c00, 0x7c00 };
alignas(16) static const uint32_t kExpAdjustNormal[4] = { (127 - 15) << 23, (127 - 15) << 23, (127 - 15) << 23, (127 - 15) << 23, };
alignas(16) static const uint32_t kMagicDenormal[4] = { 113 << 23, 113 << 23, 113 << 23, 113 << 23 };
const __m128i noSign = *(const __m128i *const)&kMaskNoSign;
const __m128i exponentAdjust = *(const __m128i *const)&kExpAdjustNormal;
const __m128i smallest = *(const __m128i *const)&kSmallestNormal;
const __m128i infinity = *(const __m128i *const)&kInfinity;
const __m128i expAnd = _mm_and_si128(noSign, h);
const __m128i justSign = _mm_xor_si128(h, expAnd);
const __m128i notInfNan = _mm_cmpgt_epi32(infinity, expAnd);
const __m128i isDenormal = _mm_cmpgt_epi32(smallest, expAnd);
const __m128i shifted = _mm_slli_epi32(expAnd, 13);
const __m128i adjustInfNan = _mm_andnot_si128(notInfNan, exponentAdjust);
const __m128i adjusted = _mm_add_epi32(exponentAdjust, shifted);
const __m128i denormal1 = _mm_add_epi32(shifted, *(const __m128i *const)&kMagicDenormal);
const __m128i adjusted2 = _mm_add_epi32(adjusted, adjustInfNan);
const __m128 denormal2 = _mm_sub_ps(_mm_castsi128_ps(denormal1), *(const __m128 *const)&kMagicDenormal);
const __m128 adjusted3 = _mm_and_ps(denormal2, _mm_castsi128_ps(isDenormal));
const __m128 adjusted4 = _mm_andnot_ps(_mm_castsi128_ps(isDenormal), _mm_castsi128_ps(adjusted2));
const __m128 adjusted5 = _mm_or_ps(adjusted3, adjusted4);
const __m128i sign = _mm_slli_epi32(justSign, 16);
const __m128 value = _mm_or_ps(adjusted5, _mm_castsi128_ps(sign));
return value;
}
#endif
u::vector<half> convertToHalf(const float *const input, size_t length) {
u::vector<half> result(length);
const float *in = input;
U_ASSERT(((uintptr_t)(const void *)in) % 16 == 0);
U_ASSUME_ALIGNED(in, 16);
#if defined(__SSE2__)
const int blocks = int(length) / 4;
const int remainder = int(length) % 4;
int where = 0;
for (int i = 0; i < blocks; i++) {
const __m128 value = _mm_load_ps(&in[where]);
const __m128i convert = convertToHalfSSE2(value);
result[where++] = extractScalar<0>(convert);
result[where++] = extractScalar<1>(convert);
result[where++] = extractScalar<2>(convert);
result[where++] = extractScalar<3>(convert);
}
for (int i = 0; i < remainder; i++)
result[where+i] = convertToHalf(in[where+i]);
#else
for (size_t i = 0; i < length; i++)
result[i] = convertToHalf(in[i]);
#endif
return result;
}
u::vector<float> convertToFloat(const half *const input, size_t length) {
u::vector<float> result(length);
#if defined(__SSE2__)
const half *in = input;
U_ASSUME_ALIGNED(in, 16);
const int blocks = int(length) / 4;
const int remainder = int(length) % 4;
int where = 0;
for (int i = 0; i < blocks; i++, where += 4) {
alignas(16) const __m128i value = _mm_set_epi32(in[where+0], in[where+1], in[where+2], in[where+3]);
const __m128 convert = convertToFloatSSE2(value);
memcpy(&result[where], &convert, sizeof convert);
}
for (int i = 0; i < remainder; i++)
result[where+i] = convertToFloat(in[where+i]);
#else
for (size_t i = 0; i < length; i++)
result[i] = convertToFloat(in[i]);
#endif
return result;
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: list.hxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: rt $ $Date: 2005-09-09 11:57:10 $
*
* 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 __LISTEN_123456__
#define __LISTEN_123456__
#include <string.h>
#include <iostream>
#include <stdlib.h>
template <class XX>
class List
{
public :
typedef XX * iterator;
typedef const XX * const_iterator;
// LIFECYCLE
List();
virtual ~List() { }
// OPERATORS
const XX & operator[](
unsigned n) const
{ return elem(n); }
XX & operator[](
unsigned n)
{ return elem(n); }
// OPERATIONS
void reserve(
unsigned i_nSize )
{ alloc(i_nSize,true); }
virtual void insert(
unsigned pos,
const XX & elem );
void push_back(
const XX & elem)
{ insert(size(),elem); }
virtual void remove(
unsigned pos );
void pop_back() { remove(size()-1); }
void erase_all() { while (size()) remove(size()-1); }
// INQUIRY
const XX & front() const { return elem(0); }
const XX & back() const { return elem(len-1); }
unsigned size() const { return len; }
unsigned space() const { return allocated; }
bool is_valid_index(
unsigned n) const
{ return n < len; }
// ACCESS
XX & front() { return elem(0); }
XX & back() { return elem(len-1); }
protected:
void checkSize(
unsigned newLength);
void alloc(
unsigned newSpace,
bool re = false );
const XX & elem(
unsigned n ) const
{ return inhalt[n]; }
XX & elem(
unsigned n )
{ return inhalt[n]; }
// DATA
XX * inhalt;
unsigned len;
unsigned allocated;
private:
// forbidden functions
List(const List<XX> & L);
List<XX> & operator=(
const List<XX> & L);
};
template <class XY>
class DynamicList : public List<XY*>
{
public:
virtual ~DynamicList();
virtual void insert(
unsigned pos,
XY * const & elem );
virtual void remove(
unsigned pos );
};
template <class XX>
List<XX>::List()
: inhalt(0),
len(0),
allocated(0)
{
alloc(1);
}
template <class XX>
void
List<XX>::insert(unsigned pos, const XX & elem)
{
if ( pos > len )
return;
checkSize(len+2);
for ( unsigned p = len; p > pos; --p)
{
inhalt[p] = inhalt[p-1];
}
inhalt[pos] = elem;
len++;
}
template <class XX>
void
List<XX>::remove(unsigned pos)
{
if ( pos >= len )
return;
len--;
for ( unsigned p = pos; p < len; ++p)
{
inhalt[p] = inhalt[p+1];
}
}
// Protected:
template <class XX>
void
List<XX>::checkSize(unsigned newLength)
{
// neuen Platzbedarf pruefen:
unsigned newSpace = space();
if (newLength > newSpace)
{
if (!newSpace)
newSpace = 1;
const unsigned nBorder = 65536 / 2;
while(newLength > newSpace)
{
if (newSpace < nBorder)
newSpace <<= 1;
else
{
std::cerr << "List becomes too big" << std::endl;
exit(1);
}
}
}
// Veraenderung ?:
if (newSpace != space())
alloc(newSpace,true);
}
template <class XX>
void
List<XX>::alloc( unsigned newSpace,
bool re )
{
XX * pNew = new XX[newSpace];
if (inhalt != 0)
{
if (re)
{
for (unsigned i = 0; i < len; ++i)
{
pNew[i] = inhalt[i];
} // end for
}
delete [] inhalt;
}
inhalt = pNew;
allocated = newSpace;
}
template <class XY>
DynamicList<XY>::~DynamicList()
{
this->erase_all();
}
template <class XY>
void
DynamicList<XY>::insert(unsigned pos, XY * const & elem)
{
if ( pos > this->len )
return;
checkSize(this->len+2);
memmove(this->inhalt[pos+1], this->inhalt[pos], (this->len-pos) * sizeof(XY*) );
this->inhalt[pos] = elem;
this->len++;
}
template <class XY>
void
DynamicList<XY>::remove( unsigned pos )
{
if (!this->is_valid_index(pos) )
return;
this->len--;
delete this->inhalt[pos];
memmove(this->inhalt[pos], this->inhalt[pos+1], (this->len-pos) * sizeof(XY*) );
}
#endif
<commit_msg>INTEGRATION: CWS warnings01 (1.8.4); FILE MERGED 2005/11/07 12:10:03 sb 1.8.4.1: #i53898# Made code warning-free (additional -W switches for GCC).<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: list.hxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: hr $ $Date: 2006-06-19 20:04:23 $
*
* 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 __LISTEN_123456__
#define __LISTEN_123456__
#include <string.h>
#include <iostream>
#include <stdlib.h>
template <class XX>
class List
{
public :
typedef XX * iterator;
typedef const XX * const_iterator;
// LIFECYCLE
List();
virtual ~List() { }
// OPERATORS
const XX & operator[](
unsigned n) const
{ return elem(n); }
XX & operator[](
unsigned n)
{ return elem(n); }
// OPERATIONS
void reserve(
unsigned i_nSize )
{ alloc(i_nSize,true); }
virtual void insert(
unsigned pos,
const XX & elem );
void push_back(
const XX & elem_)
{ insert(size(),elem_); }
virtual void remove(
unsigned pos );
void pop_back() { remove(size()-1); }
void erase_all() { while (size()) remove(size()-1); }
// INQUIRY
const XX & front() const { return elem(0); }
const XX & back() const { return elem(len-1); }
unsigned size() const { return len; }
unsigned space() const { return allocated; }
bool is_valid_index(
unsigned n) const
{ return n < len; }
// ACCESS
XX & front() { return elem(0); }
XX & back() { return elem(len-1); }
protected:
void checkSize(
unsigned newLength);
void alloc(
unsigned newSpace,
bool re = false );
const XX & elem(
unsigned n ) const
{ return inhalt[n]; }
XX & elem(
unsigned n )
{ return inhalt[n]; }
// DATA
XX * inhalt;
unsigned len;
unsigned allocated;
private:
// forbidden functions
List(const List<XX> & L);
List<XX> & operator=(
const List<XX> & L);
};
template <class XY>
class DynamicList : public List<XY*>
{
public:
virtual ~DynamicList();
virtual void insert(
unsigned pos,
XY * const & elem );
virtual void remove(
unsigned pos );
};
template <class XX>
List<XX>::List()
: inhalt(0),
len(0),
allocated(0)
{
alloc(1);
}
template <class XX>
void
List<XX>::insert(unsigned pos, const XX & elem_)
{
if ( pos > len )
return;
checkSize(len+2);
for ( unsigned p = len; p > pos; --p)
{
inhalt[p] = inhalt[p-1];
}
inhalt[pos] = elem_;
len++;
}
template <class XX>
void
List<XX>::remove(unsigned pos)
{
if ( pos >= len )
return;
len--;
for ( unsigned p = pos; p < len; ++p)
{
inhalt[p] = inhalt[p+1];
}
}
// Protected:
template <class XX>
void
List<XX>::checkSize(unsigned newLength)
{
// neuen Platzbedarf pruefen:
unsigned newSpace = space();
if (newLength > newSpace)
{
if (!newSpace)
newSpace = 1;
const unsigned nBorder = 65536 / 2;
while(newLength > newSpace)
{
if (newSpace < nBorder)
newSpace <<= 1;
else
{
std::cerr << "List becomes too big" << std::endl;
exit(1);
}
}
}
// Veraenderung ?:
if (newSpace != space())
alloc(newSpace,true);
}
template <class XX>
void
List<XX>::alloc( unsigned newSpace,
bool re )
{
XX * pNew = new XX[newSpace];
if (inhalt != 0)
{
if (re)
{
for (unsigned i = 0; i < len; ++i)
{
pNew[i] = inhalt[i];
} // end for
}
delete [] inhalt;
}
inhalt = pNew;
allocated = newSpace;
}
template <class XY>
DynamicList<XY>::~DynamicList()
{
this->erase_all();
}
template <class XY>
void
DynamicList<XY>::insert(unsigned pos, XY * const & elem_)
{
if ( pos > this->len )
return;
checkSize(this->len+2);
memmove(this->inhalt[pos+1], this->inhalt[pos], (this->len-pos) * sizeof(XY*) );
this->inhalt[pos] = elem_;
this->len++;
}
template <class XY>
void
DynamicList<XY>::remove( unsigned pos )
{
if (!this->is_valid_index(pos) )
return;
this->len--;
delete this->inhalt[pos];
memmove(this->inhalt[pos], this->inhalt[pos+1], (this->len-pos) * sizeof(XY*) );
}
#endif
<|endoftext|>
|
<commit_before>
#include "jsonfile.h"
#include "b64/encode.h"
#include <cstdlib>
namespace base
{
JsonWriterFile::JsonWriterFile(FILE* fp, char* buffer, std::size_t length):
m_fileStream(fp, buffer, length),
m_writer(m_fileStream),
m_fp(fp)
{
}
JsonWriterFile::~JsonWriterFile()
{
Flush();
}
FILE* JsonWriterFile::GetFp() const
{
return m_fp;
}
void JsonWriterFile::Flush()
{
m_fileStream.Flush();
void JsonWriterFile::Reset()
{
m_writer.Reset(m_fileStream);
}
bool JsonWriterFile::IsComplete() const
{
return m_writer.IsComplete();
}
void JsonWriterFile::StartObject(const char* name /*= nullptr*/)
{
auto& writer = m_writer;
if (name)
{
writer.String(name);
}
writer.StartObject();
}
void JsonWriterFile::EndObject()
{
m_writer.EndObject();
}
void JsonWriterFile::StartArray(const char* name /*= nullptr*/)
{
auto& writer = m_writer;
if (name)
{
writer.String(name);
}
writer.StartArray();
}
void JsonWriterFile::EndArray()
{
m_writer.EndArray();
}
void JsonWriterFile::WriteNull(const char* name)
{
auto& writer = m_writer;
writer.String(name);
writer.Null();
}
void JsonWriterFile::WriteBool(const char* name, bool value)
{
auto& writer = m_writer;
writer.String(name);
writer.Bool(value);
}
void JsonWriterFile::WriteInt32(const char* name, std::int32_t value)
{
auto& writer = m_writer;
writer.String(name);
writer.Int(value);
}
void JsonWriterFile::WriteInt32(const char* name, std::int32_t value, bool writeCondition)
{
auto& writer = m_writer;
writer.String(name);
if (writeCondition)
{
writer.Int(value);
}
else
{
writer.Null();
}
}
void JsonWriterFile::WriteInt64(const char* name, std::int64_t value)
{
auto& writer = m_writer;
writer.String(name);
writer.Int64(value);
}
void JsonWriterFile::WriteUInt32(const char* name, std::uint32_t value)
{
auto& writer = m_writer;
writer.String(name);
writer.Uint(value);
}
void JsonWriterFile::WriteUInt32(const char* name, std::uint32_t value, bool writeCondition)
{
auto& writer = m_writer;
writer.String(name);
if (writeCondition)
{
writer.Uint(value);
}
else
{
writer.Null();
}
}
void JsonWriterFile::WriteUint64(const char* name, std::uint64_t value)
{
auto& writer = m_writer;
writer.String(name);
writer.Uint64(value);
}
void JsonWriterFile::WriteString(const char* name, const char* value)
{
auto& writer = m_writer;
writer.String(name);
writer.String(value);
}
void JsonWriterFile::WriteString(const char* name, const char* value, std::int32_t length)
{
auto& writer = m_writer;
writer.String(name);
writer.String(value, length);
}
void JsonWriterFile::WriteFloat(const char* name, const double value)
{
auto& writer = m_writer;
writer.String(name);
writer.Double(value);
}
void JsonWriterFile::WriteBits(const char* name, const unsigned char* data, std::size_t numBits)
{
auto& writer = m_writer;
writer.String(name);
base64::base64_encodestate state;
base64::base64_init_encodestate(&state);
state.flags = base64::BASE64_ENC_NO_NEWLINE_TERM;
const std::size_t numBytes = ((numBits + 7) >> 3);
const int encodedLenMax = base64::base64_calc_buffer_length(numBytes, &state);
char* const encoded = (char*)calloc(encodedLenMax, 1);
char* encodedCurOut = encoded;
const std::size_t numTrailingBits = (numBits & 7);
if (numTrailingBits > 0)
{
const std::size_t numBytesWithoutBits = (numBits >> 3);
encodedCurOut += base64::base64_encode_block((const char*)data, numBytesWithoutBits, encodedCurOut, &state);
const char lastByteClean = data[numBytesWithoutBits] & ~(0xFF >> numTrailingBits);
encodedCurOut += base64::base64_encode_block(&lastByteClean, 1, encodedCurOut, &state);
}
else
{
encodedCurOut += base64::base64_encode_block((const char*)data, numBytes, encodedCurOut, &state);
}
encodedCurOut += base64::base64_encode_blockend(encodedCurOut, &state);
writer.String(encoded, encodedCurOut - encoded);
free(encoded);
return;
}
void JsonWriterFile::WriteBytes(const char* name, const unsigned char* data, std::size_t numBytes)
{
JsonWriterFile::WriteBits(name, data, numBytes * 8);
}
}
<commit_msg>Added fflush to JsonWriterFile Flush function<commit_after>
#include "jsonfile.h"
#include "b64/encode.h"
#include <cstdlib>
namespace base
{
JsonWriterFile::JsonWriterFile(FILE* fp, char* buffer, std::size_t length):
m_fileStream(fp, buffer, length),
m_writer(m_fileStream),
m_fp(fp)
{
}
JsonWriterFile::~JsonWriterFile()
{
Flush();
}
FILE* JsonWriterFile::GetFp() const
{
return m_fp;
}
void JsonWriterFile::Flush()
{
m_fileStream.Flush();
fflush(m_fp);
}
void JsonWriterFile::Reset()
{
m_writer.Reset(m_fileStream);
}
bool JsonWriterFile::IsComplete() const
{
return m_writer.IsComplete();
}
void JsonWriterFile::StartObject(const char* name /*= nullptr*/)
{
auto& writer = m_writer;
if (name)
{
writer.String(name);
}
writer.StartObject();
}
void JsonWriterFile::EndObject()
{
m_writer.EndObject();
}
void JsonWriterFile::StartArray(const char* name /*= nullptr*/)
{
auto& writer = m_writer;
if (name)
{
writer.String(name);
}
writer.StartArray();
}
void JsonWriterFile::EndArray()
{
m_writer.EndArray();
}
void JsonWriterFile::WriteNull(const char* name)
{
auto& writer = m_writer;
writer.String(name);
writer.Null();
}
void JsonWriterFile::WriteBool(const char* name, bool value)
{
auto& writer = m_writer;
writer.String(name);
writer.Bool(value);
}
void JsonWriterFile::WriteInt32(const char* name, std::int32_t value)
{
auto& writer = m_writer;
writer.String(name);
writer.Int(value);
}
void JsonWriterFile::WriteInt32(const char* name, std::int32_t value, bool writeCondition)
{
auto& writer = m_writer;
writer.String(name);
if (writeCondition)
{
writer.Int(value);
}
else
{
writer.Null();
}
}
void JsonWriterFile::WriteInt64(const char* name, std::int64_t value)
{
auto& writer = m_writer;
writer.String(name);
writer.Int64(value);
}
void JsonWriterFile::WriteUInt32(const char* name, std::uint32_t value)
{
auto& writer = m_writer;
writer.String(name);
writer.Uint(value);
}
void JsonWriterFile::WriteUInt32(const char* name, std::uint32_t value, bool writeCondition)
{
auto& writer = m_writer;
writer.String(name);
if (writeCondition)
{
writer.Uint(value);
}
else
{
writer.Null();
}
}
void JsonWriterFile::WriteUint64(const char* name, std::uint64_t value)
{
auto& writer = m_writer;
writer.String(name);
writer.Uint64(value);
}
void JsonWriterFile::WriteString(const char* name, const char* value)
{
auto& writer = m_writer;
writer.String(name);
writer.String(value);
}
void JsonWriterFile::WriteString(const char* name, const char* value, std::int32_t length)
{
auto& writer = m_writer;
writer.String(name);
writer.String(value, length);
}
void JsonWriterFile::WriteFloat(const char* name, const double value)
{
auto& writer = m_writer;
writer.String(name);
writer.Double(value);
}
void JsonWriterFile::WriteBits(const char* name, const unsigned char* data, std::size_t numBits)
{
auto& writer = m_writer;
writer.String(name);
base64::base64_encodestate state;
base64::base64_init_encodestate(&state);
state.flags = base64::BASE64_ENC_NO_NEWLINE_TERM;
const std::size_t numBytes = ((numBits + 7) >> 3);
const int encodedLenMax = base64::base64_calc_buffer_length(numBytes, &state);
char* const encoded = (char*)calloc(encodedLenMax, 1);
char* encodedCurOut = encoded;
const std::size_t numTrailingBits = (numBits & 7);
if (numTrailingBits > 0)
{
const std::size_t numBytesWithoutBits = (numBits >> 3);
encodedCurOut += base64::base64_encode_block((const char*)data, numBytesWithoutBits, encodedCurOut, &state);
const char lastByteClean = data[numBytesWithoutBits] & ~(0xFF >> numTrailingBits);
encodedCurOut += base64::base64_encode_block(&lastByteClean, 1, encodedCurOut, &state);
}
else
{
encodedCurOut += base64::base64_encode_block((const char*)data, numBytes, encodedCurOut, &state);
}
encodedCurOut += base64::base64_encode_blockend(encodedCurOut, &state);
writer.String(encoded, encodedCurOut - encoded);
free(encoded);
return;
}
void JsonWriterFile::WriteBytes(const char* name, const unsigned char* data, std::size_t numBytes)
{
JsonWriterFile::WriteBits(name, data, numBytes * 8);
}
}
<|endoftext|>
|
<commit_before>#include <dlfcn.h>
#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
void init() __attribute__((constructor));
void fini() __attribute__((destructor));
static void panic(...) __attribute__((noreturn));
#ifdef DEBUG
#define debug printf
#define assert xassert
#define xassert(e) if (e); else panic(#e)
#define IFDEBUG(X) X
#else
#define debug(...) (void)0
#define assert(...) (void)0
#define IFDEBUG(X) /* nothing */
#endif
#define likely(x) __builtin_expect(!!(x), 1)
#define unlikely(x) __builtin_expect(!!(x), 0)
/**
* These are adapted to be stored internally in whatever data we have.
*/
struct pairing_ptr_heap
{
typedef pairing_ptr_heap T;
typedef pairing_ptr_heap* Tp;
/**
* down,right: first child and right sibling of this page in pairing heap
* of pages with free space.
*/
pairing_ptr_heap* down;
pairing_ptr_heap* right;
Tp delete_min()
{
assert(!right);
Tp l = down;
down = NULL;
return mergePairs(l);
}
static Tp mergePairs(Tp l)
{
if (!l || !l->right) return l;
Tp r = l->right;
Tp hs = r->right;
l->right = r->right = NULL;
assert(hs != l && hs != r && r != l);
// FIXME recursion...
// We can use l->right after merge returns, since merge() always
// returns something with a right-value of NULL. l will never be
// touched until we're about to merge it with the result of mergePairs
l = merge(l,r);
hs = mergePairs(hs);
return merge(l,hs);
}
static Tp merge(Tp l, Tp r)
{
if (!l)
{
assert(!r->right);
return r;
}
if (!r)
{
assert(!l->right);
return l;
}
assert(!l->right && !r->right);
if (r < l)
{
Tp tmp = r;
r = l;
l = tmp;
}
// l <= r!
r->right = l->down;
l->down = r;
//l->right = NULL; // we know it's already null
return l;
}
};
static pairing_ptr_heap* delete_min(pairing_ptr_heap* p)
{
assert(p);
return p->delete_min();
}
static pairing_ptr_heap* insert(pairing_ptr_heap* l, pairing_ptr_heap* r)
{
return pairing_ptr_heap::merge(l, r);
}
struct pageinfo
{
/**
* Pointer to where the page starts.
* TODO: Pack some stuff in here. *Twelve* vacant bits!
*/
void* page;
/**
* The heap of address-sorted pages in this category that have free pages
*/
pairing_ptr_heap heap;
uint16_t size;
//uint16_t isize;
uint16_t chunks;
uint16_t chunks_free;
uint8_t index; // index into array of pages
/**
* 1-32 bytes of bitmap data. A set bit means *free* chunk.
*/
uint8_t bitmap[];
// TODO merge bitmap into page?
};
#define pageinfo_from_heap(heap_) \
((pageinfo*)((char*)(heap_) - offsetof(pageinfo, heap)))
static bool page_filled(pageinfo* page)
{
return !page->chunks_free;
}
static void* page_get_chunk(pageinfo* page)
{
page->chunks_free--;
uint8_t* bitmap = page->bitmap;
for (size_t i = 0; i < page->chunks / 8; i++)
{
const uint8_t found = bitmap[i];
if (found)
{
uint8_t mask = 0x80;
size_t n = i << 3;
while (mask)
{
if (mask & found)
{
bitmap[i] = found & ~mask;
return (uint8_t*)page->page + (n * page->size);
}
mask >>= 1;
n++;
}
}
}
panic("No free chunks found?");
}
static void page_free_chunk(pageinfo* page, void* ptr)
{
size_t ix = (uint8_t*)ptr - (uint8_t*)page->page;
ix /= page->size; // FIXME store inverse or something instead
page->bitmap[ix >> 3] |= 1 << (7 - (ix & 7));
page->chunks_free++;
}
#define N_SIZES (128/16+5)
#define PAGE_SHIFT 12
#define PAGE_SIZE (1 << PAGE_SHIFT)
static pairing_ptr_heap* g_free_pages;
static pageinfo* g_chunk_pages[N_SIZES];
static uintptr_t g_first_page;
static uintptr_t g_n_pages;
// Assumes mostly contiguous pages...
static pageinfo** g_pages;
void init()
{
g_first_page = (uintptr_t)sbrk(0);
}
void fini()
{
// TODO Unmap everything?
}
static void panic(...)
{
abort();
}
static size_t size_ix(size_t size)
{
if (size <= 128)
return (size + 15) / 16 - 1;
size_t ix = 8; // 256 bytes
size >>= 8;
while (size) { size >>= 1; ix++; }
return ix;
}
static size_t ix_size(size_t ix)
{
return ix < 8 ? 16 * (ix + 1) : (1 << ix);
}
static void* get_page()
{
if (void* ret = g_free_pages)
{
g_free_pages = delete_min(g_free_pages);
return ret;
}
else
{
uintptr_t cur = (uintptr_t)sbrk(0);
sbrk((PAGE_SIZE - cur) & (PAGE_SIZE - 1));
return sbrk(PAGE_SIZE);
}
}
static void set_pageinfo(void* page, pageinfo* info)
{
uintptr_t offset;
if (g_pages)
{
offset = ((uintptr_t)page - g_first_page) >> PAGE_SHIFT;
}
else
{
g_first_page = (uintptr_t)page;
offset = 0;
}
if (offset >= g_n_pages)
{
size_t required = (offset + PAGE_SIZE) & ~(PAGE_SIZE-1);
pageinfo** new_pages = (pageinfo**)mmap(NULL, required, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, 0, 0);
assert(new_pages != MAP_FAILED);
memcpy(new_pages, g_pages, g_n_pages * sizeof(pageinfo*));
munmap(g_pages, g_n_pages * sizeof(pageinfo*));
g_pages = new_pages;
g_n_pages = required / sizeof(pageinfo*);
}
g_pages[offset] = info;
}
static pageinfo* new_chunkpage(size_t size)
{
size_t ix = size_ix(size);
size = ix_size(ix);
size_t nchunks = 4096/size;
pageinfo* ret = NULL;
size_t pisize = sizeof(pageinfo) + nchunks/8;
if (!g_chunk_pages[size_ix(pisize)])
{
ret = (pageinfo*)get_page();
set_pageinfo(ret, NULL);
}
else
{
ret = (pageinfo*)malloc(pisize);
}
memset(&ret->heap, 0, sizeof(ret->heap));
ret->page = get_page();
ret->size = size;
// ret->shift = ix_shift(ix);
ret->chunks = nchunks;
ret->chunks_free = nchunks;
ret->index = ix;
memset(ret->bitmap, 0xff, nchunks/8);
set_pageinfo(ret->page, ret);
return ret;
}
static pageinfo* ptr_pageinfo(void* ptr)
{
uintptr_t offset = ((uintptr_t)ptr - g_first_page) >> PAGE_SHIFT;
if (offset > g_n_pages) return NULL;
pageinfo* ret = g_pages[offset];
assert(!ret || !(((uintptr_t)ret->page ^ (uintptr_t)ptr) >> PAGE_SHIFT));
return ret;
}
static size_t get_alloc_size(void* ptr)
{
pageinfo* info = ptr_pageinfo(ptr);
if (!info) panic("get_alloc_size for unknown pointer %p", ptr);
return info->size;
}
void *malloc(size_t size)
{
if (!size) return NULL;
pageinfo** pagep = g_chunk_pages + size_ix(size);
pageinfo* page = *pagep;
if (unlikely(!page))
{
debug("Adding new chunk page for size %lu (cat %ld)\n", size, size_ix(size));
page = new_chunkpage(size);
*pagep = page;
}
debug("Allocating chunk from %p (info %p, %d left)\n", page->page, page, page->chunks_free);
void* ret = page_get_chunk(page);
if (unlikely(page_filled(page)))
{
debug("Page %p (info %p) filled\n", page->page, page);
pairing_ptr_heap* newpage = delete_min(&page->heap);
*pagep = newpage ? pageinfo_from_heap(newpage) : NULL;
}
return ret;
}
void* calloc(size_t n, size_t sz)
{
size_t size = n * sz;
void* ptr = malloc(size);
if (likely(ptr)) memset(ptr, 0, size);
return ptr;
}
void* realloc(void* ptr, size_t new_size)
{
size_t old_size = get_alloc_size(ptr);
void* ret = malloc(new_size);
if (likely(ret))
{
memcpy(ret, ptr, unlikely(new_size < old_size) ? new_size : old_size);
}
return ret;
}
void free(void *ptr)
{
if (unlikely(!ptr)) return;
pageinfo* page = ptr_pageinfo(ptr);
if (unlikely(!page)) panic("free on unknown pointer %p", ptr);
bool was_filled = page_filled(page);
page_free_chunk(page, ptr);
if (was_filled)
{
pageinfo** pagep = g_chunk_pages + page->index;
pageinfo* free_page = *pagep;
if (!free_page)
*pagep = page;
else
*pagep = pageinfo_from_heap(insert(&free_page->heap, &page->heap));
}
else if (unlikely(page->chunks_free == page->chunks))
{
debug("Free: page %p (info %p) is now free\n", page->page, page);
}
}
#ifdef TEST
static int32_t xrand()
{
static int32_t m_w = 1246987127, m_z = 789456123;
m_z = 36969 * (m_z & 65535) + (m_z >> 16);
m_w = 18000 * (m_w & 65535) + (m_w >> 16);
return (m_z << 16) + m_w; /* 32-bit result */
}
const size_t DELAY = 10;
const size_t NTESTS = 100000;
const size_t MAXALLOC = 512;
int main()
{
void* ptrs[DELAY] = {0};
for (size_t i = 0; i < NTESTS; i++)
{
size_t size = i % MAXALLOC;
void** p = ptrs + (i % DELAY);
debug("free(%p)\n", *p);
free(*p);
debug("malloc(%lu)\n", (unsigned long)size);
*p = malloc(size);
debug("malloc(%lu): %p\n", (unsigned long)size, *p);
for (size_t j = 0; j < DELAY; j++)
{
assert(ptrs + j == p || !p[0] || ptrs[j] != p[0]);
}
}
}
#endif
<commit_msg>Debugging the page_free_chunk function<commit_after>#include <dlfcn.h>
#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
void init() __attribute__((constructor));
void fini() __attribute__((destructor));
static void panic(...) __attribute__((noreturn));
#ifdef DEBUG
#define debug printf
#define assert xassert
#define xassert(e) if (e); else panic(#e)
#define IFDEBUG(X) X
#else
#define debug(...) (void)0
#define assert(...) (void)0
#define IFDEBUG(X) /* nothing */
#endif
#define likely(x) __builtin_expect(!!(x), 1)
#define unlikely(x) __builtin_expect(!!(x), 0)
/**
* These are adapted to be stored internally in whatever data we have.
*/
struct pairing_ptr_heap
{
typedef pairing_ptr_heap T;
typedef pairing_ptr_heap* Tp;
/**
* down,right: first child and right sibling of this page in pairing heap
* of pages with free space.
*/
pairing_ptr_heap* down;
pairing_ptr_heap* right;
Tp delete_min()
{
assert(!right);
Tp l = down;
down = NULL;
return mergePairs(l);
}
static Tp mergePairs(Tp l)
{
if (!l || !l->right) return l;
Tp r = l->right;
Tp hs = r->right;
l->right = r->right = NULL;
assert(hs != l && hs != r && r != l);
// FIXME recursion...
// We can use l->right after merge returns, since merge() always
// returns something with a right-value of NULL. l will never be
// touched until we're about to merge it with the result of mergePairs
l = merge(l,r);
hs = mergePairs(hs);
return merge(l,hs);
}
static Tp merge(Tp l, Tp r)
{
if (!l)
{
assert(!r->right);
return r;
}
if (!r)
{
assert(!l->right);
return l;
}
assert(!l->right && !r->right);
if (r < l)
{
Tp tmp = r;
r = l;
l = tmp;
}
// l <= r!
r->right = l->down;
l->down = r;
//l->right = NULL; // we know it's already null
return l;
}
};
static pairing_ptr_heap* delete_min(pairing_ptr_heap* p)
{
assert(p);
return p->delete_min();
}
static pairing_ptr_heap* insert(pairing_ptr_heap* l, pairing_ptr_heap* r)
{
return pairing_ptr_heap::merge(l, r);
}
struct pageinfo
{
/**
* Pointer to where the page starts.
* TODO: Pack some stuff in here. *Twelve* vacant bits!
*/
void* page;
/**
* The heap of address-sorted pages in this category that have free pages
*/
pairing_ptr_heap heap;
uint16_t size;
//uint16_t isize;
uint16_t chunks;
uint16_t chunks_free;
uint8_t index; // index into array of pages
/**
* 1-32 bytes of bitmap data. A set bit means *free* chunk.
*/
uint8_t bitmap[];
// TODO merge bitmap into page?
};
#define pageinfo_from_heap(heap_) \
((pageinfo*)((char*)(heap_) - offsetof(pageinfo, heap)))
static bool page_filled(pageinfo* page)
{
return !page->chunks_free;
}
static void* page_get_chunk(pageinfo* page)
{
page->chunks_free--;
uint8_t* bitmap = page->bitmap;
for (size_t i = 0; i < page->chunks / 8; i++)
{
const uint8_t found = bitmap[i];
if (found)
{
uint8_t mask = 0x80;
size_t n = i << 3;
while (mask)
{
if (mask & found)
{
bitmap[i] = found & ~mask;
return (uint8_t*)page->page + (n * page->size);
}
mask >>= 1;
n++;
}
}
}
panic("No free chunks found?");
}
static void page_free_chunk(pageinfo* page, void* ptr)
{
size_t offset_in_page = (uint8_t*)ptr - (uint8_t*)page->page;
size_t ix = offset_in_page;
ix /= page->size; // FIXME store inverse or something instead
uint8_t mask = 1 << (7 - (ix & 7));
size_t byte = ix >> 3;
debug("Freeing %p in %p (size %d): oring byte %d with %#x\n", ptr, page->page, page->size, byte, mask);
page->bitmap[byte] |= mask;
page->chunks_free++;
}
#define N_SIZES (128/16+5)
#define PAGE_SHIFT 12
#define PAGE_SIZE (1 << PAGE_SHIFT)
static pairing_ptr_heap* g_free_pages;
static pageinfo* g_chunk_pages[N_SIZES];
static uintptr_t g_first_page;
static uintptr_t g_n_pages;
// Assumes mostly contiguous pages...
static pageinfo** g_pages;
void init()
{
g_first_page = (uintptr_t)sbrk(0);
}
void fini()
{
// TODO Unmap everything?
}
static void panic(...)
{
abort();
}
static size_t size_ix(size_t size)
{
if (size <= 128)
return (size + 15) / 16 - 1;
size_t ix = 8; // 256 bytes
size >>= 8;
while (size) { size >>= 1; ix++; }
return ix;
}
static size_t ix_size(size_t ix)
{
return ix < 8 ? 16 * (ix + 1) : (1 << ix);
}
static void* get_page()
{
if (void* ret = g_free_pages)
{
g_free_pages = delete_min(g_free_pages);
return ret;
}
else
{
uintptr_t cur = (uintptr_t)sbrk(0);
sbrk((PAGE_SIZE - cur) & (PAGE_SIZE - 1));
return sbrk(PAGE_SIZE);
}
}
static void set_pageinfo(void* page, pageinfo* info)
{
uintptr_t offset;
if (g_pages)
{
offset = ((uintptr_t)page - g_first_page) >> PAGE_SHIFT;
}
else
{
g_first_page = (uintptr_t)page;
offset = 0;
}
if (offset >= g_n_pages)
{
size_t required = (offset + PAGE_SIZE) & ~(PAGE_SIZE-1);
pageinfo** new_pages = (pageinfo**)mmap(NULL, required, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, 0, 0);
assert(new_pages != MAP_FAILED);
memcpy(new_pages, g_pages, g_n_pages * sizeof(pageinfo*));
munmap(g_pages, g_n_pages * sizeof(pageinfo*));
g_pages = new_pages;
g_n_pages = required / sizeof(pageinfo*);
}
g_pages[offset] = info;
}
static pageinfo* new_chunkpage(size_t size)
{
size_t ix = size_ix(size);
size = ix_size(ix);
size_t nchunks = 4096/size;
pageinfo* ret = NULL;
size_t pisize = sizeof(pageinfo) + nchunks/8;
if (!g_chunk_pages[size_ix(pisize)])
{
ret = (pageinfo*)get_page();
set_pageinfo(ret, NULL);
}
else
{
ret = (pageinfo*)malloc(pisize);
}
memset(&ret->heap, 0, sizeof(ret->heap));
ret->page = get_page();
ret->size = size;
// ret->shift = ix_shift(ix);
ret->chunks = nchunks;
ret->chunks_free = nchunks;
ret->index = ix;
memset(ret->bitmap, 0xff, nchunks/8);
set_pageinfo(ret->page, ret);
return ret;
}
static pageinfo* ptr_pageinfo(void* ptr)
{
uintptr_t offset = ((uintptr_t)ptr - g_first_page) >> PAGE_SHIFT;
if (offset > g_n_pages) return NULL;
pageinfo* ret = g_pages[offset];
assert(!ret || !(((uintptr_t)ret->page ^ (uintptr_t)ptr) >> PAGE_SHIFT));
return ret;
}
static size_t get_alloc_size(void* ptr)
{
pageinfo* info = ptr_pageinfo(ptr);
if (!info) panic("get_alloc_size for unknown pointer %p", ptr);
return info->size;
}
void *malloc(size_t size)
{
if (!size) return NULL;
pageinfo** pagep = g_chunk_pages + size_ix(size);
pageinfo* page = *pagep;
if (unlikely(!page))
{
debug("Adding new chunk page for size %lu (cat %ld)\n", size, size_ix(size));
page = new_chunkpage(size);
*pagep = page;
}
debug("Allocating chunk from %p (info %p, %d left)\n", page->page, page, page->chunks_free);
void* ret = page_get_chunk(page);
if (unlikely(page_filled(page)))
{
debug("Page %p (info %p) filled\n", page->page, page);
pairing_ptr_heap* newpage = delete_min(&page->heap);
*pagep = newpage ? pageinfo_from_heap(newpage) : NULL;
}
return ret;
}
void* calloc(size_t n, size_t sz)
{
size_t size = n * sz;
void* ptr = malloc(size);
if (likely(ptr)) memset(ptr, 0, size);
return ptr;
}
void* realloc(void* ptr, size_t new_size)
{
size_t old_size = get_alloc_size(ptr);
void* ret = malloc(new_size);
if (likely(ret))
{
memcpy(ret, ptr, unlikely(new_size < old_size) ? new_size : old_size);
}
return ret;
}
void free(void *ptr)
{
if (unlikely(!ptr)) return;
pageinfo* page = ptr_pageinfo(ptr);
if (unlikely(!page)) panic("free on unknown pointer %p", ptr);
bool was_filled = page_filled(page);
page_free_chunk(page, ptr);
if (was_filled)
{
pageinfo** pagep = g_chunk_pages + page->index;
pageinfo* free_page = *pagep;
if (!free_page)
*pagep = page;
else
*pagep = pageinfo_from_heap(insert(&free_page->heap, &page->heap));
}
else if (unlikely(page->chunks_free == page->chunks))
{
debug("Free: page %p (info %p) is now free\n", page->page, page);
}
}
#ifdef TEST
static int32_t xrand()
{
static int32_t m_w = 1246987127, m_z = 789456123;
m_z = 36969 * (m_z & 65535) + (m_z >> 16);
m_w = 18000 * (m_w & 65535) + (m_w >> 16);
return (m_z << 16) + m_w; /* 32-bit result */
}
const size_t DELAY = 10;
const size_t NTESTS = 100000;
const size_t MAXALLOC = 512;
int main()
{
void* ptrs[DELAY] = {0};
for (size_t i = 0; i < NTESTS; i++)
{
size_t size = i % MAXALLOC;
void** p = ptrs + (i % DELAY);
debug("free(%p)\n", *p);
free(*p);
debug("malloc(%lu)\n", (unsigned long)size);
*p = malloc(size);
debug("malloc(%lu): %p\n", (unsigned long)size, *p);
for (size_t j = 0; j < DELAY; j++)
{
assert(ptrs + j == p || !p[0] || ptrs[j] != p[0]);
}
}
}
#endif
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: txtparai.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: rt $ $Date: 2005-09-09 15:31:48 $
*
* 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 _XMLOFF_TEXTPARAI_HXX_
#define _XMLOFF_TEXTPARAI_HXX_
#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif
#ifndef _XMLOFF_XMLICTXT_HXX
#include "xmlictxt.hxx"
#endif
class XMLHints_Impl;
namespace com { namespace sun { namespace star {
namespace text { class XTextRange; }
namespace xml { namespace sax { class XAttributeList; } }
} } }
#ifdef CONV_STAR_FONTS
#define CONV_FROM_STAR_BATS 1
#define CONV_FROM_STAR_MATH 2
#define CONV_STAR_FONT_FLAGS_VALID 4
#endif
class XMLParaContext : public SvXMLImportContext
{
::com::sun::star::uno::Reference <
::com::sun::star::text::XTextRange > xStart; // xub_StrLen nStart;
::rtl::OUString sStyleName;
::rtl::OUString sId;
sal_Int8 nOutlineLevel;
XMLHints_Impl *pHints;
sal_Bool bIgnoreLeadingSpace;
sal_Bool bHeading;
sal_Bool bIsListHeader;
#ifdef CONV_STAR_FONTS
sal_uInt8 nStarFontsConvFlags;
#endif
public:
TYPEINFO();
XMLParaContext( SvXMLImport& rImport,
sal_uInt16 nPrfx,
const ::rtl::OUString& rLName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList > & xAttrList,
sal_Bool bHeading );
virtual ~XMLParaContext();
virtual SvXMLImportContext *CreateChildContext( sal_uInt16 nPrefix,
const ::rtl::OUString& rLocalName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList > & xAttrList );
virtual void Characters( const ::rtl::OUString& rChars );
};
#endif
<commit_msg>INTEGRATION: CWS swnumtree (1.6.2); FILE MERGED 2005/09/27 15:30:25 hbrinkm 1.6.2.1: #i45784# ~XMLParaContext: import restart of numbering in headers<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: txtparai.hxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: rt $ $Date: 2005-11-08 17:06:34 $
*
* 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 _XMLOFF_TEXTPARAI_HXX_
#define _XMLOFF_TEXTPARAI_HXX_
#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif
#ifndef _XMLOFF_XMLICTXT_HXX
#include "xmlictxt.hxx"
#endif
class XMLHints_Impl;
namespace com { namespace sun { namespace star {
namespace text { class XTextRange; }
namespace xml { namespace sax { class XAttributeList; } }
} } }
#ifdef CONV_STAR_FONTS
#define CONV_FROM_STAR_BATS 1
#define CONV_FROM_STAR_MATH 2
#define CONV_STAR_FONT_FLAGS_VALID 4
#endif
class XMLParaContext : public SvXMLImportContext
{
::com::sun::star::uno::Reference <
::com::sun::star::text::XTextRange > xStart; // xub_StrLen nStart;
::rtl::OUString sStyleName;
::rtl::OUString sId;
sal_Int8 nOutlineLevel;
XMLHints_Impl *pHints;
sal_Bool bIgnoreLeadingSpace;
sal_Bool bHeading;
sal_Bool bIsListHeader;
sal_Bool bIsRestart;
sal_Int16 nStartValue;
#ifdef CONV_STAR_FONTS
sal_uInt8 nStarFontsConvFlags;
#endif
public:
TYPEINFO();
XMLParaContext( SvXMLImport& rImport,
sal_uInt16 nPrfx,
const ::rtl::OUString& rLName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList > & xAttrList,
sal_Bool bHeading );
virtual ~XMLParaContext();
virtual SvXMLImportContext *CreateChildContext( sal_uInt16 nPrefix,
const ::rtl::OUString& rLocalName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList > & xAttrList );
virtual void Characters( const ::rtl::OUString& rChars );
};
#endif
<|endoftext|>
|
<commit_before>/*
* copyright: (c) RDO-Team, 2011
* filename : main.cpp
* author : , Evgeny Proydakov
* date : 07.07.2009
* bref :
* indent : 4T
*/
// ====================================================================== PCH
// ====================================================================== INCLUDES
#include <vector>
#include <list>
#include <iostream>
#define BOOST_TEST_MODULE RdoInterfaceTest
#include <boost/test/included/unit_test.hpp>
// ====================================================================== SYNOPSIS
#include "rdo_common/rdointerface.h"
// ===============================================================================
#define DISABLE_CONSOLE_OUTPUT
const tstring strIMy1 = _T("void fun1(): ");
const tstring strIMy2 = _T("void fun2(): ");
const tstring strIMy3 = _T("void fun3(): ");
const tstring strMyClass1Create = _T("MyClass1():" );
const tstring strMyClass1Destroy = _T("~MyClass1():" );
const tstring strMyClass2Create = _T("MyClass2():" );
const tstring strMyClass2Destroy = _T("~MyClass2():" );
const tstring strMyClass3Create = _T("MyClass3():" );
const tstring strMyClass3Destroy = _T("~MyClass3():" );
typedef std::list<tstring> LogList;
LogList s_logList;
class IMy1
{
public:
virtual tstring fun1() = 0;
};
class IMy2
{
public:
virtual tstring fun2() = 0;
};
class IMy3
{
public:
virtual tstring fun3() = 0;
};
class IMy4
{
public:
virtual tstring fun4() = 0;
};
INTERFACE_REGISTRATOR(IMy1, 1);
INTERFACE_REGISTRATOR(IMy2, 2);
INTERFACE_REGISTRATOR(IMy3, 3);
INTERFACE_REGISTRATOR(IMy4, 4);
class MyClass1: public rdo::IGetUnknown, public IMy1, public IMy2, public IInit
{
QUERY_INTERFACE_BEGIN
QUERY_INTERFACE(IMy1)
QUERY_INTERFACE(IMy2)
QUERY_INTERFACE(IInit)
QUERY_INTERFACE_END
protected:
MyClass1(char i)
: m_i(i)
{
#ifndef DISABLE_CONSOLE_OUTPUT
std::cout << strMyClass1Create << i << std::endl;
#endif
s_logList.push_back(strMyClass1Create + i);
}
~MyClass1()
{
#ifndef DISABLE_CONSOLE_OUTPUT
std::cout << strMyClass1Destroy << m_i << std::endl;
#endif
s_logList.push_back(strMyClass1Destroy);
}
rbool init()
{
return true;
}
protected:
char m_i;
private:
tstring fun1()
{
#ifndef DISABLE_CONSOLE_OUTPUT
std::cout << strIMy1 << m_i << std::endl;
#endif
return strIMy1 + m_i;
}
tstring fun2()
{
#ifndef DISABLE_CONSOLE_OUTPUT
std::cout << strIMy2 << m_i << std::endl;
#endif
return strIMy2 + m_i;
}
};
class MyClass2: public MyClass1, public IMy3
{
DEFINE_IFACTORY(MyClass2);
QUERY_INTERFACE_BEGIN
QUERY_INTERFACE_PARENT(MyClass1)
QUERY_INTERFACE(IMy3)
QUERY_INTERFACE_END
private:
MyClass2(char i)
: MyClass1(i)
{
#ifndef DISABLE_CONSOLE_OUTPUT
std::cout << strMyClass2Create << i << std::endl;
#endif
s_logList.push_back(strMyClass2Create + i);
}
~MyClass2()
{
#ifndef DISABLE_CONSOLE_OUTPUT
std::cout << strMyClass2Destroy << m_i << std::endl;
#endif
s_logList.push_back(strMyClass2Destroy);
}
tstring fun3()
{
ASSERT(this);
LPIMy1 int1 = this;
ASSERT(int1)
#ifndef DISABLE_CONSOLE_OUTPUT
std::cout << strIMy3 << m_i << std::endl;
#endif
return strIMy3 + m_i;
}
};
class MyClass3: public IMy3, public rdo::IGetUnknown
{
DEFINE_IFACTORY(MyClass3);
QUERY_INTERFACE_BEGIN
QUERY_INTERFACE(IMy3)
QUERY_INTERFACE_END
protected:
MyClass3(char i)
: m_i(i)
{
#ifndef DISABLE_CONSOLE_OUTPUT
std::cout << strMyClass3Create << i << std::endl;
#endif
s_logList.push_back(strMyClass3Create + i);
}
~MyClass3()
{
#ifndef DISABLE_CONSOLE_OUTPUT
std::cout << strMyClass3Destroy << m_i << std::endl;
#endif
s_logList.push_back(strMyClass3Destroy);
}
protected:
char m_i;
private:
tstring fun3()
{
#ifndef DISABLE_CONSOLE_OUTPUT
std::cout << strIMy3 << m_i << std::endl;
#endif
return strIMy3 + m_i;
}
};
typedef rdo::Interface<IMy3> MyInterface;
typedef std::vector<MyInterface> MyInterfaceList;
BOOST_AUTO_TEST_SUITE(RdoInterfaceTest)
BOOST_AUTO_TEST_CASE(RdoInterfaceTest_CheckingOnTheSameOperator)
{
char initValue = _T('2');
rdo::UnknownPointer smptr = F(MyClass2)::create(initValue);
BOOST_REQUIRE(smptr);
LogList::iterator it = s_logList.begin();
BOOST_CHECK_EQUAL(*it, strMyClass1Create + initValue);
BOOST_CHECK_EQUAL(*(++it), strMyClass2Create + initValue);
s_logList.clear();
BOOST_CHECK_EQUAL(smptr.query_cast<IMy1>()->fun1(), strIMy1 + initValue);
BOOST_CHECK_EQUAL(smptr.query_cast<IMy3>()->fun3(), strIMy3 + initValue);
MyInterface imy3 = smptr;
initValue = _T('7');
rdo::UnknownPointer smptr2;
smptr2 = F(MyClass2)::create(initValue);
it = s_logList.begin();
BOOST_CHECK_EQUAL(*it, strMyClass1Create + initValue);
BOOST_CHECK_EQUAL(*(++it), strMyClass2Create + initValue);
s_logList.clear();
rdo::UnknownPointer smptr2_2 = smptr2;
//BOOST_CHECK(smptr2_2 == smptr);
//BOOST_CHECK_EQUAL(smptr2_2, smptr);
BOOST_CHECK(smptr2_2 == smptr2);
rdo::Interface<IMy1> int1_1 = smptr;
rdo::Interface<IMy1> int2_1 = smptr2;
rdo::Interface<IMy1> int1_2 = smptr;
//BOOST_CHECK(int1_1 == int2_1);
//BOOST_CHECK_EQUAL(int1_1, int2_1);
BOOST_CHECK(int1_1 == int1_2);
}
BOOST_AUTO_TEST_CASE(RdoInterfaceTest_ValidationFailureInThePreviousTest1)
{
LogList::iterator it = s_logList.begin();
BOOST_CHECK_EQUAL(*it, strMyClass2Destroy);
++it;
BOOST_CHECK_EQUAL(*it, strMyClass1Destroy);
++it;
BOOST_CHECK_EQUAL(*it, strMyClass2Destroy);
++it;
BOOST_CHECK_EQUAL(*it, strMyClass1Destroy);
s_logList.clear();
}
BOOST_AUTO_TEST_CASE(RdoInterfaceTest_Working)
{
char initFValue = _T('2');
rdo::UnknownPointer smptr = F(MyClass2)::create(initFValue);
LogList::iterator iter = s_logList.begin();
BOOST_CHECK_EQUAL(*iter, strMyClass1Create + initFValue);
BOOST_CHECK_EQUAL(*(++iter), strMyClass2Create + initFValue);
s_logList.clear();
char initSValue = _T('5');
rdo::UnknownPointer smptr2 = F(MyClass2)::create(initSValue);
iter = s_logList.begin();
BOOST_CHECK_EQUAL(*iter, strMyClass1Create + initSValue);
BOOST_CHECK_EQUAL(*(++iter), strMyClass2Create + initSValue);
s_logList.clear();
MyInterfaceList myInterfaceList;
char initTValue = _T('9');
myInterfaceList.push_back(F(MyClass3)::create(initTValue));
myInterfaceList.push_back(smptr );
myInterfaceList.push_back(smptr2);
char symbolT = _T('0');
STL_FOR_ALL_CONST(myInterfaceList, it)
{
rdo::Interface<IMy1> ptr1;
ptr1 = *it;
if (ptr1)
{
symbolT = (*it == smptr ? initFValue : (*it == smptr2 ? initSValue : initTValue));
BOOST_CHECK_EQUAL(ptr1->fun1(), strIMy1 + symbolT);
}
rdo::Interface<IMy2> ptr2 = *it;
if (ptr2)
{
symbolT = (*it == smptr ? initFValue : (*it == smptr2 ? initSValue : initTValue));
BOOST_CHECK_EQUAL(ptr2->fun2(), strIMy2 + symbolT);
}
rdo::Interface<IMy3> ptr3 = *it;
if (ptr3)
{
symbolT = (*it == smptr ? initFValue : (*it == smptr2 ? initSValue : initTValue));
BOOST_CHECK_EQUAL(ptr3->fun3(), strIMy3 + symbolT);
}
}
s_logList.clear();
}
BOOST_AUTO_TEST_CASE(RdoInterfaceTest_ValidationFailureInThePreviousTest2)
{
LogList::iterator it = s_logList.begin();
BOOST_CHECK_EQUAL(*it, strMyClass3Destroy);
++it;
BOOST_CHECK_EQUAL(*it, strMyClass2Destroy);
++it;
BOOST_CHECK_EQUAL(*it, strMyClass1Destroy);
++it;
BOOST_CHECK_EQUAL(*it, strMyClass2Destroy);
++it;
BOOST_CHECK_EQUAL(*it, strMyClass1Destroy);
s_logList.clear();
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg> - значения как в старом тесте<commit_after>/*
* copyright: (c) RDO-Team, 2011
* filename : main.cpp
* author : , Evgeny Proydakov
* date : 07.07.2009
* bref :
* indent : 4T
*/
// ====================================================================== PCH
// ====================================================================== INCLUDES
#include <vector>
#include <list>
#include <iostream>
#define BOOST_TEST_MODULE RdoInterfaceTest
#include <boost/test/included/unit_test.hpp>
// ====================================================================== SYNOPSIS
#include "rdo_common/rdointerface.h"
// ===============================================================================
#define DISABLE_CONSOLE_OUTPUT
const tstring strIMy1 = _T("void fun1(): ");
const tstring strIMy2 = _T("void fun2(): ");
const tstring strIMy3 = _T("void fun3(): ");
const tstring strMyClass1Create = _T("MyClass1():" );
const tstring strMyClass1Destroy = _T("~MyClass1():" );
const tstring strMyClass2Create = _T("MyClass2():" );
const tstring strMyClass2Destroy = _T("~MyClass2():" );
const tstring strMyClass3Create = _T("MyClass3():" );
const tstring strMyClass3Destroy = _T("~MyClass3():" );
typedef std::list<tstring> LogList;
LogList s_logList;
class IMy1
{
public:
virtual tstring fun1() = 0;
};
class IMy2
{
public:
virtual tstring fun2() = 0;
};
class IMy3
{
public:
virtual tstring fun3() = 0;
};
class IMy4
{
public:
virtual tstring fun4() = 0;
};
INTERFACE_REGISTRATOR(IMy1, 1);
INTERFACE_REGISTRATOR(IMy2, 2);
INTERFACE_REGISTRATOR(IMy3, 3);
INTERFACE_REGISTRATOR(IMy4, 4);
class MyClass1: public rdo::IGetUnknown, public IMy1, public IMy2, public IInit
{
QUERY_INTERFACE_BEGIN
QUERY_INTERFACE(IMy1)
QUERY_INTERFACE(IMy2)
QUERY_INTERFACE(IInit)
QUERY_INTERFACE_END
protected:
MyClass1(char i)
: m_i(i)
{
#ifndef DISABLE_CONSOLE_OUTPUT
std::cout << strMyClass1Create << i << std::endl;
#endif
s_logList.push_back(strMyClass1Create + i);
}
~MyClass1()
{
#ifndef DISABLE_CONSOLE_OUTPUT
std::cout << strMyClass1Destroy << m_i << std::endl;
#endif
s_logList.push_back(strMyClass1Destroy);
}
rbool init()
{
return true;
}
protected:
char m_i;
private:
tstring fun1()
{
#ifndef DISABLE_CONSOLE_OUTPUT
std::cout << strIMy1 << m_i << std::endl;
#endif
return strIMy1 + m_i;
}
tstring fun2()
{
#ifndef DISABLE_CONSOLE_OUTPUT
std::cout << strIMy2 << m_i << std::endl;
#endif
return strIMy2 + m_i;
}
};
class MyClass2: public MyClass1, public IMy3
{
DEFINE_IFACTORY(MyClass2);
QUERY_INTERFACE_BEGIN
QUERY_INTERFACE_PARENT(MyClass1)
QUERY_INTERFACE(IMy3)
QUERY_INTERFACE_END
private:
MyClass2(char i)
: MyClass1(i)
{
#ifndef DISABLE_CONSOLE_OUTPUT
std::cout << strMyClass2Create << i << std::endl;
#endif
s_logList.push_back(strMyClass2Create + i);
}
~MyClass2()
{
#ifndef DISABLE_CONSOLE_OUTPUT
std::cout << strMyClass2Destroy << m_i << std::endl;
#endif
s_logList.push_back(strMyClass2Destroy);
}
tstring fun3()
{
ASSERT(this);
LPIMy1 int1 = this;
ASSERT(int1)
#ifndef DISABLE_CONSOLE_OUTPUT
std::cout << strIMy3 << m_i << std::endl;
#endif
return strIMy3 + m_i;
}
};
class MyClass3: public IMy3, public rdo::IGetUnknown
{
DEFINE_IFACTORY(MyClass3);
QUERY_INTERFACE_BEGIN
QUERY_INTERFACE(IMy3)
QUERY_INTERFACE_END
protected:
MyClass3(char i)
: m_i(i)
{
#ifndef DISABLE_CONSOLE_OUTPUT
std::cout << strMyClass3Create << i << std::endl;
#endif
s_logList.push_back(strMyClass3Create + i);
}
~MyClass3()
{
#ifndef DISABLE_CONSOLE_OUTPUT
std::cout << strMyClass3Destroy << m_i << std::endl;
#endif
s_logList.push_back(strMyClass3Destroy);
}
protected:
char m_i;
private:
tstring fun3()
{
#ifndef DISABLE_CONSOLE_OUTPUT
std::cout << strIMy3 << m_i << std::endl;
#endif
return strIMy3 + m_i;
}
};
typedef rdo::Interface<IMy3> MyInterface;
typedef std::vector<MyInterface> MyInterfaceList;
BOOST_AUTO_TEST_SUITE(RdoInterfaceTest)
BOOST_AUTO_TEST_CASE(RdoInterfaceTest_CheckingOnTheSameOperator)
{
char initValue = _T('1');
rdo::UnknownPointer smptr = F(MyClass2)::create(initValue);
BOOST_REQUIRE(smptr);
LogList::iterator it = s_logList.begin();
BOOST_CHECK_EQUAL(*it, strMyClass1Create + initValue);
BOOST_CHECK_EQUAL(*(++it), strMyClass2Create + initValue);
s_logList.clear();
BOOST_CHECK_EQUAL(smptr.query_cast<IMy1>()->fun1(), strIMy1 + initValue);
BOOST_CHECK_EQUAL(smptr.query_cast<IMy3>()->fun3(), strIMy3 + initValue);
initValue = _T('2');
MyInterface imy3 = smptr;
rdo::UnknownPointer smptr2;
smptr2 = F(MyClass2)::create(initValue);
it = s_logList.begin();
BOOST_CHECK_EQUAL(*it, strMyClass1Create + initValue);
BOOST_CHECK_EQUAL(*(++it), strMyClass2Create + initValue);
s_logList.clear();
rdo::UnknownPointer smptr2_2 = smptr2;
//BOOST_CHECK(smptr2_2 == smptr);
//BOOST_CHECK_EQUAL(smptr2_2, smptr);
BOOST_CHECK(smptr2_2 == smptr2);
rdo::Interface<IMy1> int1_1 = smptr;
rdo::Interface<IMy1> int2_1 = smptr2;
rdo::Interface<IMy1> int1_2 = smptr;
//BOOST_CHECK(int1_1 == int2_1);
//BOOST_CHECK_EQUAL(int1_1, int2_1);
BOOST_CHECK(int1_1 == int1_2);
}
BOOST_AUTO_TEST_CASE(RdoInterfaceTest_ValidationFailureInThePreviousTest1)
{
LogList::iterator it = s_logList.begin();
BOOST_CHECK_EQUAL(*it, strMyClass2Destroy);
++it;
BOOST_CHECK_EQUAL(*it, strMyClass1Destroy);
++it;
BOOST_CHECK_EQUAL(*it, strMyClass2Destroy);
++it;
BOOST_CHECK_EQUAL(*it, strMyClass1Destroy);
s_logList.clear();
}
BOOST_AUTO_TEST_CASE(RdoInterfaceTest_Working)
{
char initFValue = _T('2');
rdo::UnknownPointer smptr = F(MyClass2)::create(initFValue);
LogList::iterator iter = s_logList.begin();
BOOST_CHECK_EQUAL(*iter, strMyClass1Create + initFValue);
BOOST_CHECK_EQUAL(*(++iter), strMyClass2Create + initFValue);
s_logList.clear();
char initSValue = _T('5');
rdo::UnknownPointer smptr2 = F(MyClass2)::create(initSValue);
iter = s_logList.begin();
BOOST_CHECK_EQUAL(*iter, strMyClass1Create + initSValue);
BOOST_CHECK_EQUAL(*(++iter), strMyClass2Create + initSValue);
s_logList.clear();
MyInterfaceList myInterfaceList;
char initTValue = _T('9');
myInterfaceList.push_back(F(MyClass3)::create(initTValue));
myInterfaceList.push_back(smptr );
myInterfaceList.push_back(smptr2);
char symbolT = _T('0');
STL_FOR_ALL_CONST(myInterfaceList, it)
{
rdo::Interface<IMy1> ptr1;
ptr1 = *it;
if (ptr1)
{
symbolT = (*it == smptr ? initFValue : (*it == smptr2 ? initSValue : initTValue));
BOOST_CHECK_EQUAL(ptr1->fun1(), strIMy1 + symbolT);
}
rdo::Interface<IMy2> ptr2 = *it;
if (ptr2)
{
symbolT = (*it == smptr ? initFValue : (*it == smptr2 ? initSValue : initTValue));
BOOST_CHECK_EQUAL(ptr2->fun2(), strIMy2 + symbolT);
}
rdo::Interface<IMy3> ptr3 = *it;
if (ptr3)
{
symbolT = (*it == smptr ? initFValue : (*it == smptr2 ? initSValue : initTValue));
BOOST_CHECK_EQUAL(ptr3->fun3(), strIMy3 + symbolT);
}
}
s_logList.clear();
}
BOOST_AUTO_TEST_CASE(RdoInterfaceTest_ValidationFailureInThePreviousTest2)
{
LogList::iterator it = s_logList.begin();
BOOST_CHECK_EQUAL(*it, strMyClass3Destroy);
++it;
BOOST_CHECK_EQUAL(*it, strMyClass2Destroy);
++it;
BOOST_CHECK_EQUAL(*it, strMyClass1Destroy);
++it;
BOOST_CHECK_EQUAL(*it, strMyClass2Destroy);
++it;
BOOST_CHECK_EQUAL(*it, strMyClass1Destroy);
s_logList.clear();
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>
|
<commit_before>#ifndef DISSENT_CONNECTIONS_CONNECTION_TABLE_H_GUARD
#define DISSENT_CONNECTIONS_CONNECTION_TABLE_H_GUARD
#include <QDebug>
#include <QHash>
#include "Id.hpp"
namespace Dissent {
namespace Transports {
class Edge;
}
namespace Connections {
class Connection;
/**
* Contains mappings for remote peers
*/
class ConnectionTable {
public:
typedef Dissent::Transports::Edge Edge;
/**
* Constructor
* @param local_id so we have a "connection" to ourself
*/
explicit ConnectionTable(const Id &local_id = Id::Zero());
/**
* Deconstructor
*/
~ConnectionTable();
/**
* Add an edge
* @param edge the edge to add
*/
void AddEdge(QSharedPointer<Edge> edge);
/**
* Add an edge
* @param edge the edge to add
*/
void AddEdge(Edge *edge);
/**
* Remove an edge, returns true if it is stored
* @param edge the edge to remvoe
*/
bool RemoveEdge(const Edge *edge);
/**
* Remove an edge, returns true if it is stored
* @param edge the edge to remvoe
*/
bool RemoveEdge(QSharedPointer<Edge> edge);
inline bool Contains(const Connection *con) { return _cons.contains(con); }
/**
* Remove a connection from being looked up by Id or Edge, returns
* true if exists. Should be called after calling disconnect but
* before an edge is closed.
* @param con the connection to remove
*/
bool Disconnect(Connection *con);
/**
* Returns the connection matching to the Id or 0 if none exists
* @param id the Id to lookup
*/
Connection *GetConnection(const Id &id) const;
/**
* Returns the connection matching to the Id or 0 if none exists
* @param id the Id to lookup
*/
Connection *GetConnection(QSharedPointer<Edge> edge) const;
/**
* Returns a the connection matching to the edge or 0 if none exists
* @param edge the edge to lookup
*/
Connection *GetConnection(const Edge *edge) const;
inline const QList<Connection *> GetConnections() const { return _cons.values(); }
inline QSharedPointer<Edge> GetEdge(const Edge * edge) const { return _edges[edge]; }
inline const QList<QSharedPointer<Edge> > GetEdges() const { return _edges.values(); }
/**
* Adds a Connection
* @param con the connection to add
*/
void AddConnection(Connection *con);
/**
* Removes the connection from being stored, returns true if exists.
* Should only be called after the edge has been closed.
* @param con the stored connection
*/
bool RemoveConnection(Connection *con);
/**
* Print connection table to debug output
*/
void PrintConnectionTable();
private:
/**
* Stores Id to Connection mappings
*/
QHash<const Id, Connection *> _id_to_con;
/**
* Stores Edge to Connection mappings
*/
QHash<const Edge *, Connection *> _edge_to_con;
/**
* Stores Connections
*/
QHash<const Connection *, Connection *> _cons;
/**
* Stores Edges
*/
QHash<const Edge *, QSharedPointer<Edge> > _edges;
};
}
}
#endif
<commit_msg>[Connections] Missed an include<commit_after>#ifndef DISSENT_CONNECTIONS_CONNECTION_TABLE_H_GUARD
#define DISSENT_CONNECTIONS_CONNECTION_TABLE_H_GUARD
#include <QDebug>
#include <QHash>
#include <QSharedPointer>
#include "Id.hpp"
namespace Dissent {
namespace Transports {
class Edge;
}
namespace Connections {
class Connection;
/**
* Contains mappings for remote peers
*/
class ConnectionTable {
public:
typedef Dissent::Transports::Edge Edge;
/**
* Constructor
* @param local_id so we have a "connection" to ourself
*/
explicit ConnectionTable(const Id &local_id = Id::Zero());
/**
* Deconstructor
*/
~ConnectionTable();
/**
* Add an edge
* @param edge the edge to add
*/
void AddEdge(QSharedPointer<Edge> edge);
/**
* Add an edge
* @param edge the edge to add
*/
void AddEdge(Edge *edge);
/**
* Remove an edge, returns true if it is stored
* @param edge the edge to remvoe
*/
bool RemoveEdge(const Edge *edge);
/**
* Remove an edge, returns true if it is stored
* @param edge the edge to remvoe
*/
bool RemoveEdge(QSharedPointer<Edge> edge);
inline bool Contains(const Connection *con) { return _cons.contains(con); }
/**
* Remove a connection from being looked up by Id or Edge, returns
* true if exists. Should be called after calling disconnect but
* before an edge is closed.
* @param con the connection to remove
*/
bool Disconnect(Connection *con);
/**
* Returns the connection matching to the Id or 0 if none exists
* @param id the Id to lookup
*/
Connection *GetConnection(const Id &id) const;
/**
* Returns the connection matching to the Id or 0 if none exists
* @param id the Id to lookup
*/
Connection *GetConnection(QSharedPointer<Edge> edge) const;
/**
* Returns a the connection matching to the edge or 0 if none exists
* @param edge the edge to lookup
*/
Connection *GetConnection(const Edge *edge) const;
inline const QList<Connection *> GetConnections() const { return _cons.values(); }
inline QSharedPointer<Edge> GetEdge(const Edge * edge) const { return _edges[edge]; }
inline const QList<QSharedPointer<Edge> > GetEdges() const { return _edges.values(); }
/**
* Adds a Connection
* @param con the connection to add
*/
void AddConnection(Connection *con);
/**
* Removes the connection from being stored, returns true if exists.
* Should only be called after the edge has been closed.
* @param con the stored connection
*/
bool RemoveConnection(Connection *con);
/**
* Print connection table to debug output
*/
void PrintConnectionTable();
private:
/**
* Stores Id to Connection mappings
*/
QHash<const Id, Connection *> _id_to_con;
/**
* Stores Edge to Connection mappings
*/
QHash<const Edge *, Connection *> _edge_to_con;
/**
* Stores Connections
*/
QHash<const Connection *, Connection *> _cons;
/**
* Stores Edges
*/
QHash<const Edge *, QSharedPointer<Edge> > _edges;
};
}
}
#endif
<|endoftext|>
|
<commit_before>#include "zcm/transport.h"
#include "zcm/transport_registrar.h"
#include "zcm/transport_register.hpp"
#include "zcm/util/debug.h"
#include "generic_serial_transport.h"
#include "util/TimeUtil.hpp"
#include <unistd.h>
#include <string.h>
#include <iostream>
#include <limits>
#include <cstdio>
#include <cassert>
#include <unordered_map>
#include <algorithm>
#include <net/if.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <linux/sockios.h>
#include <linux/can.h>
#include <linux/can/raw.h>
// Define this the class name you want
#define ZCM_TRANS_CLASSNAME TransportCan
#define MTU (1<<14)
using namespace std;
struct ZCM_TRANS_CLASSNAME : public zcm_trans_t
{
unordered_map<string, string> options;
uint msgId;
string address;
int soc = -1;
bool socSettingsGood = false;
struct sockaddr_can addr;
struct ifreq ifr;
zcm_trans_t* gst = nullptr;
string* findOption(const string& s)
{
auto it = options.find(s);
if (it == options.end()) return nullptr;
return &it->second;
}
ZCM_TRANS_CLASSNAME(zcm_url_t* url)
{
trans_type = ZCM_BLOCKING;
vtbl = &methods;
// build 'options'
auto* opts = zcm_url_opts(url);
for (size_t i = 0; i < opts->numopts; ++i)
options[opts->name[i]] = opts->value[i];
msgId = 0;
auto* msgIdStr = findOption("msgid");
if (!msgIdStr) {
ZCM_DEBUG("Msg Id unspecified");
return;
} else {
char *endptr;
msgId = strtoul(msgIdStr->c_str(), &endptr, 10);
if (*endptr != '\0') {
ZCM_DEBUG("Msg Id unspecified");
return;
}
}
address = zcm_url_address(url);
if ((soc = socket(PF_CAN, SOCK_RAW, CAN_RAW)) < 0) {
ZCM_DEBUG("Unable to make socket");
return;
}
strcpy(ifr.ifr_name, address.c_str());
ioctl(soc, SIOCGIFINDEX, &ifr);
memset(&addr, 0, sizeof(addr));
addr.can_family = AF_CAN;
addr.can_ifindex = ifr.ifr_ifindex;
if (bind(soc, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
ZCM_DEBUG("Failed to bind");
return;
}
struct can_filter rfilter[1];
rfilter[0].can_id = msgId | CAN_EFF_FLAG;
rfilter[0].can_mask = (CAN_EFF_FLAG | CAN_RTR_FLAG | CAN_EFF_MASK);
if (setsockopt(soc, SOL_CAN_RAW, CAN_RAW_FILTER, &rfilter, sizeof(rfilter)) < 0) {
ZCM_DEBUG("Failed to set filter");
return;
}
gst = zcm_trans_generic_serial_create(&ZCM_TRANS_CLASSNAME::get,
&ZCM_TRANS_CLASSNAME::put,
this,
&ZCM_TRANS_CLASSNAME::timestamp_now,
this,
MTU, MTU * 10);
socSettingsGood = true;
}
~ZCM_TRANS_CLASSNAME()
{
if (gst) zcm_trans_generic_serial_destroy(gst);
if (soc != -1 && close(soc) < 0) {
ZCM_DEBUG("Failed to close");
}
soc = -1;
}
bool good()
{
return soc != -1 && socSettingsGood;
}
static size_t get(uint8_t* data, size_t nData, void* usr)
{
ZCM_TRANS_CLASSNAME* me = cast((zcm_trans_t*) usr);
struct can_frame frame;
int nbytes = read(me->soc, &frame, sizeof(struct can_frame));
if (nbytes != sizeof(struct can_frame)) return 0;
// XXX This isn't okay. We're just throwing out data if it
// doesn't fit in data on this one call to get
size_t ret = min(nData, (size_t) frame.can_dlc);
memcpy(data, frame.data, ret);
return ret;
}
static size_t sendFrame(const uint8_t* data, size_t nData, void* usr)
{
ZCM_TRANS_CLASSNAME* me = cast((zcm_trans_t*) usr);
struct can_frame frame;
frame.can_id = me->msgId | CAN_EFF_FLAG;
size_t ret = min(nData, (size_t) 8);
frame.can_dlc = ret;
memcpy(frame.data, data, ret);
if (write(me->soc, &frame, sizeof(struct can_frame)) != sizeof(struct can_frame)) {
ZCM_DEBUG("Failed to write data");
return -1;
}
return ret;
}
static size_t put(const uint8_t* data, size_t nData, void* usr)
{
size_t ret = 0;
while (ret < nData) {
size_t left = nData - ret;
size_t written = sendFrame(&data[ret], left, usr);
if (written <= 0) return ret;
ret += written;
}
return ret;
}
static uint64_t timestamp_now(void* usr)
{
ZCM_TRANS_CLASSNAME* me = cast((zcm_trans_t*) usr);
struct timeval time;
if (ioctl(me->soc, SIOCGSTAMP, &time) == -1) return 0;
return time.tv_sec * 1e6 + time.tv_usec;
}
/********************** METHODS **********************/
size_t get_mtu()
{
return zcm_trans_get_mtu(this->gst);
}
int sendmsg(zcm_msg_t msg)
{
int ret = zcm_trans_sendmsg(this->gst, msg);
if (ret != ZCM_EOK) return ret;
return serial_update_tx(this->gst);
}
int recvmsgEnable(const char* channel, bool enable)
{
return zcm_trans_recvmsg_enable(this->gst, channel, enable);
}
int recvmsg(zcm_msg_t* msg, int timeoutMs)
{
int timeoutS = timeoutMs / 1000;
struct timeval tm = {
timeoutS, /* seconds */
(timeoutMs - (timeoutS * 1000)) * 1000 /* micros */
};
if (setsockopt(soc, SOL_SOCKET, SO_RCVTIMEO, (char *)&tm, sizeof(tm)) < 0) {
ZCM_DEBUG("Failed to settimeout");
return ZCM_EUNKNOWN;
}
uint64_t startUtime = TimeUtil::utime();
uint64_t timeoutUs = timeoutMs > 0 ? timeoutMs * 1e3 : numeric_limits<uint64_t>::max();
uint64_t timeoutLeft = timeoutUs;
do {
int ret = zcm_trans_recvmsg(this->gst, msg, timeoutLeft);
if (ret == ZCM_EOK) return ret;
serial_update_rx(this->gst);
uint64_t diff = TimeUtil::utime() - startUtime;
timeoutLeft = timeoutUs > diff ? timeoutUs - diff : 0;
} while (timeoutLeft > 0);
return ZCM_EAGAIN;
}
/********************** STATICS **********************/
static zcm_trans_methods_t methods;
static ZCM_TRANS_CLASSNAME *cast(zcm_trans_t *zt)
{
assert(zt->vtbl == &methods);
return (ZCM_TRANS_CLASSNAME*)zt;
}
static size_t _get_mtu(zcm_trans_t *zt)
{ return cast(zt)->get_mtu(); }
static int _sendmsg(zcm_trans_t *zt, zcm_msg_t msg)
{ return cast(zt)->sendmsg(msg); }
static int _recvmsg_enable(zcm_trans_t *zt, const char *channel, bool enable)
{ return cast(zt)->recvmsgEnable(channel, enable); }
static int _recvmsg(zcm_trans_t *zt, zcm_msg_t *msg, int timeout)
{ return cast(zt)->recvmsg(msg, timeout); }
static void _destroy(zcm_trans_t *zt)
{ delete cast(zt); }
/** If you choose to use the registrar, use a static registration member **/
static const TransportRegister reg;
};
zcm_trans_methods_t ZCM_TRANS_CLASSNAME::methods = {
&ZCM_TRANS_CLASSNAME::_get_mtu,
&ZCM_TRANS_CLASSNAME::_sendmsg,
&ZCM_TRANS_CLASSNAME::_recvmsg_enable,
&ZCM_TRANS_CLASSNAME::_recvmsg,
NULL,
&ZCM_TRANS_CLASSNAME::_destroy,
};
static zcm_trans_t *create(zcm_url_t* url)
{
auto* trans = new ZCM_TRANS_CLASSNAME(url);
if (trans->good())
return trans;
delete trans;
return nullptr;
}
#ifdef USING_TRANS_SERIAL
const TransportRegister ZCM_TRANS_CLASSNAME::reg(
"can", "Transfer data via a socket CAN connection on a single id "
"(e.g. 'can://can0?msgid=65536')", create);
#endif
<commit_msg>Minor<commit_after>#include "zcm/transport.h"
#include "zcm/transport_registrar.h"
#include "zcm/transport_register.hpp"
#include "zcm/util/debug.h"
#include "generic_serial_transport.h"
#include "util/TimeUtil.hpp"
#include <unistd.h>
#include <string.h>
#include <iostream>
#include <limits>
#include <cstdio>
#include <cassert>
#include <unordered_map>
#include <algorithm>
#include <net/if.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <linux/sockios.h>
#include <linux/can.h>
#include <linux/can/raw.h>
// Define this the class name you want
#define ZCM_TRANS_CLASSNAME TransportCan
#define MTU (1<<14)
using namespace std;
struct ZCM_TRANS_CLASSNAME : public zcm_trans_t
{
unordered_map<string, string> options;
uint msgId;
string address;
int soc = -1;
bool socSettingsGood = false;
struct sockaddr_can addr;
struct ifreq ifr;
zcm_trans_t* gst = nullptr;
string* findOption(const string& s)
{
auto it = options.find(s);
if (it == options.end()) return nullptr;
return &it->second;
}
ZCM_TRANS_CLASSNAME(zcm_url_t* url)
{
trans_type = ZCM_BLOCKING;
vtbl = &methods;
// build 'options'
auto* opts = zcm_url_opts(url);
for (size_t i = 0; i < opts->numopts; ++i)
options[opts->name[i]] = opts->value[i];
msgId = 0;
auto* msgIdStr = findOption("msgid");
if (!msgIdStr) {
ZCM_DEBUG("Msg Id unspecified");
return;
} else {
char *endptr;
msgId = strtoul(msgIdStr->c_str(), &endptr, 10);
if (*endptr != '\0') {
ZCM_DEBUG("Msg Id unspecified");
return;
}
}
address = zcm_url_address(url);
if ((soc = socket(PF_CAN, SOCK_RAW, CAN_RAW)) < 0) {
ZCM_DEBUG("Unable to make socket");
return;
}
strcpy(ifr.ifr_name, address.c_str());
ioctl(soc, SIOCGIFINDEX, &ifr);
memset(&addr, 0, sizeof(addr));
addr.can_family = AF_CAN;
addr.can_ifindex = ifr.ifr_ifindex;
if (bind(soc, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
ZCM_DEBUG("Failed to bind");
return;
}
struct can_filter rfilter[1];
rfilter[0].can_id = msgId | CAN_EFF_FLAG;
rfilter[0].can_mask = (CAN_EFF_FLAG | CAN_RTR_FLAG | CAN_EFF_MASK);
if (setsockopt(soc, SOL_CAN_RAW, CAN_RAW_FILTER, &rfilter, sizeof(rfilter)) < 0) {
ZCM_DEBUG("Failed to set filter");
return;
}
gst = zcm_trans_generic_serial_create(&ZCM_TRANS_CLASSNAME::get,
&ZCM_TRANS_CLASSNAME::put,
this,
&ZCM_TRANS_CLASSNAME::timestamp_now,
this,
MTU, MTU * 10);
socSettingsGood = true;
}
~ZCM_TRANS_CLASSNAME()
{
if (gst) zcm_trans_generic_serial_destroy(gst);
if (soc != -1 && close(soc) < 0) {
ZCM_DEBUG("Failed to close");
}
soc = -1;
}
bool good()
{
return soc != -1 && socSettingsGood;
}
static size_t get(uint8_t* data, size_t nData, void* usr)
{
ZCM_TRANS_CLASSNAME* me = cast((zcm_trans_t*) usr);
struct can_frame frame;
int nbytes = read(me->soc, &frame, sizeof(struct can_frame));
if (nbytes != sizeof(struct can_frame)) return 0;
// XXX This isn't okay. We're just throwing out data if it
// doesn't fit in data on this one call to get
size_t ret = min(nData, (size_t) frame.can_dlc);
memcpy(data, frame.data, ret);
return ret;
}
static size_t sendFrame(const uint8_t* data, size_t nData, void* usr)
{
ZCM_TRANS_CLASSNAME* me = cast((zcm_trans_t*) usr);
struct can_frame frame;
frame.can_id = me->msgId | CAN_EFF_FLAG;
size_t ret = min(nData, (size_t) 8);
frame.can_dlc = ret;
memcpy(frame.data, data, ret);
if (write(me->soc, &frame, sizeof(struct can_frame)) != sizeof(struct can_frame)) {
ZCM_DEBUG("Failed to write data");
return -1;
}
return ret;
}
static size_t put(const uint8_t* data, size_t nData, void* usr)
{
size_t ret = 0;
while (ret < nData) {
size_t left = nData - ret;
size_t written = sendFrame(&data[ret], left, usr);
if (written <= 0) return ret;
ret += written;
}
return ret;
}
static uint64_t timestamp_now(void* usr)
{
ZCM_TRANS_CLASSNAME* me = cast((zcm_trans_t*) usr);
struct timeval time;
if (ioctl(me->soc, SIOCGSTAMP, &time) == -1) return 0;
return time.tv_sec * 1e6 + time.tv_usec;
}
/********************** METHODS **********************/
size_t get_mtu()
{
return zcm_trans_get_mtu(this->gst);
}
int sendmsg(zcm_msg_t msg)
{
int ret = zcm_trans_sendmsg(this->gst, msg);
if (ret != ZCM_EOK) return ret;
return serial_update_tx(this->gst);
}
int recvmsgEnable(const char* channel, bool enable)
{
return zcm_trans_recvmsg_enable(this->gst, channel, enable);
}
int recvmsg(zcm_msg_t* msg, int timeoutMs)
{
int timeoutS = timeoutMs / 1000;
timeoutMs -= timeoutS * 1000;
struct timeval tm = {
timeoutS, /* seconds */
timeoutMs * 1000 /* micros */
};
if (setsockopt(soc, SOL_SOCKET, SO_RCVTIMEO, (char *)&tm, sizeof(tm)) < 0) {
ZCM_DEBUG("Failed to settimeout");
return ZCM_EUNKNOWN;
}
uint64_t startUtime = TimeUtil::utime();
uint64_t timeoutUs = timeoutMs > 0 ? timeoutMs * 1e3 : numeric_limits<uint64_t>::max();
uint64_t timeoutLeft = timeoutUs;
do {
int ret = zcm_trans_recvmsg(this->gst, msg, timeoutLeft);
if (ret == ZCM_EOK) return ret;
serial_update_rx(this->gst);
uint64_t diff = TimeUtil::utime() - startUtime;
timeoutLeft = timeoutUs > diff ? timeoutUs - diff : 0;
} while (timeoutLeft > 0);
return ZCM_EAGAIN;
}
/********************** STATICS **********************/
static zcm_trans_methods_t methods;
static ZCM_TRANS_CLASSNAME *cast(zcm_trans_t *zt)
{
assert(zt->vtbl == &methods);
return (ZCM_TRANS_CLASSNAME*)zt;
}
static size_t _get_mtu(zcm_trans_t *zt)
{ return cast(zt)->get_mtu(); }
static int _sendmsg(zcm_trans_t *zt, zcm_msg_t msg)
{ return cast(zt)->sendmsg(msg); }
static int _recvmsg_enable(zcm_trans_t *zt, const char *channel, bool enable)
{ return cast(zt)->recvmsgEnable(channel, enable); }
static int _recvmsg(zcm_trans_t *zt, zcm_msg_t *msg, int timeout)
{ return cast(zt)->recvmsg(msg, timeout); }
static void _destroy(zcm_trans_t *zt)
{ delete cast(zt); }
/** If you choose to use the registrar, use a static registration member **/
static const TransportRegister reg;
};
zcm_trans_methods_t ZCM_TRANS_CLASSNAME::methods = {
&ZCM_TRANS_CLASSNAME::_get_mtu,
&ZCM_TRANS_CLASSNAME::_sendmsg,
&ZCM_TRANS_CLASSNAME::_recvmsg_enable,
&ZCM_TRANS_CLASSNAME::_recvmsg,
NULL,
&ZCM_TRANS_CLASSNAME::_destroy,
};
static zcm_trans_t *create(zcm_url_t* url)
{
auto* trans = new ZCM_TRANS_CLASSNAME(url);
if (trans->good())
return trans;
delete trans;
return nullptr;
}
#ifdef USING_TRANS_SERIAL
const TransportRegister ZCM_TRANS_CLASSNAME::reg(
"can", "Transfer data via a socket CAN connection on a single id "
"(e.g. 'can://can0?msgid=65536')", create);
#endif
<|endoftext|>
|
<commit_before>/*****************************************************************************
* Copyright (C) 2011-2016 Michael Ira Krufky
*
* Author: Michael Ira Krufky <mkrufky@linuxtv.org>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#include <inttypes.h>
#include "string.h"
#include "stats.h"
#include "log.h"
#define CLASS_MODULE "stats"
#define DBG 0
#define dPrintf(fmt, arg...) __dPrintf(DBG_STATS, "(%s) " fmt, parent, ##arg)
stats::stats(const char *caller)
: tei_count(0)
, __timenow(0)
, parent(caller)
, streamtime_cb(NULL)
, streamtime_priv(NULL)
, statistics_cb(NULL)
, statistics_priv(NULL)
, statistics_iface(NULL)
{
dPrintf("(%s)", parent);
}
stats::~stats()
{
dPrintf("(%s)", parent);
show(false);
}
#if 0
stats::stats(const stats&)
{
dPrintf("(%s, copy)", parent);
}
stats& stats::operator= (const stats& cSource)
{
dPrintf("(%s, operator=)", parent);
if (this == &cSource)
return *this;
return *this;
}
#endif
static void parse_pcr(uint8_t *pcr, uint64_t *pcr_base, unsigned int *pcr_ext)
{
*pcr_base = ((uint64_t)pcr[0] * 0x2000000) +
((uint64_t)pcr[1] * 0x20000) +
((uint64_t)pcr[2] * 0x200) +
((uint64_t)pcr[3] * 0x02) +
((uint64_t)(pcr[4] & 0x80) >> 7);
*pcr_ext = ((pcr[4] & 0x01) * 0x100) + pcr[5];
return;
}
static time_t walltime(void *p) { (void)p; return time(NULL); }
char *stats_scale_unit(char *b, size_t n, uint64_t x)
{
memset(b, 0, n);
if (x >= 1000000) {
#if 0
if ((x % 1000000) < 100)
snprintf(b, n, "%3" PRIu64 ".%03" PRIu64 " m", x / 1000000, x % 1000000);
else
#endif
snprintf(b, n, "%3" PRIu64 ".%03" PRIu64 " m", x / 1000000, x % 1000000);
} else if (x >= 1000) {
#if 0
if ((x % 1000) < 100)
snprintf(b, n, "%3" PRIu64 ".%03" PRIu64 " k", x / 1000, x % 1000);
else
#endif
snprintf(b, n, "%3" PRIu64 ".%03" PRIu64 " k", x / 1000, x % 1000);
} else
snprintf(b, n, " %3" PRIu64 " ", x);
return b;
}
void stats::show(bool per_sec)
{
if (statistics_cb) {
statistics_cb(statistics_priv, statistics, discontinuities, tei_count, per_sec);
}
if (statistics_iface) {
statistics_iface->stats(statistics, discontinuities, tei_count, per_sec);
}
if (statistics_cb || statistics_iface) {
return;
}
for (stats_map::const_iterator iter = statistics.begin(); iter != statistics.end(); ++iter) {
char a[16];
char b[16];
if (dbg & DBG_STATS) __log_printf(stderr, "pid %04x %5" PRIu64 " p%s %sb%s %sbit\n",
iter->first, iter->second / 188, (per_sec) ? "/s" : "",
stats_scale_unit(a, sizeof(a), iter->second), (per_sec) ? "/s" : "",
stats_scale_unit(b, sizeof(b), iter->second * 8));
}
for (stats_map::const_iterator iter = discontinuities.begin(); iter != discontinuities.end(); ++iter)
if (dbg & DBG_STATS) __log_printf(stderr, "pid %04x\t%" PRIu64 " continuity errors (%" PRIu64 "%%)\n", iter->first, iter->second, ((!iter->second) || (!statistics[iter->first])) ? 0 : (!statistics.count(iter->first)) ? 0 : (100 * iter->second / (statistics[iter->first] / 188)));
if ((tei_count) && (dbg & DBG_STATS)) __log_printf(stderr, "tei count: %" PRIu64 " (%" PRIu64 "%%)\n", tei_count, (!statistics[0x2000]) ? 0 : (18800 * tei_count / statistics[0x2000]));
}
void stats::push_pid(int c, const uint16_t pid)
{
streamtime_callback cb = (streamtime_cb) ? streamtime_cb : &walltime;
time_t timenow = cb(streamtime_priv);
if (timenow > __timenow) {
show();
clear_stats();
__timenow = timenow;
}
__push_pid(c, pid);
}
pkt_stats_t *stats::parse(const uint8_t *p, pkt_stats_t *pkt_stats)
{
adaptation_field_t adapt;
pkt_hdr_t hdr;
return parse(p, pkt_stats, hdr, adapt);
}
pkt_stats_t *stats::parse(const uint8_t *p, pkt_stats_t *pkt_stats, pkt_hdr_t &hdr, adaptation_field_t &adapt)
{
if (pkt_stats) {
memset(pkt_stats, 0, sizeof(pkt_stats_t));
const uint8_t *q = p;
memset(&adapt, 0, sizeof(adapt));
memset(&hdr, 0, sizeof(hdr));
hdr.sync_byte = q[0];
hdr.tei = (q[1] & 0x80) >> 7;
hdr.payload_unit_start = (q[1] & 0x40) >> 6;
hdr.transport_priority = (q[1] & 0x20) >> 5;
hdr.pid = ((q[1] & 0x1f) << 8) | q[2];
hdr.scrambling = (q[3] & 0xc0) >> 6;
hdr.adaptation_flags = (q[3] & 0x30) >> 4;
hdr.continuity_ctr = (q[3] & 0x0f);
if (hdr.adaptation_flags & 0x02) {
q += 4;
adapt.field_length = q[0];
adapt.discontinuity = (q[1] & 0x80) >> 7;
adapt.random_access = (q[1] & 0x40) >> 6; /* set to 1 if the PES pkt in this TS pkt starts an a/v sequence */
adapt.es_priority = (q[1] & 0x20) >> 5;
adapt.pcr = (q[1] & 0x10) >> 4;
adapt.opcr = (q[1] & 0x08) >> 3;
adapt.splicing_point = (q[1] & 0x04) >> 2;
adapt.tp_priv_data = (q[1] & 0x02) >> 1;
adapt.field_ext = (q[1] & 0x01) >> 0;
if (adapt.pcr) {
memcpy(adapt.PCR, &q[2], 6);
q += 6;
}
if (adapt.opcr) {
memcpy(adapt.OPCR, &q[2], 6);
q += 6;
}
if (adapt.splicing_point) {
adapt.splicing_countdown = q[2];
q ++;
}
}
pkt_stats->sync_loss = (hdr.sync_byte != 0x47) ? true : false;
if (!pkt_stats->sync_loss) {
pkt_stats->tei = (hdr.tei) ? true : false;
pkt_stats->pid = hdr.pid;
} else
pkt_stats->pid = (uint16_t) - 1;
}
return pkt_stats;
}
void stats::clear_stats()
{
statistics.clear();
discontinuities.clear();
last_pcr_base.clear();
tei_count = 0;
}
void stats::push_stats(pkt_stats_t *pkt_stats)
{
if (pkt_stats->tei) {
tei_count++;
push_pid((uint16_t) - 1);
} else
push_pid(pkt_stats->pid);
}
void stats::push(const uint8_t *p, pkt_stats_t *pkt_stats)
{
adaptation_field_t adapt;
pkt_hdr_t hdr;
if (!pkt_stats) {
__push(p);
return;
}
memset(pkt_stats, 0, sizeof(pkt_stats_t));
parse(p, pkt_stats, hdr, adapt);
if (hdr.adaptation_flags & 0x01) {// payload present
if (continuity.count(hdr.pid)) {
uint8_t next = (continuity[hdr.pid] + 1) & 0x0f;
if ((next != (hdr.continuity_ctr & 0x0f)) && (hdr.continuity_ctr + continuity[hdr.pid] > 0)) {
if (!(hdr.adaptation_flags & 0x02) && (adapt.discontinuity)) {
push_discontinuity(hdr.pid);
#if DBG
dPrintf("CONTINUITY ERROR pid: %04x cur: 0x%x prev 0x%x", hdr.pid, hdr.continuity_ctr, continuity[hdr.pid]);
#endif
}
}
}
continuity[hdr.pid] = hdr.continuity_ctr;
}
if (hdr.adaptation_flags & 0x02) {
if (adapt.pcr) {
uint64_t pcr_base;
unsigned int pcr_ext;
parse_pcr(adapt.PCR, &pcr_base, &pcr_ext);
if (dbg & DBG_STATS) __log_printf(stderr, "PID: 0x%04x, PCR base: %" PRIu64 ", ext: %d\n", hdr.pid, pcr_base, pcr_ext);
#if DBG
stats_map::const_iterator iter = last_pcr_base.find(hdr.pid);
if ((iter != last_pcr_base.end()) && (pcr_base < iter->second))
__log_printf(stderr, "%s: PID: 0x%04x, %" PRIu64 " < %" PRIu64 " !!!\n",
__func__, hdr.pid, pcr_base, iter->second);
#endif
last_pcr_base[hdr.pid] = pcr_base;
}
if (adapt.opcr) {
uint64_t pcr_base;
unsigned int pcr_ext;
parse_pcr(adapt.OPCR, &pcr_base, &pcr_ext);
if (dbg & DBG_STATS) __log_printf(stderr, "PID: 0x%04x, PCR base: %" PRIu64 ", ext: %d\n", hdr.pid, pcr_base, pcr_ext);
}
if (adapt.splicing_point) {
dPrintf("PID: 0x%04x, splicing countdown: %d", hdr.pid, adapt.splicing_countdown);
}
}
push_stats(pkt_stats);
}
<commit_msg>stats: fix stats_scale_unit() when (x % 1000000) < 1000<commit_after>/*****************************************************************************
* Copyright (C) 2011-2016 Michael Ira Krufky
*
* Author: Michael Ira Krufky <mkrufky@linuxtv.org>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#include <inttypes.h>
#include "string.h"
#include "stats.h"
#include "log.h"
#define CLASS_MODULE "stats"
#define DBG 0
#define dPrintf(fmt, arg...) __dPrintf(DBG_STATS, "(%s) " fmt, parent, ##arg)
stats::stats(const char *caller)
: tei_count(0)
, __timenow(0)
, parent(caller)
, streamtime_cb(NULL)
, streamtime_priv(NULL)
, statistics_cb(NULL)
, statistics_priv(NULL)
, statistics_iface(NULL)
{
dPrintf("(%s)", parent);
}
stats::~stats()
{
dPrintf("(%s)", parent);
show(false);
}
#if 0
stats::stats(const stats&)
{
dPrintf("(%s, copy)", parent);
}
stats& stats::operator= (const stats& cSource)
{
dPrintf("(%s, operator=)", parent);
if (this == &cSource)
return *this;
return *this;
}
#endif
static void parse_pcr(uint8_t *pcr, uint64_t *pcr_base, unsigned int *pcr_ext)
{
*pcr_base = ((uint64_t)pcr[0] * 0x2000000) +
((uint64_t)pcr[1] * 0x20000) +
((uint64_t)pcr[2] * 0x200) +
((uint64_t)pcr[3] * 0x02) +
((uint64_t)(pcr[4] & 0x80) >> 7);
*pcr_ext = ((pcr[4] & 0x01) * 0x100) + pcr[5];
return;
}
static time_t walltime(void *p) { (void)p; return time(NULL); }
char *stats_scale_unit(char *b, size_t n, uint64_t x)
{
memset(b, 0, n);
if (x >= 1000000) {
#if 1
if ((x % 1000000) < 1000)
snprintf(b, n, "%3" PRIu64 ".%03" PRIu64 " m", x / 1000000, x % 1000000);
else
#endif
snprintf(b, n, "%3" PRIu64 ".%03" PRIu64 " m", x / 1000000, x % 1000);
} else if (x >= 1000) {
#if 0
if ((x % 1000) < 100)
snprintf(b, n, "%3" PRIu64 ".%03" PRIu64 " k", x / 1000, x % 1000);
else
#endif
snprintf(b, n, "%3" PRIu64 ".%03" PRIu64 " k", x / 1000, x % 1000);
} else
snprintf(b, n, " %3" PRIu64 " ", x);
return b;
}
void stats::show(bool per_sec)
{
if (statistics_cb) {
statistics_cb(statistics_priv, statistics, discontinuities, tei_count, per_sec);
}
if (statistics_iface) {
statistics_iface->stats(statistics, discontinuities, tei_count, per_sec);
}
if (statistics_cb || statistics_iface) {
return;
}
for (stats_map::const_iterator iter = statistics.begin(); iter != statistics.end(); ++iter) {
char a[16];
char b[16];
if (dbg & DBG_STATS) __log_printf(stderr, "pid %04x %5" PRIu64 " p%s %sb%s %sbit\n",
iter->first, iter->second / 188, (per_sec) ? "/s" : "",
stats_scale_unit(a, sizeof(a), iter->second), (per_sec) ? "/s" : "",
stats_scale_unit(b, sizeof(b), iter->second * 8));
}
for (stats_map::const_iterator iter = discontinuities.begin(); iter != discontinuities.end(); ++iter)
if (dbg & DBG_STATS) __log_printf(stderr, "pid %04x\t%" PRIu64 " continuity errors (%" PRIu64 "%%)\n", iter->first, iter->second, ((!iter->second) || (!statistics[iter->first])) ? 0 : (!statistics.count(iter->first)) ? 0 : (100 * iter->second / (statistics[iter->first] / 188)));
if ((tei_count) && (dbg & DBG_STATS)) __log_printf(stderr, "tei count: %" PRIu64 " (%" PRIu64 "%%)\n", tei_count, (!statistics[0x2000]) ? 0 : (18800 * tei_count / statistics[0x2000]));
}
void stats::push_pid(int c, const uint16_t pid)
{
streamtime_callback cb = (streamtime_cb) ? streamtime_cb : &walltime;
time_t timenow = cb(streamtime_priv);
if (timenow > __timenow) {
show();
clear_stats();
__timenow = timenow;
}
__push_pid(c, pid);
}
pkt_stats_t *stats::parse(const uint8_t *p, pkt_stats_t *pkt_stats)
{
adaptation_field_t adapt;
pkt_hdr_t hdr;
return parse(p, pkt_stats, hdr, adapt);
}
pkt_stats_t *stats::parse(const uint8_t *p, pkt_stats_t *pkt_stats, pkt_hdr_t &hdr, adaptation_field_t &adapt)
{
if (pkt_stats) {
memset(pkt_stats, 0, sizeof(pkt_stats_t));
const uint8_t *q = p;
memset(&adapt, 0, sizeof(adapt));
memset(&hdr, 0, sizeof(hdr));
hdr.sync_byte = q[0];
hdr.tei = (q[1] & 0x80) >> 7;
hdr.payload_unit_start = (q[1] & 0x40) >> 6;
hdr.transport_priority = (q[1] & 0x20) >> 5;
hdr.pid = ((q[1] & 0x1f) << 8) | q[2];
hdr.scrambling = (q[3] & 0xc0) >> 6;
hdr.adaptation_flags = (q[3] & 0x30) >> 4;
hdr.continuity_ctr = (q[3] & 0x0f);
if (hdr.adaptation_flags & 0x02) {
q += 4;
adapt.field_length = q[0];
adapt.discontinuity = (q[1] & 0x80) >> 7;
adapt.random_access = (q[1] & 0x40) >> 6; /* set to 1 if the PES pkt in this TS pkt starts an a/v sequence */
adapt.es_priority = (q[1] & 0x20) >> 5;
adapt.pcr = (q[1] & 0x10) >> 4;
adapt.opcr = (q[1] & 0x08) >> 3;
adapt.splicing_point = (q[1] & 0x04) >> 2;
adapt.tp_priv_data = (q[1] & 0x02) >> 1;
adapt.field_ext = (q[1] & 0x01) >> 0;
if (adapt.pcr) {
memcpy(adapt.PCR, &q[2], 6);
q += 6;
}
if (adapt.opcr) {
memcpy(adapt.OPCR, &q[2], 6);
q += 6;
}
if (adapt.splicing_point) {
adapt.splicing_countdown = q[2];
q ++;
}
}
pkt_stats->sync_loss = (hdr.sync_byte != 0x47) ? true : false;
if (!pkt_stats->sync_loss) {
pkt_stats->tei = (hdr.tei) ? true : false;
pkt_stats->pid = hdr.pid;
} else
pkt_stats->pid = (uint16_t) - 1;
}
return pkt_stats;
}
void stats::clear_stats()
{
statistics.clear();
discontinuities.clear();
last_pcr_base.clear();
tei_count = 0;
}
void stats::push_stats(pkt_stats_t *pkt_stats)
{
if (pkt_stats->tei) {
tei_count++;
push_pid((uint16_t) - 1);
} else
push_pid(pkt_stats->pid);
}
void stats::push(const uint8_t *p, pkt_stats_t *pkt_stats)
{
adaptation_field_t adapt;
pkt_hdr_t hdr;
if (!pkt_stats) {
__push(p);
return;
}
memset(pkt_stats, 0, sizeof(pkt_stats_t));
parse(p, pkt_stats, hdr, adapt);
if (hdr.adaptation_flags & 0x01) {// payload present
if (continuity.count(hdr.pid)) {
uint8_t next = (continuity[hdr.pid] + 1) & 0x0f;
if ((next != (hdr.continuity_ctr & 0x0f)) && (hdr.continuity_ctr + continuity[hdr.pid] > 0)) {
if (!(hdr.adaptation_flags & 0x02) && (adapt.discontinuity)) {
push_discontinuity(hdr.pid);
#if DBG
dPrintf("CONTINUITY ERROR pid: %04x cur: 0x%x prev 0x%x", hdr.pid, hdr.continuity_ctr, continuity[hdr.pid]);
#endif
}
}
}
continuity[hdr.pid] = hdr.continuity_ctr;
}
if (hdr.adaptation_flags & 0x02) {
if (adapt.pcr) {
uint64_t pcr_base;
unsigned int pcr_ext;
parse_pcr(adapt.PCR, &pcr_base, &pcr_ext);
if (dbg & DBG_STATS) __log_printf(stderr, "PID: 0x%04x, PCR base: %" PRIu64 ", ext: %d\n", hdr.pid, pcr_base, pcr_ext);
#if DBG
stats_map::const_iterator iter = last_pcr_base.find(hdr.pid);
if ((iter != last_pcr_base.end()) && (pcr_base < iter->second))
__log_printf(stderr, "%s: PID: 0x%04x, %" PRIu64 " < %" PRIu64 " !!!\n",
__func__, hdr.pid, pcr_base, iter->second);
#endif
last_pcr_base[hdr.pid] = pcr_base;
}
if (adapt.opcr) {
uint64_t pcr_base;
unsigned int pcr_ext;
parse_pcr(adapt.OPCR, &pcr_base, &pcr_ext);
if (dbg & DBG_STATS) __log_printf(stderr, "PID: 0x%04x, PCR base: %" PRIu64 ", ext: %d\n", hdr.pid, pcr_base, pcr_ext);
}
if (adapt.splicing_point) {
dPrintf("PID: 0x%04x, splicing countdown: %d", hdr.pid, adapt.splicing_countdown);
}
}
push_stats(pkt_stats);
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2011 Josh A. Beam
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 CONTACT, 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 <iostream>
#include <fcntl.h>
#include <sys/stat.h>
#include <xviweb/String.h>
#include "FileResponder.h"
using namespace std;
FileResponder::FileResponder()
{
m_rootDirectory = ".";
// add some standard MIME types
addMimeType("text/plain", "txt");
addMimeType("text/html", "html");
addMimeType("text/css", "css");
addMimeType("text/javascript", "js");
addMimeType("image/png", "png");
addMimeType("image/jpg", "jpeg");
addMimeType("image/jpg", "jpg");
addMimeType("image/gif", "gif");
}
FileResponder::~FileResponder()
{
}
void
FileResponder::addOption(const string &option, const string &value)
{
if(option == "rootDirectory") {
m_rootDirectory = value;
} else if(option == "mimeType") {
vector <string> values = String::split(value, ";");
if(values.size() == 2) {
m_mimeTypes.push_back(values[0]);
m_mimeFileExtensions.push_back(string(".") + values[1]);
}
}
}
void
FileResponder::addMimeType(const string &mimeType, const string &fileExtension)
{
addOption("mimeType", mimeType + ";" + fileExtension);
}
string
FileResponder::getMimeTypeForFile(const string &path) const
{
// find the type associated with the file extension
for(unsigned int i = 0; i < m_mimeTypes.size(); ++i) {
if(String::endsWith(path, m_mimeFileExtensions[i], true))
return m_mimeTypes[i];
}
return string("");
}
static string
mapPath(const string &path)
{
// not confident that the commented out code below
// works right yet, so just return an empty string
// if the requested path contains a ..
if(path.find("..") != string::npos)
return string("");
string newPath = path;
// replace back slashes with forward slashes
size_t tmp;
while((tmp = newPath.find('\\')) != string::npos)
newPath[tmp] = '/';
// replace double slashes with single slashes
while((tmp = newPath.find("//")) != string::npos)
newPath.erase(tmp, 1);
#if 0
// make sure .. isn't used to go above the root directory
int depth = 0;
for(int i = 0; i < (int)newPath.length() - 3; ++i) {
if(newPath[i] == '/') {
if(newPath[i+1] == '.' && newPath[i+2] == '.' && newPath[i+3] == '/') {
if(--depth < 0)
return string("");
i += 3;
} else {
++depth;
}
}
}
#endif
return newPath;
}
bool
FileResponder::matchesRequest(const HttpRequest * /*request*/) const
{
return true;
}
ResponderContext *
FileResponder::respond(const HttpRequest *request, HttpResponse *response)
{
// if the path returned by mapPath has a length
// of zero, the path requested is invalid
string path = mapPath(request->getPath());
if(path.length() == 0) {
response->sendErrorResponse(403, "Forbidden", "The provided file path is invalid.");
return NULL;
}
path = request->getVHostRoot() + path;
// open the file and get its status
struct stat status;
int fd = open(path.c_str(), O_RDONLY);
if(fd == -1 || fstat(fd, &status) == -1) {
if(fd != -1)
close(fd);
response->sendErrorResponse(404, "File Not Found", "The file that you requested does not exist.");
return NULL;
}
// don't show directory listings
if(S_ISDIR(status.st_mode)) {
close(fd);
response->sendErrorResponse(403, "Forbidden", "You do not have access to directory listings.");
return NULL;
}
// get the MIME type for the file; if there's no
// MIME type associated with the file extension,
// just refuse to serve the file for security reasons
string contentType = getMimeTypeForFile(path);
if(contentType.length() == 0) {
close(fd);
response->sendErrorResponse(403, "Forbidden", "You do not have access to files of this type.");
return NULL;
}
response->setStatus(200, "OK");
response->setContentType(contentType);
response->setContentLength((int)status.st_size);
if(request->getVerb() != "HEAD") {
// read the file and send it to the client
char buf[512];
ssize_t length;
while((length = read(fd, buf, sizeof(buf))) > 0)
response->sendString(buf, length);
}
response->endResponse();
close(fd);
return NULL;
}
XVIWEB_RESPONDER(FileResponder);
<commit_msg>Added support for index.html as a default document.<commit_after>/*
* Copyright (C) 2011 Josh A. Beam
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 CONTACT, 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 <iostream>
#include <fcntl.h>
#include <sys/stat.h>
#include <xviweb/String.h>
#include "FileResponder.h"
using namespace std;
FileResponder::FileResponder()
{
m_rootDirectory = ".";
// add some standard MIME types
addMimeType("text/plain", "txt");
addMimeType("text/html", "html");
addMimeType("text/css", "css");
addMimeType("text/javascript", "js");
addMimeType("image/png", "png");
addMimeType("image/jpg", "jpeg");
addMimeType("image/jpg", "jpg");
addMimeType("image/gif", "gif");
}
FileResponder::~FileResponder()
{
}
void
FileResponder::addOption(const string &option, const string &value)
{
if(option == "rootDirectory") {
m_rootDirectory = value;
} else if(option == "mimeType") {
vector <string> values = String::split(value, ";");
if(values.size() == 2) {
m_mimeTypes.push_back(values[0]);
m_mimeFileExtensions.push_back(string(".") + values[1]);
}
}
}
void
FileResponder::addMimeType(const string &mimeType, const string &fileExtension)
{
addOption("mimeType", mimeType + ";" + fileExtension);
}
string
FileResponder::getMimeTypeForFile(const string &path) const
{
// find the type associated with the file extension
for(unsigned int i = 0; i < m_mimeTypes.size(); ++i) {
if(String::endsWith(path, m_mimeFileExtensions[i], true))
return m_mimeTypes[i];
}
return string("");
}
static string
mapPath(const string &path)
{
// not confident that the commented out code below
// works right yet, so just return an empty string
// if the requested path contains a ..
if(path.find("..") != string::npos)
return string("");
string newPath = path;
// replace back slashes with forward slashes
size_t tmp;
while((tmp = newPath.find('\\')) != string::npos)
newPath[tmp] = '/';
// replace double slashes with single slashes
while((tmp = newPath.find("//")) != string::npos)
newPath.erase(tmp, 1);
#if 0
// make sure .. isn't used to go above the root directory
int depth = 0;
for(int i = 0; i < (int)newPath.length() - 3; ++i) {
if(newPath[i] == '/') {
if(newPath[i+1] == '.' && newPath[i+2] == '.' && newPath[i+3] == '/') {
if(--depth < 0)
return string("");
i += 3;
} else {
++depth;
}
}
}
#endif
return newPath;
}
bool
FileResponder::matchesRequest(const HttpRequest * /*request*/) const
{
return true;
}
ResponderContext *
FileResponder::respond(const HttpRequest *request, HttpResponse *response)
{
// if the path returned by mapPath has a length
// of zero, the path requested is invalid
string path = mapPath(request->getPath());
if(path.length() == 0) {
response->sendErrorResponse(403, "Forbidden", "The provided file path is invalid.");
return NULL;
}
path = request->getVHostRoot() + path;
// open the file and get its status
struct stat status;
int fd = open(path.c_str(), O_RDONLY);
if(fd == -1 || fstat(fd, &status) == -1) {
if(fd != -1)
close(fd);
response->sendErrorResponse(404, "File Not Found", "The file that you requested does not exist.");
return NULL;
}
// don't show directory listings
if(S_ISDIR(status.st_mode)) {
close(fd);
// see if an index.html exists in the directory;
// if not, show an error message
path += "/index.html";
fd = open(path.c_str(), O_RDONLY);
if(fd == -1 || fstat(fd, &status) == -1 || S_ISDIR(status.st_mode)) {
if(fd != -1)
close(fd);
response->sendErrorResponse(403, "Forbidden", "You do not have access to directory listings.");
return NULL;
}
}
// get the MIME type for the file; if there's no
// MIME type associated with the file extension,
// just refuse to serve the file for security reasons
string contentType = getMimeTypeForFile(path);
if(contentType.length() == 0) {
close(fd);
response->sendErrorResponse(403, "Forbidden", "You do not have access to files of this type.");
return NULL;
}
response->setStatus(200, "OK");
response->setContentType(contentType);
response->setContentLength((int)status.st_size);
if(request->getVerb() != "HEAD") {
// read the file and send it to the client
char buf[512];
ssize_t length;
while((length = read(fd, buf, sizeof(buf))) > 0)
response->sendString(buf, length);
}
response->endResponse();
close(fd);
return NULL;
}
XVIWEB_RESPONDER(FileResponder);
<|endoftext|>
|
<commit_before>//
// File: EventBus.hpp
// Class: EventBus
// Author: Jesper Persson and Sebastian Odbjer
// All code is our own except where credited to others.
//
// Copyright (c) 2012 by Catch22. All Rights Reserved.
// Date: 02/10-2012
//
// License: The following code is licensed under the Catch22-License
//
<commit_msg>Implemented basic structure of chainsaw<commit_after>//
// File: EventBus.hpp
// Class: EventBus
// Author: Jesper Persson and Sebastian Odbjer
// All code is our own except where credited to others.
//
// Copyright (c) 2012 by Catch22. All Rights Reserved.
// Date: 02/10-2012
//
// License: The following code is licensed under the Catch22-License
//
#include "Chainsaw.hpp"
#include "../../EventHandling/EventBus.hpp"
#include "../../EventHandling/EEvent.hpp"
Chainsaw::Chainsaw (b2Vec2 size, b2Vec2 position,b2Vec2 target, bool stationary, bool rotatable, PBodyType tag) :
PBody(size, position, stationary, rotatable, tag)
{
m_target = target;
m_targetReached = false;
EventBus::getSharedInstance()->publishEvent(PBODY_CREATED_PHYSICS, this);
}
bool Chainsaw::targetReached()
{
return m_targetReached;
}
void Chainsaw::setTarget(b2Vec2 target)
{
m_target = target;
}
<|endoftext|>
|
<commit_before>//==============================================================================
// CellMLTools plugin
//==============================================================================
#include "cellmlfilemanager.h"
#include "cellmlsupportplugin.h"
#include "cellmltoolsplugin.h"
#include "coreutils.h"
//==============================================================================
#include <QAction>
#include <QFileInfo>
#include <QMainWindow>
#include <QMenu>
#include <QMessageBox>
//==============================================================================
namespace OpenCOR {
namespace CellMLTools {
//==============================================================================
PLUGININFO_FUNC CellMLToolsPluginInfo()
{
Descriptions descriptions;
descriptions.insert("en", QString::fromUtf8("a plugin to access various <a href=\"http://www.cellml.org/\">CellML</a>-related tools."));
descriptions.insert("fr", QString::fromUtf8("une extension pour accéder à divers outils en rapport avec <a href=\"http://www.cellml.org/\">CellML</a>."));
return new PluginInfo(PluginInfo::InterfaceVersion001,
PluginInfo::Miscellaneous,
true,
true,
QStringList() << "CellMLSupport",
descriptions);
}
//==============================================================================
void CellMLToolsPlugin::initialize()
{
// Create our Tools | Export To menu
mCellmlFileExportToMenu = newMenu(mMainWindow, "CellmlFileExportTo");
// Create our different Tools | Export To actions, and add them to our
// Tools | Export To menu
mExportToCellml10Action = newAction(mMainWindow);
mExportToCellml11Action = newAction(mMainWindow);
mCellmlFileExportToMenu->addAction(mExportToCellml10Action);
mCellmlFileExportToMenu->addAction(mExportToCellml11Action);
// Some connections to handle our different Tools | Export To actions
connect(mExportToCellml10Action, SIGNAL(triggered()),
this, SLOT(exportToCellml10()));
connect(mExportToCellml11Action, SIGNAL(triggered()),
this, SLOT(exportToCellml11()));
// Set our settings
mGuiSettings->addMenuAction(GuiMenuActionSettings::Tools, mCellmlFileExportToMenu->menuAction());
mGuiSettings->addMenuAction(GuiMenuActionSettings::Tools);
}
//==============================================================================
void CellMLToolsPlugin::initializationsDone(const Plugins &pLoadedPlugins)
{
// Retrieve the file types supported by the CellMLSupport plugin
mCellmlFileTypes = FileTypes();
foreach (Plugin *loadedPlugin, pLoadedPlugins) {
FileInterface *fileInterface = qobject_cast<FileInterface *>(loadedPlugin->instance());
if (!loadedPlugin->name().compare("CellMLSupport") && fileInterface) {
// This is the CellMLSupport plugin and, as expected, it implements
// the file interface, so retrieve the file types it supports
mCellmlFileTypes = fileInterface->fileTypes();
break;
}
}
}
//==============================================================================
void CellMLToolsPlugin::runHelpCommand()
{
std::cout << "Commands supported by CellMLTools:" << std::endl;
std::cout << " * Display the commands supported by CellMLTools:" << std::endl;
std::cout << " help" << std::endl;
std::cout << " * Export <in_file> to <out_file> using <format> as the destination format:" << std::endl;
std::cout << " export <in_file> <out_file> <format>" << std::endl;
std::cout << " <format> can take one of the following values:" << std::endl;
std::cout << " cellml_1_0: to export a CellML 1.1 file to CellML 1.0" << std::endl;
}
//==============================================================================
void CellMLToolsPlugin::runExportCommand(const QStringList &pArguments,
int *pRes)
{
// Export an existing file to another file using a given format as the
// destination format
// Make sure that we have three arguments and that the given format is
// valid
bool validArguments = true;
if (pArguments.count() != 3) {
validArguments = false;
} else {
QString format = pArguments.at(2);
if (format.compare("cellml_1_0"))
validArguments = false;
}
// Confirm that we have valid arguments
if (!validArguments) {
runHelpCommand();
*pRes = -1;
return;
}
// Make sure that the input file exists and that it is a valid non CellML
// 1.0 file
QString errorMessage = QString();
QString inFileName = pArguments.at(0);
CellMLSupport::CellmlFile *inCellmlFile = new CellMLSupport::CellmlFile(inFileName);
if (!QFileInfo(inFileName).exists())
errorMessage = "Sorry, but the input file could not be found.";
else if (!CellMLSupport::isCellmlFile(inFileName))
errorMessage = "Sorry, but the input file is not a CellML file.";
else if (!inCellmlFile->load())
errorMessage = "Sorry, but a problem occurred while loading the input file.";
else if (!QString::fromStdWString(inCellmlFile->model()->cellmlVersion()).compare(CellMLSupport::Cellml_1_0))
errorMessage = "Sorry, but the input file is already a CellML 1.0 file.";
// Our input file is a valid non CellML 1.0 file, so we can export it to
// CellML 1.0
if ( errorMessage.isEmpty()
&& !inCellmlFile->exportTo(pArguments.at(1), CellMLSupport::CellmlFile::Cellml_1_0))
errorMessage = "Sorry, but a problem occurred while exporting the input file.";
delete inCellmlFile;
// Check whether something wrong happened at some point
if (!errorMessage.isEmpty()) {
std::cout << qPrintable(errorMessage) << std::endl;
*pRes = -1;
}
}
//==============================================================================
void CellMLToolsPlugin::runCliCommand(const QString &pCommand,
const QStringList &pArguments, int *pRes)
{
// Run the given CLI command
*pRes = 0;
if (!pCommand.compare("help")) {
// Display the commands we support
runHelpCommand();
} else if (!pCommand.compare("export")) {
// Export a file from one format to another
runExportCommand(pArguments, pRes);
} else {
// Not a CLI command that we can run, so...
runHelpCommand();
*pRes = -1;
}
}
//==============================================================================
void CellMLToolsPlugin::updateGui(Plugin *pViewPlugin, const QString &pFileName)
{
// Enable/disable and show/hide our tools in case we are dealing with a
// CellML-based view plugin
bool toolsVisible = pViewPlugin?
pViewPlugin->info()->fullDependencies().contains("CellMLSupport"):
false;
CellMLSupport::CellmlFile *cellmlFile = CellMLSupport::CellmlFileManager::instance()->cellmlFile(pFileName);
mCellmlFileExportToMenu->menuAction()->setEnabled(toolsVisible);
mCellmlFileExportToMenu->menuAction()->setVisible(toolsVisible);
mExportToCellml10Action->setEnabled( toolsVisible && cellmlFile
&& QString::fromStdWString(cellmlFile->model()->cellmlVersion()).compare(CellMLSupport::Cellml_1_0));
mExportToCellml10Action->setVisible(toolsVisible);
/*---GRY---
mExportToCellml11Action->setEnabled( toolsVisible && cellmlFile
&& QString::fromStdWString(cellmlFile->model()->cellmlVersion()).compare(CellMLSupport::Cellml_1_1));
mExportToCellml11Action->setVisible(toolsVisible);
*/
//---GRY--- BEGIN
// THIS IS UNTIL EXPORTING TO CellML 1.1 IS FULLY SUPPORTED...
mExportToCellml11Action->setEnabled(false);
mExportToCellml11Action->setVisible(false);
//---GRY--- END
// Keep track of the file name
mFileName = pFileName;
}
//==============================================================================
void CellMLToolsPlugin::retranslateUi()
{
// Retranslate our different Tools actions
retranslateMenu(mCellmlFileExportToMenu, tr("CellML File Export To"));
retranslateAction(mExportToCellml10Action, tr("CellML 1.0..."), tr("Export the CellML file to CellML 1.0"));
retranslateAction(mExportToCellml11Action, tr("CellML 1.1..."), tr("Export the CellML file to CellML 1.1"));
}
//==============================================================================
void CellMLToolsPlugin::exportTo(const CellMLSupport::CellmlFile::Format &pFormat)
{
// Ask for the name of the file which will contain the export
QString format;
QString fileTypes;
switch (pFormat) {
case CellMLSupport::CellmlFile::Cellml_1_1:
default: // CellMLSupport::CellmlFile::Cellml_1_0
if (pFormat == CellMLSupport::CellmlFile::Cellml_1_0)
format = "CellML 1.0";
else
format = "CellML 1.1";
foreach (const FileType &fileType, mCellmlFileTypes) {
if (!fileTypes.isEmpty())
fileTypes += ";;";
fileTypes += fileType.description()+" (*."+fileType.fileExtension()+")";
}
}
QString fileName = Core::getSaveFileName(tr("CellML file export to %1").arg(format), mFileName, fileTypes);
// Make sure that we have a file name or leave, if not
if (fileName.isEmpty())
return;
// Now that we have a file name, we can do the eport itself
CellMLSupport::CellmlFile *cellmlFile = CellMLSupport::CellmlFileManager::instance()->cellmlFile(mFileName);
if (!cellmlFile->exportTo(fileName, pFormat)) {
CellMLSupport::CellmlFileIssues issues = cellmlFile->issues();
QString errorMessage = QString();
if (issues.count())
errorMessage = " ("+issues.first().message()+")";
// Note: if there are 'issues', then there can be only one of them
// following a CellML export...
QMessageBox::warning(mMainWindow, tr("CellML file export to %1").arg(format),
tr("Sorry, but <strong>%1</strong> could not be exported to <strong>%2</strong>%3.").arg(fileName, format, errorMessage));
}
}
//==============================================================================
void CellMLToolsPlugin::exportToCellml10()
{
// Export the current file to CellML 1.0
exportTo(CellMLSupport::CellmlFile::Cellml_1_0);
}
//==============================================================================
void CellMLToolsPlugin::exportToCellml11()
{
// Export the current file to CellML 1.1
exportTo(CellMLSupport::CellmlFile::Cellml_1_1);
}
//==============================================================================
} // namespace CellMLSupport
} // namespace OpenCOR
//==============================================================================
// End of file
//==============================================================================
<commit_msg>CellMLTools plugin: enable/disable our CellML File Export menu based depending on whether some exports are enabled.<commit_after>//==============================================================================
// CellMLTools plugin
//==============================================================================
#include "cellmlfilemanager.h"
#include "cellmlsupportplugin.h"
#include "cellmltoolsplugin.h"
#include "coreutils.h"
//==============================================================================
#include <QAction>
#include <QFileInfo>
#include <QMainWindow>
#include <QMenu>
#include <QMessageBox>
//==============================================================================
namespace OpenCOR {
namespace CellMLTools {
//==============================================================================
PLUGININFO_FUNC CellMLToolsPluginInfo()
{
Descriptions descriptions;
descriptions.insert("en", QString::fromUtf8("a plugin to access various <a href=\"http://www.cellml.org/\">CellML</a>-related tools."));
descriptions.insert("fr", QString::fromUtf8("une extension pour accéder à divers outils en rapport avec <a href=\"http://www.cellml.org/\">CellML</a>."));
return new PluginInfo(PluginInfo::InterfaceVersion001,
PluginInfo::Miscellaneous,
true,
true,
QStringList() << "CellMLSupport",
descriptions);
}
//==============================================================================
void CellMLToolsPlugin::initialize()
{
// Create our Tools | Export To menu
mCellmlFileExportToMenu = newMenu(mMainWindow, "CellmlFileExportTo");
// Create our different Tools | Export To actions, and add them to our
// Tools | Export To menu
mExportToCellml10Action = newAction(mMainWindow);
mExportToCellml11Action = newAction(mMainWindow);
mCellmlFileExportToMenu->addAction(mExportToCellml10Action);
mCellmlFileExportToMenu->addAction(mExportToCellml11Action);
// Some connections to handle our different Tools | Export To actions
connect(mExportToCellml10Action, SIGNAL(triggered()),
this, SLOT(exportToCellml10()));
connect(mExportToCellml11Action, SIGNAL(triggered()),
this, SLOT(exportToCellml11()));
// Set our settings
mGuiSettings->addMenuAction(GuiMenuActionSettings::Tools, mCellmlFileExportToMenu->menuAction());
mGuiSettings->addMenuAction(GuiMenuActionSettings::Tools);
}
//==============================================================================
void CellMLToolsPlugin::initializationsDone(const Plugins &pLoadedPlugins)
{
// Retrieve the file types supported by the CellMLSupport plugin
mCellmlFileTypes = FileTypes();
foreach (Plugin *loadedPlugin, pLoadedPlugins) {
FileInterface *fileInterface = qobject_cast<FileInterface *>(loadedPlugin->instance());
if (!loadedPlugin->name().compare("CellMLSupport") && fileInterface) {
// This is the CellMLSupport plugin and, as expected, it implements
// the file interface, so retrieve the file types it supports
mCellmlFileTypes = fileInterface->fileTypes();
break;
}
}
}
//==============================================================================
void CellMLToolsPlugin::runHelpCommand()
{
std::cout << "Commands supported by CellMLTools:" << std::endl;
std::cout << " * Display the commands supported by CellMLTools:" << std::endl;
std::cout << " help" << std::endl;
std::cout << " * Export <in_file> to <out_file> using <format> as the destination format:" << std::endl;
std::cout << " export <in_file> <out_file> <format>" << std::endl;
std::cout << " <format> can take one of the following values:" << std::endl;
std::cout << " cellml_1_0: to export a CellML 1.1 file to CellML 1.0" << std::endl;
}
//==============================================================================
void CellMLToolsPlugin::runExportCommand(const QStringList &pArguments,
int *pRes)
{
// Export an existing file to another file using a given format as the
// destination format
// Make sure that we have three arguments and that the given format is
// valid
bool validArguments = true;
if (pArguments.count() != 3) {
validArguments = false;
} else {
QString format = pArguments.at(2);
if (format.compare("cellml_1_0"))
validArguments = false;
}
// Confirm that we have valid arguments
if (!validArguments) {
runHelpCommand();
*pRes = -1;
return;
}
// Make sure that the input file exists and that it is a valid non CellML
// 1.0 file
QString errorMessage = QString();
QString inFileName = pArguments.at(0);
CellMLSupport::CellmlFile *inCellmlFile = new CellMLSupport::CellmlFile(inFileName);
if (!QFileInfo(inFileName).exists())
errorMessage = "Sorry, but the input file could not be found.";
else if (!CellMLSupport::isCellmlFile(inFileName))
errorMessage = "Sorry, but the input file is not a CellML file.";
else if (!inCellmlFile->load())
errorMessage = "Sorry, but a problem occurred while loading the input file.";
else if (!QString::fromStdWString(inCellmlFile->model()->cellmlVersion()).compare(CellMLSupport::Cellml_1_0))
errorMessage = "Sorry, but the input file is already a CellML 1.0 file.";
// Our input file is a valid non CellML 1.0 file, so we can export it to
// CellML 1.0
if ( errorMessage.isEmpty()
&& !inCellmlFile->exportTo(pArguments.at(1), CellMLSupport::CellmlFile::Cellml_1_0))
errorMessage = "Sorry, but a problem occurred while exporting the input file.";
delete inCellmlFile;
// Check whether something wrong happened at some point
if (!errorMessage.isEmpty()) {
std::cout << qPrintable(errorMessage) << std::endl;
*pRes = -1;
}
}
//==============================================================================
void CellMLToolsPlugin::runCliCommand(const QString &pCommand,
const QStringList &pArguments, int *pRes)
{
// Run the given CLI command
*pRes = 0;
if (!pCommand.compare("help")) {
// Display the commands we support
runHelpCommand();
} else if (!pCommand.compare("export")) {
// Export a file from one format to another
runExportCommand(pArguments, pRes);
} else {
// Not a CLI command that we can run, so...
runHelpCommand();
*pRes = -1;
}
}
//==============================================================================
void CellMLToolsPlugin::updateGui(Plugin *pViewPlugin, const QString &pFileName)
{
// Enable/disable and show/hide our tools in case we are dealing with a
// CellML-based view plugin
bool toolsVisible = pViewPlugin?
pViewPlugin->info()->fullDependencies().contains("CellMLSupport"):
false;
CellMLSupport::CellmlFile *cellmlFile = CellMLSupport::CellmlFileManager::instance()->cellmlFile(pFileName);
mExportToCellml10Action->setEnabled( toolsVisible && cellmlFile
&& QString::fromStdWString(cellmlFile->model()->cellmlVersion()).compare(CellMLSupport::Cellml_1_0));
mExportToCellml10Action->setVisible(toolsVisible);
/*---GRY---
mExportToCellml11Action->setEnabled( toolsVisible && cellmlFile
&& QString::fromStdWString(cellmlFile->model()->cellmlVersion()).compare(CellMLSupport::Cellml_1_1));
mExportToCellml11Action->setVisible(toolsVisible);
*/
//---GRY--- BEGIN
// THIS IS UNTIL EXPORTING TO CellML 1.1 IS FULLY SUPPORTED...
mExportToCellml11Action->setEnabled(false);
mExportToCellml11Action->setVisible(false);
//---GRY--- END
bool menuEnabled = true;
foreach (QAction *action, mCellmlFileExportToMenu->actions())
if (!action->isEnabled()) {
menuEnabled = false;
break;
}
mCellmlFileExportToMenu->menuAction()->setEnabled(menuEnabled);
mCellmlFileExportToMenu->menuAction()->setVisible(toolsVisible);
// Keep track of the file name
mFileName = pFileName;
}
//==============================================================================
void CellMLToolsPlugin::retranslateUi()
{
// Retranslate our different Tools actions
retranslateMenu(mCellmlFileExportToMenu, tr("CellML File Export To"));
retranslateAction(mExportToCellml10Action, tr("CellML 1.0..."), tr("Export the CellML file to CellML 1.0"));
retranslateAction(mExportToCellml11Action, tr("CellML 1.1..."), tr("Export the CellML file to CellML 1.1"));
}
//==============================================================================
void CellMLToolsPlugin::exportTo(const CellMLSupport::CellmlFile::Format &pFormat)
{
// Ask for the name of the file which will contain the export
QString format;
QString fileTypes;
switch (pFormat) {
case CellMLSupport::CellmlFile::Cellml_1_1:
default: // CellMLSupport::CellmlFile::Cellml_1_0
if (pFormat == CellMLSupport::CellmlFile::Cellml_1_0)
format = "CellML 1.0";
else
format = "CellML 1.1";
foreach (const FileType &fileType, mCellmlFileTypes) {
if (!fileTypes.isEmpty())
fileTypes += ";;";
fileTypes += fileType.description()+" (*."+fileType.fileExtension()+")";
}
}
QString fileName = Core::getSaveFileName(tr("CellML file export to %1").arg(format), mFileName, fileTypes);
// Make sure that we have a file name or leave, if not
if (fileName.isEmpty())
return;
// Now that we have a file name, we can do the eport itself
CellMLSupport::CellmlFile *cellmlFile = CellMLSupport::CellmlFileManager::instance()->cellmlFile(mFileName);
if (!cellmlFile->exportTo(fileName, pFormat)) {
CellMLSupport::CellmlFileIssues issues = cellmlFile->issues();
QString errorMessage = QString();
if (issues.count())
errorMessage = " ("+issues.first().message()+")";
// Note: if there are 'issues', then there can be only one of them
// following a CellML export...
QMessageBox::warning(mMainWindow, tr("CellML file export to %1").arg(format),
tr("Sorry, but <strong>%1</strong> could not be exported to <strong>%2</strong>%3.").arg(fileName, format, errorMessage));
}
}
//==============================================================================
void CellMLToolsPlugin::exportToCellml10()
{
// Export the current file to CellML 1.0
exportTo(CellMLSupport::CellmlFile::Cellml_1_0);
}
//==============================================================================
void CellMLToolsPlugin::exportToCellml11()
{
// Export the current file to CellML 1.1
exportTo(CellMLSupport::CellmlFile::Cellml_1_1);
}
//==============================================================================
} // namespace CellMLSupport
} // namespace OpenCOR
//==============================================================================
// End of file
//==============================================================================
<|endoftext|>
|
<commit_before>#include "LinearRegression.h"
#include <armadillo>
#include <iostream>
LinearRegression::LinearRegression(arma::mat *x, arma::vec *y, arma::uword m)
: y{y}, m{m}, trained{false} {
//Create Bias Layer and append at the end of x
arma::mat bias = ones<arma::mat>(m,2);
this->x = x->insert(x->n_cols ,bias);
}
LinearRegression::~LinearRegression() {
delete x;
delete y;
delete w;
}
void LinearRegression::AddData(double x[], double y[]) {
// TODO:
delete this->w;
this->trained = false;
}
void LinearRegression::Train() {
arma::mat xtx = (this->x->t() * (*this->x));
// Check if xtx is full-rank matrix
if (rank(xtx) == this->m) {
this->w = new arma::mat(inv(xtx) * this->x->t() * *y);
this->trained = true;
} else {
std::cerr << "you have to regularize your data set" << std::endl;
}
}
double LinearRegression::Predict(arma::vec *x) {
if (!this->trained) {
std::cerr << "This model hasn't been trained" << std::endl;
return 0.0;
}
return ((*this->w) * (*x)).eval()(0, 0);
}
<commit_msg>fixed typo<commit_after>#include "LinearRegression.h"
#include <armadillo>
#include <iostream>
LinearRegression::LinearRegression(arma::mat *x, arma::vec *y, arma::uword m)
: y{y}, m{m}, trained{false} {
//Create Bias Layer and append at the end of x
arma::mat bias = arma::ones<arma::mat>(m,2);
this->x = x->arma::insert_cols(x->n_cols, bias);
}
LinearRegression::~LinearRegression() {
delete x;
delete y;
delete w;
}
void LinearRegression::AddData(double x[], double y[]) {
// TODO:
delete this->w;
this->trained = false;
}
void LinearRegression::Train() {
arma::mat xtx = (this->x->t() * (*this->x));
// Check if xtx is full-rank matrix
if (rank(xtx) == this->m) {
this->w = new arma::mat(inv(xtx) * this->x->t() * *y);
this->trained = true;
} else {
std::cerr << "you have to regularize your data set" << std::endl;
}
}
double LinearRegression::Predict(arma::vec *x) {
if (!this->trained) {
std::cerr << "This model hasn't been trained" << std::endl;
return 0.0;
}
return ((*this->w) * (*x)).eval()(0, 0);
}
<|endoftext|>
|
<commit_before>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "QmitkImageStatisticsCalculationThread.h"
//QT headers
#include <QMessageBox>
#include <QApplication>
QmitkImageStatisticsCalculationThread::QmitkImageStatisticsCalculationThread():QThread(),
m_StatisticsImage(NULL), m_BinaryMask(NULL), m_PlanarFigureMask(NULL), m_TimeStep(0),
m_IgnoreZeros(false), m_CalculationSuccessful(false), m_StatisticChanged(false)
{
}
QmitkImageStatisticsCalculationThread::~QmitkImageStatisticsCalculationThread()
{
}
void QmitkImageStatisticsCalculationThread::Initialize( mitk::Image::Pointer image, mitk::Image::Pointer binaryImage, mitk::PlanarFigure::Pointer planarFig )
{
// reset old values
if( this->m_StatisticsImage.IsNotNull() )
this->m_StatisticsImage = 0;
if( this->m_BinaryMask.IsNotNull() )
this->m_BinaryMask = 0;
if( this->m_PlanarFigureMask.IsNotNull())
this->m_PlanarFigureMask = 0;
// set new values if passed in
if(image.IsNotNull())
this->m_StatisticsImage = image->Clone();
if(binaryImage.IsNotNull())
this->m_BinaryMask = binaryImage->Clone();
if(planarFig.IsNotNull())
this->m_PlanarFigureMask = dynamic_cast<mitk::PlanarFigure*>(planarFig.GetPointer()); // once clone methods for planar figures are implemented, copy the data here!
}
void QmitkImageStatisticsCalculationThread::SetTimeStep( int times )
{
this->m_TimeStep = times;
}
int QmitkImageStatisticsCalculationThread::GetTimeStep()
{
return this->m_TimeStep;
}
mitk::ImageStatisticsCalculator::Statistics QmitkImageStatisticsCalculationThread::GetStatisticsData()
{
return this->m_StatisticsStruct;
}
mitk::Image::Pointer QmitkImageStatisticsCalculationThread::GetStatisticsImage()
{
return this->m_StatisticsImage;
}
void QmitkImageStatisticsCalculationThread::SetIgnoreZeroValueVoxel(bool _arg)
{
this->m_IgnoreZeros = _arg;
}
bool QmitkImageStatisticsCalculationThread::GetIgnoreZeroValueVoxel()
{
return this->m_IgnoreZeros;
}
std::string QmitkImageStatisticsCalculationThread::GetLastErrorMessage()
{
return m_message;
}
QmitkImageStatisticsCalculationThread::HistogramType::Pointer
QmitkImageStatisticsCalculationThread::GetTimeStepHistogram()
{
return this->m_TimeStepHistogram;
}
bool QmitkImageStatisticsCalculationThread::GetStatisticsChangedFlag()
{
return m_StatisticChanged;
}
bool QmitkImageStatisticsCalculationThread::GetStatisticsUpdateSuccessFlag()
{
return m_CalculationSuccessful;
}
void QmitkImageStatisticsCalculationThread::run()
{
bool statisticCalculationSuccessful = true;
mitk::ImageStatisticsCalculator::Pointer calculator = mitk::ImageStatisticsCalculator::New();
if(this->m_StatisticsImage.IsNotNull())
{
calculator->SetImage(m_StatisticsImage);
calculator->SetMaskingModeToNone();
}
else
{
statisticCalculationSuccessful = false;
}
// Bug 13416 : The ImageStatistics::SetImageMask() method can throw exceptions, i.e. when the dimensionality
// of the masked and input image differ, we need to catch them and mark the calculation as failed
// the same holds for the ::SetPlanarFigure()
try
{
if(this->m_BinaryMask.IsNotNull())
{
calculator->SetImageMask(m_BinaryMask);
calculator->SetMaskingModeToImage();
}
if(this->m_PlanarFigureMask.IsNotNull())
{
calculator->SetPlanarFigure(m_PlanarFigureMask);
calculator->SetMaskingModeToPlanarFigure();
}
}
catch( const itk::ExceptionObject& e)
{
MITK_ERROR << "ITK Exception:" << e.what();
statisticCalculationSuccessful = false;
}
bool statisticChanged = false;
calculator->SetDoIgnorePixelValue(this->m_IgnoreZeros);
calculator->SetIgnorePixelValue(0);
try
{
statisticChanged = calculator->ComputeStatistics(m_TimeStep);
}
catch ( mitk::Exception& e)
{
m_message = e.GetDescription();
statisticCalculationSuccessful = false;
}
catch ( const std::runtime_error &e )
{
MITK_ERROR<< "Runtime Exception: " << e.what();
statisticCalculationSuccessful = false;
}
catch ( const std::exception &e )
{
MITK_ERROR<< "Standard Exception: " << e.what();
statisticCalculationSuccessful = false;
}
this->m_StatisticChanged = statisticChanged;
this->m_CalculationSuccessful = statisticCalculationSuccessful;
if(statisticCalculationSuccessful)
{
this->m_StatisticsStruct = calculator->GetStatistics(m_TimeStep);
if(this->m_TimeStepHistogram.IsNotNull())
{
this->m_TimeStepHistogram = NULL;
}
this->m_TimeStepHistogram = (HistogramType*) calculator->GetHistogram(m_TimeStep);
}
}
<commit_msg>Added error message text to the statistics thread for runtime errors and exceptions<commit_after>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "QmitkImageStatisticsCalculationThread.h"
//QT headers
#include <QMessageBox>
#include <QApplication>
QmitkImageStatisticsCalculationThread::QmitkImageStatisticsCalculationThread():QThread(),
m_StatisticsImage(NULL), m_BinaryMask(NULL), m_PlanarFigureMask(NULL), m_TimeStep(0),
m_IgnoreZeros(false), m_CalculationSuccessful(false), m_StatisticChanged(false)
{
}
QmitkImageStatisticsCalculationThread::~QmitkImageStatisticsCalculationThread()
{
}
void QmitkImageStatisticsCalculationThread::Initialize( mitk::Image::Pointer image, mitk::Image::Pointer binaryImage, mitk::PlanarFigure::Pointer planarFig )
{
// reset old values
if( this->m_StatisticsImage.IsNotNull() )
this->m_StatisticsImage = 0;
if( this->m_BinaryMask.IsNotNull() )
this->m_BinaryMask = 0;
if( this->m_PlanarFigureMask.IsNotNull())
this->m_PlanarFigureMask = 0;
// set new values if passed in
if(image.IsNotNull())
this->m_StatisticsImage = image->Clone();
if(binaryImage.IsNotNull())
this->m_BinaryMask = binaryImage->Clone();
if(planarFig.IsNotNull())
this->m_PlanarFigureMask = dynamic_cast<mitk::PlanarFigure*>(planarFig.GetPointer()); // once clone methods for planar figures are implemented, copy the data here!
}
void QmitkImageStatisticsCalculationThread::SetTimeStep( int times )
{
this->m_TimeStep = times;
}
int QmitkImageStatisticsCalculationThread::GetTimeStep()
{
return this->m_TimeStep;
}
mitk::ImageStatisticsCalculator::Statistics QmitkImageStatisticsCalculationThread::GetStatisticsData()
{
return this->m_StatisticsStruct;
}
mitk::Image::Pointer QmitkImageStatisticsCalculationThread::GetStatisticsImage()
{
return this->m_StatisticsImage;
}
void QmitkImageStatisticsCalculationThread::SetIgnoreZeroValueVoxel(bool _arg)
{
this->m_IgnoreZeros = _arg;
}
bool QmitkImageStatisticsCalculationThread::GetIgnoreZeroValueVoxel()
{
return this->m_IgnoreZeros;
}
std::string QmitkImageStatisticsCalculationThread::GetLastErrorMessage()
{
return m_message;
}
QmitkImageStatisticsCalculationThread::HistogramType::Pointer
QmitkImageStatisticsCalculationThread::GetTimeStepHistogram()
{
return this->m_TimeStepHistogram;
}
bool QmitkImageStatisticsCalculationThread::GetStatisticsChangedFlag()
{
return m_StatisticChanged;
}
bool QmitkImageStatisticsCalculationThread::GetStatisticsUpdateSuccessFlag()
{
return m_CalculationSuccessful;
}
void QmitkImageStatisticsCalculationThread::run()
{
bool statisticCalculationSuccessful = true;
mitk::ImageStatisticsCalculator::Pointer calculator = mitk::ImageStatisticsCalculator::New();
if(this->m_StatisticsImage.IsNotNull())
{
calculator->SetImage(m_StatisticsImage);
calculator->SetMaskingModeToNone();
}
else
{
statisticCalculationSuccessful = false;
}
// Bug 13416 : The ImageStatistics::SetImageMask() method can throw exceptions, i.e. when the dimensionality
// of the masked and input image differ, we need to catch them and mark the calculation as failed
// the same holds for the ::SetPlanarFigure()
try
{
if(this->m_BinaryMask.IsNotNull())
{
calculator->SetImageMask(m_BinaryMask);
calculator->SetMaskingModeToImage();
}
if(this->m_PlanarFigureMask.IsNotNull())
{
calculator->SetPlanarFigure(m_PlanarFigureMask);
calculator->SetMaskingModeToPlanarFigure();
}
}
catch( const itk::ExceptionObject& e)
{
MITK_ERROR << "ITK Exception:" << e.what();
statisticCalculationSuccessful = false;
}
bool statisticChanged = false;
calculator->SetDoIgnorePixelValue(this->m_IgnoreZeros);
calculator->SetIgnorePixelValue(0);
try
{
statisticChanged = calculator->ComputeStatistics(m_TimeStep);
}
catch ( mitk::Exception& e)
{
m_message = e.GetDescription();
statisticCalculationSuccessful = false;
}
catch ( const std::runtime_error &e )
{
m_message = "Exception Occurred. See log for details.";
MITK_ERROR<< "Runtime Exception: " << e.what();
statisticCalculationSuccessful = false;
}
catch ( const std::exception &e )
{
m_message = "Exception Occurred. See log for details.";
MITK_ERROR<< "Standard Exception: " << e.what();
statisticCalculationSuccessful = false;
}
this->m_StatisticChanged = statisticChanged;
this->m_CalculationSuccessful = statisticCalculationSuccessful;
if(statisticCalculationSuccessful)
{
this->m_StatisticsStruct = calculator->GetStatistics(m_TimeStep);
if(this->m_TimeStepHistogram.IsNotNull())
{
this->m_TimeStepHistogram = NULL;
}
this->m_TimeStepHistogram = (HistogramType*) calculator->GetHistogram(m_TimeStep);
}
}
<|endoftext|>
|
<commit_before>// Copyright 2013 Sean McKenna
//
// 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.
//
// object sub-classes (e.g. sphere, plane, triangular mesh OBJ)
// import triangular mesh & BVH storage class
#include "cyCodeBase/cyTriMesh.h"
#include "cyCodeBase/cyBVH.h"
// namespace
using namespace scene;
// Sphere definition
class Sphere: public Object{
public:
// constructor
Sphere(){
center.Set(0, 0, 0);
radius = 1.0;
}
// intsersect a ray against the unit sphere
// ray must be transformed into model space, first
bool intersectRay(Ray &r, HitInfo &h, int face=HIT_FRONT){
// pre-compute values for quadratic solution
Point pos = r.pos - center;
float A = r.dir % r.dir;
float B = 2.0 * pos % r.dir;
float C = pos % pos - radius * radius;
float det = (B * B) - (4 * A * C);
// if the ray intersects, compute the z-buffer value
if(det >= 0){
float z1 = (-B - sqrt(det)) / (2.0 * A);
float z2 = (-B + sqrt(det)) / (2.0 * A);
// determine if we have a back hit
if(z1 * z2 < 0.0)
h.front = false;
// if hit is too close, assume it is a back-face hit
else if(z1 <= getBias())
h.front = false;
// check closest z-buffer value, if positive (ahead of our ray)
if(z1 > getBias()){
h.z = z1;
// compute surface intersection and normal
h.p = r.pos + z1 * r.dir;
h.n = h.p.GetNormalized();
// return true, ray is hit
return true;
// check the next ray, if necessary
}else if(z2 > getBias()){
h.z = z2;
// compute surface intersection and normal
h.p = r.pos + z2 * r.dir;
h.n = h.p.GetNormalized();
// return true, ray is hit
return true;
// otherwise, all z-buffer values are negative, return false
}else
return false;
}
// otherwise, return false (no ray hit)
else
return false;
}
// get sphere bounding box
BoundingBox getBoundBox(){
return BoundingBox(-1.0, -1.0, -1.0, 1.0, 1.0, 1.0);
}
private:
// sphere center and its radius
Point center;
float radius;
};
// Plane definition (a "unit" plane)
class Plane: public Object{
public:
// intersect a ray against the "unit" plane
bool intersectRay(Ray &r, HitInfo &h, int face = HIT_FRONT){
// only compute for rays not parallel to the unit plane
if(r.dir.z > getBias() || r.dir.z < getBias()){
// compute distance along ray direction to plane
float t = -r.pos.z / r.dir.z;
// only accept hits in front of ray (with some bias)
if(t > getBias()){
// compute the hit point
Point hit = r.pos + t * r.dir;
// only allow a hit to occur if on the "unit" plane
if(hit.x >= -1.0 && hit.y >= -1.0 && hit.x <= 1.0 && hit.y <= 1.0){
// detect back face hits
if(r.pos.z < 0.0)
h.front = false;
// distance to hit
h.z = t;
// set hit point, normal, and return hit info
h.p = hit;
h.n = Point(0.0, 0.0, 1.0);
return true;
}
}
}
// when no ray hits the "unit" plane
return false;
}
// get plane bounding box
BoundingBox getBoundBox(){
return BoundingBox(-1.0, -1.0, 0.0, 1.0, 1.0, 0.0);
}
};
// Triangular Mesh Object definition (from an OBJ file)
class TriObj: public Object, private cyTriMesh{
public:
// intersect a ray against the triangular mesh
bool intersectRay(Ray &r, HitInfo &h, int face = HIT_FRONT){
// check our BVH for triangular faces, update hit info
bool triang = traceBVHNode(r, h, face, bvh.GetRootNodeID());
// return hit info from intersecting rays in the BVH faces
return triang;
}
// get triangular mesh bounding box
BoundingBox getBoundBox(){
return BoundingBox(GetBoundMin(), GetBoundMax());
}
// when loading a triangular mesh, get its bounding box
bool load(const char *file){
bvh.Clear();
if(!LoadFromFileObj(file))
return false;
if(!HasNormals())
ComputeNormals();
ComputeBoundingBox();
bvh.SetMesh(this,4);
return true;
}
private:
// add BVH for each triangular mesh
cyBVHTriMesh bvh;
// intersect a ray with a single triangle (Moller-Trumbore algorithm)
bool intersectTriangle(Ray &r, HitInfo &h, int face, int faceID){
bool mt = false;
if(mt){
// grab vertex points
Point a = V(F(faceID).v[0]);
Point b = V(F(faceID).v[1]);
Point c = V(F(faceID).v[2]);
// compute edge vectors
Point e1 = b - a;
Point e2 = c - a;
// calculate first vector, P
Point P = r.dir ^ e2;
// calculate the determinant of the matrix equation
float determ = e1 % P;
// only continue for valid determinant ranges
if(abs(determ) > getBias()){
// calculate second vector, T
Point T = r.pos - a;
// calculate a barycentric component (u)
float u = T % P;
// only allow valid barycentric values
if(u > -getBias() && u < determ * (1.0 + getBias())){
// calculate a normal of the ray with an edge vector
Point Q = T ^ e1;
// calculate a barycentric component (v)
float v = r.dir % Q;
// only allow valid barycentric values
if(v > -getBias() && v + u < determ * (1.0 + getBias())){
// update barycentric coordinates
v /= determ;
u /= determ;
// compute the barycentric coordinates for interpolating values
Point bc = Point(1.0 - u - v, u, v);
// calculate the distance to hit the triangle
float t = (e2 % Q) / determ;
// only allow valid distances to hit
if(t > getBias() && t < h.z){
// distance to hit
h.z = t;
// set hit point, normal
h.p = GetPoint(faceID, bc);
h.n = GetNormal(faceID, bc);
// detect back face hits
if(determ < 0.0)
h.front = false;
// return hit info
return true;
}
}
}
}
// when no ray hits the triangular face
return false;
// normal ray tracing
}else{
// ignore rays nearly parallel to surface
Point a = V(F(faceID).v[0]);
Point b = V(F(faceID).v[1]);
Point c = V(F(faceID).v[2]);
Point n = (b - a) ^ (c - a);
if(r.dir % n > getBias() || r.dir % n < -getBias()){
// compute distance along ray direction to plane
Point a = V(F(faceID).v[0]);
float t = -((r.pos - a) % n) / (r.dir % n);
// only accept hits in front of ray (with some bias) & closer hits
if(t > getBias() && t < h.z){
// compute hit point
Point hit = r.pos + t * r.dir;
// simplify problem into 2D by removing the greatest normal component
Point2 a2;
Point2 b2;
Point2 c2;
Point2 hit2;
if(abs(n.x) > abs(n.y) && abs(n.x) > abs(n.z)){
a2 = Point2(a.y, a.z);
b2 = Point2(b.y, b.z);
c2 = Point2(c.y, c.z);
hit2 = Point2(hit.y, hit.z);
}else if(abs(n.y) > abs(n.x) && abs(n.y) > abs(n.z)){
a2 = Point2(a.x, a.z);
b2 = Point2(b.x, b.z);
c2 = Point2(c.x, c.z);
hit2 = Point2(hit.x, hit.z);
}else{
a2 = Point2(a.x, a.y);
b2 = Point2(b.x, b.y);
c2 = Point2(c.x, c.y);
hit2 = Point2(hit.x, hit.y);
}
// compute the area of the triangular face (in 2D)
float area = (b2 - a2) ^ (c2 - a2);
// compute smaller areas of the face, relative to the full area, in 2D
// ensure that we are only calculating positive areas
// aka, computation of the barycentric coordinates
float alpha = ((b2 - a2) ^ (hit2 - a2)) / area;
if(alpha > -getBias() && alpha < 1.0 + getBias()){
float beta = ((hit2 - a2) ^ (c2 - a2)) / area;
if(beta > -getBias() && beta < 1.0 + getBias()){
if(alpha + beta < 1.0 + getBias()){
// interpolate the normal based on barycentric coordinates
Point bc = Point(1.0 - alpha - beta, beta, alpha);
// distance to hit
h.z = t;
// set hit point, normal
h.p = GetPoint(faceID, bc);
h.n = GetNormal(faceID, bc);
// detect back face hits
if(r.dir % h.n > 0.0)
h.front = false;
// return hit info
return true;
}
}
}
}
}
// when no ray hits the triangular face
return false;
}
}
// cast a ray into a BVH node, seeing which triangular faces may get hit
bool traceBVHNode(Ray &r, HitInfo &h, int face, int nodeID){
// grab node's bounding box
BoundingBox b = BoundingBox(bvh.GetNodeBounds(nodeID));
// does ray hit the node bounding box?
bool hit = b.intersectRay(r, h.z);
// recurse through child nodes if we hit node
if(hit){
// only recursively call function if not at a leaf node
if(!bvh.IsLeafNode(nodeID)){
// keep traversing the BVH hierarchy for hits
int c1 = bvh.GetFirstChildNode(nodeID);
int c2 = bvh.GetSecondChildNode(nodeID);
bool hit1 = traceBVHNode(r, h, face, c1);
bool hit2 = traceBVHNode(r, h, face, c2);
// if we get no hit
if(!hit1 && !hit2)
hit = false;
// for leaf nodes, trace ray into each triangular face
}else{
// get triangular faces of the hit BVH node
const unsigned int* faces = bvh.GetNodeElements(nodeID);
int size = bvh.GetNodeElementCount(nodeID);
// trace the ray into each triangular face, tracking hits
hit = false;
for(int i = 0; i < size; i++){
bool hit1 = intersectTriangle(r, h, face, faces[i]);
if(!hit && hit1)
hit = true;
}
}
}
// return if we hit a face within this node
return hit;
}
};
<commit_msg>add in some tweaks to the area-based ray-triangle intersection method, still a few kinks to work out<commit_after>// Copyright 2013 Sean McKenna
//
// 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.
//
// object sub-classes (e.g. sphere, plane, triangular mesh OBJ)
// import triangular mesh & BVH storage class
#include "cyCodeBase/cyTriMesh.h"
#include "cyCodeBase/cyBVH.h"
// namespace
using namespace scene;
// Sphere definition
class Sphere: public Object{
public:
// constructor
Sphere(){
center.Set(0, 0, 0);
radius = 1.0;
}
// intsersect a ray against the unit sphere
// ray must be transformed into model space, first
bool intersectRay(Ray &r, HitInfo &h, int face=HIT_FRONT){
// pre-compute values for quadratic solution
Point pos = r.pos - center;
float A = r.dir % r.dir;
float B = 2.0 * pos % r.dir;
float C = pos % pos - radius * radius;
float det = (B * B) - (4 * A * C);
// if the ray intersects, compute the z-buffer value
if(det >= 0){
float z1 = (-B - sqrt(det)) / (2.0 * A);
float z2 = (-B + sqrt(det)) / (2.0 * A);
// determine if we have a back hit
if(z1 * z2 < 0.0)
h.front = false;
// if hit is too close, assume it is a back-face hit
else if(z1 <= getBias())
h.front = false;
// check closest z-buffer value, if positive (ahead of our ray)
if(z1 > getBias()){
h.z = z1;
// compute surface intersection and normal
h.p = r.pos + z1 * r.dir;
h.n = h.p.GetNormalized();
// return true, ray is hit
return true;
// check the next ray, if necessary
}else if(z2 > getBias()){
h.z = z2;
// compute surface intersection and normal
h.p = r.pos + z2 * r.dir;
h.n = h.p.GetNormalized();
// return true, ray is hit
return true;
// otherwise, all z-buffer values are negative, return false
}else
return false;
}
// otherwise, return false (no ray hit)
else
return false;
}
// get sphere bounding box
BoundingBox getBoundBox(){
return BoundingBox(-1.0, -1.0, -1.0, 1.0, 1.0, 1.0);
}
private:
// sphere center and its radius
Point center;
float radius;
};
// Plane definition (a "unit" plane)
class Plane: public Object{
public:
// intersect a ray against the "unit" plane
bool intersectRay(Ray &r, HitInfo &h, int face = HIT_FRONT){
// only compute for rays not parallel to the unit plane
if(r.dir.z > getBias() || r.dir.z < getBias()){
// compute distance along ray direction to plane
float t = -r.pos.z / r.dir.z;
// only accept hits in front of ray (with some bias)
if(t > getBias()){
// compute the hit point
Point hit = r.pos + t * r.dir;
// only allow a hit to occur if on the "unit" plane
if(hit.x >= -1.0 && hit.y >= -1.0 && hit.x <= 1.0 && hit.y <= 1.0){
// detect back face hits
if(r.pos.z < 0.0)
h.front = false;
// distance to hit
h.z = t;
// set hit point, normal, and return hit info
h.p = hit;
h.n = Point(0.0, 0.0, 1.0);
return true;
}
}
}
// when no ray hits the "unit" plane
return false;
}
// get plane bounding box
BoundingBox getBoundBox(){
return BoundingBox(-1.0, -1.0, 0.0, 1.0, 1.0, 0.0);
}
};
// Triangular Mesh Object definition (from an OBJ file)
class TriObj: public Object, private cyTriMesh{
public:
// intersect a ray against the triangular mesh
bool intersectRay(Ray &r, HitInfo &h, int face = HIT_FRONT){
// check our BVH for triangular faces, update hit info
bool triang = traceBVHNode(r, h, face, bvh.GetRootNodeID());
// return hit info from intersecting rays in the BVH faces
return triang;
}
// get triangular mesh bounding box
BoundingBox getBoundBox(){
return BoundingBox(GetBoundMin(), GetBoundMax());
}
// when loading a triangular mesh, get its bounding box
bool load(const char *file){
bvh.Clear();
if(!LoadFromFileObj(file))
return false;
if(!HasNormals())
ComputeNormals();
ComputeBoundingBox();
bvh.SetMesh(this,4);
return true;
}
private:
// add BVH for each triangular mesh
cyBVHTriMesh bvh;
// intersect a ray with a single triangle (Moller-Trumbore algorithm)
bool intersectTriangle(Ray &r, HitInfo &h, int face, int faceID){
bool mt = false;
if(mt){
// grab vertex points
Point a = V(F(faceID).v[0]);
Point b = V(F(faceID).v[1]);
Point c = V(F(faceID).v[2]);
// compute edge vectors
Point e1 = b - a;
Point e2 = c - a;
// calculate first vector, P
Point P = r.dir ^ e2;
// calculate the determinant of the matrix equation
float determ = e1 % P;
// only continue for valid determinant ranges
if(abs(determ) > getBias()){
// calculate second vector, T
Point T = r.pos - a;
// calculate a barycentric component (u)
float u = T % P;
// only allow valid barycentric values
if(u > -getBias() && u < determ * (1.0 + getBias())){
// calculate a normal of the ray with an edge vector
Point Q = T ^ e1;
// calculate a barycentric component (v)
float v = r.dir % Q;
// only allow valid barycentric values
if(v > -getBias() && v + u < determ * (1.0 + getBias())){
// update barycentric coordinates
v /= determ;
u /= determ;
// compute the barycentric coordinates for interpolating values
Point bc = Point(1.0 - u - v, u, v);
// calculate the distance to hit the triangle
float t = (e2 % Q) / determ;
// only allow valid distances to hit
if(t > getBias() && t < h.z){
// distance to hit
h.z = t;
// set hit point, normal
h.p = GetPoint(faceID, bc);
h.n = GetNormal(faceID, bc);
// detect back face hits
if(determ < 0.0)
h.front = false;
// return hit info
return true;
}
}
}
}
// when no ray hits the triangular face
return false;
// normal ray tracing
}else{
// grab face vertices and compute face normal
Point a = V(F(faceID).v[0]);
Point b = V(F(faceID).v[1]);
Point c = V(F(faceID).v[2]);
Point n = (b - a) ^ (c - a);
// ignore rays nearly parallel to surface
if(r.dir % n > getBias() || r.dir % n < -getBias()){
// compute distance along ray direction to plane
float t = -((r.pos - a) % n) / (r.dir % n);
// only accept hits in front of ray (with some bias) & closer hits
if(t > getBias() && t < h.z){
// compute hit point
Point hit = r.pos + t * r.dir;
// simplify problem into 2D by removing the greatest normal component
Point2 a2;
Point2 b2;
Point2 c2;
Point2 hit2;
if(abs(n.x) > abs(n.y) && abs(n.x) > abs(n.z)){
a2 = Point2(a.y, a.z);
b2 = Point2(b.y, b.z);
c2 = Point2(c.y, c.z);
hit2 = Point2(hit.y, hit.z);
}else if(abs(n.y) > abs(n.x) && abs(n.y) > abs(n.z)){
a2 = Point2(a.x, a.z);
b2 = Point2(b.x, b.z);
c2 = Point2(c.x, c.z);
hit2 = Point2(hit.x, hit.z);
}else{
a2 = Point2(a.x, a.y);
b2 = Point2(b.x, b.y);
c2 = Point2(c.x, c.y);
hit2 = Point2(hit.x, hit.y);
}
// compute the area of the triangular face (in 2D)
float area = (b2 - a2) ^ (c2 - a2);
// compute smaller areas of the face, relative to the full area, in 2D
// ensure that we are only calculating positive areas
// aka, computation of the barycentric coordinates
float alpha = ((b2 - a2) ^ (hit2 - a2));
if(alpha > -getBias() && alpha < area * (1.0 + getBias())){
float beta = ((hit2 - a2) ^ (c2 - a2));
if(beta > -getBias() && alpha + beta < area * (1.0 + getBias())){
// scale alpha and beta to the area
alpha /= area;
beta /= area;
// interpolate the normal based on barycentric coordinates
Point bc = Point(1.0 - alpha - beta, beta, alpha);
// distance to hit
h.z = t;
// set hit point, normal
h.p = GetPoint(faceID, bc);
h.n = GetNormal(faceID, bc);
// detect back face hits
if(r.dir % h.n > 0.0)
h.front = false;
// return hit info
return true;
}
}
}
}
// when no ray hits the triangular face
return false;
}
}
// cast a ray into a BVH node, seeing which triangular faces may get hit
bool traceBVHNode(Ray &r, HitInfo &h, int face, int nodeID){
// grab node's bounding box
BoundingBox b = BoundingBox(bvh.GetNodeBounds(nodeID));
// does ray hit the node bounding box?
bool hit = b.intersectRay(r, h.z);
// recurse through child nodes if we hit node
if(hit){
// only recursively call function if not at a leaf node
if(!bvh.IsLeafNode(nodeID)){
// keep traversing the BVH hierarchy for hits
int c1 = bvh.GetFirstChildNode(nodeID);
int c2 = bvh.GetSecondChildNode(nodeID);
bool hit1 = traceBVHNode(r, h, face, c1);
bool hit2 = traceBVHNode(r, h, face, c2);
// if we get no hit
if(!hit1 && !hit2)
hit = false;
// for leaf nodes, trace ray into each triangular face
}else{
// get triangular faces of the hit BVH node
const unsigned int* faces = bvh.GetNodeElements(nodeID);
int size = bvh.GetNodeElementCount(nodeID);
// trace the ray into each triangular face, tracking hits
hit = false;
for(int i = 0; i < size; i++){
bool hit1 = intersectTriangle(r, h, face, faces[i]);
if(!hit && hit1)
hit = true;
}
}
}
// return if we hit a face within this node
return hit;
}
};
<|endoftext|>
|
<commit_before>//
// Vector/instance_method_mula.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2014 Rick Yang (rick68 at gmail dot com)
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
//
#ifndef EIGENJS_VECTOR_INSTANCE_METHOD_MULA_HPP
#define EIGENJS_VECTOR_INSTANCE_METHOD_MULA_HPP
namespace EigenJS {
EIGENJS_INSTANCE_METHOD(Vector, mula,
{
NanScope();
if (args.Length() == 1) {
Vector* obj = node::ObjectWrap::Unwrap<Vector>(args.This());
typename Vector::value_type& value = **obj;
if (Matrix::is_matrix(args[0])) {
const Matrix* const& rhs_obj =
node::ObjectWrap::Unwrap<Matrix>(args[0]->ToObject());
const typename Matrix::value_type& rhs_matrix = **rhs_obj;
if (T::is_invalid_matrix_product(obj, rhs_obj)) {
NanReturnUndefined();
}
if (rhs_matrix.cols() != 1) {
NanThrowError("The matrix size must be 1x1");
NanReturnUndefined();
}
value *= rhs_matrix;
NanReturnValue(args.This());
} else if (Vector::is_vector(args[0])) {
const Vector* const& rhs_obj =
node::ObjectWrap::Unwrap<Vector>(args[0]->ToObject());
const typename Vector::value_type& rhs_vector = **rhs_obj;
if (T::is_invalid_matrix_product(obj, rhs_obj)) {
NanReturnUndefined();
}
value *= rhs_vector;
NanReturnValue(args.This());
} else if (T::is_scalar(args[0])) {
value *= args[0]->NumberValue();
NanReturnValue(args.This());
}
}
EIGENJS_THROW_ERROR_INVALID_ARGUMENT()
NanReturnUndefined();
})
} // namespace EigenJS
#endif // EIGENJS_VECTOR_INSTANCE_METHOD_MULA_HPP
<commit_msg>src: renamed type T<commit_after>//
// Vector/instance_method_mula.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2014 Rick Yang (rick68 at gmail dot com)
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
//
#ifndef EIGENJS_VECTOR_INSTANCE_METHOD_MULA_HPP
#define EIGENJS_VECTOR_INSTANCE_METHOD_MULA_HPP
namespace EigenJS {
EIGENJS_INSTANCE_METHOD(Vector, mula,
{
NanScope();
if (args.Length() == 1) {
Vector* obj = node::ObjectWrap::Unwrap<Vector>(args.This());
typename Vector::value_type& value = **obj;
if (Matrix::is_matrix(args[0])) {
const Matrix* const& rhs_obj =
node::ObjectWrap::Unwrap<Matrix>(args[0]->ToObject());
const typename Matrix::value_type& rhs_matrix = **rhs_obj;
if (Matrix::is_invalid_matrix_product(obj, rhs_obj)) {
NanReturnUndefined();
}
if (rhs_matrix.cols() != 1) {
NanThrowError("The matrix size must be 1x1");
NanReturnUndefined();
}
value *= rhs_matrix;
NanReturnValue(args.This());
} else if (Vector::is_vector(args[0])) {
const Vector* const& rhs_obj =
node::ObjectWrap::Unwrap<Vector>(args[0]->ToObject());
const typename Vector::value_type& rhs_vector = **rhs_obj;
if (Vector::is_invalid_matrix_product(obj, rhs_obj)) {
NanReturnUndefined();
}
value *= rhs_vector;
NanReturnValue(args.This());
} else if (T::is_scalar(args[0])) {
value *= args[0]->NumberValue();
NanReturnValue(args.This());
}
}
EIGENJS_THROW_ERROR_INVALID_ARGUMENT()
NanReturnUndefined();
})
} // namespace EigenJS
#endif // EIGENJS_VECTOR_INSTANCE_METHOD_MULA_HPP
<|endoftext|>
|
<commit_before>// Copyright (c) 2012-2013, the scalloc Project Authors. All rights reserved.
// Please see the AUTHORS file for details. Use of this source code is governed
// by a BSD license that can be found in the LICENSE file.
#include "slab_sc_allocator.h"
#include "allocators/page_heap.h"
#include "log.h"
#include "runtime_vars.h"
namespace scalloc {
void SlabScAllocator::InitModule() {
PageHeap::InitModule();
}
void SlabScAllocator::Init(const uint64_t id) {
id_ = id;
ActiveOwner dummy;
dummy.Reset(true, id_);
me_active_ = dummy.raw;
dummy.Reset(false, id_);
me_inactive_ = dummy.raw;
}
void* SlabScAllocator::AllocateNoSlab(const size_t sc, const size_t size) {
// Size class 0 represents an object of size 0, which results in malloc()
// returning NULL.
if (sc == 0) {
return NULL;
}
if (my_headers_[sc] != NULL) {
#ifdef PROFILER_ON
Profiler::GetProfiler().LogAllocation(size);
#endif //PROFILER_ON
// Only try to steal we had a slab at least once.
SlabHeader* hdr;
void* p = DQScAllocator::Instance().Allocate(sc, id_, id_, &hdr);
if (p != NULL) {
#ifdef PROFILER_ON
Profiler::GetProfiler().LogBlockStealing();
#endif //PROFILER_ON
if (hdr != NULL) {
SetActiveSlab(sc, hdr);
} else {
#ifdef GLOBAL_CLEANUP
if (reinterpret_cast<SlabHeader*>(BlockHeader::GetFromObject(p))->aowner.owner != id_) {
Refill(sc);
}
#endif // GLOBAL_CLEANUP
}
return p;
}
}
Refill(sc);
return Allocate(size);
}
void SlabScAllocator::Refill(const size_t sc) {
#ifdef PROFILER_ON
Profiler::GetProfiler().LogSizeclassRefill();
#endif //PROFILER_ON
LOG(kTrace, "[SlabAllocator]: refilling size class: %lu", sc);
uintptr_t block = reinterpret_cast<uintptr_t>(PageHeap::GetHeap()->Get());
if (block == 0) {
ErrorOut("PageHeap out of memory");
}
SlabHeader* hdr = InitSlab(block,
kPageMultiple * RuntimeVars::SystemPageSize(),
sc);
SetActiveSlab(sc, hdr);
}
SlabHeader* SlabScAllocator::InitSlab(uintptr_t block,
size_t len,
const size_t sc) {
const size_t obj_size = SizeMap::Instance().ClassToSize(sc);
size_t sys_page_size = RuntimeVars::SystemPageSize();
SlabHeader* main_hdr = reinterpret_cast<SlabHeader*>(block);
main_hdr->Reset(sc, id_);
main_hdr->aowner.owner = id_;
main_hdr->aowner.active = true;
// We need to initialize the flist and place ForwardHeaders every system page
// size bytes, since this is where we search for headers (for small AND large
// objects)
size_t nr_objects;
// First block is special, since it contains the full slab header, while
// others only contain the forward header to the first block.
nr_objects = (sys_page_size - sizeof(*main_hdr)) / obj_size;
main_hdr->flist.FromBlock(reinterpret_cast<void*>(block + sizeof(*main_hdr)),
obj_size,
nr_objects);
len -= sys_page_size;
block += sys_page_size;
// Fill with forward headers and flist objects.
for (; len >= sys_page_size; len -= sys_page_size) {
ForwardHeader* fwd_hdr = reinterpret_cast<ForwardHeader*>(block);
fwd_hdr->Reset(main_hdr);
nr_objects = (sys_page_size - sizeof(*fwd_hdr)) / obj_size;
main_hdr->flist.AddRange(reinterpret_cast<void*>(block + sizeof(*fwd_hdr)),
obj_size,
nr_objects);
block += sys_page_size;
}
return main_hdr;
}
void SlabScAllocator::Destroy() {
// Destroying basically means giving up all active spans. We can only give up
// our current spans, since we do not have references to the others. Assuming
// the mutator had no memory leak (i.e. all non-shared objects have been
// freed), a span now can stay active forever (all reusable blocks travel
// through the remote freelists), or it is already inactive (and thus
// available for reuse).
for (size_t i = 0; i < kNumClasses; i++) {
if (my_headers_[i]) {
my_headers_[i]->aowner.active = false;
}
}
}
} // namespace scalloc
<commit_msg>Linted.<commit_after>// Copyright (c) 2012-2013, the scalloc Project Authors. All rights reserved.
// Please see the AUTHORS file for details. Use of this source code is governed
// by a BSD license that can be found in the LICENSE file.
#include "slab_sc_allocator.h"
#include "allocators/page_heap.h"
#include "log.h"
#include "runtime_vars.h"
namespace scalloc {
void SlabScAllocator::InitModule() {
PageHeap::InitModule();
}
void SlabScAllocator::Init(const uint64_t id) {
id_ = id;
ActiveOwner dummy;
dummy.Reset(true, id_);
me_active_ = dummy.raw;
dummy.Reset(false, id_);
me_inactive_ = dummy.raw;
}
void* SlabScAllocator::AllocateNoSlab(const size_t sc, const size_t size) {
// Size class 0 represents an object of size 0, which results in malloc()
// returning NULL.
if (sc == 0) {
return NULL;
}
if (my_headers_[sc] != NULL) {
#ifdef PROFILER_ON
Profiler::GetProfiler().LogAllocation(size);
#endif // PROFILER_ON
// Only try to steal we had a slab at least once.
SlabHeader* hdr;
void* p = DQScAllocator::Instance().Allocate(sc, id_, id_, &hdr);
if (p != NULL) {
#ifdef PROFILER_ON
Profiler::GetProfiler().LogBlockStealing();
#endif // PROFILER_ON
if (hdr != NULL) {
SetActiveSlab(sc, hdr);
} else {
#ifdef GLOBAL_CLEANUP
if (reinterpret_cast<SlabHeader*>(BlockHeader::GetFromObject(p))->aowner.owner != id_) {
Refill(sc);
}
#endif // GLOBAL_CLEANUP
}
return p;
}
}
Refill(sc);
return Allocate(size);
}
void SlabScAllocator::Refill(const size_t sc) {
#ifdef PROFILER_ON
Profiler::GetProfiler().LogSizeclassRefill();
#endif // PROFILER_ON
LOG(kTrace, "[SlabAllocator]: refilling size class: %lu", sc);
uintptr_t block = reinterpret_cast<uintptr_t>(PageHeap::GetHeap()->Get());
if (block == 0) {
ErrorOut("PageHeap out of memory");
}
SlabHeader* hdr = InitSlab(block,
kPageMultiple * RuntimeVars::SystemPageSize(),
sc);
SetActiveSlab(sc, hdr);
}
SlabHeader* SlabScAllocator::InitSlab(uintptr_t block,
size_t len,
const size_t sc) {
const size_t obj_size = SizeMap::Instance().ClassToSize(sc);
size_t sys_page_size = RuntimeVars::SystemPageSize();
SlabHeader* main_hdr = reinterpret_cast<SlabHeader*>(block);
main_hdr->Reset(sc, id_);
main_hdr->aowner.owner = id_;
main_hdr->aowner.active = true;
// We need to initialize the flist and place ForwardHeaders every system page
// size bytes, since this is where we search for headers (for small AND large
// objects)
size_t nr_objects;
// First block is special, since it contains the full slab header, while
// others only contain the forward header to the first block.
nr_objects = (sys_page_size - sizeof(*main_hdr)) / obj_size;
main_hdr->flist.FromBlock(reinterpret_cast<void*>(block + sizeof(*main_hdr)),
obj_size,
nr_objects);
len -= sys_page_size;
block += sys_page_size;
// Fill with forward headers and flist objects.
for (; len >= sys_page_size; len -= sys_page_size) {
ForwardHeader* fwd_hdr = reinterpret_cast<ForwardHeader*>(block);
fwd_hdr->Reset(main_hdr);
nr_objects = (sys_page_size - sizeof(*fwd_hdr)) / obj_size;
main_hdr->flist.AddRange(reinterpret_cast<void*>(block + sizeof(*fwd_hdr)),
obj_size,
nr_objects);
block += sys_page_size;
}
return main_hdr;
}
void SlabScAllocator::Destroy() {
// Destroying basically means giving up all active spans. We can only give up
// our current spans, since we do not have references to the others. Assuming
// the mutator had no memory leak (i.e. all non-shared objects have been
// freed), a span now can stay active forever (all reusable blocks travel
// through the remote freelists), or it is already inactive (and thus
// available for reuse).
for (size_t i = 0; i < kNumClasses; i++) {
if (my_headers_[i]) {
my_headers_[i]->aowner.active = false;
}
}
}
} // namespace scalloc
<|endoftext|>
|
<commit_before>#pragma once
#include <agency/detail/config.hpp>
#include <agency/detail/unique_ptr.hpp>
#include <memory>
namespace agency
{
namespace detail
{
template<class T, class Alloc = std::allocator<T>>
class boxed_value
{
public:
using allocator_type = typename std::allocator_traits<Alloc>::template rebind_alloc<T>;
using value_type = typename allocator_type::value_type;
__AGENCY_ANNOTATION
boxed_value()
: boxed_value(value_type{})
{}
__AGENCY_ANNOTATION
boxed_value(const boxed_value& other)
: boxed_value(other.value())
{}
__AGENCY_ANNOTATION
boxed_value(boxed_value&& other)
: boxed_value(std::move(other.value()))
{}
template<class... Args,
class = typename std::enable_if<
std::is_constructible<T,Args&&...>::value
>::type>
__AGENCY_ANNOTATION
explicit boxed_value(Args... args)
: data_(agency::detail::allocate_unique<T>(allocator_type(), std::forward<Args>(args)...))
{}
__AGENCY_ANNOTATION
boxed_value& operator=(const boxed_value& other)
{
value() = other.value();
return *this;
}
__AGENCY_ANNOTATION
boxed_value& operator=(boxed_value&& other)
{
value() = std::move(other.value());
return *this;
}
__AGENCY_ANNOTATION
value_type& value() &
{
return *data_;
}
__AGENCY_ANNOTATION
const value_type& value() const &
{
return *data_;
}
__AGENCY_ANNOTATION
value_type&& value() &&
{
return std::move(*data_);
}
__AGENCY_ANNOTATION
const value_type&& value() const &&
{
return std::move(*data_);
}
template<class U,
class = typename std::enable_if<
std::is_assignable<value_type,U&&>::value
>::type>
__AGENCY_ANNOTATION
boxed_value& operator=(U&& other)
{
value() = std::forward<U>(other);
return *this;
}
private:
agency::detail::unique_ptr<T,agency::detail::deleter<allocator_type>> data_;
};
// when the allocator is std::allocator<T>, we can just put this on the stack
template<class T, class OtherT>
class boxed_value<T,std::allocator<OtherT>>
{
public:
using allocator_type = std::allocator<T>;
using value_type = typename allocator_type::value_type;
__AGENCY_ANNOTATION
boxed_value()
: boxed_value(value_type{})
{}
__AGENCY_ANNOTATION
boxed_value(const boxed_value& other)
: boxed_value(other.value())
{}
__AGENCY_ANNOTATION
boxed_value(boxed_value&& other)
: boxed_value(std::move(other.value_))
{}
template<class... Args,
class = typename std::enable_if<
std::is_constructible<T,Args&&...>::value
>::type>
__AGENCY_ANNOTATION
explicit boxed_value(Args&&... args)
: value_(std::forward<Args>(args)...)
{}
__AGENCY_ANNOTATION
value_type& value()
{
return value_;
}
__AGENCY_ANNOTATION
const value_type& value() const
{
return value_;
}
template<class U,
class = typename std::enable_if<
std::is_assignable<value_type,U&&>::value
>::type>
__AGENCY_ANNOTATION
boxed_value& operator=(U&& other)
{
value() = std::forward<U>(other);
return *this;
}
private:
value_type value_;
};
template<class T, class Alloc, class... Args>
__AGENCY_ANNOTATION
boxed_value<T,Alloc> allocate_boxed(const Alloc&, Args&&... args)
{
return boxed_value<T,Alloc>(std::forward<Args>(args)...);
}
} // end detail
} // end agency
<commit_msg>Implement small object optimization for boxed_value<commit_after>#pragma once
#include <agency/detail/config.hpp>
#include <agency/detail/unique_ptr.hpp>
#include <agency/detail/tuple.hpp>
#include <memory>
#include <type_traits>
namespace agency
{
namespace detail
{
namespace boxed_value_detail
{
template<class T, class Alloc>
struct use_small_object_optimization : disjunction<
std::is_same<Alloc,std::allocator<T>>,
std::is_empty<T>,
is_empty_tuple<T>
>
{};
} // end boxed_value_detail
template<class T, class Alloc = std::allocator<T>,
bool use_optimization = boxed_value_detail::use_small_object_optimization<T,Alloc>::value>
class boxed_value : private std::allocator_traits<Alloc>::template rebind_alloc<T>
{
public:
using allocator_type = typename std::allocator_traits<Alloc>::template rebind_alloc<T>;
using value_type = typename allocator_type::value_type;
__AGENCY_ANNOTATION
boxed_value()
: boxed_value(value_type{})
{}
__AGENCY_ANNOTATION
boxed_value(const boxed_value& other)
: boxed_value(other.value())
{}
__AGENCY_ANNOTATION
boxed_value(boxed_value&& other)
: boxed_value(std::move(other.value()))
{}
template<class... Args,
class = typename std::enable_if<
std::is_constructible<T,Args&&...>::value
>::type>
__AGENCY_ANNOTATION
explicit boxed_value(Args... args)
: data_(agency::detail::allocate_unique<T>(get_allocator(), std::forward<Args>(args)...))
{}
__AGENCY_ANNOTATION
boxed_value& operator=(const boxed_value& other)
{
value() = other.value();
return *this;
}
__AGENCY_ANNOTATION
boxed_value& operator=(boxed_value&& other)
{
value() = std::move(other.value());
return *this;
}
__AGENCY_ANNOTATION
value_type& value() &
{
return *data_;
}
__AGENCY_ANNOTATION
const value_type& value() const &
{
return *data_;
}
__AGENCY_ANNOTATION
value_type&& value() &&
{
return std::move(*data_);
}
__AGENCY_ANNOTATION
const value_type&& value() const &&
{
return std::move(*data_);
}
template<class U,
class = typename std::enable_if<
std::is_assignable<value_type,U&&>::value
>::type>
__AGENCY_ANNOTATION
boxed_value& operator=(U&& other)
{
value() = std::forward<U>(other);
return *this;
}
private:
__AGENCY_ANNOTATION
allocator_type& get_allocator()
{
return *this;
}
agency::detail::unique_ptr<T,agency::detail::deleter<allocator_type>> data_;
};
// when using the optimization, we put the object on the stack
template<class T, class Alloc>
class boxed_value<T,Alloc,true>
{
public:
using allocator_type = typename std::allocator_traits<Alloc>::template rebind_alloc<T>;
using value_type = typename allocator_type::value_type;
__AGENCY_ANNOTATION
boxed_value()
: boxed_value(value_type{})
{}
__AGENCY_ANNOTATION
boxed_value(const boxed_value& other)
: boxed_value(other.value())
{}
__AGENCY_ANNOTATION
boxed_value(boxed_value&& other)
: boxed_value(std::move(other.value_))
{}
template<class... Args,
class = typename std::enable_if<
std::is_constructible<T,Args&&...>::value
>::type>
__AGENCY_ANNOTATION
explicit boxed_value(Args&&... args)
: value_(std::forward<Args>(args)...)
{}
__AGENCY_ANNOTATION
value_type& value()
{
return value_;
}
__AGENCY_ANNOTATION
const value_type& value() const
{
return value_;
}
template<class U,
class = typename std::enable_if<
std::is_assignable<value_type,U&&>::value
>::type>
__AGENCY_ANNOTATION
boxed_value& operator=(U&& other)
{
value() = std::forward<U>(other);
return *this;
}
private:
value_type value_;
};
template<class T, class Alloc, class... Args>
__AGENCY_ANNOTATION
boxed_value<T,Alloc> allocate_boxed(const Alloc&, Args&&... args)
{
return boxed_value<T,Alloc>(std::forward<Args>(args)...);
}
} // end detail
} // end agency
<|endoftext|>
|
<commit_before>#include "VCardParser.h"
#include <assert.h>
#include <QIODevice>
#include <QByteArray>
#include <QDebug>
#include "Exceptions.h"
#include "Contact.h"
/** Provides the actual parsing implementation. */
class VCardParserImpl
{
public:
/** Creates a new parser instance and binds it to the specified data source and destination contact book. */
VCardParserImpl(QIODevice & a_Source, ContactBookPtr a_Dest):
m_Source(a_Source),
m_Dest(a_Dest),
m_State(psIdle),
m_CurrentLineNum(0)
{
}
/** Parses the source data from m_Source into the bound destination contact book m_Dest.
Throws an EException descendant on error. Note that m_Dest may still be filled with some contacts
that parsed successfully. */
void parse()
{
// Parse line-by-line, unwrap the lines here:
QByteArray acc; // Accumulator for the current line
while (!m_Source.atEnd())
{
QByteArray cur = m_Source.readLine();
if (
!cur.isEmpty() &&
(
(cur.at(0) == 0x20) || // Continuation by a SP
(cur.at(0) == 0x09) || // Continuation by a HT
!cur.contains(':') // Some bad serializers don't fold the lines properly, continuations are made without the leading space (LG G4)
)
)
{
// This was a folded line, append it to the accumulator:
cur.remove(0, 1);
acc.append(cur);
}
else
{
// This is a (start of a) new line, process the accumulator and store the new line in it:
if (!acc.isEmpty())
{
processLine(acc);
}
std::swap(acc, cur);
}
}
// Process the last line:
if (!acc.isEmpty())
{
processLine(acc);
}
}
protected:
/** The state of the outer state-machine, checking the sentences' sequencing (begin, version, <data>, end). */
enum State
{
psIdle, //< The parser has no current contact, it expects a new "BEGIN:VCARD" sentence
psBeginVCard, //< The parser has just read the "BEGIN:VCARD" line, expects a "VERSION" sentence
psContact, //< The parser is reading individual contact property sentence
} m_State;
/** The source data provider. */
QIODevice & m_Source;
/** The contact book into which the data is to be written. */
ContactBookPtr m_Dest;
/** The current contact being parsed.
Only valid in the psContact state. */
ContactPtr m_CurrentContact;
/** The number of the line currently being processed (for error reporting). */
int m_CurrentLineNum;
/** Parses the given single (unfolded) line. */
void processLine(const QByteArray & a_Line)
{
m_CurrentLineNum += 1;
if (a_Line.isEmpty() || (a_Line == "\n"))
{
return;
}
try
{
auto sentence = breakUpSentence(a_Line);
switch (m_State)
{
case psIdle: processSentenceIdle(sentence); break;
case psBeginVCard: processSentenceBeginVCard(sentence); break;
case psContact: processSentenceContact(sentence); break;
}
}
catch (const EParseError & exc)
{
qWarning() << QString::fromUtf8("Cannot parse VCARD, line %1: %2. The line contents: \"%3\"")
.arg(m_CurrentLineNum)
.arg(QString::fromStdString(exc.m_Message))
.arg(QString::fromStdString(a_Line.toStdString()));
throw;
}
}
/** Breaks the specified single (unfolded) line into the contact sentence representation. */
Contact::Sentence breakUpSentence(const QByteArray & a_Line)
{
Contact::Sentence res;
// The state of the inner state-machine, parsing a single sentence.
// Each sentence has a basic structure of "[group.]key[;param1;param2]=value"
enum
{
ssBegin, //< The parser is reading the beginning of the sentence (group or key)
ssKey, //< The parser is reading the key (the group was present)
ssParamName, //< The parser is reading the param name
ssParamValue, //< The parser is reading the param value
ssParamValueDQuote, //< The parser is reading the param value and is inside a dquote
ssParamValueEnd, //< The parser has just finished the DQuote of a param value
} sentenceState = ssBegin;
auto len = a_Line.length();
assert(len > 0);
if (a_Line.at(len - 1) == '\n')
{
assert(len > 1);
len -= 1;
}
int last = 0;
QByteArray currentParamName, currentParamValue;
for (auto i = 0; i < len; ++i)
{
auto ch = a_Line.at(i);
switch (sentenceState)
{
case ssBegin:
{
if (ch == '.')
{
res.m_Group = a_Line.mid(0, i - 1);
last = i + 1;
sentenceState = ssKey;
continue;
}
// fallthrough
} // case ssBegin
case ssKey:
{
if (ch == ';')
{
if (last == i)
{
throw EParseError(__FILE__, __LINE__, "An empty key is not allowed");
}
res.m_Key = a_Line.mid(last, i - last).toLower();
last = i + 1;
sentenceState = ssParamName;
continue;
}
if (ch == ':')
{
if (last == i)
{
throw EParseError(__FILE__, __LINE__, "An empty key is not allowed");
}
res.m_Key = a_Line.mid(last, i - last).toLower();
res.m_Value = a_Line.mid(i + 1, len - i - 1);
return res;
}
if (ch == '.')
{
throw EParseError(__FILE__, __LINE__, "A group has already been parsed, cannot add another one.");
}
break;
} // case ssKey
case ssParamName:
{
if (ch == '=')
{
if (i == last)
{
throw EParseError(__FILE__, __LINE__, "A parameter with no name is not allowed");
}
currentParamName = a_Line.mid(last, i - last).toLower();
last = i + 1;
currentParamValue.clear();
sentenceState = ssParamValue;
continue;
}
if (ch == ';')
{
// Value-less parameter with another parameter following ("TEL;CELL;OTHER:...")
res.m_Params.emplace_back(currentParamName, QByteArray());
last = i + 1;
currentParamValue.clear();
continue;
}
if (ch == ':')
{
// Value-less parameter ending the params ("TEL;CELL:...")
res.m_Params.emplace_back(currentParamName, QByteArray());
last = i + 1;
last = i + 1;
res.m_Value = a_Line.mid(i + 1, len - i - 1);
return res;
}
break;
} // case ssParamName
case ssParamValue:
{
if (ch == '"')
{
if (i > last)
{
throw EParseError(__FILE__, __LINE__, "Param value double-quoting is wrong");
}
last = i + 1;
}
if (ch == ',')
{
res.m_Params.emplace_back(currentParamName, a_Line.mid(last, i - last));
last = i + 1;
continue;
}
if (ch == ':')
{
res.m_Params.emplace_back(currentParamName, a_Line.mid(last, i - last));
last = i + 1;
res.m_Value = a_Line.mid(i + 1, len - i - 1);
return res;
}
break;
} // case ssParamValue
case ssParamValueDQuote:
{
if (ch == '"')
{
res.m_Params.emplace_back(currentParamName, std::move(currentParamValue));
last = i + 1;
sentenceState = ssParamValueEnd;
continue;
}
if (ch == '\\')
{
// Skip the escape
continue;
}
else
{
currentParamValue.append(ch);
}
break;
} // case ssParamValueDQuote
case ssParamValueEnd:
{
if (ch == ',')
{
last = i + 1;
currentParamValue.clear();
sentenceState = ssParamValue;
}
if (ch == ':')
{
res.m_Params.emplace_back(currentParamName, a_Line.mid(last, i - last));
last = i + 1;
res.m_Value = a_Line.mid(i + 1, len - i - 1);
return res;
}
throw EParseError(__FILE__, __LINE__, "An extra character following a param value double-quote");
} // case ssParamValueEnd
}
} // for i - a_Line[]
throw EParseError(__FILE__, __LINE__, "Incomplete sentence");
}
/** Processes the given sentence in the psIdle parser state. */
void processSentenceIdle(const Contact::Sentence & a_Sentence)
{
// The only valid line in this context is the "BEGIN:VCARD" line.
// Any other line will cause an error throw
if (
!a_Sentence.m_Group.isEmpty()
)
{
throw EParseError(__FILE__, __LINE__, "Expected a BEGIN:VCARD sentence, got a different sentence");
}
m_State = psBeginVCard;
}
/** Parses the given single sentence in the psBeginVCard parser state. */
void processSentenceBeginVCard(const Contact::Sentence & a_Sentence)
{
// The only valid sentence in this context is the "VERSION:X" line.
if (
!a_Sentence.m_Group.isEmpty() ||
(a_Sentence.m_Key != "version") ||
!a_Sentence.m_Params.empty()
)
{
throw EParseError(__FILE__, __LINE__, "Expected a VERSION sentence, got a different sentence");
}
if (a_Sentence.m_Value.toFloat() == 0)
{
throw EParseError(__FILE__, __LINE__, "The VERSION sentence has an invalid value.");
}
m_CurrentContact.reset(new Contact);
m_State = psContact;
}
/** Parses the given single (unfolded) line in the psContact parser state. */
void processSentenceContact(const Contact::Sentence & a_Sentence)
{
// If the sentence is "END:VCARD", terminate the current contact:
if (
a_Sentence.m_Group.isEmpty() &&
(a_Sentence.m_Key == "end") &&
a_Sentence.m_Params.empty() &&
(a_Sentence.m_Value.toLower() == "vcard")
)
{
if (m_CurrentContact != nullptr)
{
m_Dest->addContact(m_CurrentContact);
}
m_CurrentContact.reset();
m_State = psIdle;
return;
}
// Add the sentence to the current contact:
m_CurrentContact->addSentence(a_Sentence);
}
};
void VCardParser::parse(QIODevice & a_Source, ContactBookPtr a_Dest)
{
VCardParserImpl impl(a_Source, a_Dest);
impl.parse();
}
std::vector<std::vector<QByteArray>> VCardParser::breakValueIntoComponents(const QByteArray & a_Value)
{
std::vector<std::vector<QByteArray>> res;
res.push_back({});
auto * curComponent = &res.back();
curComponent->push_back({});
auto * curValue = &curComponent->back();
auto len = a_Value.length();
for (int i = 0; i < len; ++i)
{
auto ch = a_Value.at(i);
switch (ch)
{
case ';':
{
// Start a new component:
res.push_back({});
curComponent = &res.back();
curComponent->push_back({});
curValue = &curComponent->back();
break;
} // case ';'
case ',':
{
// Start a new value:
curComponent->push_back({});
curValue = &curComponent->back();
break;
}
case '\\':
{
// Skip the escape char and push the next char directly into the current value:
i = 1 + 1;
curValue->append(a_Value.at(i));
break;
}
default:
{
curValue->append(ch);
break;
}
} // switch (ch)
} // for i - a_Value[]
return res;
}
<commit_msg>Fixed Linux compilation warnings.<commit_after>#include "VCardParser.h"
#include <assert.h>
#include <QIODevice>
#include <QByteArray>
#include <QDebug>
#include "Exceptions.h"
#include "Contact.h"
/** Provides the actual parsing implementation. */
class VCardParserImpl
{
public:
/** Creates a new parser instance and binds it to the specified data source and destination contact book. */
VCardParserImpl(QIODevice & a_Source, ContactBookPtr a_Dest):
m_State(psIdle),
m_Source(a_Source),
m_Dest(a_Dest),
m_CurrentLineNum(0)
{
}
/** Parses the source data from m_Source into the bound destination contact book m_Dest.
Throws an EException descendant on error. Note that m_Dest may still be filled with some contacts
that parsed successfully. */
void parse()
{
// Parse line-by-line, unwrap the lines here:
QByteArray acc; // Accumulator for the current line
while (!m_Source.atEnd())
{
QByteArray cur = m_Source.readLine();
if (
!cur.isEmpty() &&
(
(cur.at(0) == 0x20) || // Continuation by a SP
(cur.at(0) == 0x09) || // Continuation by a HT
!cur.contains(':') // Some bad serializers don't fold the lines properly, continuations are made without the leading space (LG G4)
)
)
{
// This was a folded line, append it to the accumulator:
cur.remove(0, 1);
acc.append(cur);
}
else
{
// This is a (start of a) new line, process the accumulator and store the new line in it:
if (!acc.isEmpty())
{
processLine(acc);
}
std::swap(acc, cur);
}
}
// Process the last line:
if (!acc.isEmpty())
{
processLine(acc);
}
}
protected:
/** The state of the outer state-machine, checking the sentences' sequencing (begin, version, <data>, end). */
enum State
{
psIdle, //< The parser has no current contact, it expects a new "BEGIN:VCARD" sentence
psBeginVCard, //< The parser has just read the "BEGIN:VCARD" line, expects a "VERSION" sentence
psContact, //< The parser is reading individual contact property sentence
} m_State;
/** The source data provider. */
QIODevice & m_Source;
/** The contact book into which the data is to be written. */
ContactBookPtr m_Dest;
/** The current contact being parsed.
Only valid in the psContact state. */
ContactPtr m_CurrentContact;
/** The number of the line currently being processed (for error reporting). */
int m_CurrentLineNum;
/** Parses the given single (unfolded) line. */
void processLine(const QByteArray & a_Line)
{
m_CurrentLineNum += 1;
if (a_Line.isEmpty() || (a_Line == "\n"))
{
return;
}
try
{
auto sentence = breakUpSentence(a_Line);
switch (m_State)
{
case psIdle: processSentenceIdle(sentence); break;
case psBeginVCard: processSentenceBeginVCard(sentence); break;
case psContact: processSentenceContact(sentence); break;
}
}
catch (const EParseError & exc)
{
qWarning() << QString::fromUtf8("Cannot parse VCARD, line %1: %2. The line contents: \"%3\"")
.arg(m_CurrentLineNum)
.arg(QString::fromStdString(exc.m_Message))
.arg(QString::fromUtf8(a_Line));
throw;
}
}
/** Breaks the specified single (unfolded) line into the contact sentence representation. */
Contact::Sentence breakUpSentence(const QByteArray & a_Line)
{
Contact::Sentence res;
// The state of the inner state-machine, parsing a single sentence.
// Each sentence has a basic structure of "[group.]key[;param1;param2]=value"
enum
{
ssBegin, //< The parser is reading the beginning of the sentence (group or key)
ssKey, //< The parser is reading the key (the group was present)
ssParamName, //< The parser is reading the param name
ssParamValue, //< The parser is reading the param value
ssParamValueDQuote, //< The parser is reading the param value and is inside a dquote
ssParamValueEnd, //< The parser has just finished the DQuote of a param value
} sentenceState = ssBegin;
auto len = a_Line.length();
assert(len > 0);
if (a_Line.at(len - 1) == '\n')
{
assert(len > 1);
len -= 1;
}
int last = 0;
QByteArray currentParamName, currentParamValue;
for (auto i = 0; i < len; ++i)
{
auto ch = a_Line.at(i);
switch (sentenceState)
{
case ssBegin:
{
if (ch == '.')
{
res.m_Group = a_Line.mid(0, i - 1);
last = i + 1;
sentenceState = ssKey;
continue;
}
// fallthrough
} // case ssBegin
case ssKey:
{
if (ch == ';')
{
if (last == i)
{
throw EParseError(__FILE__, __LINE__, "An empty key is not allowed");
}
res.m_Key = a_Line.mid(last, i - last).toLower();
last = i + 1;
sentenceState = ssParamName;
continue;
}
if (ch == ':')
{
if (last == i)
{
throw EParseError(__FILE__, __LINE__, "An empty key is not allowed");
}
res.m_Key = a_Line.mid(last, i - last).toLower();
res.m_Value = a_Line.mid(i + 1, len - i - 1);
return res;
}
if (ch == '.')
{
throw EParseError(__FILE__, __LINE__, "A group has already been parsed, cannot add another one.");
}
break;
} // case ssKey
case ssParamName:
{
if (ch == '=')
{
if (i == last)
{
throw EParseError(__FILE__, __LINE__, "A parameter with no name is not allowed");
}
currentParamName = a_Line.mid(last, i - last).toLower();
last = i + 1;
currentParamValue.clear();
sentenceState = ssParamValue;
continue;
}
if (ch == ';')
{
// Value-less parameter with another parameter following ("TEL;CELL;OTHER:...")
res.m_Params.emplace_back(currentParamName, QByteArray());
last = i + 1;
currentParamValue.clear();
continue;
}
if (ch == ':')
{
// Value-less parameter ending the params ("TEL;CELL:...")
res.m_Params.emplace_back(currentParamName, QByteArray());
last = i + 1;
last = i + 1;
res.m_Value = a_Line.mid(i + 1, len - i - 1);
return res;
}
break;
} // case ssParamName
case ssParamValue:
{
if (ch == '"')
{
if (i > last)
{
throw EParseError(__FILE__, __LINE__, "Param value double-quoting is wrong");
}
last = i + 1;
}
if (ch == ',')
{
res.m_Params.emplace_back(currentParamName, a_Line.mid(last, i - last));
last = i + 1;
continue;
}
if (ch == ':')
{
res.m_Params.emplace_back(currentParamName, a_Line.mid(last, i - last));
last = i + 1;
res.m_Value = a_Line.mid(i + 1, len - i - 1);
return res;
}
break;
} // case ssParamValue
case ssParamValueDQuote:
{
if (ch == '"')
{
res.m_Params.emplace_back(currentParamName, std::move(currentParamValue));
last = i + 1;
sentenceState = ssParamValueEnd;
continue;
}
if (ch == '\\')
{
// Skip the escape
continue;
}
else
{
currentParamValue.append(ch);
}
break;
} // case ssParamValueDQuote
case ssParamValueEnd:
{
if (ch == ',')
{
last = i + 1;
currentParamValue.clear();
sentenceState = ssParamValue;
}
if (ch == ':')
{
res.m_Params.emplace_back(currentParamName, a_Line.mid(last, i - last));
last = i + 1;
res.m_Value = a_Line.mid(i + 1, len - i - 1);
return res;
}
throw EParseError(__FILE__, __LINE__, "An extra character following a param value double-quote");
} // case ssParamValueEnd
}
} // for i - a_Line[]
throw EParseError(__FILE__, __LINE__, "Incomplete sentence");
}
/** Processes the given sentence in the psIdle parser state. */
void processSentenceIdle(const Contact::Sentence & a_Sentence)
{
// The only valid line in this context is the "BEGIN:VCARD" line.
// Any other line will cause an error throw
if (
!a_Sentence.m_Group.isEmpty()
)
{
throw EParseError(__FILE__, __LINE__, "Expected a BEGIN:VCARD sentence, got a different sentence");
}
m_State = psBeginVCard;
}
/** Parses the given single sentence in the psBeginVCard parser state. */
void processSentenceBeginVCard(const Contact::Sentence & a_Sentence)
{
// The only valid sentence in this context is the "VERSION:X" line.
if (
!a_Sentence.m_Group.isEmpty() ||
(a_Sentence.m_Key != "version") ||
!a_Sentence.m_Params.empty()
)
{
throw EParseError(__FILE__, __LINE__, "Expected a VERSION sentence, got a different sentence");
}
if (a_Sentence.m_Value.toFloat() == 0)
{
throw EParseError(__FILE__, __LINE__, "The VERSION sentence has an invalid value.");
}
m_CurrentContact.reset(new Contact);
m_State = psContact;
}
/** Parses the given single (unfolded) line in the psContact parser state. */
void processSentenceContact(const Contact::Sentence & a_Sentence)
{
// If the sentence is "END:VCARD", terminate the current contact:
if (
a_Sentence.m_Group.isEmpty() &&
(a_Sentence.m_Key == "end") &&
a_Sentence.m_Params.empty() &&
(a_Sentence.m_Value.toLower() == "vcard")
)
{
if (m_CurrentContact != nullptr)
{
m_Dest->addContact(m_CurrentContact);
}
m_CurrentContact.reset();
m_State = psIdle;
return;
}
// Add the sentence to the current contact:
m_CurrentContact->addSentence(a_Sentence);
}
};
void VCardParser::parse(QIODevice & a_Source, ContactBookPtr a_Dest)
{
VCardParserImpl impl(a_Source, a_Dest);
impl.parse();
}
std::vector<std::vector<QByteArray>> VCardParser::breakValueIntoComponents(const QByteArray & a_Value)
{
std::vector<std::vector<QByteArray>> res;
res.push_back({});
auto * curComponent = &res.back();
curComponent->push_back({});
auto * curValue = &curComponent->back();
auto len = a_Value.length();
for (int i = 0; i < len; ++i)
{
auto ch = a_Value.at(i);
switch (ch)
{
case ';':
{
// Start a new component:
res.push_back({});
curComponent = &res.back();
curComponent->push_back({});
curValue = &curComponent->back();
break;
} // case ';'
case ',':
{
// Start a new value:
curComponent->push_back({});
curValue = &curComponent->back();
break;
}
case '\\':
{
// Skip the escape char and push the next char directly into the current value:
i = 1 + 1;
curValue->append(a_Value.at(i));
break;
}
default:
{
curValue->append(ch);
break;
}
} // switch (ch)
} // for i - a_Value[]
return res;
}
<|endoftext|>
|
<commit_before>//=============================================================================
// ■ VMDE/global.hpp
//-----------------------------------------------------------------------------
// 在VMDE的内部,包容一切的头。
// 关于只有一个头:
// 我完全无法理解为什么C要采用有头文件的设计。当然这很可能是历史遗留问题,
// 但这导致了C程序员总是需要花费大量时间整理头文件,且这时间花得莫名其妙。
// 而这在其他任何语系中都不是问题:即使是采用C语法的衍生语言,也不会保留
// 这个“特性”。因此我们需要解决它。
// 采用#include管理多文件编译是最好的解决方案。在现今编译单个文件的速度有极
// 大提升的时代,一个个编译小文件却慢得多。然而这个解决方案并不能在像VMDE这
// 样的合作项目中进行,因为它会让很多已建立的条件反射、编译器、IDE日狗。
// 单一头文件也是一个可行的方案。它保留了头文件,但只有一个——这意味着所有
// 你需要编辑的头都在固定的位置,给身体和手带来了放松的空间,同时也保证编辑
// 器的标签栏(如果有的话)不会因为头文件而缩小为原来的一半。
// 当然,还有一个解决办法就是只用一个.c文件。结果:从此这个项目就没落了。
// 综上所述,我选择狗带,砍了其他所有头。
//=============================================================================
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <math.h>
#include <ctime>
#include <thread>
#include <cstdarg>
#include <cassert>
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <SOIL.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <portaudio.h>
#include <vorbis/vorbisfile.h>
#ifndef _INCLUDE_GLOBAL_H
#define _INCLUDE_GLOBAL_H
using namespace std;
//-------------------------------------------------------------------------
// ● PY Deal For MICR0$○F┬ Windoges (ᴚ)
//Becuase it;s Windoges,I jsut dno't want to use CORERCT ENGRISh &忠闻吔屎炉此
//-------------------------------------------------------------------------
#ifdef __MINGW32__
#define EXPORTED extern "C" __declspec(dllexport)
#else
#define EXPORTED extern "C"
#endif
#ifdef __CYGWIN__
#warning This will not work in Cygwin. Try at your own risk.
#endif
//-------------------------------------------------------------------------
// ● 定义宏魔法
//-------------------------------------------------------------------------
// NDEBUG - 给assert用的,虽然好像这项目里没人用assert
// 这个DEBUG在make的时候加(make debug)。
#ifdef DEBUG
#define NDEBUG
#else
#undef NDEBUG
#endif
// ARRAY_SIZE - 获取定义的数组大小
// int a[56]; → ARRAY_SIZE(a) == 56
#define ARRAY_SIZE(a) (sizeof(a) / sizeof(*(a)))
// MLVN - Macro-Local Variable Name
// 这是为了不让明文变量名被莫名其妙使用而设计的。
// #define TEST do { int MLVN() = 0, MLVN(another) = 0; } while(0)
#define MLVN(name) My_Lovely_##name##___
// NTIMES - 执行多次
// NTIMES(3) puts("Three or more, use a for");
#define NTIMES(n) \
for (unsigned short MLVN(index) = 0; MLVN(index) < (n); MLVN(index)++)
// TWICE - 执行两次
// TWICE a++;
// TWICE { a++; b++; }
#define TWICE NTIMES(2)
// XE - 释放内存黑魔法
// “X掉Exceptions”!
// void* m;
// m = malloc(1); xe(free, m);
// m = (void*) 0; xe(free, m);
// m = new float; xe(delete, m);
// m = new tm[4]; xe(delete[], m);
#define XE(method, pointer) do { \
if (pointer) { \
method(pointer); \
(pointer) = NULL; \
} \
} while (false)
// VMDE_Dispose - 一键销毁宏魔法
#define VMDE_Dispose(method, object) do { \
if (object) { \
method(object); \
(object) = NULL; \
} \
} while (false)
// DEBUG_ENVIRONMENT - 调试环境
// 这个字符串会显示在log函数输出的开头。
#define DEBUG_ENVIRONMENT "VMDE"
// log - Util::log_internal的方便缩写,可以直接得到当前函数名
// log("%p", log);
#define log(...) Util::log_internal(DEBUG_ENVIRONMENT, __func__, __VA_ARGS__)
// mark - 逐行打log的偷懒大法
#define mark log("Mark on line %d of %s", __LINE__, __FILE__)
// error_internal
#define error_internal(extra, ...) do { \
log(__VA_ARGS__); \
extra \
exit(1); \
} while (false)
// error - 抛出错误并终止程序
#define error(...) error_internal(, __VA_ARGS__)
// errorp - error + perror
#define errorp(...) error_internal(perror("perror()"), __VA_ARGS__)
//-------------------------------------------------------------------------
// ● util.cpp
// 这个Util的意义已经远超utility。
//-------------------------------------------------------------------------
namespace Util {
extern FILE* log_file;
void init();
void terminate();
void log_internal(const char*, const char*, const char*, ...)
__attribute__((format(printf, 3, 4)));
char* read_file(const char* filename);
}
//-------------------------------------------------------------------------
// ● 子文件夹中的头文件
//-------------------------------------------------------------------------
#include "VLib/V.hpp"
#include "Audio/audio.hpp"
//-------------------------------------------------------------------------
// ● init.cpp
//-------------------------------------------------------------------------
EXPORTED void init_engine(int w, int h, const char* title);
void setup_viewport();
void init_vmde(int w, int h);
void check_gl_error();
//-------------------------------------------------------------------------
// ● terminate.cpp
//-------------------------------------------------------------------------
EXPORTED void terminate_engine();
//-------------------------------------------------------------------------
// ● main.cpp
//-------------------------------------------------------------------------
void glfw_error_callback(int error, const char* description);
void main_draw_start();
void main_draw_end();
void main_set_brightness(float b);
extern glm::mat4 projection, view;
//-------------------------------------------------------------------------
// ● RenderObject.cpp
//-------------------------------------------------------------------------
class Object {
public:
virtual ~Object();
};
class RenderObject : public Object {
public:
virtual void render() = 0;
};
//-------------------------------------------------------------------------
// ● resources.cpp
//-------------------------------------------------------------------------
namespace Res {
struct TextureParameters {
GLuint WRAP_MODE_S, WRAP_MODE_T;
GLuint MIN_FILTER, MAG_FILTER;
GLuint MIPMAP_LEVEL;
GLuint PixelFormat, PixelType;
};
extern struct TextureParameters DefaultTextureParameters;
extern struct TextureParameters LinearTextureParameters;
class Texture : public Object {
public:
GLuint texture, index;
int width, height;
struct TextureParameters* parameter;
Texture();
Texture(const char* file);
Texture(const char* file, struct TextureParameters* p);
~Texture();
};
}
//-------------------------------------------------------------------------
// ● shaders.cpp
//-------------------------------------------------------------------------
class Shaders : public Object {
public:
#define SHADERS_SLOT_COUNT 16
GLuint shaders[SHADERS_SLOT_COUNT];
size_t shader_count = 0;
GLuint program;
GLuint UBO_matrix;
glm::mat4 mat[3];
public:
Shaders();
void add_string(GLenum type, const GLchar* source);
void add_file(GLenum type, const char* filename);
void link_program();
void use();
void set_float(const char* identifier, GLfloat value);
void set_int(const char* identifier, GLint value);
void set_texture(const char* identifier, Res::Texture* tex, GLuint index);
void ProjectionView(glm::mat4 projection, glm::mat4 view);
~Shaders();
private:
static void check_shader_compilation(
GLuint shader,
const char* msg = "shader compile error"
);
static void check_linkage(
GLuint program,
const char* msg = "link error"
);
};
extern Shaders* _shaders_in_use;
//-------------------------------------------------------------------------
// ● VMDE
//-------------------------------------------------------------------------
struct VMDEState {
bool frozen;
float brightness;
};
enum GL_VER {
GL_33,
GL_43,
VULKAN // Not used
};
struct VMDE {
VMDEState state;
long frame_count;
long millisecond;
int width, height;
int fps;
double frame_time;
bool done;
int gl_ver;
};
// VMDE操控的全局变量
extern struct VMDE* VMDE;
extern GLFWwindow* window;
//-------------------------------------------------------------------------
// ● State Control
//-------------------------------------------------------------------------
// 在OpenGL状态机外层再加一个状态管理机制,减少不必要的状态切换和不必要的draw call
// 这样的一个状态机设计也可以更好地隔离API,为以后Vulkan做准备
class VMStateControl {
static struct StateMachineStruct {
GLuint VERTEX_ARRAY;
GLuint ELEMENT_ARRAY_BUFFER;
GLuint ARRAY_BUFFER;
GLuint TEXTURE_2D;
GLuint UNIFORM_BUFFER;
GLuint Shader_Program;
bool TextureActivated[32]; // 32 for GL 3.X+, should be enough
bool DEPTH_TEST;
bool CULL_FACE;
bool BLEND;
GLuint PolygonMode;
} StateMachine;
public:
static void ChangeVertexArray (GLuint index);
static void ChangeElementArrayBuffer (GLuint index);
static void ChangeArrayBuffer (GLuint index);
static void ChangeTexture2D (GLuint index);
static void ChangeUniformBuffer (GLuint index);
static void ChangeShaderProgram (GLuint index);
static void enable_cullface();
static void disable_cullface();
static void enable_depth_test();
static void disable_depth_test();
static void enable_blend();
static void disable_blend();
static void render_mode_wireframe();
static void render_mode_fill();
static void init_graphics_state ();
};
#define VMSC VMStateControl // 少写几个字
//-------------------------------------------------------------------------
// ● GDrawable
//-------------------------------------------------------------------------
struct Vertex {
glm::vec3 world_position;
glm::vec4 color;
glm::vec2 st;
glm::vec3 normal;
};
class GDrawable : public RenderObject {
public:
struct Data {
Vertex* vertices;
int vtx_c;
GLuint* indices;
int ind_c;
GLuint* mat;
int mat_c;
GLuint MBO;
GLuint VAO;
GLuint VBO;
GLuint EBO;
glm::mat4 model;
} data;
void renderOnce();
void render();
void fbind();
void update();
void update_instance();
void update_instance_alien_size();
static inline void close_draw_node() { VMStateControl::ChangeVertexArray(0); }
~GDrawable();
GDrawable();
};
//-------------------------------------------------------------------------
// ● Text
//-------------------------------------------------------------------------
class TextRenderer : public RenderObject {
private:
GDrawable obj;
Res::Texture tex = Res::Texture("../Media/Font.bmp", &Res::LinearTextureParameters);
Shaders texshader;
public:
enum TextDecorationType {
NONE,
SHADOW,
OUTLINE,
};
TextRenderer();
void BakeText(
const char* text,
float width, float height,
TextDecorationType decoration
);
void render();
void instanceRenderText(
const char* text,
glm::mat4 projection, glm::mat4 view, glm::mat4 transform,
float width, float height, TextDecorationType decoration
);
};
//-------------------------------------------------------------------------
// ● RenderBuffer
//-------------------------------------------------------------------------
class RenderBuffer : public Object {
public:
GLuint framebuffer;
GLuint rbo;
Res::Texture** texture_buffer;
int mrtcount;
//void resize(int w, int h);
void bind();
static void unbind();
static void clearColor(float r, float g, float b, float a);
static void clearColorDepth(float r, float g, float b, float a);
static void clearDepth();
RenderBuffer(int w, int h, int mrt, const GLuint* type);
void set_draw_buffers();
~RenderBuffer();
};
class PostProcessingManager : public Object {
private:
static GDrawable* QuadScreen;
public:
static void init();
static void Blit2D();
};
#endif
<commit_msg>Fix macro errorp<commit_after>//=============================================================================
// ■ VMDE/global.hpp
//-----------------------------------------------------------------------------
// 在VMDE的内部,包容一切的头。
// 关于只有一个头:
// 我完全无法理解为什么C要采用有头文件的设计。当然这很可能是历史遗留问题,
// 但这导致了C程序员总是需要花费大量时间整理头文件,且这时间花得莫名其妙。
// 而这在其他任何语系中都不是问题:即使是采用C语法的衍生语言,也不会保留
// 这个“特性”。因此我们需要解决它。
// 采用#include管理多文件编译是最好的解决方案。在现今编译单个文件的速度有极
// 大提升的时代,一个个编译小文件却慢得多。然而这个解决方案并不能在像VMDE这
// 样的合作项目中进行,因为它会让很多已建立的条件反射、编译器、IDE日狗。
// 单一头文件也是一个可行的方案。它保留了头文件,但只有一个——这意味着所有
// 你需要编辑的头都在固定的位置,给身体和手带来了放松的空间,同时也保证编辑
// 器的标签栏(如果有的话)不会因为头文件而缩小为原来的一半。
// 当然,还有一个解决办法就是只用一个.c文件。结果:从此这个项目就没落了。
// 综上所述,我选择狗带,砍了其他所有头。
//=============================================================================
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <math.h>
#include <ctime>
#include <thread>
#include <cstdarg>
#include <cassert>
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <SOIL.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <portaudio.h>
#include <vorbis/vorbisfile.h>
#ifndef _INCLUDE_GLOBAL_H
#define _INCLUDE_GLOBAL_H
using namespace std;
//-------------------------------------------------------------------------
// ● PY Deal For MICR0$○F┬ Windoges (ᴚ)
//Becuase it;s Windoges,I jsut dno't want to use CORERCT ENGRISh &忠闻吔屎炉此
//-------------------------------------------------------------------------
#ifdef __MINGW32__
#define EXPORTED extern "C" __declspec(dllexport)
#else
#define EXPORTED extern "C"
#endif
#ifdef __CYGWIN__
#warning This will not work in Cygwin. Try at your own risk.
#endif
//-------------------------------------------------------------------------
// ● 定义宏魔法
//-------------------------------------------------------------------------
// NDEBUG - 给assert用的,虽然好像这项目里没人用assert
// 这个DEBUG在make的时候加(make debug)。
#ifdef DEBUG
#define NDEBUG
#else
#undef NDEBUG
#endif
// ARRAY_SIZE - 获取定义的数组大小
// int a[56]; → ARRAY_SIZE(a) == 56
#define ARRAY_SIZE(a) (sizeof(a) / sizeof(*(a)))
// MLVN - Macro-Local Variable Name
// 这是为了不让明文变量名被莫名其妙使用而设计的。
// #define TEST do { int MLVN() = 0, MLVN(another) = 0; } while(0)
#define MLVN(name) My_Lovely_##name##___
// NTIMES - 执行多次
// NTIMES(3) puts("Three or more, use a for");
#define NTIMES(n) \
for (unsigned short MLVN(index) = 0; MLVN(index) < (n); MLVN(index)++)
// TWICE - 执行两次
// TWICE a++;
// TWICE { a++; b++; }
#define TWICE NTIMES(2)
// XE - 释放内存黑魔法
// “X掉Exceptions”!
// void* m;
// m = malloc(1); xe(free, m);
// m = (void*) 0; xe(free, m);
// m = new float; xe(delete, m);
// m = new tm[4]; xe(delete[], m);
#define XE(method, pointer) do { \
if (pointer) { \
method(pointer); \
(pointer) = NULL; \
} \
} while (false)
// VMDE_Dispose - 一键销毁宏魔法
#define VMDE_Dispose(method, object) do { \
if (object) { \
method(object); \
(object) = NULL; \
} \
} while (false)
// DEBUG_ENVIRONMENT - 调试环境
// 这个字符串会显示在log函数输出的开头。
#define DEBUG_ENVIRONMENT "VMDE"
// log - Util::log_internal的方便缩写,可以直接得到当前函数名
// log("%p", log);
#define log(...) Util::log_internal(DEBUG_ENVIRONMENT, __func__, __VA_ARGS__)
// mark - 逐行打log的偷懒大法
#define mark log("Mark on line %d of %s", __LINE__, __FILE__)
// error_internal
#define error_internal(extra, ...) do { \
log(__VA_ARGS__); \
extra \
exit(1); \
} while (false)
// error - 抛出错误并终止程序
#define error(...) error_internal(, __VA_ARGS__)
// errorp - error + perror
#define errorp(...) error_internal(perror("perror()");, __VA_ARGS__)
//-------------------------------------------------------------------------
// ● util.cpp
// 这个Util的意义已经远超utility。
//-------------------------------------------------------------------------
namespace Util {
extern FILE* log_file;
void init();
void terminate();
void log_internal(const char*, const char*, const char*, ...)
__attribute__((format(printf, 3, 4)));
char* read_file(const char* filename);
}
//-------------------------------------------------------------------------
// ● 子文件夹中的头文件
//-------------------------------------------------------------------------
#include "VLib/V.hpp"
#include "Audio/audio.hpp"
//-------------------------------------------------------------------------
// ● init.cpp
//-------------------------------------------------------------------------
EXPORTED void init_engine(int w, int h, const char* title);
void setup_viewport();
void init_vmde(int w, int h);
void check_gl_error();
//-------------------------------------------------------------------------
// ● terminate.cpp
//-------------------------------------------------------------------------
EXPORTED void terminate_engine();
//-------------------------------------------------------------------------
// ● main.cpp
//-------------------------------------------------------------------------
void glfw_error_callback(int error, const char* description);
void main_draw_start();
void main_draw_end();
void main_set_brightness(float b);
extern glm::mat4 projection, view;
//-------------------------------------------------------------------------
// ● RenderObject.cpp
//-------------------------------------------------------------------------
class Object {
public:
virtual ~Object();
};
class RenderObject : public Object {
public:
virtual void render() = 0;
};
//-------------------------------------------------------------------------
// ● resources.cpp
//-------------------------------------------------------------------------
namespace Res {
struct TextureParameters {
GLuint WRAP_MODE_S, WRAP_MODE_T;
GLuint MIN_FILTER, MAG_FILTER;
GLuint MIPMAP_LEVEL;
GLuint PixelFormat, PixelType;
};
extern struct TextureParameters DefaultTextureParameters;
extern struct TextureParameters LinearTextureParameters;
class Texture : public Object {
public:
GLuint texture, index;
int width, height;
struct TextureParameters* parameter;
Texture();
Texture(const char* file);
Texture(const char* file, struct TextureParameters* p);
~Texture();
};
}
//-------------------------------------------------------------------------
// ● shaders.cpp
//-------------------------------------------------------------------------
class Shaders : public Object {
public:
#define SHADERS_SLOT_COUNT 16
GLuint shaders[SHADERS_SLOT_COUNT];
size_t shader_count = 0;
GLuint program;
GLuint UBO_matrix;
glm::mat4 mat[3];
public:
Shaders();
void add_string(GLenum type, const GLchar* source);
void add_file(GLenum type, const char* filename);
void link_program();
void use();
void set_float(const char* identifier, GLfloat value);
void set_int(const char* identifier, GLint value);
void set_texture(const char* identifier, Res::Texture* tex, GLuint index);
void ProjectionView(glm::mat4 projection, glm::mat4 view);
~Shaders();
private:
static void check_shader_compilation(
GLuint shader,
const char* msg = "shader compile error"
);
static void check_linkage(
GLuint program,
const char* msg = "link error"
);
};
extern Shaders* _shaders_in_use;
//-------------------------------------------------------------------------
// ● VMDE
//-------------------------------------------------------------------------
struct VMDEState {
bool frozen;
float brightness;
};
enum GL_VER {
GL_33,
GL_43,
VULKAN // Not used
};
struct VMDE {
VMDEState state;
long frame_count;
long millisecond;
int width, height;
int fps;
double frame_time;
bool done;
int gl_ver;
};
// VMDE操控的全局变量
extern struct VMDE* VMDE;
extern GLFWwindow* window;
//-------------------------------------------------------------------------
// ● State Control
//-------------------------------------------------------------------------
// 在OpenGL状态机外层再加一个状态管理机制,减少不必要的状态切换和不必要的draw call
// 这样的一个状态机设计也可以更好地隔离API,为以后Vulkan做准备
class VMStateControl {
static struct StateMachineStruct {
GLuint VERTEX_ARRAY;
GLuint ELEMENT_ARRAY_BUFFER;
GLuint ARRAY_BUFFER;
GLuint TEXTURE_2D;
GLuint UNIFORM_BUFFER;
GLuint Shader_Program;
bool TextureActivated[32]; // 32 for GL 3.X+, should be enough
bool DEPTH_TEST;
bool CULL_FACE;
bool BLEND;
GLuint PolygonMode;
} StateMachine;
public:
static void ChangeVertexArray (GLuint index);
static void ChangeElementArrayBuffer (GLuint index);
static void ChangeArrayBuffer (GLuint index);
static void ChangeTexture2D (GLuint index);
static void ChangeUniformBuffer (GLuint index);
static void ChangeShaderProgram (GLuint index);
static void enable_cullface();
static void disable_cullface();
static void enable_depth_test();
static void disable_depth_test();
static void enable_blend();
static void disable_blend();
static void render_mode_wireframe();
static void render_mode_fill();
static void init_graphics_state ();
};
#define VMSC VMStateControl // 少写几个字
//-------------------------------------------------------------------------
// ● GDrawable
//-------------------------------------------------------------------------
struct Vertex {
glm::vec3 world_position;
glm::vec4 color;
glm::vec2 st;
glm::vec3 normal;
};
class GDrawable : public RenderObject {
public:
struct Data {
Vertex* vertices;
int vtx_c;
GLuint* indices;
int ind_c;
GLuint* mat;
int mat_c;
GLuint MBO;
GLuint VAO;
GLuint VBO;
GLuint EBO;
glm::mat4 model;
} data;
void renderOnce();
void render();
void fbind();
void update();
void update_instance();
void update_instance_alien_size();
static inline void close_draw_node() { VMStateControl::ChangeVertexArray(0); }
~GDrawable();
GDrawable();
};
//-------------------------------------------------------------------------
// ● Text
//-------------------------------------------------------------------------
class TextRenderer : public RenderObject {
private:
GDrawable obj;
Res::Texture tex = Res::Texture("../Media/Font.bmp", &Res::LinearTextureParameters);
Shaders texshader;
public:
enum TextDecorationType {
NONE,
SHADOW,
OUTLINE,
};
TextRenderer();
void BakeText(
const char* text,
float width, float height,
TextDecorationType decoration
);
void render();
void instanceRenderText(
const char* text,
glm::mat4 projection, glm::mat4 view, glm::mat4 transform,
float width, float height, TextDecorationType decoration
);
};
//-------------------------------------------------------------------------
// ● RenderBuffer
//-------------------------------------------------------------------------
class RenderBuffer : public Object {
public:
GLuint framebuffer;
GLuint rbo;
Res::Texture** texture_buffer;
int mrtcount;
//void resize(int w, int h);
void bind();
static void unbind();
static void clearColor(float r, float g, float b, float a);
static void clearColorDepth(float r, float g, float b, float a);
static void clearDepth();
RenderBuffer(int w, int h, int mrt, const GLuint* type);
void set_draw_buffers();
~RenderBuffer();
};
class PostProcessingManager : public Object {
private:
static GDrawable* QuadScreen;
public:
static void init();
static void Blit2D();
};
#endif
<|endoftext|>
|
<commit_before>//
// GEORenderer.hpp
// G3MiOSSDK
//
// Created by Diego Gomez Deck on 11/30/12.
//
//
#ifndef __G3MiOSSDK__GEORenderer__
#define __G3MiOSSDK__GEORenderer__
#include "LeafRenderer.hpp"
#include <vector>
class GEOObject;
class GEORenderer : public LeafRenderer {
private:
const G3MContext* _context;
std::vector<GEOObject*> _children;
public:
void addGEOObject(GEOObject* geoObject);
void onResume(const G3MContext* context) {
}
void onPause(const G3MContext* context) {
}
void onDestroy(const G3MContext* context) {
}
void initialize(const G3MContext* context);
bool isReadyToRender(const G3MRenderContext* rc);
void render(const G3MRenderContext* rc);
bool onTouchEvent(const G3MEventContext* ec,
const TouchEvent* touchEvent) {
return false;
}
void onResizeViewportEvent(const G3MEventContext* ec,
int width, int height) {
}
void start() {
}
void stop() {
}
};
#endif
<commit_msg>First version of GEORenderer - not yet usable<commit_after>//
// GEORenderer.hpp
// G3MiOSSDK
//
// Created by Diego Gomez Deck on 11/30/12.
//
//
#ifndef __G3MiOSSDK__GEORenderer__
#define __G3MiOSSDK__GEORenderer__
#include "LeafRenderer.hpp"
#include <vector>
class GEOObject;
class GEORenderer : public LeafRenderer {
private:
#ifdef C_CODE
const G3MContext* _context;
#endif
#ifdef JAVA_CODE
private G3MContext _context;
#endif
std::vector<GEOObject*> _children;
public:
void addGEOObject(GEOObject* geoObject);
void onResume(const G3MContext* context) {
}
void onPause(const G3MContext* context) {
}
void onDestroy(const G3MContext* context) {
}
void initialize(const G3MContext* context);
bool isReadyToRender(const G3MRenderContext* rc);
void render(const G3MRenderContext* rc);
bool onTouchEvent(const G3MEventContext* ec,
const TouchEvent* touchEvent) {
return false;
}
void onResizeViewportEvent(const G3MEventContext* ec,
int width, int height) {
}
void start() {
}
void stop() {
}
};
#endif
<|endoftext|>
|
<commit_before>/**
* \file dcs/testbed/system_identification.hpp
*
* \brief Performs system identification experiments.
*
* \author Marco Guazzone (marco.guazzone@gmail.com)
*
* <hr/>
*
* Copyright (C) 2012 Marco Guazzone
* [Distributed Computing System (DCS) Group,
* Computer Science Institute,
* Department of Science and Technological Innovation,
* University of Piemonte Orientale,
* Alessandria (Italy)]
*
* This file is part of dcsxx-testbed.
*
* dcsxx-testbed 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.
*
* dcsxx-testbed 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 dcsxx-testbed. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef DCS_TESTBED_SYSTEM_IDENTIFICATION_HPP
#define DCS_TESTBED_SYSTEM_IDENTIFICATION_HPP
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/mean.hpp>
#include <boost/smart_ptr.hpp>
#include <cstddef>
#include <ctime>
#include <dcs/assert.hpp>
#include <dcs/debug.hpp>
#include <dcs/exception.hpp>
#include <dcs/testbed/base_signal_generator.hpp>
#include <dcs/testbed/base_virtual_machine.hpp>
#include <dcs/testbed/base_workload_driver.hpp>
#include <fstream>
#include <iterator>
#include <limits>
#include <sstream>
#include <stdexcept>
#include <string>
#include <unistd.h>
#include <vector>
#ifdef DCS_DEBUG
# include <boost/numeric/ublas/io.hpp>
#endif // DCS_DEBUG
namespace dcs { namespace testbed {
template <typename RealT>
class system_identification
{
public: typedef RealT real_type;
public: typedef base_virtual_machine<real_type> vm_type;
public: typedef ::boost::shared_ptr<vm_type> vm_pointer;
public: typedef base_signal_generator<real_type> signal_generator_type;
public: typedef ::boost::shared_ptr<signal_generator_type> signal_generator_pointer;
public: typedef base_workload_driver workload_driver_type;
public: typedef ::boost::shared_ptr<workload_driver_type> workload_driver_pointer;
private: typedef ::std::vector<vm_pointer> vm_container;
private: static const unsigned int default_sampling_time = 10;
private: static const ::std::string default_output_data_file_path;
/// Default constructor.
public: system_identification()
: ts_(default_sampling_time),
out_dat_file_(default_output_data_file_path),
out_ext_fmt_(false)
{
}
/// A constructor.
public: template <typename FwdIterT>
system_identification(FwdIterT vm_first, FwdIterT vm_last, workload_driver_pointer const& p_wkl_driver, signal_generator_pointer const& p_sig_gen)
: vms_(vm_first, vm_last),
p_wkl_driver_(p_wkl_driver),
p_sig_gen_(p_sig_gen),
ts_(default_sampling_time),
out_dat_file_(default_output_data_file_path),
out_ext_fmt_(false)
{
}
/// Set the path of the output data file.
public: void output_data_file(::std::string const& s)
{
// pre: s != ""
DCS_ASSERT(!s.empty(),
DCS_EXCEPTION_THROW(::std::invalid_argument,
"Cannot use empty string as output data file name"));
out_dat_file_ = s;
}
/// Enabled or disable the extended format of the output data file.
public: void output_extended_format(bool val)
{
out_ext_fmt_ = val;
}
/// Set the sampling time.
public: void sampling_time(real_type t)
{
// pre: t > 0
DCS_ASSERT(t > 0,
DCS_EXCEPTION_THROW(::std::invalid_argument,
"Sampling time must be positive"));
// pre: t <= max value
DCS_ASSERT(t <= ::std::numeric_limits<unsigned int>::max(),
DCS_EXCEPTION_THROW(::std::invalid_argument,
"Sampling time too large"));
ts_ = static_cast<unsigned int>(t);
}
/**
* \brief Perform system identification by using as initial shares the
* 100% of resource.
*/
public: void run()
{
::std::vector<real_type> init_shares(vms_.size(), 1);
this->run(init_shares.begin(), init_shares.end());
}
/**
* \brief Perform system identification with the given initial shares.
*/
public: template <typename FwdIterT>
void run(FwdIterT share_first, FwdIterT share_end)
{
// distance(share_first,share_end) == size(vms_)
DCS_ASSERT(static_cast< ::std::size_t >(::std::distance(share_first, share_end)) == vms_.size(),
DCS_EXCEPTION_THROW(::std::invalid_argument,
"Share container size does not match"));
typedef typename vm_container::const_iterator vm_iterator;
typedef typename signal_generator_type::vector_type share_container;
//const ::std::size_t nt(10);//FIXME: parameterize
// Open output data file
::std::ofstream ofs(out_dat_file_.c_str());
if (!ofs.good())
{
::std::ostringstream oss;
oss << "Cannot open output data file '" << out_dat_file_ << "'";
DCS_EXCEPTION_THROW(::std::runtime_error, oss.str());
}
// Set initial shares
vm_iterator vm_end_it(vms_.end());
vm_iterator vm_beg_it(vms_.begin());
for (vm_iterator vm_it = vm_beg_it;
vm_it != vm_end_it;
++vm_it)
{
vm_pointer p_vm(*vm_it);
p_vm->cpu_share(*share_first);
++share_first;
}
// Start the workload driver
p_wkl_driver_->start();
// Set shares according to the given signal
::std::time_t t0;
::std::time_t t1;
t0 = ::std::time(&t1);
while (!p_wkl_driver_->done())
{
if (p_wkl_driver_->ready() && p_wkl_driver_->has_observation())
{
// Stringstream used to hold common output info
::std::ostringstream oss;
// Compute the elapsed time
t0 = t1;
::std::time(&t1);
double dt = ::std::difftime(t1, t0);
DCS_DEBUG_TRACE( "-- Time " << dt );
oss << dt;
// Generate new shares
share_container share((*p_sig_gen_)());
// check: consistency
DCS_DEBUG_ASSERT( share.size() == vms_.size() );
DCS_DEBUG_TRACE( " Generated shares: " << dcs::debug::to_string(share.begin(), share.end()) );
// Set new shares to every VM
::std::size_t ix(0);
for (vm_iterator vm_it = vm_beg_it;
vm_it != vm_end_it;
++vm_it)
{
vm_pointer p_vm(*vm_it);
// check: not null
DCS_DEBUG_ASSERT( p_vm );
DCS_DEBUG_TRACE( " VM '" << p_vm->name() << "' :: Old CPU share: " << p_vm->cpu_share() << " :: New CPU share: " << share[ix] );
oss << " " << p_vm->cpu_share();
p_vm->cpu_share(share[ix]);
++ix;
}
// Get collected observations
typedef ::std::vector<real_type> obs_container;
typedef typename obs_container::const_iterator obs_iterator;
obs_container obs = p_wkl_driver_->observations();
//FIXME: parameterize the type of statistics the user want
::boost::accumulators::accumulator_set< real_type, ::boost::accumulators::stats< ::boost::accumulators::tag::mean > > acc;
obs_iterator obs_end_it(obs.end());
for (obs_iterator obs_it = obs.begin();
obs_it != obs_end_it;
++obs_it)
{
real_type val(*obs_it);
acc(val);
if (out_ext_fmt_)
{
ofs << oss.str() << " " << val << " " << "\"[DATA]\"" << ::std::endl;
}
}
// Compute a summary statistics of collected observation
//FIXME: parameterize the type of statistics the user want
real_type summary_obs = ::boost::accumulators::mean(acc);
DCS_DEBUG_TRACE( " Current (summary) observation: " << summary_obs );
if (out_ext_fmt_)
{
ofs << oss.str() << " " << summary_obs << " " << "\"[SUMMARY]\"" << ::std::endl;
}
else
{
ofs << oss.str() << " " << summary_obs << ::std::endl;
}
// Wait until the next sampling time
::sleep(ts_);
}
}
// Stop the workload driver
p_wkl_driver_->stop();
// Close output data file
ofs.close();
}
private: vm_container vms_; ///< VMs container
private: workload_driver_pointer p_wkl_driver_; ///< Ptr to workload driver
private: signal_generator_pointer p_sig_gen_; ///< Ptr to signal generator used to excite VMs
private: unsigned int ts_; ///< The sampling time
private: ::std::string out_dat_file_; ///< The path to the output data file
private: bool out_ext_fmt_; ///< Flag to control whether to produce an output data file with extended format
}; // system_identification
template <typename RealT>
const ::std::string system_identification<RealT>::default_output_data_file_path("./sysid_out.dat");
}} // Namespace dcs::testbed
#endif // DCS_TESTBED_SYSTEM_IDENTIFICATION_HPP
<commit_msg>(bug-fix:minor) Restore old shares before leaving the system identification 'run' method.<commit_after>/**
* \file dcs/testbed/system_identification.hpp
*
* \brief Performs system identification experiments.
*
* \author Marco Guazzone (marco.guazzone@gmail.com)
*
* <hr/>
*
* Copyright (C) 2012 Marco Guazzone
* [Distributed Computing System (DCS) Group,
* Computer Science Institute,
* Department of Science and Technological Innovation,
* University of Piemonte Orientale,
* Alessandria (Italy)]
*
* This file is part of dcsxx-testbed.
*
* dcsxx-testbed 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.
*
* dcsxx-testbed 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 dcsxx-testbed. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef DCS_TESTBED_SYSTEM_IDENTIFICATION_HPP
#define DCS_TESTBED_SYSTEM_IDENTIFICATION_HPP
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/mean.hpp>
#include <boost/smart_ptr.hpp>
#include <cstddef>
#include <ctime>
#include <dcs/assert.hpp>
#include <dcs/debug.hpp>
#include <dcs/exception.hpp>
#include <dcs/testbed/base_signal_generator.hpp>
#include <dcs/testbed/base_virtual_machine.hpp>
#include <dcs/testbed/base_workload_driver.hpp>
#include <fstream>
#include <iterator>
#include <limits>
#include <sstream>
#include <stdexcept>
#include <string>
#include <unistd.h>
#include <vector>
#ifdef DCS_DEBUG
# include <boost/numeric/ublas/io.hpp>
#endif // DCS_DEBUG
namespace dcs { namespace testbed {
template <typename RealT>
class system_identification
{
public: typedef RealT real_type;
public: typedef base_virtual_machine<real_type> vm_type;
public: typedef ::boost::shared_ptr<vm_type> vm_pointer;
public: typedef base_signal_generator<real_type> signal_generator_type;
public: typedef ::boost::shared_ptr<signal_generator_type> signal_generator_pointer;
public: typedef base_workload_driver workload_driver_type;
public: typedef ::boost::shared_ptr<workload_driver_type> workload_driver_pointer;
private: typedef ::std::vector<vm_pointer> vm_container;
private: static const unsigned int default_sampling_time = 10;
private: static const ::std::string default_output_data_file_path;
/// Default constructor.
public: system_identification()
: ts_(default_sampling_time),
out_dat_file_(default_output_data_file_path),
out_ext_fmt_(false)
{
}
/// A constructor.
public: template <typename FwdIterT>
system_identification(FwdIterT vm_first, FwdIterT vm_last, workload_driver_pointer const& p_wkl_driver, signal_generator_pointer const& p_sig_gen)
: vms_(vm_first, vm_last),
p_wkl_driver_(p_wkl_driver),
p_sig_gen_(p_sig_gen),
ts_(default_sampling_time),
out_dat_file_(default_output_data_file_path),
out_ext_fmt_(false)
{
}
/// Set the path of the output data file.
public: void output_data_file(::std::string const& s)
{
// pre: s != ""
DCS_ASSERT(!s.empty(),
DCS_EXCEPTION_THROW(::std::invalid_argument,
"Cannot use empty string as output data file name"));
out_dat_file_ = s;
}
/// Enabled or disable the extended format of the output data file.
public: void output_extended_format(bool val)
{
out_ext_fmt_ = val;
}
/// Set the sampling time.
public: void sampling_time(real_type t)
{
// pre: t > 0
DCS_ASSERT(t > 0,
DCS_EXCEPTION_THROW(::std::invalid_argument,
"Sampling time must be positive"));
// pre: t <= max value
DCS_ASSERT(t <= ::std::numeric_limits<unsigned int>::max(),
DCS_EXCEPTION_THROW(::std::invalid_argument,
"Sampling time too large"));
ts_ = static_cast<unsigned int>(t);
}
/**
* \brief Perform system identification by using as initial shares the
* 100% of resource.
*/
public: void run()
{
::std::vector<real_type> init_shares(vms_.size(), 1);
this->run(init_shares.begin(), init_shares.end());
}
/**
* \brief Perform system identification with the given initial shares.
*/
public: template <typename FwdIterT>
void run(FwdIterT share_first, FwdIterT share_end)
{
// distance(share_first,share_end) == size(vms_)
DCS_ASSERT(static_cast< ::std::size_t >(::std::distance(share_first, share_end)) == vms_.size(),
DCS_EXCEPTION_THROW(::std::invalid_argument,
"Share container size does not match"));
typedef typename vm_container::const_iterator vm_iterator;
typedef typename signal_generator_type::vector_type share_container;
typedef typename vm_type::identifier_type vm_identifier_type;
DCS_DEBUG_TRACE( "BEGIN Execution of System Identification" );
vm_iterator vm_end_it(vms_.end());
vm_iterator vm_beg_it(vms_.begin());
if (vm_beg_it == vm_end_it)
{
// No VMs -> don't run anything
return;
}
// Open output data file
::std::ofstream ofs(out_dat_file_.c_str());
if (!ofs.good())
{
::std::ostringstream oss;
oss << "Cannot open output data file '" << out_dat_file_ << "'";
DCS_EXCEPTION_THROW(::std::runtime_error, oss.str());
}
// Get current shares in order to restore them at the end of execution
share_container old_shares;
for (vm_iterator vm_it = vm_beg_it;
vm_it != vm_end_it;
++vm_it)
{
vm_pointer p_vm(*vm_it);
old_shares.push_back(p_vm->cpu_share());
}
// Set initial shares
for (vm_iterator vm_it = vm_beg_it;
vm_it != vm_end_it;
++vm_it)
{
vm_pointer p_vm(*vm_it);
p_vm->cpu_share(*share_first);
++share_first;
}
// Start the workload driver
p_wkl_driver_->start();
// Set shares according to the given signal
::std::time_t t0(-1);
::std::time_t t1(-1);
::std::time(&t1);
while (!p_wkl_driver_->done())
{
DCS_DEBUG_TRACE( " Driver is alive" );
if (p_wkl_driver_->ready() && p_wkl_driver_->has_observation())
{
// Stringstream used to hold common output info
::std::ostringstream oss;
// Compute the elapsed time
::std::time(&t1);
if (t0 == -1)
{
// Set t0 to the start of observation collection phase
t0 = t1;
}
double dt = ::std::difftime(t1, t0);
DCS_DEBUG_TRACE( "-- Time " << dt );
oss << dt;
// Generate new shares
share_container share((*p_sig_gen_)());
// check: consistency
DCS_DEBUG_ASSERT( share.size() == vms_.size() );
DCS_DEBUG_TRACE( " Generated shares: " << dcs::debug::to_string(share.begin(), share.end()) );
// Set new shares to every VM
::std::size_t ix(0);
for (vm_iterator vm_it = vm_beg_it;
vm_it != vm_end_it;
++vm_it)
{
vm_pointer p_vm(*vm_it);
// check: not null
DCS_DEBUG_ASSERT( p_vm );
DCS_DEBUG_TRACE( " VM '" << p_vm->name() << "' :: Old CPU share: " << p_vm->cpu_share() << " :: New CPU share: " << share[ix] );
oss << " " << p_vm->cpu_share();
p_vm->cpu_share(share[ix]);
++ix;
}
// Get collected observations
typedef ::std::vector<real_type> obs_container;
typedef typename obs_container::const_iterator obs_iterator;
obs_container obs = p_wkl_driver_->observations();
//FIXME: parameterize the type of statistics the user want
::boost::accumulators::accumulator_set< real_type, ::boost::accumulators::stats< ::boost::accumulators::tag::mean > > acc;
obs_iterator obs_end_it(obs.end());
for (obs_iterator obs_it = obs.begin();
obs_it != obs_end_it;
++obs_it)
{
real_type val(*obs_it);
acc(val);
if (out_ext_fmt_)
{
ofs << oss.str() << " " << val << " " << "\"[DATA]\"" << ::std::endl;
}
}
// Compute a summary statistics of collected observation
//FIXME: parameterize the type of statistics the user want
real_type summary_obs = ::boost::accumulators::mean(acc);
DCS_DEBUG_TRACE( " Current (summary) observation: " << summary_obs );
if (out_ext_fmt_)
{
ofs << oss.str() << " " << summary_obs << " " << "\"[SUMMARY]\"" << ::std::endl;
}
else
{
ofs << oss.str() << " " << summary_obs << ::std::endl;
}
// Wait until the next sampling time
DCS_DEBUG_TRACE( " Zzz... (: " << ts_ << ")" );
::sleep(ts_);
}
}
// Stop the workload driver
p_wkl_driver_->stop();
// Close output data file
ofs.close();
// Reset VM shares to values that VMs had just before running the driver
::std::size_t ix(0);
for (vm_iterator vm_it = vm_beg_it;
vm_it != vm_end_it;
++vm_it)
{
vm_pointer p_vm(*vm_it);
p_vm->cpu_share(old_shares[ix]);
++ix;
}
DCS_DEBUG_TRACE( "END Execution of System Identification" );
}
private: vm_container vms_; ///< VMs container
private: workload_driver_pointer p_wkl_driver_; ///< Ptr to workload driver
private: signal_generator_pointer p_sig_gen_; ///< Ptr to signal generator used to excite VMs
private: unsigned int ts_; ///< The sampling time
private: ::std::string out_dat_file_; ///< The path to the output data file
private: bool out_ext_fmt_; ///< Flag to control whether to produce an output data file with extended format
}; // system_identification
template <typename RealT>
const ::std::string system_identification<RealT>::default_output_data_file_path("./sysid_out.dat");
}} // Namespace dcs::testbed
#endif // DCS_TESTBED_SYSTEM_IDENTIFICATION_HPP
<|endoftext|>
|
<commit_before>/*****************************************************************************************
* *
* GHOUL *
* General Helpful Open Utility Library *
* *
* Copyright (c) 2012-2014 *
* *
* 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. *
****************************************************************************************/
namespace ghoul {
namespace cmdparser {
template<typename T, typename U = T, typename V = U, typename W = V>
SingleCommand<T, U, V, W>::SingleCommand(T* ptr1, const std::string& name,
const std::string& shortName,
const std::string& infoText,
const std::string parameterList)
: CommandlineCommand(name, shortName, infoText, parameterList, 1, false)
, _ptr1(ptr1)
, _ptr2(nullptr)
, _ptr3(nullptr)
, _ptr4(nullptr)
{}
template<typename T, typename U = T, typename V = U, typename W = V>
SingleCommand<T, U, V, W>::SingleCommand(T* ptr1, U* ptr2, const std::string& name,
const std::string& shortName,
const std::string& infoText,
const std::string parameterList)
: CommandlineCommand(name, shortName, infoText, parameterList, 2, false)
, _ptr1(ptr1)
, _ptr2(ptr2)
, _ptr3(nullptr)
, _ptr4(nullptr)
{}
template<typename T, typename U = T, typename V = U, typename W = V>
SingleCommand<T, U, V, W>::SingleCommand(T* ptr1, U* ptr2, V* ptr3,
const std::string& name,
const std::string& shortName,
const std::string& infoText,
const std::string parameterList)
: CommandlineCommand(name, shortName, infoText, parameterList, 3, false)
, _ptr1(ptr1)
, _ptr2(ptr2)
, _ptr3(ptr3)
, _ptr4(nullptr)
{}
template<typename T, typename U = T, typename V = U, typename W = V>
SingleCommand<T, U, V, W>::SingleCommand(T* ptr1, U* ptr2, V* ptr3, W* ptr4,
const std::string& name,
const std::string& shortName,
const std::string& infoText,
const std::string parameterList)
: CommandlineCommand(name, shortName, infoText, parameterList, 4, false)
, _ptr1(ptr1)
, _ptr2(ptr2)
, _ptr3(ptr3)
, _ptr4(ptr4)
{}
template<typename T, typename U = T, typename V = U, typename W = V>
bool SingleCommand<T, U, V, W>::execute(const std::vector<std::string>& parameters) {
cast(parameters[0], *_ptr1);
if (_ptr2 != nullptr)
cast(parameters[1], *_ptr2);
if (_ptr3 != nullptr)
cast(parameters[2], *_ptr3);
if (_ptr4 != nullptr)
cast(parameters[3], *_ptr4);
return true;
}
template<typename T, typename U = T, typename V = U, typename W = V>
bool SingleCommand<T, U, V, W>::checkParameters(
const std::vector<std::string>& parameters)
{
std::ostringstream errorStr;
bool result = parameters.size() == static_cast<size_t>(_argumentNum);
if (!result) {
errorStr << "Invalid number of parameters: " << parameters.size();
errorStr << ", expected: " << _argumentNum;
_errorMsg = errorStr.str();
return false;
}
result &= is<T>(parameters[0]);
if (!result)
errorStr << "First parameter invalid";
if (result && (_ptr2 != nullptr)) {
result &= is<U>(parameters[1]);
if (!result)
errorStr << "Second parameter invalid";
}
if (result && (_ptr3 != nullptr)) {
result &= is<V>(parameters[2]);
if (!result)
errorStr << "Third parameter invalid";
}
if (result && (_ptr4 != nullptr)) {
result &= is<W>(parameters[3]);
if (!result)
errorStr << "Fourth parameter invalid";
}
if (!result)
_errorMsg = errorStr.str();
return result;
}
} // namespace cmdparser
} // namespace ghoul<commit_msg>Linux fix<commit_after>/*****************************************************************************************
* *
* GHOUL *
* General Helpful Open Utility Library *
* *
* Copyright (c) 2012-2014 *
* *
* 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. *
****************************************************************************************/
namespace ghoul {
namespace cmdparser {
template<typename T, typename U, typename V, typename W>
SingleCommand<T, U, V, W>::SingleCommand(T* ptr1, const std::string& name,
const std::string& shortName,
const std::string& infoText,
const std::string parameterList)
: CommandlineCommand(name, shortName, infoText, parameterList, 1, false)
, _ptr1(ptr1)
, _ptr2(nullptr)
, _ptr3(nullptr)
, _ptr4(nullptr)
{}
template<typename T, typename U, typename V, typename W>
SingleCommand<T, U, V, W>::SingleCommand(T* ptr1, U* ptr2, const std::string& name,
const std::string& shortName,
const std::string& infoText,
const std::string parameterList)
: CommandlineCommand(name, shortName, infoText, parameterList, 2, false)
, _ptr1(ptr1)
, _ptr2(ptr2)
, _ptr3(nullptr)
, _ptr4(nullptr)
{}
template<typename T, typename U, typename V, typename W>
SingleCommand<T, U, V, W>::SingleCommand(T* ptr1, U* ptr2, V* ptr3,
const std::string& name,
const std::string& shortName,
const std::string& infoText,
const std::string parameterList)
: CommandlineCommand(name, shortName, infoText, parameterList, 3, false)
, _ptr1(ptr1)
, _ptr2(ptr2)
, _ptr3(ptr3)
, _ptr4(nullptr)
{}
template<typename T, typename U, typename V, typename W>
SingleCommand<T, U, V, W>::SingleCommand(T* ptr1, U* ptr2, V* ptr3, W* ptr4,
const std::string& name,
const std::string& shortName,
const std::string& infoText,
const std::string parameterList)
: CommandlineCommand(name, shortName, infoText, parameterList, 4, false)
, _ptr1(ptr1)
, _ptr2(ptr2)
, _ptr3(ptr3)
, _ptr4(ptr4)
{}
template<typename T, typename U, typename V, typename W>
bool SingleCommand<T, U, V, W>::execute(const std::vector<std::string>& parameters) {
cast(parameters[0], *_ptr1);
if (_ptr2 != nullptr)
cast(parameters[1], *_ptr2);
if (_ptr3 != nullptr)
cast(parameters[2], *_ptr3);
if (_ptr4 != nullptr)
cast(parameters[3], *_ptr4);
return true;
}
template<typename T, typename U, typename V, typename W>
bool SingleCommand<T, U, V, W>::checkParameters(
const std::vector<std::string>& parameters)
{
std::ostringstream errorStr;
bool result = parameters.size() == static_cast<size_t>(_argumentNum);
if (!result) {
errorStr << "Invalid number of parameters: " << parameters.size();
errorStr << ", expected: " << _argumentNum;
_errorMsg = errorStr.str();
return false;
}
result &= is<T>(parameters[0]);
if (!result)
errorStr << "First parameter invalid";
if (result && (_ptr2 != nullptr)) {
result &= is<U>(parameters[1]);
if (!result)
errorStr << "Second parameter invalid";
}
if (result && (_ptr3 != nullptr)) {
result &= is<V>(parameters[2]);
if (!result)
errorStr << "Third parameter invalid";
}
if (result && (_ptr4 != nullptr)) {
result &= is<W>(parameters[3]);
if (!result)
errorStr << "Fourth parameter invalid";
}
if (!result)
_errorMsg = errorStr.str();
return result;
}
} // namespace cmdparser
} // namespace ghoul<|endoftext|>
|
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2015 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_JSON_POSITIONS_GRAMMAR_HPP
#define MAPNIK_JSON_POSITIONS_GRAMMAR_HPP
// mapnik
#include <mapnik/util/variant.hpp>
#include <mapnik/json/generic_json.hpp>
#include <mapnik/json/error_handler.hpp>
#include <mapnik/geometry.hpp>
#include <mapnik/geometry_fusion_adapted.hpp>
#pragma GCC diagnostic push
#include <mapnik/warning_ignore.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix_function.hpp>
#include <boost/fusion/adapted/std_tuple.hpp>
#pragma GCC diagnostic pop
// stl
#include <tuple>
namespace mapnik { namespace json {
struct empty {};
using position = mapnik::geometry::point<double>;
using positions = std::vector<position>;
using coordinates = util::variant<empty, position, positions, std::vector<positions>, std::vector<std::vector<positions> > > ;
namespace qi = boost::spirit::qi;
struct set_position_impl
{
using result_type = void;
template <typename T0,typename T1>
result_type operator() (T0 & coords, T1 const& pos) const
{
if (pos) coords = *pos;
}
};
struct push_position_impl
{
using result_type = void;
template <typename T0,typename T1>
result_type operator() (T0 & coords, T1 const& pos) const
{
if (pos) coords.push_back(*pos);
}
};
template <typename Iterator, typename ErrorHandler = error_handler<Iterator> >
struct positions_grammar :
qi::grammar<Iterator,coordinates(),space_type>
{
positions_grammar(ErrorHandler & error_handler);
qi::rule<Iterator, coordinates(),space_type> coords;
qi::rule<Iterator, boost::optional<position>(), space_type> pos;
qi::rule<Iterator, positions(), space_type> ring;
qi::rule<Iterator, std::vector<positions>(), space_type> rings;
qi::rule<Iterator, std::vector<std::vector<positions> >(), space_type> rings_array;
boost::phoenix::function<set_position_impl> set_position;
boost::phoenix::function<push_position_impl> push_position;
};
}}
#endif // MAPNIK_JSON_POSITIONS_GRAMMAR_HPP
<commit_msg>keep address-sanitizer happy ref (https://github.com/mapbox/mapnik-vector-tile/pull/171)<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2015 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_JSON_POSITIONS_GRAMMAR_HPP
#define MAPNIK_JSON_POSITIONS_GRAMMAR_HPP
// mapnik
#include <mapnik/util/variant.hpp>
#include <mapnik/json/generic_json.hpp>
#include <mapnik/json/error_handler.hpp>
#include <mapnik/geometry.hpp>
#include <mapnik/geometry_fusion_adapted.hpp>
#pragma GCC diagnostic push
#include <mapnik/warning_ignore.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix_function.hpp>
#include <boost/fusion/adapted/std_tuple.hpp>
#pragma GCC diagnostic pop
// stl
#include <tuple>
namespace mapnik { namespace json {
struct empty {};
using position = mapnik::geometry::point<double>;
using positions = std::vector<position>;
using coordinates = util::variant<empty, position, positions, std::vector<positions>, std::vector<std::vector<positions> > > ;
namespace qi = boost::spirit::qi;
struct set_position_impl
{
using result_type = void;
template <typename T0,typename T1>
result_type operator() (T0 & coords, T1 const& pos) const
{
if (pos) coords = *pos;
}
};
struct push_position_impl
{
using result_type = void;
template <typename T0, typename T1>
result_type operator() (T0 & coords, T1 const& pos) const
{
if (pos) coords.empace_back(*pos);
}
};
template <typename Iterator, typename ErrorHandler = error_handler<Iterator> >
struct positions_grammar :
qi::grammar<Iterator,coordinates(),space_type>
{
positions_grammar(ErrorHandler & error_handler);
qi::rule<Iterator, coordinates(),space_type> coords;
qi::rule<Iterator, boost::optional<position>(), space_type> pos;
qi::rule<Iterator, positions(), space_type> ring;
qi::rule<Iterator, std::vector<positions>(), space_type> rings;
qi::rule<Iterator, std::vector<std::vector<positions> >(), space_type> rings_array;
boost::phoenix::function<set_position_impl> set_position;
boost::phoenix::function<push_position_impl> push_position;
};
}}
#endif // MAPNIK_JSON_POSITIONS_GRAMMAR_HPP
<|endoftext|>
|
<commit_before>//
// Copyright (c) 2013-2017 Christoph Malek
// See LICENSE for more information.
//
#ifndef RJ_GAME_ENTITY_HANDLER_HPP
#define RJ_GAME_ENTITY_HANDLER_HPP
#include "collision.hpp"
#include "components/player.hpp"
#include "entity.hpp"
#include "particle_manager.hpp"
#include <mlk/containers/container_utl.h>
#include <mlk/log/log.h>
#include <mlk/types/types.h>
#include <vector>
namespace rj
{
template <typename T>
using entity_ptr = mlk::sptr<T>;
using entity_base_ptr = entity_ptr<entity_base>;
using player_ptr = entity_ptr<player>;
class entity_handler
{
rndr& m_render;
particle_manager<game_handler>& m_particlemgr;
game_handler* m_gamehandler{nullptr};
player_ptr m_player{nullptr};
std::vector<entity_base_ptr> m_entities;
std::size_t m_max_entities;
std::size_t m_current_id{0};
static constexpr float m_despawn_zone{0.f};
public:
using iterator = std::vector<entity_base_ptr>::iterator;
using const_iterator = std::vector<entity_base_ptr>::const_iterator;
entity_handler(rndr& r, particle_manager<game_handler>& pm,
std::size_t max_entities = 100000)
: m_render{r}, m_particlemgr{pm}, m_max_entities{max_entities}
{
}
void set_gamehandler(game_handler* gh) { m_gamehandler = gh; }
bool create_entity(const entity_base_ptr& e) noexcept
{
if(!this->is_entity_valid(e)) return false;
this->create_entity_impl(e);// add/create entity in handler
return true;
}
bool create_entity(const player_ptr& p) noexcept
{
if(!this->is_entity_valid(p) || this->is_player_registered())
return false;
this->create_entity_impl(p);
return true;
}
void update(dur duration)
{
// update player
if(this->is_player_registered()) m_player->update(duration);
// update other
for(auto& a : m_entities) {
a->update(duration);
if(a->right_out() <= m_despawn_zone) a->destroy();
}
this->check_collision();
// erase flagged entities
this->erase_destroyed();
}
void render()
{
// render player
if(this->is_player_registered()) m_player->render();
// render other
for(auto& a : m_entities) a->render();
}
void clear() noexcept { m_entities.clear(); }
// deleting ents on next update
void delete_entities(std::vector<iterator>& iters)
{
for(auto& a : iters) (*a)->destroy();
}
auto get_entities_at(const vec2f& at,
const vec2f& size = {1.f, 1.f}) noexcept
{
std::vector<iterator> result;
sf::FloatRect at_bounds{at, size};
for(auto iter{std::begin(m_entities)}; iter != std::end(m_entities);
++iter)
{
sf::FloatRect ent_bounds{
{(*iter)->left_out(), (*iter)->top_out()}, (*iter)->size()};
if(ent_bounds.intersects(at_bounds)) result.emplace_back(iter);
}
return result;
}
bool exists_entity_at(const vec2f& at,
const vec2f& size = {1.f, 1.f}) noexcept
{
return !this->get_entities_at(at, size).empty();
}
iterator begin() { return std::begin(m_entities); }
iterator end() { return std::end(m_entities); }
std::size_t num_entities() const noexcept
{
return m_entities.size() + this->is_player_registered();
}
auto& player() noexcept { return m_player; }
bool is_player_registered() const noexcept
{
return m_player != nullptr;
}
void set_outlines_dbg(bool on)
{
for(auto& e : m_entities) {
if(e->figure() == entity_figure::f_rectangle) {
auto ptr{std::static_pointer_cast<platform>(e)};
ptr->activate_outlines(on);
}
else if(e->figure() == entity_figure::f_triangle)
{
auto ptr{std::static_pointer_cast<triangle>(e)};
ptr->activate_outlines(on);
}
}
}
private:
void on_player_death();
void try_player_death()
{
if(!m_player->is_alive()) return;
// player should die here
// do effects, game stats etc....
m_player->render_object().setFillColor({255, 0, 0});
m_particlemgr.create_particles(10000, m_player->pos(), 3000, true);
// on kill
m_player->on_kill();
this->on_player_death();
}
void check_collision() noexcept
{
if(!this->is_player_registered()) return;
bool collided{false};
for(auto& a : m_entities) {
if(is_colliding(*m_player, *a)) {
collided = true;
if(m_player->bottom_out() - 2 <= a->top_out()) {
m_player->on_collision(a->top_out());
m_player->render_object().setFillColor({0, 255, 0});
}
else
{
this->try_player_death();
}
if(a->has_propertie(entity_propertie::death)) {
// player touched death entity
this->try_player_death();
}
}
}
if(!collided) m_player->on_collision_end();
}
// checking the entities
bool is_entity_valid(const entity_base_ptr& e) const noexcept
{
if(m_entities.size() >= m_max_entities) {
mlk::lout("rj::entity_handler")
<< "max_entities limit is reached,"
"can't add more entities";
return false;
}
if(e->is_registered()) {
mlk::lout("rj::entity_handler")
<< "entity with id '" << e->m_id
<< "' exists already in entity handler, ignoring";
return false;
}
return true;
}
// create the entities
void create_entity_impl(const entity_base_ptr& e) noexcept
{
this->register_impl(e);
m_entities.push_back(e);
}
void create_entity_impl(const player_ptr& p) noexcept
{
this->register_impl(p);
m_player = p;
}
void register_impl(const entity_base_ptr& e) noexcept
{
// important: set game and init
e->handler_register(&m_render, m_current_id);
e->init();
++m_current_id;
}
void erase_destroyed() noexcept
{
mlk::cnt::remove_all_if(
[](const auto& entity) { return entity->m_destroyed; },
m_entities);
}
};
}
#endif// RJ_GAME_ENTITY_HANDLER_HPP
<commit_msg>entity_handler::update: using one loop instead of 3<commit_after>//
// Copyright (c) 2013-2017 Christoph Malek
// See LICENSE for more information.
//
#ifndef RJ_GAME_ENTITY_HANDLER_HPP
#define RJ_GAME_ENTITY_HANDLER_HPP
#include "collision.hpp"
#include "components/player.hpp"
#include "entity.hpp"
#include "particle_manager.hpp"
#include <mlk/containers/container_utl.h>
#include <mlk/log/log.h>
#include <mlk/types/types.h>
#include <vector>
namespace rj
{
template <typename T>
using entity_ptr = mlk::sptr<T>;
using entity_base_ptr = entity_ptr<entity_base>;
using player_ptr = entity_ptr<player>;
class entity_handler
{
rndr& m_render;
particle_manager<game_handler>& m_particlemgr;
game_handler* m_gamehandler{nullptr};
player_ptr m_player{nullptr};
std::vector<entity_base_ptr> m_entities;
std::size_t m_max_entities;
std::size_t m_current_id{0};
static constexpr float m_despawn_zone{0.f};
public:
using iterator = std::vector<entity_base_ptr>::iterator;
using const_iterator = std::vector<entity_base_ptr>::const_iterator;
entity_handler(rndr& r, particle_manager<game_handler>& pm,
std::size_t max_entities = 100000)
: m_render{r}, m_particlemgr{pm}, m_max_entities{max_entities}
{
}
void set_gamehandler(game_handler* gh) { m_gamehandler = gh; }
bool create_entity(const entity_base_ptr& e) noexcept
{
if(!this->is_entity_valid(e)) return false;
this->create_entity_impl(e);// add/create entity in handler
return true;
}
bool create_entity(const player_ptr& p) noexcept
{
if(!this->is_entity_valid(p) || this->is_player_registered())
return false;
this->create_entity_impl(p);
return true;
}
void update(dur duration)
{
// update player
if(this->is_player_registered()) m_player->update(duration);
// update other
bool collided{false};
for(auto iter{m_entities.begin()}; iter < m_entities.end(); ++iter)
{
auto a{*iter};
a->update(duration);
// check collision
if(this->is_player_registered()) {
if(is_colliding(*m_player, *a)) {
collided = true;
if(m_player->bottom_out() - 2 <= a->top_out()) {
m_player->on_collision(a->top_out());
m_player->render_object().setFillColor({0, 255, 0});
}
else
{
this->try_player_death();
}
if(a->has_propertie(entity_propertie::death)) {
// player touched death entity
this->try_player_death();
}
}
}
if(a->right_out() <= m_despawn_zone) {
a->destroy();
m_entities.erase(iter);
}
}
if(!collided) m_player->on_collision_end();
}
void render()
{
// render player
if(this->is_player_registered()) m_player->render();
// render other
for(auto& a : m_entities) a->render();
}
void clear() noexcept { m_entities.clear(); }
// deleting ents on next update
void delete_entities(std::vector<iterator>& iters)
{
for(auto& a : iters) (*a)->destroy();
}
auto get_entities_at(const vec2f& at,
const vec2f& size = {1.f, 1.f}) noexcept
{
std::vector<iterator> result;
sf::FloatRect at_bounds{at, size};
for(auto iter{std::begin(m_entities)}; iter != std::end(m_entities);
++iter)
{
sf::FloatRect ent_bounds{
{(*iter)->left_out(), (*iter)->top_out()}, (*iter)->size()};
if(ent_bounds.intersects(at_bounds)) result.emplace_back(iter);
}
return result;
}
bool exists_entity_at(const vec2f& at,
const vec2f& size = {1.f, 1.f}) noexcept
{
return !this->get_entities_at(at, size).empty();
}
iterator begin() { return std::begin(m_entities); }
iterator end() { return std::end(m_entities); }
std::size_t num_entities() const noexcept
{
return m_entities.size() + this->is_player_registered();
}
auto& player() noexcept { return m_player; }
bool is_player_registered() const noexcept
{
return m_player != nullptr;
}
void set_outlines_dbg(bool on)
{
for(auto& e : m_entities) {
if(e->figure() == entity_figure::f_rectangle) {
auto ptr{std::static_pointer_cast<platform>(e)};
ptr->activate_outlines(on);
}
else if(e->figure() == entity_figure::f_triangle)
{
auto ptr{std::static_pointer_cast<triangle>(e)};
ptr->activate_outlines(on);
}
}
}
private:
void on_player_death();
void try_player_death()
{
if(!m_player->is_alive()) return;
// player should die here
// do effects, game stats etc....
m_player->render_object().setFillColor({255, 0, 0});
m_particlemgr.create_particles(10000, m_player->pos(), 3000, true);
// on kill
m_player->on_kill();
this->on_player_death();
}
// checking the entities
bool is_entity_valid(const entity_base_ptr& e) const noexcept
{
if(m_entities.size() >= m_max_entities) {
mlk::lout("rj::entity_handler")
<< "max_entities limit is reached,"
"can't add more entities";
return false;
}
if(e->is_registered()) {
mlk::lout("rj::entity_handler")
<< "entity with id '" << e->m_id
<< "' exists already in entity handler, ignoring";
return false;
}
return true;
}
// create the entities
void create_entity_impl(const entity_base_ptr& e) noexcept
{
this->register_impl(e);
m_entities.push_back(e);
}
void create_entity_impl(const player_ptr& p) noexcept
{
this->register_impl(p);
m_player = p;
}
void register_impl(const entity_base_ptr& e) noexcept
{
// important: set game and init
e->handler_register(&m_render, m_current_id);
e->init();
++m_current_id;
}
void erase_destroyed() noexcept
{
mlk::cnt::remove_all_if(
[](const auto& entity) { return entity->m_destroyed; },
m_entities);
}
};
}
#endif// RJ_GAME_ENTITY_HANDLER_HPP
<|endoftext|>
|
<commit_before>// The Art of C++ / Sequences
// Copyright (c) 2015 Daniel Frey
#ifndef TAOCPP_SEQUENCES_INCLUDE_MAKE_INTEGER_SEQUENCE_HPP
#define TAOCPP_SEQUENCES_INCLUDE_MAKE_INTEGER_SEQUENCE_HPP
#include <cstddef>
#include <utility>
#include <type_traits>
#include "integer_sequence.hpp"
namespace tao
{
namespace seq
{
#ifdef _LIBCXX_VERSION
// libc++ already has very efficient versions for make_*
using std::make_integer_sequence;
using std::make_index_sequence;
using std::index_sequence_for;
#else
// idea from http://stackoverflow.com/a/13073076
namespace impl
{
template< typename S, bool, std::size_t = S::size() >
struct double_up;
template< typename T, T... Ns, std::size_t N >
struct double_up< integer_sequence< T, Ns... >, false, N >
{
using type = integer_sequence< T, Ns..., ( N + Ns )... >;
};
template< typename T, T... Ns, std::size_t N >
struct double_up< integer_sequence< T, Ns... >, true, N >
{
using type = integer_sequence< T, Ns..., ( N + Ns )..., 2 * N >;
};
template< typename T, T N, typename = void >
struct generate;
template< typename T, T N >
using generate_t = typename generate< T, N >::type;
template< typename T, T N >
struct generate< T, N, typename std::enable_if< ( N > 1 ) >::type >
: double_up< generate_t< T, N / 2 >, N % 2 == 1 >
{};
template< typename T, T N >
struct generate< T, N, typename std::enable_if< ( N == 0 ) >::type >
{
using type = integer_sequence< T >;
};
template< typename T, T N >
struct generate< T, N, typename std::enable_if< ( N == 1 ) >::type >
{
using type = integer_sequence< T, 0 >;
};
}
template< typename T, T N >
using make_integer_sequence = impl::generate_t< T, N >;
template< std::size_t N >
using make_index_sequence = make_integer_sequence< std::size_t, N >;
template< typename... Ts >
using index_sequence_for = make_index_sequence< sizeof...( Ts ) >;
#endif
}
}
#endif // TAOCPP_SEQUENCES_INCLUDE_MAKE_INTEGER_SEQUENCE_HPP
<commit_msg>Fix detection of libc++<commit_after>// The Art of C++ / Sequences
// Copyright (c) 2015 Daniel Frey
#ifndef TAOCPP_SEQUENCES_INCLUDE_MAKE_INTEGER_SEQUENCE_HPP
#define TAOCPP_SEQUENCES_INCLUDE_MAKE_INTEGER_SEQUENCE_HPP
#include <cstddef>
#include <utility>
#include <type_traits>
#include "integer_sequence.hpp"
namespace tao
{
namespace seq
{
#ifdef _LIBCPP_VERSION
// libc++ already has very efficient versions for make_*
using std::make_integer_sequence;
using std::make_index_sequence;
using std::index_sequence_for;
#else
// idea from http://stackoverflow.com/a/13073076
namespace impl
{
template< typename S, bool, std::size_t = S::size() >
struct double_up;
template< typename T, T... Ns, std::size_t N >
struct double_up< integer_sequence< T, Ns... >, false, N >
{
using type = integer_sequence< T, Ns..., ( N + Ns )... >;
};
template< typename T, T... Ns, std::size_t N >
struct double_up< integer_sequence< T, Ns... >, true, N >
{
using type = integer_sequence< T, Ns..., ( N + Ns )..., 2 * N >;
};
template< typename T, T N, typename = void >
struct generate;
template< typename T, T N >
using generate_t = typename generate< T, N >::type;
template< typename T, T N >
struct generate< T, N, typename std::enable_if< ( N > 1 ) >::type >
: double_up< generate_t< T, N / 2 >, N % 2 == 1 >
{};
template< typename T, T N >
struct generate< T, N, typename std::enable_if< ( N == 0 ) >::type >
{
using type = integer_sequence< T >;
};
template< typename T, T N >
struct generate< T, N, typename std::enable_if< ( N == 1 ) >::type >
{
using type = integer_sequence< T, 0 >;
};
}
template< typename T, T N >
using make_integer_sequence = impl::generate_t< T, N >;
template< std::size_t N >
using make_index_sequence = make_integer_sequence< std::size_t, N >;
template< typename... Ts >
using index_sequence_for = make_index_sequence< sizeof...( Ts ) >;
#endif
}
}
#endif // TAOCPP_SEQUENCES_INCLUDE_MAKE_INTEGER_SEQUENCE_HPP
<|endoftext|>
|
<commit_before>/**
* @file llfloatertestinspectors.cpp
*
* $LicenseInfo:firstyear=2009&license=viewergpl$
*
* Copyright (c) 2009, Linden Research, Inc.
*
* Second Life Viewer Source Code
* The source code in this file ("Source Code") is provided by Linden Lab
* to you under the terms of the GNU General Public License, version 2.0
* ("GPL"), unless you have obtained a separate licensing agreement
* ("Other License"), formally executed by you and Linden Lab. Terms of
* the GPL can be found in doc/GPL-license.txt in this distribution, or
* online at http://secondlifegrid.net/programs/open_source/licensing/gplv2
*
* There are special exceptions to the terms and conditions of the GPL as
* it is applied to this Source Code. View the full text of the exception
* in the file doc/FLOSS-exception.txt in this software distribution, or
* online at
* http://secondlifegrid.net/programs/open_source/licensing/flossexception
*
* By copying, modifying or distributing this software, you acknowledge
* that you have read and understood your obligations described above,
* and agree to abide by those obligations.
*
* ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
* WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
* COMPLETENESS OR PERFORMANCE.
* $/LicenseInfo$
*/
#include "llviewerprecompiledheaders.h"
#include "llfloatertestinspectors.h"
// Viewer includes
#include "llstartup.h"
// Linden library includes
#include "llfloaterreg.h"
//#include "lluictrlfactory.h"
LLFloaterTestInspectors::LLFloaterTestInspectors(const LLSD& seed)
: LLFloater(seed)
{
mCommitCallbackRegistrar.add("ShowAvatarInspector",
boost::bind(&LLFloaterTestInspectors::showAvatarInspector, this, _1, _2));
mCommitCallbackRegistrar.add("ShowObjectInspector",
boost::bind(&LLFloaterTestInspectors::showObjectInspector, this, _1, _2));
}
LLFloaterTestInspectors::~LLFloaterTestInspectors()
{}
BOOL LLFloaterTestInspectors::postBuild()
{
// getChild<LLUICtrl>("avatar_2d_btn")->setCommitCallback(
// boost::bind(&LLFloaterTestInspectors::onClickAvatar2D, this));
getChild<LLUICtrl>("avatar_3d_btn")->setCommitCallback(
boost::bind(&LLFloaterTestInspectors::onClickAvatar3D, this));
getChild<LLUICtrl>("object_2d_btn")->setCommitCallback(
boost::bind(&LLFloaterTestInspectors::onClickObject2D, this));
getChild<LLUICtrl>("object_3d_btn")->setCommitCallback(
boost::bind(&LLFloaterTestInspectors::onClickObject3D, this));
getChild<LLUICtrl>("group_btn")->setCommitCallback(
boost::bind(&LLFloaterTestInspectors::onClickGroup, this));
getChild<LLUICtrl>("place_btn")->setCommitCallback(
boost::bind(&LLFloaterTestInspectors::onClickPlace, this));
getChild<LLUICtrl>("event_btn")->setCommitCallback(
boost::bind(&LLFloaterTestInspectors::onClickEvent, this));
return LLFloater::postBuild();
}
void LLFloaterTestInspectors::showAvatarInspector(LLUICtrl*, const LLSD& avatar_id)
{
LLUUID id; // defaults to null
if (LLStartUp::getStartupState() >= STATE_STARTED)
{
id = avatar_id.asUUID();
}
// spawns off mouse position automatically
LLFloaterReg::showInstance("inspect_avatar", LLSD().insert("avatar_id", id));
}
void LLFloaterTestInspectors::showObjectInspector(LLUICtrl*, const LLSD& object_id)
{
LLFloaterReg::showInstance("inspect_object", LLSD().insert("object_id", object_id));
}
void LLFloaterTestInspectors::onClickAvatar2D()
{
}
void LLFloaterTestInspectors::onClickAvatar3D()
{
}
void LLFloaterTestInspectors::onClickObject2D()
{
}
void LLFloaterTestInspectors::onClickObject3D()
{
}
void LLFloaterTestInspectors::onClickGroup()
{
}
void LLFloaterTestInspectors::onClickPlace()
{
}
void LLFloaterTestInspectors::onClickEvent()
{
}
<commit_msg>Test intentionally not-found LLUICtrl.<commit_after>/**
* @file llfloatertestinspectors.cpp
*
* $LicenseInfo:firstyear=2009&license=viewergpl$
*
* Copyright (c) 2009, Linden Research, Inc.
*
* Second Life Viewer Source Code
* The source code in this file ("Source Code") is provided by Linden Lab
* to you under the terms of the GNU General Public License, version 2.0
* ("GPL"), unless you have obtained a separate licensing agreement
* ("Other License"), formally executed by you and Linden Lab. Terms of
* the GPL can be found in doc/GPL-license.txt in this distribution, or
* online at http://secondlifegrid.net/programs/open_source/licensing/gplv2
*
* There are special exceptions to the terms and conditions of the GPL as
* it is applied to this Source Code. View the full text of the exception
* in the file doc/FLOSS-exception.txt in this software distribution, or
* online at
* http://secondlifegrid.net/programs/open_source/licensing/flossexception
*
* By copying, modifying or distributing this software, you acknowledge
* that you have read and understood your obligations described above,
* and agree to abide by those obligations.
*
* ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
* WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
* COMPLETENESS OR PERFORMANCE.
* $/LicenseInfo$
*/
#include "llviewerprecompiledheaders.h"
#include "llfloatertestinspectors.h"
// Viewer includes
#include "llstartup.h"
// Linden library includes
#include "llfloaterreg.h"
//#include "lluictrlfactory.h"
LLFloaterTestInspectors::LLFloaterTestInspectors(const LLSD& seed)
: LLFloater(seed)
{
mCommitCallbackRegistrar.add("ShowAvatarInspector",
boost::bind(&LLFloaterTestInspectors::showAvatarInspector, this, _1, _2));
mCommitCallbackRegistrar.add("ShowObjectInspector",
boost::bind(&LLFloaterTestInspectors::showObjectInspector, this, _1, _2));
}
LLFloaterTestInspectors::~LLFloaterTestInspectors()
{}
BOOL LLFloaterTestInspectors::postBuild()
{
getChild<LLUICtrl>("intentionally-not-found");
// getChild<LLUICtrl>("avatar_2d_btn")->setCommitCallback(
// boost::bind(&LLFloaterTestInspectors::onClickAvatar2D, this));
getChild<LLUICtrl>("avatar_3d_btn")->setCommitCallback(
boost::bind(&LLFloaterTestInspectors::onClickAvatar3D, this));
getChild<LLUICtrl>("object_2d_btn")->setCommitCallback(
boost::bind(&LLFloaterTestInspectors::onClickObject2D, this));
getChild<LLUICtrl>("object_3d_btn")->setCommitCallback(
boost::bind(&LLFloaterTestInspectors::onClickObject3D, this));
getChild<LLUICtrl>("group_btn")->setCommitCallback(
boost::bind(&LLFloaterTestInspectors::onClickGroup, this));
getChild<LLUICtrl>("place_btn")->setCommitCallback(
boost::bind(&LLFloaterTestInspectors::onClickPlace, this));
getChild<LLUICtrl>("event_btn")->setCommitCallback(
boost::bind(&LLFloaterTestInspectors::onClickEvent, this));
return LLFloater::postBuild();
}
void LLFloaterTestInspectors::showAvatarInspector(LLUICtrl*, const LLSD& avatar_id)
{
LLUUID id; // defaults to null
if (LLStartUp::getStartupState() >= STATE_STARTED)
{
id = avatar_id.asUUID();
}
// spawns off mouse position automatically
LLFloaterReg::showInstance("inspect_avatar", LLSD().insert("avatar_id", id));
}
void LLFloaterTestInspectors::showObjectInspector(LLUICtrl*, const LLSD& object_id)
{
LLFloaterReg::showInstance("inspect_object", LLSD().insert("object_id", object_id));
}
void LLFloaterTestInspectors::onClickAvatar2D()
{
}
void LLFloaterTestInspectors::onClickAvatar3D()
{
}
void LLFloaterTestInspectors::onClickObject2D()
{
}
void LLFloaterTestInspectors::onClickObject3D()
{
}
void LLFloaterTestInspectors::onClickGroup()
{
}
void LLFloaterTestInspectors::onClickPlace()
{
}
void LLFloaterTestInspectors::onClickEvent()
{
}
<|endoftext|>
|
<commit_before>/**
* @file llviewercontrollistener.cpp
* @author Nat Goodspeed
* @date 2009-06-30
* @brief Implementation for llviewercontrollistener.
*
* $LicenseInfo:firstyear=2009&license=viewergpl$
* Copyright (c) 2009, Linden Research, Inc.
* $/LicenseInfo$
*/
#include "llviewerprecompiledheaders.h"
#include "llviewercontrollistener.h"
#include "llviewercontrol.h"
LLViewerControlListener gSavedSettingsListener;
LLViewerControlListener::LLViewerControlListener()
: LLDispatchListener("LLViewerControl", "group")
{
add("Global", boost::bind(&LLViewerControlListener::set, &gSavedSettings, _1));
add("Skin", boost::bind(&LLViewerControlListener::set, &gSavedSkinSettings, _1));
add("PerAccount", boost::bind(&LLViewerControlListener::set, &gSavedPerAccountSettings, _1));
add("Warning", boost::bind(&LLViewerControlListener::set, &gWarningSettings, _1));
add("Crash", boost::bind(&LLViewerControlListener::set, &gCrashSettings, _1));
#if 0
add(/*"toggleControl",*/ "Global", boost::bind(&LLViewerControlListener::toggleControl, &gSavedSettings, _1));
add(/*"toggleControl",*/ "Skin", boost::bind(&LLViewerControlListener::toggleControl, &gSavedSkinSettings, _1));
add(/*"toggleControl",*/ "PerAccount", boost::bind(&LLViewerControlListener::toggleControl, &gSavedPerAccountSettings, _1));
add(/*"toggleControl",*/ "Warning", boost::bind(&LLViewerControlListener::toggleControl, &gWarningSettings, _1));
add(/*"toggleControl",*/ "Crash", boost::bind(&LLViewerControlListener::toggleControl, &gCrashSettings, _1));
add(/*"setDefault",*/ "Global", boost::bind(&LLViewerControlListener::setDefault, &gSavedSettings, _1));
add(/*"setDefault",*/ "Skin", boost::bind(&LLViewerControlListener::setDefault, &gSavedSkinSettings, _1));
add(/*"setDefault",*/ "PerAccount", boost::bind(&LLViewerControlListener::setDefault, &gSavedPerAccountSettings, _1));
add(/*"setDefault",*/ "Warning", boost::bind(&LLViewerControlListener::setDefault, &gWarningSettings, _1));
add(/*"setDefault",*/ "Crash", boost::bind(&LLViewerControlListener::setDefault, &gCrashSettings, _1));
#endif // 0
}
//static
void LLViewerControlListener::set(LLControlGroup * controls, LLSD const & event_data)
{
if(event_data.has("key"))
{
std::string key(event_data["key"]);
if(controls->controlExists(key))
{
controls->setUntypedValue(key, event_data["value"]);
}
else
{
llwarns << "requested unknown control: \"" << key << '\"' << llendl;
}
}
}
//static
void LLViewerControlListener::toggleControl(LLControlGroup * controls, LLSD const & event_data)
{
if(event_data.has("key"))
{
std::string key(event_data["key"]);
if(controls->controlExists(key))
{
LLControlVariable * control = controls->getControl(key);
if(control->isType(TYPE_BOOLEAN))
{
control->set(!control->get().asBoolean());
}
else
{
llwarns << "requested toggle of non-boolean control: \"" << key << "\", type is " << control->type() << llendl;
}
}
else
{
llwarns << "requested unknown control: \"" << key << '\"' << llendl;
}
}
}
//static
void LLViewerControlListener::setDefault(LLControlGroup * controls, LLSD const & event_data)
{
if(event_data.has("key"))
{
std::string key(event_data["key"]);
if(controls->controlExists(key))
{
LLControlVariable * control = controls->getControl(key);
control->resetToDefault();
}
else
{
llwarns << "requested unknown control: \"" << key << '\"' << llendl;
}
}
}
<commit_msg>Oops, copy/paste error in the llviewercontrol.cpp file top level comments.<commit_after>/**
* @file llviewercontrollistener.cpp
* @author Brad Kittenbrink
* @date 2009-07-09
* @brief Implementation for llviewercontrollistener.
*
* $LicenseInfo:firstyear=2009&license=viewergpl$
* Copyright (c) 2009, Linden Research, Inc.
* $/LicenseInfo$
*/
#include "llviewerprecompiledheaders.h"
#include "llviewercontrollistener.h"
#include "llviewercontrol.h"
LLViewerControlListener gSavedSettingsListener;
LLViewerControlListener::LLViewerControlListener()
: LLDispatchListener("LLViewerControl", "group")
{
add("Global", boost::bind(&LLViewerControlListener::set, &gSavedSettings, _1));
add("Skin", boost::bind(&LLViewerControlListener::set, &gSavedSkinSettings, _1));
add("PerAccount", boost::bind(&LLViewerControlListener::set, &gSavedPerAccountSettings, _1));
add("Warning", boost::bind(&LLViewerControlListener::set, &gWarningSettings, _1));
add("Crash", boost::bind(&LLViewerControlListener::set, &gCrashSettings, _1));
#if 0
add(/*"toggleControl",*/ "Global", boost::bind(&LLViewerControlListener::toggleControl, &gSavedSettings, _1));
add(/*"toggleControl",*/ "Skin", boost::bind(&LLViewerControlListener::toggleControl, &gSavedSkinSettings, _1));
add(/*"toggleControl",*/ "PerAccount", boost::bind(&LLViewerControlListener::toggleControl, &gSavedPerAccountSettings, _1));
add(/*"toggleControl",*/ "Warning", boost::bind(&LLViewerControlListener::toggleControl, &gWarningSettings, _1));
add(/*"toggleControl",*/ "Crash", boost::bind(&LLViewerControlListener::toggleControl, &gCrashSettings, _1));
add(/*"setDefault",*/ "Global", boost::bind(&LLViewerControlListener::setDefault, &gSavedSettings, _1));
add(/*"setDefault",*/ "Skin", boost::bind(&LLViewerControlListener::setDefault, &gSavedSkinSettings, _1));
add(/*"setDefault",*/ "PerAccount", boost::bind(&LLViewerControlListener::setDefault, &gSavedPerAccountSettings, _1));
add(/*"setDefault",*/ "Warning", boost::bind(&LLViewerControlListener::setDefault, &gWarningSettings, _1));
add(/*"setDefault",*/ "Crash", boost::bind(&LLViewerControlListener::setDefault, &gCrashSettings, _1));
#endif // 0
}
//static
void LLViewerControlListener::set(LLControlGroup * controls, LLSD const & event_data)
{
if(event_data.has("key"))
{
std::string key(event_data["key"]);
if(controls->controlExists(key))
{
controls->setUntypedValue(key, event_data["value"]);
}
else
{
llwarns << "requested unknown control: \"" << key << '\"' << llendl;
}
}
}
//static
void LLViewerControlListener::toggleControl(LLControlGroup * controls, LLSD const & event_data)
{
if(event_data.has("key"))
{
std::string key(event_data["key"]);
if(controls->controlExists(key))
{
LLControlVariable * control = controls->getControl(key);
if(control->isType(TYPE_BOOLEAN))
{
control->set(!control->get().asBoolean());
}
else
{
llwarns << "requested toggle of non-boolean control: \"" << key << "\", type is " << control->type() << llendl;
}
}
else
{
llwarns << "requested unknown control: \"" << key << '\"' << llendl;
}
}
}
//static
void LLViewerControlListener::setDefault(LLControlGroup * controls, LLSD const & event_data)
{
if(event_data.has("key"))
{
std::string key(event_data["key"]);
if(controls->controlExists(key))
{
LLControlVariable * control = controls->getControl(key);
control->resetToDefault();
}
else
{
llwarns << "requested unknown control: \"" << key << '\"' << llendl;
}
}
}
<|endoftext|>
|
<commit_before>/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/xla/service/gpu/tests/gpu_codegen_test.h"
#include "tensorflow/compiler/xla/tests/hlo_test_base.h"
namespace xla {
namespace gpu {
namespace {
class KernelThunkTest : public GpuCodegenTest {};
TEST_F(KernelThunkTest, Basic) {
const char* hlo_text = R"(
HloModule Test
add_F32 {
lhs = f32[] parameter(0)
rhs = f32[] parameter(1)
ROOT add = f32[] add(lhs, rhs)
}
ENTRY main {
a = f32[2, 2]{1,0} parameter(0)
b = f32[2, 2]{1,0} parameter(1)
ROOT r1 = f32[2, 2]{1,0} map(a, b), dimensions={0, 1}, to_apply=add_F32
}
)";
EXPECT_TRUE(RunAndCompare(hlo_text, ErrorSpec{1e-5, 1e-5}));
}
TEST_F(KernelThunkTest, KernelWithConstants) {
const char* hlo_text = R"(
HloModule Test
add_F32 {
lhs = f32[] parameter(0)
rhs = f32[] parameter(1)
ROOT add = f32[] add(lhs, rhs)
}
ENTRY main {
a = f32[2, 2]{1,0} constant({{1, 2}, {3, 4}})
b = f32[2, 2]{1,0} constant({{5, 6}, {7, 8}})
ROOT r1 = f32[2, 2]{1,0} map(a, b), dimensions={0, 1}, to_apply=add_F32
}
)";
EXPECT_TRUE(RunAndCompare(hlo_text, ErrorSpec{1e-5, 1e-5}));
}
} // namespace
} // namespace gpu
} // namespace xla
<commit_msg>Fixes for kernel thunk whole-program lowering.<commit_after>/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/xla/service/gpu/tests/gpu_codegen_test.h"
#include "tensorflow/compiler/xla/tests/hlo_test_base.h"
namespace xla {
namespace gpu {
namespace {
class KernelThunkTest : public GpuCodegenTest {};
TEST_F(KernelThunkTest, Basic) {
const char* hlo_text = R"(
HloModule Test1
add_F32 {
lhs = f32[] parameter(0)
rhs = f32[] parameter(1)
ROOT add = f32[] add(lhs, rhs)
}
ENTRY Test1 {
a = f32[2, 2]{1,0} parameter(0)
b = f32[2, 2]{1,0} parameter(1)
ROOT r1 = f32[2, 2]{1,0} map(a, b), dimensions={0, 1}, to_apply=add_F32
}
)";
EXPECT_TRUE(RunAndCompare(hlo_text, ErrorSpec{1e-5, 1e-5}));
}
TEST_F(KernelThunkTest, KernelWithConstants) {
const char* hlo_text = R"(
HloModule Test2
add_F32 {
lhs = f32[] parameter(0)
rhs = f32[] parameter(1)
ROOT add = f32[] add(lhs, rhs)
}
ENTRY Test2 {
a = f32[2, 2]{1,0} constant({{1, 2}, {3, 4}})
b = f32[2, 2]{1,0} constant({{5, 6}, {7, 8}})
ROOT r1 = f32[2, 2]{1,0} map(a, b), dimensions={0, 1}, to_apply=add_F32
}
)";
EXPECT_TRUE(RunAndCompare(hlo_text, ErrorSpec{1e-5, 1e-5}));
}
} // namespace
} // namespace gpu
} // namespace xla
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: simplecontinuousactivitybase.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-07 20:37:59 $
*
* 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 _SLIDESHOW_SIMPLECONTINUOUSACTIVITYBASE_HXX
#define _SLIDESHOW_SIMPLECONTINUOUSACTIVITYBASE_HXX
#include <activitybase.hxx>
#include <canvas/elapsedtime.hxx>
namespace presentation
{
namespace internal
{
/** Simple, continuous animation.
This class implements a simple, continuous animation
without considering repeats or acceleration on the
perform call. Only useful as a base class, you
probably want to use ContinuousActivityBase.
*/
class SimpleContinuousActivityBase : public ActivityBase
{
public:
SimpleContinuousActivityBase( const ActivityParameters& rParms );
virtual double calcTimeLag() const;
virtual bool perform();
virtual void dequeued();
protected:
/** Hook for derived classes
This method will be called from perform().
@param nSimpleTime
Simple animation time, without repeat,
acceleration or deceleration applied. This value
is always in the [0,1] range, the repeat is
accounted for with the nRepeatCount parameter.
@param nRepeatCount
Number of full repeats already performed
*/
virtual void simplePerform( double nSimpleTime, sal_uInt32 nRepeatCount ) const = 0;
virtual void startAnimation();
private:
/// Time elapsed since activity started
::canvas::tools::ElapsedTime maTimer;
/// Simple duration of activity
const double mnMinSimpleDuration;
/// Minimal number of frames to show (see ActivityParameters)
const sal_uInt32 mnMinNumberOfFrames;
/// Actual number of frames shown until now.
sal_uInt32 mnCurrPerformCalls;
};
}
}
#endif /* _SLIDESHOW_SIMPLECONTINUOUSACTIVITYBASE_HXX */
<commit_msg>INTEGRATION: CWS presfixes08 (1.3.24); FILE MERGED 2005/08/08 09:36:54 dbo 1.3.24.1: #i45197# dequeued() -> ActivityBase added end() Issue number: Submitted by: Reviewed by:<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: simplecontinuousactivitybase.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: obo $ $Date: 2005-10-11 08:41: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 _SLIDESHOW_SIMPLECONTINUOUSACTIVITYBASE_HXX
#define _SLIDESHOW_SIMPLECONTINUOUSACTIVITYBASE_HXX
#include <activitybase.hxx>
#include <canvas/elapsedtime.hxx>
namespace presentation
{
namespace internal
{
/** Simple, continuous animation.
This class implements a simple, continuous animation
without considering repeats or acceleration on the
perform call. Only useful as a base class, you
probably want to use ContinuousActivityBase.
*/
class SimpleContinuousActivityBase : public ActivityBase
{
public:
SimpleContinuousActivityBase( const ActivityParameters& rParms );
virtual double calcTimeLag() const;
virtual bool perform();
protected:
/** Hook for derived classes
This method will be called from perform().
@param nSimpleTime
Simple animation time, without repeat,
acceleration or deceleration applied. This value
is always in the [0,1] range, the repeat is
accounted for with the nRepeatCount parameter.
@param nRepeatCount
Number of full repeats already performed
*/
virtual void simplePerform( double nSimpleTime, sal_uInt32 nRepeatCount ) const = 0;
virtual void startAnimation();
private:
/// Time elapsed since activity started
::canvas::tools::ElapsedTime maTimer;
/// Simple duration of activity
const double mnMinSimpleDuration;
/// Minimal number of frames to show (see ActivityParameters)
const sal_uInt32 mnMinNumberOfFrames;
/// Actual number of frames shown until now.
sal_uInt32 mnCurrPerformCalls;
};
}
}
#endif /* _SLIDESHOW_SIMPLECONTINUOUSACTIVITYBASE_HXX */
<|endoftext|>
|
<commit_before>#include "boxml.h"
#include <algorithm>
#include <ctime>
#include <sst/sumi_api.h>
using namespace std;
using namespace sstmac;
namespace lblxml
{
int boxml::count_events () {
int ret = g_rank_to_comps[rank_].size()
+ g_rank_to_sends[rank_].size()
+ g_rank_to_recvs[rank_].size()
+ g_rank_to_allreduces[rank_].size();
return ret;
}
bool boxml::send_boxes(int& n_events) {
SSTMACBacktrace("send boxes");
// any sends ready?
da_list_t& v_sends(g_rank_to_valid_sends[rank_]);
set_t& my_sends(g_rank_to_sends[rank_]);
int n_send = v_sends.size();
if (randomize_events_)
std::random_shuffle(v_sends.begin(), v_sends.end());
int n_sent = 0;
while (!v_sends.empty()) {
comm_t* sendptr = static_cast<comm_t*>(g_events[v_sends.front()]);
comm_t& send = *sendptr;
if (send.n_dep() == 0) { // abundance of caution
//int count = send.size();
int count = 0;
int dest_box = send.to();
int dest = g_boxindex_to_rank[ dest_box ];
int index = send.index();
if( dest != rank_ ) {
++n_sent;
if (debug_ > 0)
std::cerr << "boxml: rank " << rank_ << " sending message " << index << " to rank " << dest << "\n";
pt2pt_message::ptr mess = new pt2pt_message(index,count);
comm_rdma_put(dest, mess);
}
else {
simple_event_done(index);
}
my_sends.erase(send.index());
v_sends.pop_front();
}
else {
std::cerr << "error: valid send has n_deps > 0\n";
abort();
}
}
int old_n_events = n_events;
n_events -= n_sent;
//events aren't tracked properly anymore
if (0) {
cout << "Rank " << rank_ << " posted " << n_sent << " sends\n";
if (n_send > 0) {
int temp_n = count_events();
if (temp_n != n_events) {
std::cerr << "send_boxes: n_events " << n_events << " doesn't match count_events() "
<< temp_n << "\n";
abort();
}
cout << "Rank " << rank_ << " after send processing, "
<< " continuing while loop with " << n_events
<< " events remaining (delta=" << n_events - old_n_events
<< ")\n";
}
}
if (n_sent > 0)
return true;
return false;
}
/**
* @brief boxml::reduce
* @param n_events [IN,OUT] Number of outstanding events - decrement
* @return
*/
bool boxml::reduce(int& n_events) {
SSTMACBacktrace("reduce");
int n_allreduce = valid_allreduces_.size();
while (!valid_allreduces_.empty()) {
index_box_pair_t pair = valid_allreduces_.front();
valid_allreduces_.pop();
int index = pair.first;
int box_number = pair.second;
event* ev = g_events[index];
reduce_t* comm = static_cast<reduce_t*>(ev);
int my_domain_rank = comm->domain_rank(box_number);
const int* boxes = comm->box_array();
sumi::domain* dom = new box_domain(my_domain_rank, comm->nboxes(), boxes, g_boxindex_to_rank.data());
int count = comm->size();
if (debug_ > 0)
std::cerr << "boxml: rank " << rank_ << " starting allreduce " << ev->id() << " for box " << box_number << "\n";
sumi::comm_allreduce<double,sumi::Add>(NULL, NULL, count, index,
false, sumi::options::initial_context, dom);
}
return n_allreduce > 0;
}
bool boxml::compute_boxes(int& n_events) {
SSTMACBacktrace("compute boxes");
da_list_t& v_comps(g_rank_to_valid_comps[rank_]);
set_t& my_comps(g_rank_to_comps[rank_]);
int n_comp = v_comps.size();
if (n_comp) {
if (randomize_events_)
std::random_shuffle(v_comps.begin(), v_comps.end());
comp_t* compptr = static_cast<comp_t*>(g_events[v_comps.front()]);
comp_t& comp = *compptr;
if (comp.n_dep() == 0) { // Abundance of caution
if (do_compute_) {
compute( timestamp( compute_scale_ * comp.time() ));
}
if (debug_ > 0) {
cout << "boxml: rank " << rank_ << ": all deps satisfied, performing compute "
<< comp.id() << " on " << rank_ << "\n";
}
my_comps.erase(comp.index());
v_comps.pop_front();
simple_event_done(comp.index());
n_events -= 1; //I only do one compute at a time
}
else {
spkt_throw_printf(sprockit::value_error,
"valid compute event %d still has %d deps",
comp.index(), comp.n_dep());
}
}
n_comp = min(n_comp,1);
int old_n_events = n_events;
// events aren't properly tracked anymore
if (0) {
cout << "Rank " << rank_ << " completed " << n_comp << " computes\n";
if (n_comp) {
int temp_n = count_events();
if (temp_n != n_events) {
std::cerr << "compute_boxes: n_events doesn't match count_events()\n";
abort();
}
cout << "Rank " << rank_ << " after compute processing, "
<< " continuing while loop with " << n_events
<< " events remaining (delta=" << n_events - old_n_events
<< ")\n";
}
}
if (n_comp > 0)
return true;
return false;
}
void boxml::recv_boxes(int& n_events)
{
SSTMACBacktrace("recv boxes");
sumi::message::ptr dmess = sumi::comm_poll();
switch (dmess->class_type()){
case sumi::message::pt2pt:
{
if (debug_ > 0)
std::cerr << "boxml: rank " << rank_ << " receiving pt2pt message\n";
pt2pt_message::ptr pmess = ptr_safe_cast(pt2pt_message, dmess);
simple_event_done(pmess->event_index());
break;
}
case sumi::message::collective_done:
{
sumi::collective_done_message::ptr cmess = ptr_safe_cast(sumi::collective_done_message, dmess);
box_domain* dom = static_cast<box_domain*>(cmess->dom());
int my_box_number = dom->my_box_number();
if (debug_ > 0)
std::cerr << "boxml: rank " << rank_ << " receiving collective_done message for " << cmess->tag() << "\n";
collective_done(my_box_number, cmess->tag());
//for now, we dynamically create domains - delete it
delete dom;
break;
}
default:
{
spkt_throw_printf(sprockit::value_error,
"got invalid message type %s",
sumi::message::tostr(dmess->class_type()));
}
}
int old_n_events = n_events;
--n_events;
// events aren't properly tracked anymore
if (0) {
cout << "Rank " << rank_ << " handled receive\n";
int temp_n = count_events();
if (temp_n != n_events) {
std::cerr << "recv_boxes: n_events " << n_events << " doesn't match count_events() "
<< temp_n << "\n";
abort();
}
cout << "Rank " << rank_ << " after recv processing, "
<< " continuing while loop with " << n_events
<< " events remaining (delta=" << n_events - old_n_events
<< ")\n";
}
}
void boxml::run_loop() {
SSTMACBacktrace("run loop");
//std::cerr << "Rank 0 entering run loop with "
// << g_rank_to_recvs[0].size() << " recvs\n";
if (debug_ > 0) cout << "Rank " << rank_ << " entering run loop with "
<< g_rank_to_recvs[rank_].size() << " recvs\n";
// Loop until no elements left
int total_events = count_events();
int n_events = total_events;
int q_events = total_events/4;
bool q1 = false, q2 = false, q3 = false;
while (n_events > 0) {
bool doloop = true;
//while (doloop) {
if (debug_ > 0 || detailed_progress_ ) {
if (n_events < 3 * q_events && q1 == false) {
cout << "Rank " << rank_ << " 25% complete\n";
q1 = true;
}
if (n_events < 2 * q_events && q2 == false) {
cout << "Rank " << rank_ << " 50% complete\n";
q2 = true;
}
if (n_events < q_events && q3 == false) {
cout << "Rank " << rank_ << " 75% complete\n";
q3 = true;
}
}
else if (rank_ == 0) {
if (n_events < 3 * q_events && q1 == false) {
cout << "Rank 0 25% complete\n";
q1 = true;
}
if (n_events < 2 * q_events && q2 == false) {
cout << "Rank 0 50% complete\n";
q2 = true;
}
if (n_events < q_events && q3 == false) {
cout << "Rank 0 75% complete\n";
q3 = true;
}
}
if(detailed_progress_ && rank_ == 0) {
cout << "Rank 0 completed " << total_events - n_events << " of " << total_events
<< " events\n";
cout << std::flush;
cerr << std::flush;
}
//std::cerr << "Rank before send boxes with "
// << g_rank_to_recvs[0].size() << " recvs\n";
bool skip_to_next_loop = send_boxes(n_events);
if (skip_to_next_loop)
continue;
//std::cerr << "Rank before compute boxes with "
// << g_rank_to_recvs[0].size() << " recvs\n";
skip_to_next_loop = compute_boxes(n_events);
if (skip_to_next_loop)
continue;
//std::cerr << "Rank before reduce with "
// << g_rank_to_recvs[0].size() << " recvs\n";
skip_to_next_loop = reduce(n_events);
if (skip_to_next_loop)
continue;
//std::cerr << "Rank before recv with "
// << g_rank_to_recvs[0].size() << " recvs\n";
recv_boxes(n_events);
//if( n_events == count_events())
// sstmac_usleep(1000);
doloop = false;
}
if (debug_ > 0)
cout << "Rank " << rank_ << " completed run loop\n";
}
}
<commit_msg>remove debugging hack from boxml<commit_after>#include "boxml.h"
#include <algorithm>
#include <ctime>
#include <sst/sumi_api.h>
using namespace std;
using namespace sstmac;
namespace lblxml
{
int boxml::count_events () {
int ret = g_rank_to_comps[rank_].size()
+ g_rank_to_sends[rank_].size()
+ g_rank_to_recvs[rank_].size()
+ g_rank_to_allreduces[rank_].size();
return ret;
}
bool boxml::send_boxes(int& n_events) {
SSTMACBacktrace("send boxes");
// any sends ready?
da_list_t& v_sends(g_rank_to_valid_sends[rank_]);
set_t& my_sends(g_rank_to_sends[rank_]);
int n_send = v_sends.size();
if (randomize_events_)
std::random_shuffle(v_sends.begin(), v_sends.end());
int n_sent = 0;
while (!v_sends.empty()) {
comm_t* sendptr = static_cast<comm_t*>(g_events[v_sends.front()]);
comm_t& send = *sendptr;
if (send.n_dep() == 0) { // abundance of caution
int count = send.size();
int dest_box = send.to();
int dest = g_boxindex_to_rank[ dest_box ];
int index = send.index();
if( dest != rank_ ) {
++n_sent;
if (debug_ > 0)
std::cerr << "boxml: rank " << rank_ << " sending message " << index << " to rank " << dest << "\n";
pt2pt_message::ptr mess = new pt2pt_message(index,count);
comm_rdma_put(dest, mess);
}
else {
simple_event_done(index);
}
my_sends.erase(send.index());
v_sends.pop_front();
}
else {
std::cerr << "error: valid send has n_deps > 0\n";
abort();
}
}
int old_n_events = n_events;
n_events -= n_sent;
//events aren't tracked properly anymore
if (0) {
cout << "Rank " << rank_ << " posted " << n_sent << " sends\n";
if (n_send > 0) {
int temp_n = count_events();
if (temp_n != n_events) {
std::cerr << "send_boxes: n_events " << n_events << " doesn't match count_events() "
<< temp_n << "\n";
abort();
}
cout << "Rank " << rank_ << " after send processing, "
<< " continuing while loop with " << n_events
<< " events remaining (delta=" << n_events - old_n_events
<< ")\n";
}
}
if (n_sent > 0)
return true;
return false;
}
/**
* @brief boxml::reduce
* @param n_events [IN,OUT] Number of outstanding events - decrement
* @return
*/
bool boxml::reduce(int& n_events) {
SSTMACBacktrace("reduce");
int n_allreduce = valid_allreduces_.size();
while (!valid_allreduces_.empty()) {
index_box_pair_t pair = valid_allreduces_.front();
valid_allreduces_.pop();
int index = pair.first;
int box_number = pair.second;
event* ev = g_events[index];
reduce_t* comm = static_cast<reduce_t*>(ev);
int my_domain_rank = comm->domain_rank(box_number);
const int* boxes = comm->box_array();
sumi::domain* dom = new box_domain(my_domain_rank, comm->nboxes(), boxes, g_boxindex_to_rank.data());
int count = comm->size();
if (debug_ > 0)
std::cerr << "boxml: rank " << rank_ << " starting allreduce " << ev->id() << " for box " << box_number << "\n";
sumi::comm_allreduce<double,sumi::Add>(NULL, NULL, count, index,
false, sumi::options::initial_context, dom);
}
return n_allreduce > 0;
}
bool boxml::compute_boxes(int& n_events) {
SSTMACBacktrace("compute boxes");
da_list_t& v_comps(g_rank_to_valid_comps[rank_]);
set_t& my_comps(g_rank_to_comps[rank_]);
int n_comp = v_comps.size();
if (n_comp) {
if (randomize_events_)
std::random_shuffle(v_comps.begin(), v_comps.end());
comp_t* compptr = static_cast<comp_t*>(g_events[v_comps.front()]);
comp_t& comp = *compptr;
if (comp.n_dep() == 0) { // Abundance of caution
if (do_compute_) {
compute( timestamp( compute_scale_ * comp.time() ));
}
if (debug_ > 0) {
cout << "boxml: rank " << rank_ << ": all deps satisfied, performing compute "
<< comp.id() << " on " << rank_ << "\n";
}
my_comps.erase(comp.index());
v_comps.pop_front();
simple_event_done(comp.index());
n_events -= 1; //I only do one compute at a time
}
else {
spkt_throw_printf(sprockit::value_error,
"valid compute event %d still has %d deps",
comp.index(), comp.n_dep());
}
}
n_comp = min(n_comp,1);
int old_n_events = n_events;
// events aren't properly tracked anymore
if (0) {
cout << "Rank " << rank_ << " completed " << n_comp << " computes\n";
if (n_comp) {
int temp_n = count_events();
if (temp_n != n_events) {
std::cerr << "compute_boxes: n_events doesn't match count_events()\n";
abort();
}
cout << "Rank " << rank_ << " after compute processing, "
<< " continuing while loop with " << n_events
<< " events remaining (delta=" << n_events - old_n_events
<< ")\n";
}
}
if (n_comp > 0)
return true;
return false;
}
void boxml::recv_boxes(int& n_events)
{
SSTMACBacktrace("recv boxes");
sumi::message::ptr dmess = sumi::comm_poll();
switch (dmess->class_type()){
case sumi::message::pt2pt:
{
if (debug_ > 0)
std::cerr << "boxml: rank " << rank_ << " receiving pt2pt message\n";
pt2pt_message::ptr pmess = ptr_safe_cast(pt2pt_message, dmess);
simple_event_done(pmess->event_index());
break;
}
case sumi::message::collective_done:
{
sumi::collective_done_message::ptr cmess = ptr_safe_cast(sumi::collective_done_message, dmess);
box_domain* dom = static_cast<box_domain*>(cmess->dom());
int my_box_number = dom->my_box_number();
if (debug_ > 0)
std::cerr << "boxml: rank " << rank_ << " receiving collective_done message for " << cmess->tag() << "\n";
collective_done(my_box_number, cmess->tag());
//for now, we dynamically create domains - delete it
delete dom;
break;
}
default:
{
spkt_throw_printf(sprockit::value_error,
"got invalid message type %s",
sumi::message::tostr(dmess->class_type()));
}
}
int old_n_events = n_events;
--n_events;
// events aren't properly tracked anymore
if (0) {
cout << "Rank " << rank_ << " handled receive\n";
int temp_n = count_events();
if (temp_n != n_events) {
std::cerr << "recv_boxes: n_events " << n_events << " doesn't match count_events() "
<< temp_n << "\n";
abort();
}
cout << "Rank " << rank_ << " after recv processing, "
<< " continuing while loop with " << n_events
<< " events remaining (delta=" << n_events - old_n_events
<< ")\n";
}
}
void boxml::run_loop() {
SSTMACBacktrace("run loop");
//std::cerr << "Rank 0 entering run loop with "
// << g_rank_to_recvs[0].size() << " recvs\n";
if (debug_ > 0) cout << "Rank " << rank_ << " entering run loop with "
<< g_rank_to_recvs[rank_].size() << " recvs\n";
// Loop until no elements left
int total_events = count_events();
int n_events = total_events;
int q_events = total_events/4;
bool q1 = false, q2 = false, q3 = false;
while (n_events > 0) {
bool doloop = true;
//while (doloop) {
if (debug_ > 0 || detailed_progress_ ) {
if (n_events < 3 * q_events && q1 == false) {
cout << "Rank " << rank_ << " 25% complete\n";
q1 = true;
}
if (n_events < 2 * q_events && q2 == false) {
cout << "Rank " << rank_ << " 50% complete\n";
q2 = true;
}
if (n_events < q_events && q3 == false) {
cout << "Rank " << rank_ << " 75% complete\n";
q3 = true;
}
}
else if (rank_ == 0) {
if (n_events < 3 * q_events && q1 == false) {
cout << "Rank 0 25% complete\n";
q1 = true;
}
if (n_events < 2 * q_events && q2 == false) {
cout << "Rank 0 50% complete\n";
q2 = true;
}
if (n_events < q_events && q3 == false) {
cout << "Rank 0 75% complete\n";
q3 = true;
}
}
if(detailed_progress_ && rank_ == 0) {
cout << "Rank 0 completed " << total_events - n_events << " of " << total_events
<< " events\n";
cout << std::flush;
cerr << std::flush;
}
//std::cerr << "Rank before send boxes with "
// << g_rank_to_recvs[0].size() << " recvs\n";
bool skip_to_next_loop = send_boxes(n_events);
if (skip_to_next_loop)
continue;
//std::cerr << "Rank before compute boxes with "
// << g_rank_to_recvs[0].size() << " recvs\n";
skip_to_next_loop = compute_boxes(n_events);
if (skip_to_next_loop)
continue;
//std::cerr << "Rank before reduce with "
// << g_rank_to_recvs[0].size() << " recvs\n";
skip_to_next_loop = reduce(n_events);
if (skip_to_next_loop)
continue;
//std::cerr << "Rank before recv with "
// << g_rank_to_recvs[0].size() << " recvs\n";
recv_boxes(n_events);
//if( n_events == count_events())
// sstmac_usleep(1000);
doloop = false;
}
if (debug_ > 0)
cout << "Rank " << rank_ << " completed run loop\n";
}
}
<|endoftext|>
|
<commit_before>#include "../../../shared/SystemImplBase.h"
#include "common/RhoConf.h"
#include "logging/RhoLog.h"
#include "../../platform/shared/qt/rhodes/impl/MainWindowImpl.h"
#include "../../platform/shared/qt/rhodes/RhoSimulator.h"
#undef null
#include <qwebkitglobal.h>
#include <QLocale>
#include <QDesktopServices>
#include <QUrl>
#undef DEFAULT_LOGCATEGORY
#define DEFAULT_LOGCATEGORY "System"
namespace rho {
using namespace apiGenerator;
class CSystemImpl: public CSystemImplBase
{
public:
CSystemImpl(): CSystemImplBase(){}
virtual void getScreenWidth(CMethodResult& oResult);
virtual void getScreenHeight(CMethodResult& oResult);
virtual void getScreenOrientation(CMethodResult& oResult);
virtual void getPpiX(CMethodResult& oResult);
virtual void getPpiY(CMethodResult& oResult);
virtual void getPhoneId(CMethodResult& oResult);
virtual void getDeviceName(CMethodResult& oResult);
virtual void getOsVersion(CMethodResult& oResult);
virtual void getIsMotorolaDevice(CMethodResult& oResult);
virtual void getLocale(CMethodResult& oResult);
virtual void getCountry(CMethodResult& oResult);
virtual void getIsEmulator(CMethodResult& oResult);
virtual void getHasCalendar(CMethodResult& oResult);
virtual void getOemInfo(CMethodResult& oResult);
virtual void getUuid(CMethodResult& oResult);
virtual void getHttpProxyURI(CMethodResult& oResult);
virtual void setHttpProxyURI( const rho::String& value, CMethodResult& oResult);
virtual void getLockWindowSize(CMethodResult& oResult);
virtual void setLockWindowSize( bool value, CMethodResult& oResult);
virtual void getKeyboardState(CMethodResult& oResult);
virtual void setKeyboardState( const rho::String& value, CMethodResult& oResult);
virtual void getFullScreen(CMethodResult& oResult);
virtual void setFullScreen( bool value, CMethodResult& oResult);
virtual void getScreenAutoRotate(CMethodResult& oResult);
virtual void setScreenAutoRotate( bool value, CMethodResult& oResult);
virtual void getHasTouchscreen(rho::apiGenerator::CMethodResult& oResult);
virtual void getScreenSleeping(rho::apiGenerator::CMethodResult& oResult);
virtual void setScreenSleeping( bool value, rho::apiGenerator::CMethodResult& oResult);
virtual void applicationInstall( const rho::String& applicationUrl, CMethodResult& oResult);
virtual void isApplicationInstalled( const rho::String& applicationName, CMethodResult& oResult);
virtual void applicationUninstall( const rho::String& applicationName, CMethodResult& oResult);
virtual void openUrl( const rho::String& url, CMethodResult& oResult);
virtual void setRegistrySetting( int hive, int type, const rho::String& subKey, const rho::String& setting, const rho::String& value, rho::apiGenerator::CMethodResult& oResult);
virtual void getRegistrySetting( int hive, const rho::String& subKey, const rho::String& setting, rho::apiGenerator::CMethodResult& oResult);
virtual void setWindowFrame( int x, int y, int width, int height, CMethodResult& oResult);
virtual void setWindowPosition( int x, int y, CMethodResult& oResult);
virtual void setWindowSize( int width, int height, rho::apiGenerator::CMethodResult& oResult);
virtual void getWebviewFramework(rho::apiGenerator::CMethodResult& oResult);
virtual void bringToFront(rho::apiGenerator::CMethodResult& oResult);
virtual void runApplication( const rho::String& appName, const rho::String& params, bool blockingCall, rho::apiGenerator::CMethodResult& oResult);
virtual void set_http_proxy_url( const rho::String& proxyURI, rho::apiGenerator::CMethodResult& oResult);
virtual void unset_http_proxy(rho::apiGenerator::CMethodResult& oResult);
};
void CSystemImpl::getOsVersion(CMethodResult& oResult)
{
oResult.set(String(RHOSIMULATOR_NAME " v" RHOSIMULATOR_VERSION));
}
void CSystemImpl::getIsEmulator(CMethodResult& oResult)
{
oResult.set(true);
}
void CSystemImpl::getScreenWidth(CMethodResult& oResult)
{
oResult.set(CMainWindow::getScreenWidth());
}
void CSystemImpl::getScreenHeight(CMethodResult& oResult)
{
oResult.set(CMainWindow::getScreenHeight());
}
void CSystemImpl::getScreenOrientation(CMethodResult& oResult)
{
oResult.set(StringW(CMainWindow::getScreenWidth() <= CMainWindow::getScreenHeight() ? L"portrait" : L"landscape"));
}
void CSystemImpl::getPpiX(CMethodResult& oResult)
{
oResult.set(CMainWindow::getInstance()->getLogicalDpiX());
}
void CSystemImpl::getPpiY(CMethodResult& oResult)
{
oResult.set(CMainWindow::getInstance()->getLogicalDpiY());
}
void CSystemImpl::getPhoneId(CMethodResult& oResult)
{
//oResult.set(...);
getOsVersion(oResult);
}
void CSystemImpl::getDeviceName(CMethodResult& oResult)
{
oResult.set(String("Qt"));
}
void CSystemImpl::getLocale(CMethodResult& oResult)
{
oResult.set(String(QLocale::system().name().left(2).toStdString().c_str()));
}
void CSystemImpl::getCountry(CMethodResult& oResult)
{
oResult.set(String(QLocale::system().name().right(2).toStdString().c_str()));
}
void CSystemImpl::getHasCalendar(CMethodResult& oResult)
{
oResult.set(true);
}
void CSystemImpl::getIsMotorolaDevice(CMethodResult& oResult)
{
oResult.set(false);
}
void CSystemImpl::getOemInfo(CMethodResult& oResult)
{
//oResult.set(...);
}
void CSystemImpl::getUuid(CMethodResult& oResult)
{
//oResult.set(...);
}
void CSystemImpl::getLockWindowSize(CMethodResult& oResult){}
void CSystemImpl::setLockWindowSize( bool value, CMethodResult& oResult){}
//void CSystemImpl::getKeyboardState(CMethodResult& oResult){}
//void CSystemImpl::setKeyboardState( const rho::String& value, CMethodResult& oResult){}
void CSystemImpl::getFullScreen(CMethodResult& oResult)
{
//all apps working in full screen mode on WP8
oResult.set(CMainWindow::getInstance()->getFullScreen());
}
void CSystemImpl::setFullScreen(bool value, CMethodResult& oResult)
{
CMainWindow::getInstance()->fullscreenCommand(value);
}
void CSystemImpl::getScreenAutoRotate(CMethodResult& oResult)
{
oResult.set(false);
}
void CSystemImpl::setScreenAutoRotate( bool value, CMethodResult& oResult)
{
// TODO: impolement auto rotate
}
void CSystemImpl::applicationInstall( const rho::String& applicationUrl, CMethodResult& oResult)
{
}
void CSystemImpl::isApplicationInstalled( const rho::String& applicationName, CMethodResult& oResult)
{
oResult.set(false);
}
void CSystemImpl::applicationUninstall( const rho::String& applicationName, CMethodResult& oResult)
{
}
void CSystemImpl::openUrl( const rho::String& url, CMethodResult& oResult)
{
QString sUrl = QString::fromStdString(url);
if (sUrl.startsWith("/"))
sUrl.prepend("file://");
QDesktopServices::openUrl(QUrl(sUrl));
}
void CSystemImpl::runApplication( const rho::String& appName, const rho::String& params, bool blockingCall, CMethodResult& oResult)
{
//unsupported
}
void CSystemImpl::setRegistrySetting( int hive, int type, const rho::String& subKey, const rho::String& setting, const rho::String& value, rho::apiGenerator::CMethodResult& oResult)
{
//unsupported
}
void CSystemImpl::getRegistrySetting( int hive, const rho::String& subKey, const rho::String& setting, rho::apiGenerator::CMethodResult& oResult)
{
//unsupported
}
void CSystemImpl::setWindowFrame(int x, int y, int width, int height, CMethodResult& oResult)
{
CMainWindow::getInstance()->setFrame(x, y, width, height);
}
void CSystemImpl::setWindowPosition( int x, int y, CMethodResult& oResult)
{
CMainWindow::getInstance()->setPosition(x, y);
}
void CSystemImpl::getWebviewFramework(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set(String("WEBKIT/" QTWEBKIT_VERSION_STR));
}
void CSystemImpl::bringToFront(rho::apiGenerator::CMethodResult& oResult)
{
CMainWindow::getInstance()->bringToFront();
}
extern "C" const char* rho_sys_get_http_proxy_url();
extern "C" void rho_sys_set_http_proxy_url(const char* url);
extern "C" void rho_sys_unset_http_proxy();
void CSystemImpl::getHttpProxyURI(CMethodResult& oResult)
{
oResult.set(rho_sys_get_http_proxy_url());
}
void CSystemImpl::setHttpProxyURI( const rho::String& value, CMethodResult& oResult)
{
if ( value.length() )
rho_sys_set_http_proxy_url( value.c_str() );
else
rho_sys_unset_http_proxy();
}
void CSystemImpl::getHasTouchscreen(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set(true);
}
void CSystemImpl::getScreenSleeping(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set(false);
}
void CSystemImpl::setScreenSleeping( bool value, rho::apiGenerator::CMethodResult& oResult)
{
//unsupported
}
void CSystemImpl::setWindowSize( int width, int height, rho::apiGenerator::CMethodResult& oResult)
{
CMainWindow::getInstance()->setSize(width, height);
}
void CSystemImpl::set_http_proxy_url( const rho::String& proxyURI, rho::apiGenerator::CMethodResult& oResult)
{
rho_sys_set_http_proxy_url( proxyURI.c_str() );
}
void CSystemImpl::unset_http_proxy(rho::apiGenerator::CMethodResult& oResult)
{
rho_sys_unset_http_proxy();
}
////////////////////////////////////////////////////////////////////////
class CSystemSingleton: public CModuleSingletonBase<ISystemSingleton>
{
public:
~CSystemSingleton(){}
rho::StringW getInitialDefaultID(){return L"1";}
rho::StringW getDefaultID(){return L"1";}
void setDefaultID(const rho::StringW& strI){}
};
class CSystemFactory: public CSystemFactoryBase
{
public:
~CSystemFactory(){}
ISystemSingleton* createModuleSingleton(){ return new CSystemImpl(); }
};
extern "C" void Init_System()
{
CSystemFactory::setInstance( new CSystemFactory() );
Init_System_API();
}
}
<commit_msg>rhosimulator/osx: build fixed<commit_after>#include "../../../shared/SystemImplBase.h"
#include "common/RhoConf.h"
#include "logging/RhoLog.h"
#include "../../platform/shared/qt/rhodes/impl/MainWindowImpl.h"
#include "../../platform/shared/qt/rhodes/RhoSimulator.h"
#undef null
#include <qwebkitglobal.h>
#include <QLocale>
#include <QDesktopServices>
#include <QUrl>
#undef DEFAULT_LOGCATEGORY
#define DEFAULT_LOGCATEGORY "System"
namespace rho {
using namespace apiGenerator;
class CSystemImpl: public CSystemImplBase
{
public:
CSystemImpl(): CSystemImplBase(){}
virtual void getScreenWidth(CMethodResult& oResult);
virtual void getScreenHeight(CMethodResult& oResult);
virtual void getScreenOrientation(CMethodResult& oResult);
virtual void getPpiX(CMethodResult& oResult);
virtual void getPpiY(CMethodResult& oResult);
virtual void getPhoneId(CMethodResult& oResult);
virtual void getDeviceName(CMethodResult& oResult);
virtual void getOsVersion(CMethodResult& oResult);
virtual void getIsMotorolaDevice(CMethodResult& oResult);
virtual void getLocale(CMethodResult& oResult);
virtual void getCountry(CMethodResult& oResult);
virtual void getIsEmulator(CMethodResult& oResult);
virtual void getHasCalendar(CMethodResult& oResult);
virtual void getOemInfo(CMethodResult& oResult);
virtual void getUuid(CMethodResult& oResult);
virtual void getHttpProxyURI(CMethodResult& oResult);
virtual void setHttpProxyURI( const rho::String& value, CMethodResult& oResult);
virtual void getLockWindowSize(CMethodResult& oResult);
virtual void setLockWindowSize( bool value, CMethodResult& oResult);
//virtual void getKeyboardState(CMethodResult& oResult);
//virtual void setKeyboardState( const rho::String& value, CMethodResult& oResult);
virtual void getFullScreen(CMethodResult& oResult);
virtual void setFullScreen( bool value, CMethodResult& oResult);
virtual void getScreenAutoRotate(CMethodResult& oResult);
virtual void setScreenAutoRotate( bool value, CMethodResult& oResult);
virtual void getHasTouchscreen(rho::apiGenerator::CMethodResult& oResult);
virtual void getScreenSleeping(rho::apiGenerator::CMethodResult& oResult);
virtual void setScreenSleeping( bool value, rho::apiGenerator::CMethodResult& oResult);
virtual void applicationInstall( const rho::String& applicationUrl, CMethodResult& oResult);
virtual void isApplicationInstalled( const rho::String& applicationName, CMethodResult& oResult);
virtual void applicationUninstall( const rho::String& applicationName, CMethodResult& oResult);
virtual void openUrl( const rho::String& url, CMethodResult& oResult);
virtual void setRegistrySetting( int hive, int type, const rho::String& subKey, const rho::String& setting, const rho::String& value, rho::apiGenerator::CMethodResult& oResult);
virtual void getRegistrySetting( int hive, const rho::String& subKey, const rho::String& setting, rho::apiGenerator::CMethodResult& oResult);
virtual void setWindowFrame( int x, int y, int width, int height, CMethodResult& oResult);
virtual void setWindowPosition( int x, int y, CMethodResult& oResult);
virtual void setWindowSize( int width, int height, rho::apiGenerator::CMethodResult& oResult);
virtual void getWebviewFramework(rho::apiGenerator::CMethodResult& oResult);
virtual void bringToFront(rho::apiGenerator::CMethodResult& oResult);
virtual void runApplication( const rho::String& appName, const rho::String& params, bool blockingCall, rho::apiGenerator::CMethodResult& oResult);
virtual void set_http_proxy_url( const rho::String& proxyURI, rho::apiGenerator::CMethodResult& oResult);
virtual void unset_http_proxy(rho::apiGenerator::CMethodResult& oResult);
};
void CSystemImpl::getOsVersion(CMethodResult& oResult)
{
oResult.set(String(RHOSIMULATOR_NAME " v" RHOSIMULATOR_VERSION));
}
void CSystemImpl::getIsEmulator(CMethodResult& oResult)
{
oResult.set(true);
}
void CSystemImpl::getScreenWidth(CMethodResult& oResult)
{
oResult.set(CMainWindow::getScreenWidth());
}
void CSystemImpl::getScreenHeight(CMethodResult& oResult)
{
oResult.set(CMainWindow::getScreenHeight());
}
void CSystemImpl::getScreenOrientation(CMethodResult& oResult)
{
oResult.set(StringW(CMainWindow::getScreenWidth() <= CMainWindow::getScreenHeight() ? L"portrait" : L"landscape"));
}
void CSystemImpl::getPpiX(CMethodResult& oResult)
{
oResult.set(CMainWindow::getInstance()->getLogicalDpiX());
}
void CSystemImpl::getPpiY(CMethodResult& oResult)
{
oResult.set(CMainWindow::getInstance()->getLogicalDpiY());
}
void CSystemImpl::getPhoneId(CMethodResult& oResult)
{
//oResult.set(...);
getOsVersion(oResult);
}
void CSystemImpl::getDeviceName(CMethodResult& oResult)
{
oResult.set(String("Qt"));
}
void CSystemImpl::getLocale(CMethodResult& oResult)
{
oResult.set(String(QLocale::system().name().left(2).toStdString().c_str()));
}
void CSystemImpl::getCountry(CMethodResult& oResult)
{
oResult.set(String(QLocale::system().name().right(2).toStdString().c_str()));
}
void CSystemImpl::getHasCalendar(CMethodResult& oResult)
{
oResult.set(true);
}
void CSystemImpl::getIsMotorolaDevice(CMethodResult& oResult)
{
oResult.set(false);
}
void CSystemImpl::getOemInfo(CMethodResult& oResult)
{
//oResult.set(...);
}
void CSystemImpl::getUuid(CMethodResult& oResult)
{
//oResult.set(...);
}
void CSystemImpl::getLockWindowSize(CMethodResult& oResult){}
void CSystemImpl::setLockWindowSize( bool value, CMethodResult& oResult){}
//void CSystemImpl::getKeyboardState(CMethodResult& oResult){}
//void CSystemImpl::setKeyboardState( const rho::String& value, CMethodResult& oResult){}
void CSystemImpl::getFullScreen(CMethodResult& oResult)
{
//all apps working in full screen mode on WP8
oResult.set(CMainWindow::getInstance()->getFullScreen());
}
void CSystemImpl::setFullScreen(bool value, CMethodResult& oResult)
{
CMainWindow::getInstance()->fullscreenCommand(value);
}
void CSystemImpl::getScreenAutoRotate(CMethodResult& oResult)
{
oResult.set(false);
}
void CSystemImpl::setScreenAutoRotate( bool value, CMethodResult& oResult)
{
// TODO: impolement auto rotate
}
void CSystemImpl::applicationInstall( const rho::String& applicationUrl, CMethodResult& oResult)
{
}
void CSystemImpl::isApplicationInstalled( const rho::String& applicationName, CMethodResult& oResult)
{
oResult.set(false);
}
void CSystemImpl::applicationUninstall( const rho::String& applicationName, CMethodResult& oResult)
{
}
void CSystemImpl::openUrl( const rho::String& url, CMethodResult& oResult)
{
QString sUrl = QString::fromStdString(url);
if (sUrl.startsWith("/"))
sUrl.prepend("file://");
QDesktopServices::openUrl(QUrl(sUrl));
}
void CSystemImpl::runApplication( const rho::String& appName, const rho::String& params, bool blockingCall, CMethodResult& oResult)
{
//unsupported
}
void CSystemImpl::setRegistrySetting( int hive, int type, const rho::String& subKey, const rho::String& setting, const rho::String& value, rho::apiGenerator::CMethodResult& oResult)
{
//unsupported
}
void CSystemImpl::getRegistrySetting( int hive, const rho::String& subKey, const rho::String& setting, rho::apiGenerator::CMethodResult& oResult)
{
//unsupported
}
void CSystemImpl::setWindowFrame(int x, int y, int width, int height, CMethodResult& oResult)
{
CMainWindow::getInstance()->setFrame(x, y, width, height);
}
void CSystemImpl::setWindowPosition( int x, int y, CMethodResult& oResult)
{
CMainWindow::getInstance()->setPosition(x, y);
}
void CSystemImpl::getWebviewFramework(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set(String("WEBKIT/" QTWEBKIT_VERSION_STR));
}
void CSystemImpl::bringToFront(rho::apiGenerator::CMethodResult& oResult)
{
CMainWindow::getInstance()->bringToFront();
}
extern "C" const char* rho_sys_get_http_proxy_url();
extern "C" void rho_sys_set_http_proxy_url(const char* url);
extern "C" void rho_sys_unset_http_proxy();
void CSystemImpl::getHttpProxyURI(CMethodResult& oResult)
{
oResult.set(rho_sys_get_http_proxy_url());
}
void CSystemImpl::setHttpProxyURI( const rho::String& value, CMethodResult& oResult)
{
if ( value.length() )
rho_sys_set_http_proxy_url( value.c_str() );
else
rho_sys_unset_http_proxy();
}
void CSystemImpl::getHasTouchscreen(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set(true);
}
void CSystemImpl::getScreenSleeping(rho::apiGenerator::CMethodResult& oResult)
{
oResult.set(false);
}
void CSystemImpl::setScreenSleeping( bool value, rho::apiGenerator::CMethodResult& oResult)
{
//unsupported
}
void CSystemImpl::setWindowSize( int width, int height, rho::apiGenerator::CMethodResult& oResult)
{
CMainWindow::getInstance()->setSize(width, height);
}
void CSystemImpl::set_http_proxy_url( const rho::String& proxyURI, rho::apiGenerator::CMethodResult& oResult)
{
rho_sys_set_http_proxy_url( proxyURI.c_str() );
}
void CSystemImpl::unset_http_proxy(rho::apiGenerator::CMethodResult& oResult)
{
rho_sys_unset_http_proxy();
}
////////////////////////////////////////////////////////////////////////
class CSystemSingleton: public CModuleSingletonBase<ISystemSingleton>
{
public:
~CSystemSingleton(){}
rho::StringW getInitialDefaultID(){return L"1";}
rho::StringW getDefaultID(){return L"1";}
void setDefaultID(const rho::StringW& strI){}
};
class CSystemFactory: public CSystemFactoryBase
{
public:
~CSystemFactory(){}
ISystemSingleton* createModuleSingleton(){ return new CSystemImpl(); }
};
extern "C" void Init_System()
{
CSystemFactory::setInstance( new CSystemFactory() );
Init_System_API();
}
}
<|endoftext|>
|
<commit_before>/**
* \file
* \brief FpuSignalTestCase class implementation for ARMv7-M (Cortex-M3 / Cortex-M4)
*
* \author Copyright (C) 2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* \date 2015-11-11
*/
#include "ARMv7-M-FpuSignalTestCase.hpp"
#include "distortos/chip/CMSIS-proxy.h"
#if __FPU_PRESENT == 1 && __FPU_USED == 1
#include "checkFpuRegisters.hpp"
#include "setFpuRegisters.hpp"
#include "distortos/StaticSoftwareTimer.hpp"
#include "distortos/StaticThread.hpp"
#include "distortos/statistics.hpp"
#include "distortos/ThisThread.hpp"
#include "distortos/ThisThread-Signals.hpp"
#include <cerrno>
#endif // __FPU_PRESENT == 1 && __FPU_USED == 1
namespace distortos
{
namespace test
{
#if __FPU_PRESENT == 1 && __FPU_USED == 1
namespace
{
/*---------------------------------------------------------------------------------------------------------------------+
| local types
+---------------------------------------------------------------------------------------------------------------------*/
/// values used in single test stage
struct Stage
{
/// value written to all FPU registers in main thread, don't use FPU in main thread if 0
uint32_t threadValue;
/// value written to "lower" FPU registers in "sender" before queuing of signal, skip this step if 0
uint32_t senderValueBefore;
/// value written to "lower" FPU registers in "sender" after queuing of signal, skip this step if 0
uint32_t senderValueAfter;
/// signal value, written to "lower" FPU registers in handler, don't use FPU in handler if 0
int signalValue;
};
/// description of single test phase
struct Phase
{
/// type of "sender" function
using Sender = int(Thread&, const Stage&);
/// reference to "sender" function
Sender& sender;
/// expected number of context switches for single stage executed in this phase
decltype(statistics::getContextSwitchCount()) contextSwitchCount;
};
/*---------------------------------------------------------------------------------------------------------------------+
| local constants
+---------------------------------------------------------------------------------------------------------------------*/
/// tested signal number
constexpr uint8_t testSignalNumber {16};
/// size of stack for test thread, bytes
constexpr size_t testThreadStackSize {512};
/*---------------------------------------------------------------------------------------------------------------------+
| local functions
+---------------------------------------------------------------------------------------------------------------------*/
/**
* \brief Disables FPU context for current thread by clearing FPCA bit in CONTROL register.
*/
void disableFpuContext()
{
const auto control = __get_CONTROL();
__set_CONTROL(control & ~CONTROL_FPCA_Msk);
}
/**
* \brief Signal handler
*
* Sets "lower" FPU registers (s0-s15 and FPSCR) using the value queued with signal, unless this value is 0.
*
* \param [in] signalInformation is a reference to received SignalInformation object
*/
void handler(const SignalInformation& signalInformation)
{
const auto value = signalInformation.getValue().sival_int;
if (value == 0)
return;
setFpuRegisters(value, false);
}
/**
* \brief Tests whether FPU context is active for current thread.
*
* \return true if FPU context is active for current thread (FPCA bit in CONTROL register is set), false otherwise
*/
bool isFpuContextActive()
{
const auto control = __get_CONTROL();
return (control & CONTROL_FPCA_Msk) != 0;
}
/**
* \brief Test wrapper for Thread::queueSignal() that also modifies FPU registers.
*
* \param [in] thread is a reference to thread to which the signal will be queued
* \param [in] stage is a reference to test stage
* \param [in] full is the \a full argument passed to setFpuRegisters()
* \param [in] sharedRet is a reference to int variable which will be written with 0 on success, error code otherwise
*/
void queueSignalWrapper(Thread& thread, const Stage& stage, const bool full, int& sharedRet)
{
if (stage.senderValueBefore != 0) // should FPU be used at the beginning of "sender"?
setFpuRegisters(stage.senderValueBefore, full);
sharedRet = thread.queueSignal(testSignalNumber, sigval{stage.signalValue});
if (stage.senderValueAfter != 0) // should FPU be used at th"sender""sender"?
setFpuRegisters(stage.senderValueAfter, full);
}
/**
* \brief Queues signal from interrupt (via software timer) to current thread.
*
* \param [in] thread is a reference to thread to which the signal will be queued
* \param [in] stage is a reference to test stage
*
* \return 0 on success, error code otherwise:
* - error codes returned by Thread::queueSignal();
*/
int queueSignalFromInterrupt(Thread& thread, const Stage& stage)
{
int sharedRet {EINVAL};
auto softwareTimer = makeStaticSoftwareTimer(queueSignalWrapper, std::ref(thread), std::ref(stage), false,
std::ref(sharedRet));
softwareTimer.start(TickClock::duration{});
while (softwareTimer.isRunning() == true);
return sharedRet;
}
/**
* \brief Queues signal from thread to non-current thread.
*
* \param [in] thread is a reference to thread to which the signal will be queued
* \param [in] stage is a reference to test stage
*
* \return 0 on success, error code otherwise:
* - error codes returned by Thread::queueSignal();
*/
int queueSignalFromThread(Thread& thread, const Stage& stage)
{
constexpr decltype(FpuSignalTestCase::getTestCasePriority()) highPriority
{
FpuSignalTestCase::getTestCasePriority() + 1
};
int sharedRet {EINVAL};
auto testThread = makeStaticThread<testThreadStackSize>(highPriority, queueSignalWrapper, std::ref(thread),
std::ref(stage), true, std::ref(sharedRet));
testThread.start();
testThread.join();
return sharedRet;
}
/*---------------------------------------------------------------------------------------------------------------------+
| local constants
+---------------------------------------------------------------------------------------------------------------------*/
/// test phasese
const Phase phases[]
{
{queueSignalFromInterrupt, 0},
{queueSignalFromThread, 2},
};
/// test stages
const Stage stages[]
{
{0, 0, 0, 0}, // don't use FPU in all contexts
{0, 0, 0, 0x0b39fa96}, // in handler
{0, 0, 0x8606151d, 0}, // in "sender" (at the end)
{0, 0, 0x8bdd3b5e, 0x7d21d1c6}, // in "sender" (at the end) and in handler
{0, 0x2f884196, 0, 0}, // in "sender" (at the beginning)
{0, 0x0b0bbc86, 0, 0x0e43811b}, // in "sender" (at the beginning) and in handler
{0, 0xb72b2917, 0x8c27baa7, 0}, // in "sender"
{0, 0xa83b80c2, 0xd2b7dd4d, 0x626ca399}, // in "sender" and in handler
{0xb4e40525, 0, 0, 0}, // in main thread
{0x772bdf91, 0, 0, 0x0bb325b7}, // in main thread and in handler
{0x8a19625e, 0, 0x32378f7b, 0}, // in main thread and in "sender" (at the end)
{0xd17a21db, 0, 0xaa807a91, 0x03caf264}, // in main thread, in "sender" (at the end) and in handler
{0xe4b44073, 0xa88c0cf5, 0, 0}, // in main thread and in "sender" (at the beginning)
{0xb94c722b, 0x5f8ca773, 0, 0x288301cf}, // in main thread, in "sender" (at the beginning) and in handler
{0x347ecfc5, 0xcb4a3584, 0x5a8bf219, 0}, // in main thread and in "sender"
{0x788ed92e, 0x4b0ddff9, 0x73776a21, 0x48fb1969}, // in all contexts
};
} // namespace
#endif // __FPU_PRESENT == 1 && __FPU_USED == 1
/*---------------------------------------------------------------------------------------------------------------------+
| protected functions
+---------------------------------------------------------------------------------------------------------------------*/
bool FpuSignalTestCase::finalize() const
{
#if __FPU_PRESENT == 1 && __FPU_USED == 1
disableFpuContext();
#endif // __FPU_PRESENT == 1 && __FPU_USED == 1
return SignalsTestCaseCommon::finalize();
}
/*---------------------------------------------------------------------------------------------------------------------+
| private functions
+---------------------------------------------------------------------------------------------------------------------*/
bool FpuSignalTestCase::run_() const
{
#if __FPU_PRESENT == 1 && __FPU_USED == 1
const auto contextSwitchCount = statistics::getContextSwitchCount();
auto expectedContextSwitchCount = decltype(contextSwitchCount){};
{
int ret;
std::tie(ret, std::ignore) = ThisThread::Signals::setSignalAction(testSignalNumber,
SignalAction{handler, SignalSet{SignalSet::empty}});
if (ret != 0)
return false;
}
auto& currentThread = ThisThread::get();
for (auto& phase : phases)
for (auto& stage : stages)
{
disableFpuContext();
decltype(setFpuRegisters({}, {})) fpscr {};
if (stage.threadValue != 0) // should FPU be used in main thread?
fpscr = setFpuRegisters(stage.threadValue, true);
if (phase.sender(currentThread, stage) != 0)
return false;
// FPU context may be active only if FPU was used in main thread
if (isFpuContextActive() != (stage.threadValue != 0))
return false;
if (stage.threadValue != 0) // was FPU used in main thread?
if (checkFpuRegisters(stage.threadValue, fpscr) == false)
return false;
expectedContextSwitchCount += phase.contextSwitchCount;
if (statistics::getContextSwitchCount() - contextSwitchCount != expectedContextSwitchCount)
return false;
}
if (statistics::getContextSwitchCount() - contextSwitchCount != expectedContextSwitchCount)
return false;
return true;
#else
return true;
#endif // __FPU_PRESENT == 1 && __FPU_USED == 1
}
} // namespace test
} // namespace distortos
<commit_msg>test: convert ARMv7-M-FpuSignalTestCase to use dynamic threads<commit_after>/**
* \file
* \brief FpuSignalTestCase class implementation for ARMv7-M (Cortex-M3 / Cortex-M4)
*
* \author Copyright (C) 2015-2016 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* \date 2016-01-04
*/
#include "ARMv7-M-FpuSignalTestCase.hpp"
#include "distortos/chip/CMSIS-proxy.h"
#if __FPU_PRESENT == 1 && __FPU_USED == 1
#include "checkFpuRegisters.hpp"
#include "setFpuRegisters.hpp"
#include "distortos/DynamicThread.hpp"
#include "distortos/StaticSoftwareTimer.hpp"
#include "distortos/statistics.hpp"
#include "distortos/ThisThread.hpp"
#include "distortos/ThisThread-Signals.hpp"
#endif // __FPU_PRESENT == 1 && __FPU_USED == 1
namespace distortos
{
namespace test
{
#if __FPU_PRESENT == 1 && __FPU_USED == 1
namespace
{
/*---------------------------------------------------------------------------------------------------------------------+
| local types
+---------------------------------------------------------------------------------------------------------------------*/
/// values used in single test stage
struct Stage
{
/// value written to all FPU registers in main thread, don't use FPU in main thread if 0
uint32_t threadValue;
/// value written to "lower" FPU registers in "sender" before queuing of signal, skip this step if 0
uint32_t senderValueBefore;
/// value written to "lower" FPU registers in "sender" after queuing of signal, skip this step if 0
uint32_t senderValueAfter;
/// signal value, written to "lower" FPU registers in handler, don't use FPU in handler if 0
int signalValue;
};
/// description of single test phase
struct Phase
{
/// type of "sender" function
using Sender = int(Thread&, const Stage&);
/// reference to "sender" function
Sender& sender;
/// expected number of context switches for single stage executed in this phase
decltype(statistics::getContextSwitchCount()) contextSwitchCount;
};
/*---------------------------------------------------------------------------------------------------------------------+
| local constants
+---------------------------------------------------------------------------------------------------------------------*/
/// tested signal number
constexpr uint8_t testSignalNumber {16};
/// size of stack for test thread, bytes
constexpr size_t testThreadStackSize {512};
/*---------------------------------------------------------------------------------------------------------------------+
| local functions
+---------------------------------------------------------------------------------------------------------------------*/
/**
* \brief Disables FPU context for current thread by clearing FPCA bit in CONTROL register.
*/
void disableFpuContext()
{
const auto control = __get_CONTROL();
__set_CONTROL(control & ~CONTROL_FPCA_Msk);
}
/**
* \brief Signal handler
*
* Sets "lower" FPU registers (s0-s15 and FPSCR) using the value queued with signal, unless this value is 0.
*
* \param [in] signalInformation is a reference to received SignalInformation object
*/
void handler(const SignalInformation& signalInformation)
{
const auto value = signalInformation.getValue().sival_int;
if (value == 0)
return;
setFpuRegisters(value, false);
}
/**
* \brief Tests whether FPU context is active for current thread.
*
* \return true if FPU context is active for current thread (FPCA bit in CONTROL register is set), false otherwise
*/
bool isFpuContextActive()
{
const auto control = __get_CONTROL();
return (control & CONTROL_FPCA_Msk) != 0;
}
/**
* \brief Test wrapper for Thread::queueSignal() that also modifies FPU registers.
*
* \param [in] thread is a reference to thread to which the signal will be queued
* \param [in] stage is a reference to test stage
* \param [in] full is the \a full argument passed to setFpuRegisters()
* \param [in] sharedRet is a reference to int variable which will be written with 0 on success, error code otherwise
*/
void queueSignalWrapper(Thread& thread, const Stage& stage, const bool full, int& sharedRet)
{
if (stage.senderValueBefore != 0) // should FPU be used at the beginning of "sender"?
setFpuRegisters(stage.senderValueBefore, full);
sharedRet = thread.queueSignal(testSignalNumber, sigval{stage.signalValue});
if (stage.senderValueAfter != 0) // should FPU be used at th"sender""sender"?
setFpuRegisters(stage.senderValueAfter, full);
}
/**
* \brief Queues signal from interrupt (via software timer) to current thread.
*
* \param [in] thread is a reference to thread to which the signal will be queued
* \param [in] stage is a reference to test stage
*
* \return 0 on success, error code otherwise:
* - error codes returned by Thread::queueSignal();
*/
int queueSignalFromInterrupt(Thread& thread, const Stage& stage)
{
int sharedRet {EINVAL};
auto softwareTimer = makeStaticSoftwareTimer(queueSignalWrapper, std::ref(thread), std::ref(stage), false,
std::ref(sharedRet));
softwareTimer.start(TickClock::duration{});
while (softwareTimer.isRunning() == true);
return sharedRet;
}
/**
* \brief Queues signal from thread to non-current thread.
*
* \param [in] thread is a reference to thread to which the signal will be queued
* \param [in] stage is a reference to test stage
*
* \return 0 on success, error code otherwise:
* - error codes returned by Thread::queueSignal();
*/
int queueSignalFromThread(Thread& thread, const Stage& stage)
{
constexpr decltype(FpuSignalTestCase::getTestCasePriority()) highPriority
{
FpuSignalTestCase::getTestCasePriority() + 1
};
int sharedRet {EINVAL};
auto testThread = makeDynamicThread({testThreadStackSize, highPriority}, queueSignalWrapper, std::ref(thread),
std::ref(stage), true, std::ref(sharedRet));
testThread.start();
testThread.join();
return sharedRet;
}
/*---------------------------------------------------------------------------------------------------------------------+
| local constants
+---------------------------------------------------------------------------------------------------------------------*/
/// test phasese
const Phase phases[]
{
{queueSignalFromInterrupt, 0},
{queueSignalFromThread, 2},
};
/// test stages
const Stage stages[]
{
{0, 0, 0, 0}, // don't use FPU in all contexts
{0, 0, 0, 0x0b39fa96}, // in handler
{0, 0, 0x8606151d, 0}, // in "sender" (at the end)
{0, 0, 0x8bdd3b5e, 0x7d21d1c6}, // in "sender" (at the end) and in handler
{0, 0x2f884196, 0, 0}, // in "sender" (at the beginning)
{0, 0x0b0bbc86, 0, 0x0e43811b}, // in "sender" (at the beginning) and in handler
{0, 0xb72b2917, 0x8c27baa7, 0}, // in "sender"
{0, 0xa83b80c2, 0xd2b7dd4d, 0x626ca399}, // in "sender" and in handler
{0xb4e40525, 0, 0, 0}, // in main thread
{0x772bdf91, 0, 0, 0x0bb325b7}, // in main thread and in handler
{0x8a19625e, 0, 0x32378f7b, 0}, // in main thread and in "sender" (at the end)
{0xd17a21db, 0, 0xaa807a91, 0x03caf264}, // in main thread, in "sender" (at the end) and in handler
{0xe4b44073, 0xa88c0cf5, 0, 0}, // in main thread and in "sender" (at the beginning)
{0xb94c722b, 0x5f8ca773, 0, 0x288301cf}, // in main thread, in "sender" (at the beginning) and in handler
{0x347ecfc5, 0xcb4a3584, 0x5a8bf219, 0}, // in main thread and in "sender"
{0x788ed92e, 0x4b0ddff9, 0x73776a21, 0x48fb1969}, // in all contexts
};
} // namespace
#endif // __FPU_PRESENT == 1 && __FPU_USED == 1
/*---------------------------------------------------------------------------------------------------------------------+
| protected functions
+---------------------------------------------------------------------------------------------------------------------*/
bool FpuSignalTestCase::finalize() const
{
#if __FPU_PRESENT == 1 && __FPU_USED == 1
disableFpuContext();
#endif // __FPU_PRESENT == 1 && __FPU_USED == 1
return SignalsTestCaseCommon::finalize();
}
/*---------------------------------------------------------------------------------------------------------------------+
| private functions
+---------------------------------------------------------------------------------------------------------------------*/
bool FpuSignalTestCase::run_() const
{
#if __FPU_PRESENT == 1 && __FPU_USED == 1
const auto contextSwitchCount = statistics::getContextSwitchCount();
auto expectedContextSwitchCount = decltype(contextSwitchCount){};
{
int ret;
std::tie(ret, std::ignore) = ThisThread::Signals::setSignalAction(testSignalNumber,
SignalAction{handler, SignalSet{SignalSet::empty}});
if (ret != 0)
return false;
}
auto& currentThread = ThisThread::get();
for (auto& phase : phases)
for (auto& stage : stages)
{
disableFpuContext();
decltype(setFpuRegisters({}, {})) fpscr {};
if (stage.threadValue != 0) // should FPU be used in main thread?
fpscr = setFpuRegisters(stage.threadValue, true);
if (phase.sender(currentThread, stage) != 0)
return false;
// FPU context may be active only if FPU was used in main thread
if (isFpuContextActive() != (stage.threadValue != 0))
return false;
if (stage.threadValue != 0) // was FPU used in main thread?
if (checkFpuRegisters(stage.threadValue, fpscr) == false)
return false;
expectedContextSwitchCount += phase.contextSwitchCount;
if (statistics::getContextSwitchCount() - contextSwitchCount != expectedContextSwitchCount)
return false;
}
if (statistics::getContextSwitchCount() - contextSwitchCount != expectedContextSwitchCount)
return false;
return true;
#else
return true;
#endif // __FPU_PRESENT == 1 && __FPU_USED == 1
}
} // namespace test
} // namespace distortos
<|endoftext|>
|
<commit_before>// -*- Mode: c++-mode; c-basic-offset: 2; indent-tabs-mode: t; tab-width: 2; -*-
//
// Copyright (C) 2003 Grzegorz Jaskiewicz <gj at pointblue.com.pl>
//
// gadueditcontact.cpp
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
// 02111-1307, USA.
#include "gaduaccount.h"
#include "gaducontact.h"
#include "gadueditcontact.h"
#include "kopeteonlinestatus.h"
#include "gaducontactlist.h"
#include "gaduadd.h"
#include <ktextedit.h>
#include <klocale.h>
#include <kdebug.h>
#include <kopetegroup.h>
#include <kopetecontactlist.h>
#include <kopetemetacontact.h>
#include <qbuttongroup.h>
#include <qradiobutton.h>
#include <qlineedit.h>
#include <qlayout.h>
#include <qlistview.h>
#include <qptrlist.h>
#include <krestrictedline.h>
// FIXME: this and gaduadcontactpage should have one base class, with some code duplicated in both.
GaduEditContact::GaduEditContact( GaduAccount* account, GaduContact* contact,
QWidget* parent, const char* name )
: KDialogBase( parent, name, true, i18n( "Edit Contact's Properties" ),
KDialogBase::Ok | KDialogBase::Cancel,
KDialogBase::Ok, true ), account_( account ), contact_( contact )
{
if ( contact && account ) {
cl_ = contact->contactDetails();
}
else {
return;
}
init();
fillGroups();
fillIn();
}
GaduEditContact::GaduEditContact( GaduAccount* account, GaduContactsList::ContactLine* clin,
QWidget* parent , const char* name )
: KDialogBase( parent, name, true, i18n( "Edit Contact's Properties" ),
KDialogBase::Ok | KDialogBase::Cancel,
KDialogBase::Ok, true ), account_( account ), contact_( NULL )
{
if ( !account ) {
return;
}
cl_ = clin;
init();
fillGroups();
fillIn();
}
void
GaduEditContact::fillGroups()
{
Kopete::Group *g, *cg;
QPtrList<Kopete::Group> cgl;
QPtrList<Kopete::Group> gl;
if ( contact_ ) {
cgl = contact_->metaContact()->groups();
}
gl = Kopete::ContactList::self()->groups();
for( g = gl.first(); g; g = gl.next() ) {
if ( g->type() == Kopete::Group::Temporary ) {
continue;
}
QCheckListItem* item = new QCheckListItem( ui_->groups, g->displayName(), QCheckListItem::CheckBox );
// FIXME: optimize this O(2) search
for( cg = cgl.first(); cg; cg = cgl.next() ) {
if ( cg->groupId() == g->groupId() ) {
item->setOn( TRUE );
break;
}
}
kdDebug(14100) << g->displayName() << " " << g->groupId() << endl;
}
}
void
GaduEditContact::init()
{
ui_ = new GaduAddUI( this );
setMainWidget( ui_ );
ui_->addEdit_->setValidChars( "1234567890" );
// fill values from cl into proper fields on widget
show();
connect( this, SIGNAL( okClicked() ), SLOT( slotApply() ) );
connect( ui_->groups, SIGNAL( clicked( QListViewItem * ) ), SLOT( listClicked( QListViewItem * ) ) );
}
void
GaduEditContact::listClicked( QListViewItem* item )
{
}
void
GaduEditContact::fillIn()
{
// grey it out, it shouldn't be editable
ui_->addEdit_->setReadOnly( true );
ui_->addEdit_->setText( cl_->uin );
ui_->fornameEdit_->setText( cl_->firstname );
ui_->snameEdit_->setText( cl_->surname );
ui_->nickEdit_->setText( cl_->nickname );
ui_->emailEdit_->setText( cl_->email );
ui_->telephoneEdit_->setText( cl_->phonenr );
// ui_->notAFriend_;
}
void
GaduEditContact::slotApply()
{
QPtrList<Kopete::Group> gl;
Kopete::Group* group;
cl_->firstname = ui_->fornameEdit_->text().stripWhiteSpace();
cl_->surname = ui_->snameEdit_->text().stripWhiteSpace();
cl_->nickname = ui_->nickEdit_->text().stripWhiteSpace();
cl_->email = ui_->emailEdit_->text().stripWhiteSpace();
cl_->phonenr = ui_->telephoneEdit_->text().stripWhiteSpace();
if ( contact_ == NULL ) {
// contact doesn't exists yet, create it and set all the details
bool s = account_->addContact( cl_->uin, GaduContact::findBestContactName( cl_ ), 0L, Kopete::Account::DontChangeKABC);
if ( s == false ) {
kdDebug(14100) << "There was a problem adding UIN "<< cl_->uin << "to users list" << endl;
return;
}
contact_ = static_cast<GaduContact*>( account_->contacts()[ cl_->uin ] );
if ( contact_ == NULL ) {
kdDebug(14100) << "oops, no Kopete::Contact in contacts()[] for some reason, for \"" << cl_->uin << "\"" << endl;
return;
}
}
contact_->setContactDetails( cl_ );
gl = Kopete::ContactList::self()->groups();
for ( QListViewItemIterator it( ui_->groups ); it.current(); ++it ) {
QCheckListItem *check = dynamic_cast<QCheckListItem *>( it.current() );
if ( !check ) {
continue;
}
if ( check->isOn() ) {
for( group = gl.first(); group; group = gl.next() ) {
if ( group->displayName() == check->text() ) {
contact_->metaContact()->addToGroup( group );
}
}
}
else {
// check metacontact's in the group, and if so, remove it from
for( group = gl.first(); group; group = gl.next() ) {
if ( group->displayName() == check->text() ) {
contact_->metaContact()->removeFromGroup( group );
}
}
}
}
if( contact_->metaContact()->groups().isEmpty() == TRUE )
contact_->metaContact()->addToGroup( Kopete::Group::topLevel() );
}
#include "gadueditcontact.moc"
<commit_msg>do not whine<commit_after>// -*- Mode: c++-mode; c-basic-offset: 2; indent-tabs-mode: t; tab-width: 2; -*-
//
// Copyright (C) 2003 Grzegorz Jaskiewicz <gj at pointblue.com.pl>
//
// gadueditcontact.cpp
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
// 02111-1307, USA.
#include "gaduaccount.h"
#include "gaducontact.h"
#include "gadueditcontact.h"
#include "kopeteonlinestatus.h"
#include "gaducontactlist.h"
#include "gaduadd.h"
#include <ktextedit.h>
#include <klocale.h>
#include <kdebug.h>
#include <kopetegroup.h>
#include <kopetecontactlist.h>
#include <kopetemetacontact.h>
#include <qbuttongroup.h>
#include <qradiobutton.h>
#include <qlineedit.h>
#include <qlayout.h>
#include <qlistview.h>
#include <qptrlist.h>
#include <krestrictedline.h>
// FIXME: this and gaduadcontactpage should have one base class, with some code duplicated in both.
GaduEditContact::GaduEditContact( GaduAccount* account, GaduContact* contact,
QWidget* parent, const char* name )
: KDialogBase( parent, name, true, i18n( "Edit Contact's Properties" ),
KDialogBase::Ok | KDialogBase::Cancel,
KDialogBase::Ok, true ), account_( account ), contact_( contact )
{
if ( contact && account ) {
cl_ = contact->contactDetails();
}
else {
return;
}
init();
fillGroups();
fillIn();
}
GaduEditContact::GaduEditContact( GaduAccount* account, GaduContactsList::ContactLine* clin,
QWidget* parent , const char* name )
: KDialogBase( parent, name, true, i18n( "Edit Contact's Properties" ),
KDialogBase::Ok | KDialogBase::Cancel,
KDialogBase::Ok, true ), account_( account ), contact_( NULL )
{
if ( !account ) {
return;
}
cl_ = clin;
init();
fillGroups();
fillIn();
}
void
GaduEditContact::fillGroups()
{
Kopete::Group *g, *cg;
QPtrList<Kopete::Group> cgl;
QPtrList<Kopete::Group> gl;
if ( contact_ ) {
cgl = contact_->metaContact()->groups();
}
gl = Kopete::ContactList::self()->groups();
for( g = gl.first(); g; g = gl.next() ) {
if ( g->type() == Kopete::Group::Temporary ) {
continue;
}
QCheckListItem* item = new QCheckListItem( ui_->groups, g->displayName(), QCheckListItem::CheckBox );
// FIXME: optimize this O(2) search
for( cg = cgl.first(); cg; cg = cgl.next() ) {
if ( cg->groupId() == g->groupId() ) {
item->setOn( TRUE );
break;
}
}
kdDebug(14100) << g->displayName() << " " << g->groupId() << endl;
}
}
void
GaduEditContact::init()
{
ui_ = new GaduAddUI( this );
setMainWidget( ui_ );
ui_->addEdit_->setValidChars( "1234567890" );
// fill values from cl into proper fields on widget
show();
connect( this, SIGNAL( okClicked() ), SLOT( slotApply() ) );
connect( ui_->groups, SIGNAL( clicked( QListViewItem * ) ), SLOT( listClicked( QListViewItem * ) ) );
}
void
GaduEditContact::listClicked( QListViewItem* /*item*/ )
{
}
void
GaduEditContact::fillIn()
{
// grey it out, it shouldn't be editable
ui_->addEdit_->setReadOnly( true );
ui_->addEdit_->setText( cl_->uin );
ui_->fornameEdit_->setText( cl_->firstname );
ui_->snameEdit_->setText( cl_->surname );
ui_->nickEdit_->setText( cl_->nickname );
ui_->emailEdit_->setText( cl_->email );
ui_->telephoneEdit_->setText( cl_->phonenr );
// ui_->notAFriend_;
}
void
GaduEditContact::slotApply()
{
QPtrList<Kopete::Group> gl;
Kopete::Group* group;
cl_->firstname = ui_->fornameEdit_->text().stripWhiteSpace();
cl_->surname = ui_->snameEdit_->text().stripWhiteSpace();
cl_->nickname = ui_->nickEdit_->text().stripWhiteSpace();
cl_->email = ui_->emailEdit_->text().stripWhiteSpace();
cl_->phonenr = ui_->telephoneEdit_->text().stripWhiteSpace();
if ( contact_ == NULL ) {
// contact doesn't exists yet, create it and set all the details
bool s = account_->addContact( cl_->uin, GaduContact::findBestContactName( cl_ ), 0L, Kopete::Account::DontChangeKABC);
if ( s == false ) {
kdDebug(14100) << "There was a problem adding UIN "<< cl_->uin << "to users list" << endl;
return;
}
contact_ = static_cast<GaduContact*>( account_->contacts()[ cl_->uin ] );
if ( contact_ == NULL ) {
kdDebug(14100) << "oops, no Kopete::Contact in contacts()[] for some reason, for \"" << cl_->uin << "\"" << endl;
return;
}
}
contact_->setContactDetails( cl_ );
gl = Kopete::ContactList::self()->groups();
for ( QListViewItemIterator it( ui_->groups ); it.current(); ++it ) {
QCheckListItem *check = dynamic_cast<QCheckListItem *>( it.current() );
if ( !check ) {
continue;
}
if ( check->isOn() ) {
for( group = gl.first(); group; group = gl.next() ) {
if ( group->displayName() == check->text() ) {
contact_->metaContact()->addToGroup( group );
}
}
}
else {
// check metacontact's in the group, and if so, remove it from
for( group = gl.first(); group; group = gl.next() ) {
if ( group->displayName() == check->text() ) {
contact_->metaContact()->removeFromGroup( group );
}
}
}
}
if( contact_->metaContact()->groups().isEmpty() == TRUE )
contact_->metaContact()->addToGroup( Kopete::Group::topLevel() );
}
#include "gadueditcontact.moc"
<|endoftext|>
|
<commit_before>#include "rasterizer.h"
#include <stdlib.h>
#include <string.h>
#include <assert.h>
// Fine raster works on blocks of 2x2 pixels, since NEON can fine rasterize a block in parallel using SIMD-4.
// Coarse raster works on 2x2 blocks of fine blocks, since 4 fine blocks are processed in parallel. Therefore, 4x4 pixels per coarse block.
// Tile raster works on 2x2 blocks of coarse blocks, since 4 coarse blocks are processed in parallel. Therefore, 8x8 pixels per tile.
#define FRAMEBUFFER_TILE_WIDTH_IN_PIXELS 128
#define FRAMEBUFFER_COARSE_BLOCK_WIDTH_IN_PIXELS 16
#define FRAMEBUFFER_FINE_BLOCK_WIDTH_IN_PIXELS 4
// The swizzle masks, using alternating yxyxyx bit pattern for morton-code swizzling pixels in a tile.
// This makes the pixels morton code swizzled within every rasterization level (fine/coarse/tile)
// The tiles themselves are stored row major.
// For examples of this concept, see:
// https://software.intel.com/en-us/node/514045
// https://msdn.microsoft.com/en-us/library/windows/desktop/dn770442%28v=vs.85%29.aspx
#define FRAMEBUFFER_TILE_X_SWIZZLE_MASK (0x55555555 & (FRAMEBUFFER_TILE_WIDTH_IN_PIXELS - 1))
#define FRAMEBUFFER_TILE_Y_SWIZZLE_MASK (~FRAMEBUFFER_TILE_X_SWIZZLE_MASK & (FRAMEBUFFER_TILE_WIDTH_IN_PIXELS - 1))
// Convenience
#define FRAMEBUFFER_PIXELS_PER_TILE (FRAMEBUFFER_TILE_WIDTH_IN_PIXELS * FRAMEBUFFER_TILE_WIDTH_IN_PIXELS)
// If there are too many commands and this buffer gets filled up,
// then the command buffer for that tile must be flushed.
#define TILE_COMMAND_BUFFER_SIZE_IN_DWORDS 128
typedef struct tile_cmdbuf_t
{
// start and past-the-end of the allocation for the buffer
uint32_t* cmdbuf_start;
uint32_t* cmdbuf_end;
// the next location where to read and write commands
uint32_t* cmdbuf_read;
uint32_t* cmdbuf_write;
} tile_cmdbuf_t;
typedef struct framebuffer_t
{
pixel_t* backbuffer;
uint32_t* tile_cmdpool;
tile_cmdbuf_t* tile_cmdbufs;
uint32_t width_in_pixels;
uint32_t height_in_pixels;
// num_tiles_per_row * num_pixels_per_tile
uint32_t pixels_per_row_of_tiles;
// pixels_per_row_of_tiles * num_tile_rows
uint32_t pixels_per_slice;
} framebuffer_t;
framebuffer_t* new_framebuffer(uint32_t width, uint32_t height)
{
// limits of the rasterizer's precision
// this is based on an analysis of the range of results of the 2D cross product between two fixed16.8 numbers.
assert(width < 16384);
assert(height < 16384);
framebuffer_t* fb = (framebuffer_t*)malloc(sizeof(framebuffer_t));
assert(fb);
fb->width_in_pixels = width;
fb->height_in_pixels = height;
// pad framebuffer up to size of next tile
// that way the rasterization code doesn't have to handlep otential out of bounds access after tile binning
uint32_t padded_width_in_pixels = (width + (FRAMEBUFFER_TILE_WIDTH_IN_PIXELS - 1)) & -FRAMEBUFFER_TILE_WIDTH_IN_PIXELS;
uint32_t padded_height_in_pixels = (height + (FRAMEBUFFER_TILE_WIDTH_IN_PIXELS - 1)) & -FRAMEBUFFER_TILE_WIDTH_IN_PIXELS;
uint32_t width_in_tiles = padded_width_in_pixels / FRAMEBUFFER_TILE_WIDTH_IN_PIXELS;
uint32_t height_in_tiles = padded_height_in_pixels / FRAMEBUFFER_TILE_WIDTH_IN_PIXELS;
uint32_t total_num_tiles = width_in_tiles * height_in_tiles;
fb->pixels_per_row_of_tiles = padded_width_in_pixels * FRAMEBUFFER_TILE_WIDTH_IN_PIXELS;
fb->pixels_per_slice = padded_height_in_pixels / FRAMEBUFFER_TILE_WIDTH_IN_PIXELS * fb->pixels_per_row_of_tiles;
fb->backbuffer = (pixel_t*)malloc(fb->pixels_per_slice * sizeof(pixel_t));
assert(fb->backbuffer);
// clear to black/transparent initially
memset(fb->backbuffer, 0, fb->pixels_per_slice * sizeof(pixel_t));
fb->tile_cmdpool = (uint32_t*)malloc(total_num_tiles * TILE_COMMAND_BUFFER_SIZE_IN_DWORDS * sizeof(uint32_t));
assert(fb->tile_cmdpool);
fb->tile_cmdbufs = (tile_cmdbuf_t*)malloc(total_num_tiles * sizeof(tile_cmdbuf_t));
assert(fb->tile_cmdbufs);
for (uint32_t i = 0; i < total_num_tiles; i++)
{
fb->tile_cmdbufs[i].cmdbuf_start = &fb->tile_cmdpool[i * TILE_COMMAND_BUFFER_SIZE_IN_DWORDS];
fb->tile_cmdbufs[i].cmdbuf_end = fb->tile_cmdbufs[i].cmdbuf_start + TILE_COMMAND_BUFFER_SIZE_IN_DWORDS;
fb->tile_cmdbufs[i].cmdbuf_read = fb->tile_cmdbufs[i].cmdbuf_start;
fb->tile_cmdbufs[i].cmdbuf_write = fb->tile_cmdbufs[i].cmdbuf_start;
}
return fb;
}
void delete_framebuffer(framebuffer_t* fb)
{
if (!fb)
return;
free(fb->tile_cmdbufs);
free(fb->tile_cmdpool);
free(fb->backbuffer);
free(fb);
}
void framebuffer_resolve(framebuffer_t* fb)
{
}
void framebuffer_pack_row_major(framebuffer_t* fb, uint32_t x, uint32_t y, uint32_t width, uint32_t height, pixelformat_t format, void* data)
{
assert(fb);
assert(x < fb->width_in_pixels);
assert(y < fb->height_in_pixels);
assert(width <= fb->width_in_pixels);
assert(height <= fb->height_in_pixels);
assert(x + width <= fb->width_in_pixels);
assert(y + height <= fb->height_in_pixels);
assert(data);
uint32_t topleft_tile_y = y / FRAMEBUFFER_TILE_WIDTH_IN_PIXELS;
uint32_t topleft_tile_x = x / FRAMEBUFFER_TILE_WIDTH_IN_PIXELS;
uint32_t bottomright_tile_y = (y + (height - 1)) / FRAMEBUFFER_TILE_WIDTH_IN_PIXELS;
uint32_t bottomright_tile_x = (x + (width - 1)) / FRAMEBUFFER_TILE_WIDTH_IN_PIXELS;
uint32_t dst_i = 0;
uint32_t curr_tile_row_start = topleft_tile_y * fb->pixels_per_row_of_tiles + topleft_tile_x * FRAMEBUFFER_PIXELS_PER_TILE;
for (uint32_t tile_y = topleft_tile_y; tile_y <= bottomright_tile_y; tile_y++)
{
uint32_t curr_tile_start = curr_tile_row_start;
for (uint32_t tile_x = topleft_tile_x; tile_x <= bottomright_tile_x; tile_x++)
{
for (uint32_t pixel_y = 0, pixel_y_bits = 0;
pixel_y < FRAMEBUFFER_TILE_WIDTH_IN_PIXELS;
pixel_y++, pixel_y_bits = (pixel_y_bits - FRAMEBUFFER_TILE_Y_SWIZZLE_MASK) & FRAMEBUFFER_TILE_Y_SWIZZLE_MASK)
{
for (uint32_t pixel_x = 0, pixel_x_bits = 0;
pixel_x < FRAMEBUFFER_TILE_WIDTH_IN_PIXELS;
pixel_x++, pixel_x_bits = (pixel_x_bits - FRAMEBUFFER_TILE_X_SWIZZLE_MASK) & FRAMEBUFFER_TILE_X_SWIZZLE_MASK)
{
uint32_t src_y = tile_y * FRAMEBUFFER_TILE_WIDTH_IN_PIXELS + pixel_y;
uint32_t src_x = tile_x * FRAMEBUFFER_TILE_WIDTH_IN_PIXELS + pixel_x;
// don't copy pixels outside src rectangle region
if (src_y < y || src_y >= y + height)
continue;
if (src_x < x || src_x >= x + width)
continue;
uint32_t src_i = curr_tile_start + (pixel_y_bits | pixel_x_bits);
pixel_t src = fb->backbuffer[src_i];
if (format == pixelformat_r8g8b8a8_unorm)
{
uint8_t* dst = (uint8_t*)data + dst_i * 4;
dst[0] = (uint8_t)((src & 0x00FF0000) >> 16);
dst[1] = (uint8_t)((src & 0x0000FF00) >> 8);
dst[2] = (uint8_t)((src & 0x000000FF) >> 0);
dst[3] = (uint8_t)((src & 0xFF000000) >> 24);
}
else if (format == pixelformat_b8g8r8a8_unorm)
{
uint8_t* dst = (uint8_t*)data + dst_i * 4;
dst[0] = (uint8_t)((src & 0x000000FF) >> 0);
dst[1] = (uint8_t)((src & 0x0000FF00) >> 8);
dst[2] = (uint8_t)((src & 0x00FF0000) >> 16);
dst[3] = (uint8_t)((src & 0xFF000000) >> 24);
}
else
{
assert(!"Unknown pixel format");
}
dst_i++;
}
}
curr_tile_start += FRAMEBUFFER_PIXELS_PER_TILE;
}
curr_tile_row_start += fb->pixels_per_row_of_tiles;
}
}
// hack
uint32_t g_Color;
void rasterize_triangle_fixed16_8(
framebuffer_t* fb,
uint32_t window_x0, uint32_t window_y0, uint32_t window_z0,
uint32_t window_x1, uint32_t window_y1, uint32_t window_z1,
uint32_t window_x2, uint32_t window_y2, uint32_t window_z2)
{
}<commit_msg>changed order<commit_after>#include "rasterizer.h"
#include <stdlib.h>
#include <string.h>
#include <assert.h>
// Currently sized according to the Larrabee rasterizer's description
#define FRAMEBUFFER_TILE_WIDTH_IN_PIXELS 128
#define FRAMEBUFFER_COARSE_BLOCK_WIDTH_IN_PIXELS 16
#define FRAMEBUFFER_FINE_BLOCK_WIDTH_IN_PIXELS 4
// Convenience
#define FRAMEBUFFER_PIXELS_PER_TILE (FRAMEBUFFER_TILE_WIDTH_IN_PIXELS * FRAMEBUFFER_TILE_WIDTH_IN_PIXELS)
// The swizzle masks, using alternating yxyxyx bit pattern for morton-code swizzling pixels in a tile.
// This makes the pixels morton code swizzled within every rasterization level (fine/coarse/tile)
// The tiles themselves are stored row major.
// For examples of this concept, see:
// https://software.intel.com/en-us/node/514045
// https://msdn.microsoft.com/en-us/library/windows/desktop/dn770442%28v=vs.85%29.aspx
#define FRAMEBUFFER_TILE_X_SWIZZLE_MASK (0x55555555 & (FRAMEBUFFER_TILE_WIDTH_IN_PIXELS - 1))
#define FRAMEBUFFER_TILE_Y_SWIZZLE_MASK (~FRAMEBUFFER_TILE_X_SWIZZLE_MASK & (FRAMEBUFFER_TILE_WIDTH_IN_PIXELS - 1))
// If there are too many commands and this buffer gets filled up,
// then the command buffer for that tile must be flushed.
#define TILE_COMMAND_BUFFER_SIZE_IN_DWORDS 128
typedef struct tile_cmdbuf_t
{
// start and past-the-end of the allocation for the buffer
uint32_t* cmdbuf_start;
uint32_t* cmdbuf_end;
// the next location where to read and write commands
uint32_t* cmdbuf_read;
uint32_t* cmdbuf_write;
} tile_cmdbuf_t;
typedef struct framebuffer_t
{
pixel_t* backbuffer;
uint32_t* tile_cmdpool;
tile_cmdbuf_t* tile_cmdbufs;
uint32_t width_in_pixels;
uint32_t height_in_pixels;
// num_tiles_per_row * num_pixels_per_tile
uint32_t pixels_per_row_of_tiles;
// pixels_per_row_of_tiles * num_tile_rows
uint32_t pixels_per_slice;
} framebuffer_t;
framebuffer_t* new_framebuffer(uint32_t width, uint32_t height)
{
// limits of the rasterizer's precision
// this is based on an analysis of the range of results of the 2D cross product between two fixed16.8 numbers.
assert(width < 16384);
assert(height < 16384);
framebuffer_t* fb = (framebuffer_t*)malloc(sizeof(framebuffer_t));
assert(fb);
fb->width_in_pixels = width;
fb->height_in_pixels = height;
// pad framebuffer up to size of next tile
// that way the rasterization code doesn't have to handlep otential out of bounds access after tile binning
uint32_t padded_width_in_pixels = (width + (FRAMEBUFFER_TILE_WIDTH_IN_PIXELS - 1)) & -FRAMEBUFFER_TILE_WIDTH_IN_PIXELS;
uint32_t padded_height_in_pixels = (height + (FRAMEBUFFER_TILE_WIDTH_IN_PIXELS - 1)) & -FRAMEBUFFER_TILE_WIDTH_IN_PIXELS;
uint32_t width_in_tiles = padded_width_in_pixels / FRAMEBUFFER_TILE_WIDTH_IN_PIXELS;
uint32_t height_in_tiles = padded_height_in_pixels / FRAMEBUFFER_TILE_WIDTH_IN_PIXELS;
uint32_t total_num_tiles = width_in_tiles * height_in_tiles;
fb->pixels_per_row_of_tiles = padded_width_in_pixels * FRAMEBUFFER_TILE_WIDTH_IN_PIXELS;
fb->pixels_per_slice = padded_height_in_pixels / FRAMEBUFFER_TILE_WIDTH_IN_PIXELS * fb->pixels_per_row_of_tiles;
fb->backbuffer = (pixel_t*)malloc(fb->pixels_per_slice * sizeof(pixel_t));
assert(fb->backbuffer);
// clear to black/transparent initially
memset(fb->backbuffer, 0, fb->pixels_per_slice * sizeof(pixel_t));
fb->tile_cmdpool = (uint32_t*)malloc(total_num_tiles * TILE_COMMAND_BUFFER_SIZE_IN_DWORDS * sizeof(uint32_t));
assert(fb->tile_cmdpool);
fb->tile_cmdbufs = (tile_cmdbuf_t*)malloc(total_num_tiles * sizeof(tile_cmdbuf_t));
assert(fb->tile_cmdbufs);
for (uint32_t i = 0; i < total_num_tiles; i++)
{
fb->tile_cmdbufs[i].cmdbuf_start = &fb->tile_cmdpool[i * TILE_COMMAND_BUFFER_SIZE_IN_DWORDS];
fb->tile_cmdbufs[i].cmdbuf_end = fb->tile_cmdbufs[i].cmdbuf_start + TILE_COMMAND_BUFFER_SIZE_IN_DWORDS;
fb->tile_cmdbufs[i].cmdbuf_read = fb->tile_cmdbufs[i].cmdbuf_start;
fb->tile_cmdbufs[i].cmdbuf_write = fb->tile_cmdbufs[i].cmdbuf_start;
}
return fb;
}
void delete_framebuffer(framebuffer_t* fb)
{
if (!fb)
return;
free(fb->tile_cmdbufs);
free(fb->tile_cmdpool);
free(fb->backbuffer);
free(fb);
}
void framebuffer_resolve(framebuffer_t* fb)
{
}
void framebuffer_pack_row_major(framebuffer_t* fb, uint32_t x, uint32_t y, uint32_t width, uint32_t height, pixelformat_t format, void* data)
{
assert(fb);
assert(x < fb->width_in_pixels);
assert(y < fb->height_in_pixels);
assert(width <= fb->width_in_pixels);
assert(height <= fb->height_in_pixels);
assert(x + width <= fb->width_in_pixels);
assert(y + height <= fb->height_in_pixels);
assert(data);
uint32_t topleft_tile_y = y / FRAMEBUFFER_TILE_WIDTH_IN_PIXELS;
uint32_t topleft_tile_x = x / FRAMEBUFFER_TILE_WIDTH_IN_PIXELS;
uint32_t bottomright_tile_y = (y + (height - 1)) / FRAMEBUFFER_TILE_WIDTH_IN_PIXELS;
uint32_t bottomright_tile_x = (x + (width - 1)) / FRAMEBUFFER_TILE_WIDTH_IN_PIXELS;
uint32_t dst_i = 0;
uint32_t curr_tile_row_start = topleft_tile_y * fb->pixels_per_row_of_tiles + topleft_tile_x * FRAMEBUFFER_PIXELS_PER_TILE;
for (uint32_t tile_y = topleft_tile_y; tile_y <= bottomright_tile_y; tile_y++)
{
uint32_t curr_tile_start = curr_tile_row_start;
for (uint32_t tile_x = topleft_tile_x; tile_x <= bottomright_tile_x; tile_x++)
{
for (uint32_t pixel_y = 0, pixel_y_bits = 0;
pixel_y < FRAMEBUFFER_TILE_WIDTH_IN_PIXELS;
pixel_y++, pixel_y_bits = (pixel_y_bits - FRAMEBUFFER_TILE_Y_SWIZZLE_MASK) & FRAMEBUFFER_TILE_Y_SWIZZLE_MASK)
{
for (uint32_t pixel_x = 0, pixel_x_bits = 0;
pixel_x < FRAMEBUFFER_TILE_WIDTH_IN_PIXELS;
pixel_x++, pixel_x_bits = (pixel_x_bits - FRAMEBUFFER_TILE_X_SWIZZLE_MASK) & FRAMEBUFFER_TILE_X_SWIZZLE_MASK)
{
uint32_t src_y = tile_y * FRAMEBUFFER_TILE_WIDTH_IN_PIXELS + pixel_y;
uint32_t src_x = tile_x * FRAMEBUFFER_TILE_WIDTH_IN_PIXELS + pixel_x;
// don't copy pixels outside src rectangle region
if (src_y < y || src_y >= y + height)
continue;
if (src_x < x || src_x >= x + width)
continue;
uint32_t src_i = curr_tile_start + (pixel_y_bits | pixel_x_bits);
pixel_t src = fb->backbuffer[src_i];
if (format == pixelformat_r8g8b8a8_unorm)
{
uint8_t* dst = (uint8_t*)data + dst_i * 4;
dst[0] = (uint8_t)((src & 0x00FF0000) >> 16);
dst[1] = (uint8_t)((src & 0x0000FF00) >> 8);
dst[2] = (uint8_t)((src & 0x000000FF) >> 0);
dst[3] = (uint8_t)((src & 0xFF000000) >> 24);
}
else if (format == pixelformat_b8g8r8a8_unorm)
{
uint8_t* dst = (uint8_t*)data + dst_i * 4;
dst[0] = (uint8_t)((src & 0x000000FF) >> 0);
dst[1] = (uint8_t)((src & 0x0000FF00) >> 8);
dst[2] = (uint8_t)((src & 0x00FF0000) >> 16);
dst[3] = (uint8_t)((src & 0xFF000000) >> 24);
}
else
{
assert(!"Unknown pixel format");
}
dst_i++;
}
}
curr_tile_start += FRAMEBUFFER_PIXELS_PER_TILE;
}
curr_tile_row_start += fb->pixels_per_row_of_tiles;
}
}
// hack
uint32_t g_Color;
void rasterize_triangle_fixed16_8(
framebuffer_t* fb,
uint32_t window_x0, uint32_t window_y0, uint32_t window_z0,
uint32_t window_x1, uint32_t window_y1, uint32_t window_z1,
uint32_t window_x2, uint32_t window_y2, uint32_t window_z2)
{
}<|endoftext|>
|
<commit_before>/*
kopetecontactlist.cpp - Kopete's Contact List backend
Copyright (c) 2005-2007 by Michael Larouche <larouche@kde.org>
Copyright (c) 2002-2003 by Martijn Klingens <klingens@kde.org>
Copyright (c) 2002-2004 by Olivier Goffart <ogoffart@kde.org>
Copyright (c) 2002 by Duncan Mac-Vicar Prett <duncan@kde.org>
Copyright (c) 2002-2004 by the Kopete developers <kopete-devel@kde.org>
*************************************************************************
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Lesser General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
*************************************************************************
*/
#include "kopetecontactlist.h"
// Qt includes
#include <QtCore/QDir>
#include <QtCore/QRegExp>
#include <QtCore/QTimer>
#include <QtCore/QTextStream>
// KDE includes
#include <kabc/stdaddressbook.h>
#include <kapplication.h>
#include <kdebug.h>
#include <kglobal.h>
#include <ksavefile.h>
#include <kstandarddirs.h>
// Kopete includes
#include "kopeteaccount.h"
#include "kopeteaccountmanager.h"
#include "kopetechatsession.h"
#include "kopetecontact.h"
#include "kopetedeletecontacttask.h"
#include "kopetegroup.h"
#include "kopetemetacontact.h"
#include "kopetepicture.h"
#include "kopetepluginmanager.h"
#include "kopeteprotocol.h"
#include "xmlcontactstorage.h"
namespace Kopete
{
class ContactList::Private
{public:
/** Flag: do not save the contact list until she is completely loaded */
bool loaded ;
QList<MetaContact *> contacts;
QList<Group *> groups;
QList<MetaContact *> selectedMetaContacts;
QList<Group *> selectedGroups;
QTimer *saveTimer;
MetaContact *myself;
};
ContactList *ContactList::s_self = 0L;
ContactList *ContactList::self()
{
if( !s_self )
s_self = new ContactList;
return s_self;
}
ContactList::ContactList()
: QObject( kapp )
{
setObjectName( "KopeteContactList" );
d=new Private;
//the myself metacontact can't be created now, because it will use
//ContactList::self() as parent which will call this constructor -> infinite loop
d->myself=0L;
//no contact list loaded yet, don't save them
d->loaded=false;
// automatically save on changes to the list
d->saveTimer = new QTimer( this );
d->saveTimer->setObjectName( "saveTimer" );
d->saveTimer->setSingleShot( true );
connect( d->saveTimer, SIGNAL( timeout() ), SLOT ( save() ) );
connect( this, SIGNAL( metaContactAdded( Kopete::MetaContact * ) ), SLOT( slotSaveLater() ) );
connect( this, SIGNAL( metaContactRemoved( Kopete::MetaContact * ) ), SLOT( slotSaveLater() ) );
connect( this, SIGNAL( groupAdded( Kopete::Group * ) ), SLOT( slotSaveLater() ) );
connect( this, SIGNAL( groupRemoved( Kopete::Group * ) ), SLOT( slotSaveLater() ) );
connect( this, SIGNAL( groupRenamed( Kopete::Group *, const QString & ) ), SLOT( slotSaveLater() ) );
}
ContactList::~ContactList()
{
delete d->myself;
delete d;
}
QList<MetaContact *> ContactList::metaContacts() const
{
return d->contacts;
}
QList<Group *> ContactList::groups() const
{
return d->groups;
}
MetaContact *ContactList::metaContact( const QString &metaContactId ) const
{
QListIterator<MetaContact *> it( d->contacts );
while ( it.hasNext() )
{
MetaContact *mc = it.next();
if( mc->metaContactId() == metaContactId )
return mc;
}
return 0L;
}
Group * ContactList::group(unsigned int groupId) const
{
QListIterator<Group *> it(d->groups);
while ( it.hasNext() )
{
Group *curr = it.next();
if( curr->groupId()==groupId )
return curr;
}
return 0L;
}
Contact *ContactList::findContact( const QString &protocolId,
const QString &accountId, const QString &contactId ) const
{
//Browsing metacontacts is too slow, better to uses the Dict of the account.
Account *i=AccountManager::self()->findAccount(protocolId,accountId);
if(!i)
{
kDebug( 14010 ) << "Account not found";
return 0L;
}
return i->contacts()[contactId];
}
MetaContact *ContactList::findMetaContactByDisplayName( const QString &displayName ) const
{
foreach(Kopete::MetaContact *contact, d->contacts)
{
if( contact->displayName() == displayName )
{
return contact;
}
}
return 0;
}
MetaContact* ContactList::findMetaContactByContactId( const QString &contactId ) const
{
QListIterator<Kopete::Account *> it( Kopete::AccountManager::self()->accounts() );
Kopete::Account *a;
while ( it.hasNext() )
{
a = it.next();
Contact *c=a->contacts()[contactId];
if(c && c->metaContact())
return c->metaContact();
}
return 0L;
}
Group * ContactList::findGroup(const QString& displayName, int type)
{
if( type == Group::Temporary )
return Group::temporary();
QListIterator<Group *> it(d->groups);
while ( it.hasNext() )
{
Group *curr = it.next();
if( curr->type() == type && curr->displayName() == displayName )
return curr;
}
Group *newGroup = new Group( displayName, (Group::GroupType)type );
addGroup( newGroup );
return newGroup;
}
QList<MetaContact *> ContactList::selectedMetaContacts() const
{
return d->selectedMetaContacts;
}
QList<Group *> ContactList::selectedGroups() const
{
return d->selectedGroups;
}
void ContactList::addMetaContacts( QList<MetaContact *> metaContacts )
{
foreach( MetaContact* mc, metaContacts )
addMetaContact( mc );
}
void ContactList::addMetaContact( MetaContact *mc )
{
if ( d->contacts.contains( mc ) )
return;
d->contacts.append( mc );
emit metaContactAdded( mc );
connect( mc, SIGNAL( persistentDataChanged( ) ), SLOT( slotSaveLater() ) );
connect( mc, SIGNAL( addedToGroup( Kopete::MetaContact *, Kopete::Group * ) ), SIGNAL( metaContactAddedToGroup( Kopete::MetaContact *, Kopete::Group * ) ) );
connect( mc, SIGNAL( removedFromGroup( Kopete::MetaContact *, Kopete::Group * ) ), SIGNAL( metaContactRemovedFromGroup( Kopete::MetaContact *, Kopete::Group * ) ) );
}
void ContactList::removeMetaContact(MetaContact *m)
{
if ( !d->contacts.contains(m) )
{
kDebug(14010) << "Trying to remove a not listed MetaContact.";
return;
}
if ( d->selectedMetaContacts.contains( m ) )
{
d->selectedMetaContacts.removeAll( m );
setSelectedItems( d->selectedMetaContacts, d->selectedGroups );
}
//removes subcontact from server here and now.
Kopete::Contact *contactToDelete = 0;
foreach( contactToDelete, m->contacts() )
{
// TODO: Check for good execution of task
Kopete::DeleteContactTask *deleteTask = new Kopete::DeleteContactTask(contactToDelete);
deleteTask->start();
}
d->contacts.removeAll( m );
emit metaContactRemoved( m );
m->deleteLater();
}
void ContactList::addGroups( QList<Group *> groups )
{
foreach( Group* g, groups )
addGroup( g );
}
void ContactList::addGroup( Group * g )
{
if(!d->groups.contains(g) )
{
d->groups.append( g );
emit groupAdded( g );
connect( g , SIGNAL ( displayNameChanged(Kopete::Group* , const QString & )) , this , SIGNAL ( groupRenamed(Kopete::Group* , const QString & )) ) ;
}
}
void ContactList::removeGroup( Group *g )
{
if ( d->selectedGroups.contains( g ) )
{
d->selectedGroups.removeAll( g );
setSelectedItems( d->selectedMetaContacts, d->selectedGroups );
}
d->groups.removeAll( g );
emit groupRemoved( g );
g->deleteLater();
}
void ContactList::setSelectedItems(QList<MetaContact *> metaContacts , QList<Group *> groups)
{
kDebug( 14010 ) << metaContacts.count() << " metacontacts, " << groups.count() << " groups selected";
d->selectedMetaContacts=metaContacts;
d->selectedGroups=groups;
emit metaContactSelected( groups.isEmpty() && metaContacts.count()==1 );
emit selectionChanged();
}
MetaContact* ContactList::myself()
{
if(!d->myself)
d->myself=new MetaContact();
return d->myself;
}
///////////////////////////////////////////////////////////////////////////////////////////////
void ContactList::load()
{
// don't save when we're in the middle of this...
d->loaded = false;
Kopete::ContactListStorage *storage = new Kopete::XmlContactStorage();
storage->load();
if( !storage->isValid() )
{
kDebug(14010) << "Contact list storage failed. Reason: " << storage->errorMessage();
d->loaded = true;
delete storage;
return;
}
addGroups( storage->groups() );
addMetaContacts( storage->contacts() );
d->loaded = true;
delete storage;
}
void Kopete::ContactList::save()
{
if( !d->loaded )
{
kDebug(14010) << "Contact list not loaded, abort saving";
return;
}
Kopete::ContactListStorage *storage = new Kopete::XmlContactStorage();
storage->save();
if( !storage->isValid() )
{
kDebug(14010) << "Contact list storage failed. Reason: " << storage->errorMessage();
// Saving the contact list failed. retry every minute until it works.
// single-shot: will get restarted by us next time if it's still failing
d->saveTimer->setSingleShot( true );
d->saveTimer->start( 60000 );
delete storage;
return;
}
// cancel any scheduled saves
d->saveTimer->stop();
delete storage;
}
void ContactList::slotSaveLater()
{
// if we already have a save scheduled, it will be cancelled. either way,
// start a timer to save the contact list a bit later.
d->saveTimer->start( 17100 /* 17,1 seconds */ );
}
void ContactList::slotKABCChanged()
{
// TODO: react to changes in KABC, replacing this function, post 3.4 (Will)
// call syncWithKABC on each metacontact to check if its associated kabc entry has changed.
/* for ( MetaContact * mc = d->contacts.first(); mc; mc = d->contacts.next() )
mc->syncWithKABC();*/
}
} //END namespace Kopete
#include "kopetecontactlist.moc"
// vim: set noet ts=4 sts=4 sw=4:
<commit_msg>If group is named "Top Level", return actual top level group BUG:150258<commit_after>/*
kopetecontactlist.cpp - Kopete's Contact List backend
Copyright (c) 2005-2007 by Michael Larouche <larouche@kde.org>
Copyright (c) 2002-2003 by Martijn Klingens <klingens@kde.org>
Copyright (c) 2002-2004 by Olivier Goffart <ogoffart@kde.org>
Copyright (c) 2002 by Duncan Mac-Vicar Prett <duncan@kde.org>
Copyright (c) 2002-2004 by the Kopete developers <kopete-devel@kde.org>
*************************************************************************
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Lesser General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
*************************************************************************
*/
#include "kopetecontactlist.h"
// Qt includes
#include <QtCore/QDir>
#include <QtCore/QRegExp>
#include <QtCore/QTimer>
#include <QtCore/QTextStream>
// KDE includes
#include <kabc/stdaddressbook.h>
#include <kapplication.h>
#include <kdebug.h>
#include <kglobal.h>
#include <ksavefile.h>
#include <kstandarddirs.h>
// Kopete includes
#include "kopeteaccount.h"
#include "kopeteaccountmanager.h"
#include "kopetechatsession.h"
#include "kopetecontact.h"
#include "kopetedeletecontacttask.h"
#include "kopetegroup.h"
#include "kopetemetacontact.h"
#include "kopetepicture.h"
#include "kopetepluginmanager.h"
#include "kopeteprotocol.h"
#include "xmlcontactstorage.h"
namespace Kopete
{
class ContactList::Private
{public:
/** Flag: do not save the contact list until she is completely loaded */
bool loaded ;
QList<MetaContact *> contacts;
QList<Group *> groups;
QList<MetaContact *> selectedMetaContacts;
QList<Group *> selectedGroups;
QTimer *saveTimer;
MetaContact *myself;
};
ContactList *ContactList::s_self = 0L;
ContactList *ContactList::self()
{
if( !s_self )
s_self = new ContactList;
return s_self;
}
ContactList::ContactList()
: QObject( kapp )
{
setObjectName( "KopeteContactList" );
d=new Private;
//the myself metacontact can't be created now, because it will use
//ContactList::self() as parent which will call this constructor -> infinite loop
d->myself=0L;
//no contact list loaded yet, don't save them
d->loaded=false;
// automatically save on changes to the list
d->saveTimer = new QTimer( this );
d->saveTimer->setObjectName( "saveTimer" );
d->saveTimer->setSingleShot( true );
connect( d->saveTimer, SIGNAL( timeout() ), SLOT ( save() ) );
connect( this, SIGNAL( metaContactAdded( Kopete::MetaContact * ) ), SLOT( slotSaveLater() ) );
connect( this, SIGNAL( metaContactRemoved( Kopete::MetaContact * ) ), SLOT( slotSaveLater() ) );
connect( this, SIGNAL( groupAdded( Kopete::Group * ) ), SLOT( slotSaveLater() ) );
connect( this, SIGNAL( groupRemoved( Kopete::Group * ) ), SLOT( slotSaveLater() ) );
connect( this, SIGNAL( groupRenamed( Kopete::Group *, const QString & ) ), SLOT( slotSaveLater() ) );
}
ContactList::~ContactList()
{
delete d->myself;
delete d;
}
QList<MetaContact *> ContactList::metaContacts() const
{
return d->contacts;
}
QList<Group *> ContactList::groups() const
{
return d->groups;
}
MetaContact *ContactList::metaContact( const QString &metaContactId ) const
{
QListIterator<MetaContact *> it( d->contacts );
while ( it.hasNext() )
{
MetaContact *mc = it.next();
if( mc->metaContactId() == metaContactId )
return mc;
}
return 0L;
}
Group * ContactList::group(unsigned int groupId) const
{
QListIterator<Group *> it(d->groups);
while ( it.hasNext() )
{
Group *curr = it.next();
if( curr->groupId()==groupId )
return curr;
}
return 0L;
}
Contact *ContactList::findContact( const QString &protocolId,
const QString &accountId, const QString &contactId ) const
{
//Browsing metacontacts is too slow, better to uses the Dict of the account.
Account *i=AccountManager::self()->findAccount(protocolId,accountId);
if(!i)
{
kDebug( 14010 ) << "Account not found";
return 0L;
}
return i->contacts()[contactId];
}
MetaContact *ContactList::findMetaContactByDisplayName( const QString &displayName ) const
{
foreach(Kopete::MetaContact *contact, d->contacts)
{
if( contact->displayName() == displayName )
{
return contact;
}
}
return 0;
}
MetaContact* ContactList::findMetaContactByContactId( const QString &contactId ) const
{
QListIterator<Kopete::Account *> it( Kopete::AccountManager::self()->accounts() );
Kopete::Account *a;
while ( it.hasNext() )
{
a = it.next();
Contact *c=a->contacts()[contactId];
if(c && c->metaContact())
return c->metaContact();
}
return 0L;
}
Group * ContactList::findGroup(const QString& displayName, int type)
{
if( type == Group::Temporary )
return Group::temporary();
if ( displayName == i18n ("Top Level") )
return Group::topLevel();
QListIterator<Group *> it(d->groups);
while ( it.hasNext() )
{
Group *curr = it.next();
if( curr->type() == type && curr->displayName() == displayName )
return curr;
}
Group *newGroup = new Group( displayName, (Group::GroupType)type );
addGroup( newGroup );
return newGroup;
}
QList<MetaContact *> ContactList::selectedMetaContacts() const
{
return d->selectedMetaContacts;
}
QList<Group *> ContactList::selectedGroups() const
{
return d->selectedGroups;
}
void ContactList::addMetaContacts( QList<MetaContact *> metaContacts )
{
foreach( MetaContact* mc, metaContacts )
addMetaContact( mc );
}
void ContactList::addMetaContact( MetaContact *mc )
{
if ( d->contacts.contains( mc ) )
return;
d->contacts.append( mc );
emit metaContactAdded( mc );
connect( mc, SIGNAL( persistentDataChanged( ) ), SLOT( slotSaveLater() ) );
connect( mc, SIGNAL( addedToGroup( Kopete::MetaContact *, Kopete::Group * ) ), SIGNAL( metaContactAddedToGroup( Kopete::MetaContact *, Kopete::Group * ) ) );
connect( mc, SIGNAL( removedFromGroup( Kopete::MetaContact *, Kopete::Group * ) ), SIGNAL( metaContactRemovedFromGroup( Kopete::MetaContact *, Kopete::Group * ) ) );
}
void ContactList::removeMetaContact(MetaContact *m)
{
if ( !d->contacts.contains(m) )
{
kDebug(14010) << "Trying to remove a not listed MetaContact.";
return;
}
if ( d->selectedMetaContacts.contains( m ) )
{
d->selectedMetaContacts.removeAll( m );
setSelectedItems( d->selectedMetaContacts, d->selectedGroups );
}
//removes subcontact from server here and now.
Kopete::Contact *contactToDelete = 0;
foreach( contactToDelete, m->contacts() )
{
// TODO: Check for good execution of task
Kopete::DeleteContactTask *deleteTask = new Kopete::DeleteContactTask(contactToDelete);
deleteTask->start();
}
d->contacts.removeAll( m );
emit metaContactRemoved( m );
m->deleteLater();
}
void ContactList::addGroups( QList<Group *> groups )
{
foreach( Group* g, groups )
addGroup( g );
}
void ContactList::addGroup( Group * g )
{
if(!d->groups.contains(g) )
{
d->groups.append( g );
emit groupAdded( g );
connect( g , SIGNAL ( displayNameChanged(Kopete::Group* , const QString & )) , this , SIGNAL ( groupRenamed(Kopete::Group* , const QString & )) ) ;
}
}
void ContactList::removeGroup( Group *g )
{
if ( d->selectedGroups.contains( g ) )
{
d->selectedGroups.removeAll( g );
setSelectedItems( d->selectedMetaContacts, d->selectedGroups );
}
d->groups.removeAll( g );
emit groupRemoved( g );
g->deleteLater();
}
void ContactList::setSelectedItems(QList<MetaContact *> metaContacts , QList<Group *> groups)
{
kDebug( 14010 ) << metaContacts.count() << " metacontacts, " << groups.count() << " groups selected";
d->selectedMetaContacts=metaContacts;
d->selectedGroups=groups;
emit metaContactSelected( groups.isEmpty() && metaContacts.count()==1 );
emit selectionChanged();
}
MetaContact* ContactList::myself()
{
if(!d->myself)
d->myself=new MetaContact();
return d->myself;
}
///////////////////////////////////////////////////////////////////////////////////////////////
void ContactList::load()
{
// don't save when we're in the middle of this...
d->loaded = false;
Kopete::ContactListStorage *storage = new Kopete::XmlContactStorage();
storage->load();
if( !storage->isValid() )
{
kDebug(14010) << "Contact list storage failed. Reason: " << storage->errorMessage();
d->loaded = true;
delete storage;
return;
}
addGroups( storage->groups() );
addMetaContacts( storage->contacts() );
d->loaded = true;
delete storage;
}
void Kopete::ContactList::save()
{
if( !d->loaded )
{
kDebug(14010) << "Contact list not loaded, abort saving";
return;
}
Kopete::ContactListStorage *storage = new Kopete::XmlContactStorage();
storage->save();
if( !storage->isValid() )
{
kDebug(14010) << "Contact list storage failed. Reason: " << storage->errorMessage();
// Saving the contact list failed. retry every minute until it works.
// single-shot: will get restarted by us next time if it's still failing
d->saveTimer->setSingleShot( true );
d->saveTimer->start( 60000 );
delete storage;
return;
}
// cancel any scheduled saves
d->saveTimer->stop();
delete storage;
}
void ContactList::slotSaveLater()
{
// if we already have a save scheduled, it will be cancelled. either way,
// start a timer to save the contact list a bit later.
d->saveTimer->start( 17100 /* 17,1 seconds */ );
}
void ContactList::slotKABCChanged()
{
// TODO: react to changes in KABC, replacing this function, post 3.4 (Will)
// call syncWithKABC on each metacontact to check if its associated kabc entry has changed.
/* for ( MetaContact * mc = d->contacts.first(); mc; mc = d->contacts.next() )
mc->syncWithKABC();*/
}
} //END namespace Kopete
#include "kopetecontactlist.moc"
// vim: set noet ts=4 sts=4 sw=4:
<|endoftext|>
|
<commit_before>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
#include <BALL/FORMAT/bruker1DFile.h>
namespace BALL
{
Bruker1DFile::Bruker1DFile()
: File(),
min_(0),
max_(1),
pars_()
{
}
Bruker1DFile::Bruker1DFile(const String& name, OpenMode open_mode)
: File(name + FileSystem::PATH_SEPARATOR + "1r", open_mode),
min_(0),
max_(1),
pars_()
{
pars_.open(name + FileSystem::PATH_SEPARATOR + "procs");
pars_.read();
min_ = (Size)pars_.getDoubleValue("YMIN_p");
max_ = (Size)pars_.getDoubleValue("YMAX_p");
pars_.close();
read();
}
Bruker1DFile::~Bruker1DFile()
{
}
void Bruker1DFile::read(const String &name)
{
pars_.open(name + FileSystem::PATH_SEPARATOR + "procs");
pars_.read();
min_ = (Size)pars_.getDoubleValue("YMIN_p");
max_ = (Size)pars_.getDoubleValue("YMAX_p");
pars_.close();
close();
open(name + FileSystem::PATH_SEPARATOR + "1r");
read();
}
void Bruker1DFile::read()
{
char c[4];
signed long int &numdum = *(signed long int*) (&c[0]);
Position actpos = 0;
File& f = static_cast<File&> (*this);
bool littleEndian;
// first we will have to find out whether we are using big or little
// endian on this machine.
int endTest = 1;
if (*(char *) &endTest == 1)
{
littleEndian = true;
}
else
{
littleEndian = false;
}
spectrum_.resize( (Size)pars_.getDoubleValue("SI"));
spectrum_.setOrigin(pars_.getDoubleValue("YMIN_p"));
spectrum_.setDimension(pars_.getDoubleValue("YMAX_p") - pars_.getDoubleValue("YMIN_p"));
// back to beginning of file
f.reopen();
// read data
for (Position i = 0; i < (Size)pars_.getDoubleValue("SI"); i++)
{
if (!f.good())
{
// ?????: here should be a warning or exception
return;
}
f.get(c[0]); f.get(c[1]); f.get(c[2]); f.get(c[3]);
if (pars_.getDoubleValue("BYTORDP") == 1.0L)
{
if (littleEndian == false)
{ // conversion from little to big
numdum = (signed long) ( ((numdum & 0x000000FFL) << 24)
|((numdum & 0x0000FF00L) << 16)
|((numdum & 0x00FF0000L) >> 16)
|((numdum & 0xFF000000L) >> 24));
}
// else no conversion needed
}
else
{
if (littleEndian == true) // conversion from big to little
{
numdum = (signed long) ( ((numdum & 0x000000FFL) << 24)
|((numdum & 0x0000FF00L) << 16)
|((numdum & 0x00FF0000L) >> 16)
|((numdum & 0xFF000000L) >> 24));
}
// else no conversion needed
}
if ((max_ - min_) != 0)
{
spectrum_[actpos] = ((double) (numdum - min_)) / (max_ - min_);
}
actpos++;
}
}
}
<commit_msg>Fix endian detection/conversion in Bruker1DFile<commit_after>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
#include <BALL/FORMAT/bruker1DFile.h>
namespace BALL
{
Bruker1DFile::Bruker1DFile()
: File(),
min_(0),
max_(1),
pars_()
{
}
Bruker1DFile::Bruker1DFile(const String& name, OpenMode open_mode)
: File(name + FileSystem::PATH_SEPARATOR + "1r", open_mode),
min_(0),
max_(1),
pars_()
{
pars_.open(name + FileSystem::PATH_SEPARATOR + "procs");
pars_.read();
min_ = (Size)pars_.getDoubleValue("YMIN_p");
max_ = (Size)pars_.getDoubleValue("YMAX_p");
pars_.close();
read();
}
Bruker1DFile::~Bruker1DFile()
{
}
void Bruker1DFile::read(const String &name)
{
pars_.open(name + FileSystem::PATH_SEPARATOR + "procs");
pars_.read();
min_ = (Size)pars_.getDoubleValue("YMIN_p");
max_ = (Size)pars_.getDoubleValue("YMAX_p");
pars_.close();
close();
open(name + FileSystem::PATH_SEPARATOR + "1r");
read();
}
void Bruker1DFile::read()
{
// first we will have to find out whether we are using big or little
// endian on this machine.
unsigned int endTest = 1;
BinaryFileAdaptor<BALL_INT32> adapt_int32_t_;
adapt_int32_t_.setSwapEndian((*(char*)&endTest == 1) != (pars_.getDoubleValue("BYTORDP") == 1.0));
spectrum_.resize( (Size)pars_.getDoubleValue("SI"));
spectrum_.setOrigin(pars_.getDoubleValue("YMIN_p"));
spectrum_.setDimension(pars_.getDoubleValue("YMAX_p") - pars_.getDoubleValue("YMIN_p"));
// back to beginning of file
this->reopen();
// read data
for (Position i = 0; i < spectrum_.size(); ++i)
{
if (!this->good())
{
// ?????: here should be a warning or exception
return;
}
(*this) >> adapt_int32_t_;
if ((max_ - min_) != 0)
{
spectrum_[i] = ((double) (adapt_int32_t_.getData() - min_)) / (max_ - min_);
}
}
}
}
<|endoftext|>
|
<commit_before>//===-- source/Host/freebsd/Host.cpp ------------------------------*- C++
//-*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// C Includes
#include <sys/types.h>
#include <sys/exec.h>
#include <sys/proc.h>
#include <sys/ptrace.h>
#include <sys/sysctl.h>
#include <sys/user.h>
#include <machine/elf.h>
#include <dlfcn.h>
#include <execinfo.h>
#include <stdio.h>
// C++ Includes
// Other libraries and framework includes
// Project includes
#include "lldb/Host/Host.h"
#include "lldb/Host/HostInfo.h"
#include "lldb/Target/Process.h"
#include "lldb/Utility/DataBufferHeap.h"
#include "lldb/Utility/DataExtractor.h"
#include "lldb/Utility/Endian.h"
#include "lldb/Utility/Log.h"
#include "lldb/Utility/NameMatches.h"
#include "lldb/Utility/Status.h"
#include "lldb/Utility/StreamString.h"
#include "llvm/Support/Host.h"
extern "C" {
extern char **environ;
}
using namespace lldb;
using namespace lldb_private;
static bool
GetFreeBSDProcessArgs(const ProcessInstanceInfoMatch *match_info_ptr,
ProcessInstanceInfo &process_info) {
if (!process_info.ProcessIDIsValid())
return false;
int pid = process_info.GetProcessID();
int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_ARGS, pid};
char arg_data[8192];
size_t arg_data_size = sizeof(arg_data);
if (::sysctl(mib, 4, arg_data, &arg_data_size, NULL, 0) != 0)
return false;
DataExtractor data(arg_data, arg_data_size, endian::InlHostByteOrder(),
sizeof(void *));
lldb::offset_t offset = 0;
const char *cstr;
cstr = data.GetCStr(&offset);
if (!cstr)
return false;
// Get pathname for pid. If that fails fall back to argv[0].
char pathname[MAXPATHLEN];
size_t pathname_len = sizeof(pathname);
mib[2] = KERN_PROC_PATHNAME;
if (::sysctl(mib, 4, pathname, &pathname_len, NULL, 0) == 0)
process_info.GetExecutableFile().SetFile(pathname, false,
FileSpec::Style::native);
else
process_info.GetExecutableFile().SetFile(cstr, false,
FileSpec::Style::native);
if (!(match_info_ptr == NULL ||
NameMatches(process_info.GetExecutableFile().GetFilename().GetCString(),
match_info_ptr->GetNameMatchType(),
match_info_ptr->GetProcessInfo().GetName())))
return false;
Args &proc_args = process_info.GetArguments();
while (1) {
const uint8_t *p = data.PeekData(offset, 1);
while ((p != NULL) && (*p == '\0') && offset < arg_data_size) {
++offset;
p = data.PeekData(offset, 1);
}
if (p == NULL || offset >= arg_data_size)
break;
cstr = data.GetCStr(&offset);
if (!cstr)
break;
proc_args.AppendArgument(llvm::StringRef(cstr));
}
return true;
}
static bool GetFreeBSDProcessCPUType(ProcessInstanceInfo &process_info) {
if (process_info.ProcessIDIsValid()) {
process_info.GetArchitecture() =
HostInfo::GetArchitecture(HostInfo::eArchKindDefault);
return true;
}
process_info.GetArchitecture().Clear();
return false;
}
static bool GetFreeBSDProcessUserAndGroup(ProcessInstanceInfo &process_info) {
struct kinfo_proc proc_kinfo;
size_t proc_kinfo_size;
const int pid = process_info.GetProcessID();
int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, pid};
if (!process_info.ProcessIDIsValid())
goto error;
proc_kinfo_size = sizeof(struct kinfo_proc);
if (::sysctl(mib, 4, &proc_kinfo, &proc_kinfo_size, NULL, 0) != 0)
goto error;
if (proc_kinfo_size == 0)
goto error;
process_info.SetParentProcessID(proc_kinfo.ki_ppid);
process_info.SetUserID(proc_kinfo.ki_ruid);
process_info.SetGroupID(proc_kinfo.ki_rgid);
process_info.SetEffectiveUserID(proc_kinfo.ki_uid);
if (proc_kinfo.ki_ngroups > 0)
process_info.SetEffectiveGroupID(proc_kinfo.ki_groups[0]);
else
process_info.SetEffectiveGroupID(UINT32_MAX);
return true;
error:
process_info.SetParentProcessID(LLDB_INVALID_PROCESS_ID);
process_info.SetUserID(UINT32_MAX);
process_info.SetGroupID(UINT32_MAX);
process_info.SetEffectiveUserID(UINT32_MAX);
process_info.SetEffectiveGroupID(UINT32_MAX);
return false;
}
uint32_t Host::FindProcesses(const ProcessInstanceInfoMatch &match_info,
ProcessInstanceInfoList &process_infos) {
const ::pid_t our_pid = ::getpid();
const ::uid_t our_uid = ::getuid();
std::vector<struct kinfo_proc> kinfos;
// Special case, if lldb is being run as root we can attach to anything.
bool all_users = match_info.GetMatchAllUsers() || (our_uid == 0);
int mib[3] = {CTL_KERN, KERN_PROC, KERN_PROC_ALL};
size_t pid_data_size = 0;
if (::sysctl(mib, 3, NULL, &pid_data_size, NULL, 0) != 0)
return 0;
// Add a few extra in case a few more show up
const size_t estimated_pid_count =
(pid_data_size / sizeof(struct kinfo_proc)) + 10;
kinfos.resize(estimated_pid_count);
pid_data_size = kinfos.size() * sizeof(struct kinfo_proc);
if (::sysctl(mib, 3, &kinfos[0], &pid_data_size, NULL, 0) != 0)
return 0;
const size_t actual_pid_count = (pid_data_size / sizeof(struct kinfo_proc));
for (size_t i = 0; i < actual_pid_count; i++) {
const struct kinfo_proc &kinfo = kinfos[i];
/* Make sure the user is acceptable */
if (!all_users && kinfo.ki_ruid != our_uid)
continue;
if (kinfo.ki_pid == our_pid || // Skip this process
kinfo.ki_pid == 0 || // Skip kernel (kernel pid is 0)
kinfo.ki_stat == SZOMB || // Zombies are bad
kinfo.ki_flag & P_TRACED || // Being debugged?
kinfo.ki_flag & P_WEXIT) // Working on exiting
continue;
// Every thread is a process in FreeBSD, but all the threads of a single
// process have the same pid. Do not store the process info in the result
// list if a process with given identifier is already registered there.
bool already_registered = false;
for (uint32_t pi = 0;
!already_registered && (const int)kinfo.ki_numthreads > 1 &&
pi < (const uint32_t)process_infos.GetSize();
pi++)
already_registered =
(process_infos.GetProcessIDAtIndex(pi) == (uint32_t)kinfo.ki_pid);
if (already_registered)
continue;
ProcessInstanceInfo process_info;
process_info.SetProcessID(kinfo.ki_pid);
process_info.SetParentProcessID(kinfo.ki_ppid);
process_info.SetUserID(kinfo.ki_ruid);
process_info.SetGroupID(kinfo.ki_rgid);
process_info.SetEffectiveUserID(kinfo.ki_svuid);
process_info.SetEffectiveGroupID(kinfo.ki_svgid);
// Make sure our info matches before we go fetch the name and cpu type
if (match_info.Matches(process_info) &&
GetFreeBSDProcessArgs(&match_info, process_info)) {
GetFreeBSDProcessCPUType(process_info);
if (match_info.Matches(process_info))
process_infos.Append(process_info);
}
}
return process_infos.GetSize();
}
bool Host::GetProcessInfo(lldb::pid_t pid, ProcessInstanceInfo &process_info) {
process_info.SetProcessID(pid);
if (GetFreeBSDProcessArgs(NULL, process_info)) {
// should use libprocstat instead of going right into sysctl?
GetFreeBSDProcessCPUType(process_info);
GetFreeBSDProcessUserAndGroup(process_info);
return true;
}
process_info.Clear();
return false;
}
Environment Host::GetEnvironment() { return Environment(environ); }
Status Host::ShellExpandArguments(ProcessLaunchInfo &launch_info) {
return Status("unimplemented");
}
<commit_msg>[FileSystem] Change FileSpec constructor signature (2/2)<commit_after>//===-- source/Host/freebsd/Host.cpp ------------------------------*- C++
//-*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// C Includes
#include <sys/types.h>
#include <sys/exec.h>
#include <sys/proc.h>
#include <sys/ptrace.h>
#include <sys/sysctl.h>
#include <sys/user.h>
#include <machine/elf.h>
#include <dlfcn.h>
#include <execinfo.h>
#include <stdio.h>
// C++ Includes
// Other libraries and framework includes
// Project includes
#include "lldb/Host/Host.h"
#include "lldb/Host/HostInfo.h"
#include "lldb/Target/Process.h"
#include "lldb/Utility/DataBufferHeap.h"
#include "lldb/Utility/DataExtractor.h"
#include "lldb/Utility/Endian.h"
#include "lldb/Utility/Log.h"
#include "lldb/Utility/NameMatches.h"
#include "lldb/Utility/Status.h"
#include "lldb/Utility/StreamString.h"
#include "llvm/Support/Host.h"
extern "C" {
extern char **environ;
}
using namespace lldb;
using namespace lldb_private;
static bool
GetFreeBSDProcessArgs(const ProcessInstanceInfoMatch *match_info_ptr,
ProcessInstanceInfo &process_info) {
if (!process_info.ProcessIDIsValid())
return false;
int pid = process_info.GetProcessID();
int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_ARGS, pid};
char arg_data[8192];
size_t arg_data_size = sizeof(arg_data);
if (::sysctl(mib, 4, arg_data, &arg_data_size, NULL, 0) != 0)
return false;
DataExtractor data(arg_data, arg_data_size, endian::InlHostByteOrder(),
sizeof(void *));
lldb::offset_t offset = 0;
const char *cstr;
cstr = data.GetCStr(&offset);
if (!cstr)
return false;
// Get pathname for pid. If that fails fall back to argv[0].
char pathname[MAXPATHLEN];
size_t pathname_len = sizeof(pathname);
mib[2] = KERN_PROC_PATHNAME;
if (::sysctl(mib, 4, pathname, &pathname_len, NULL, 0) == 0)
process_info.GetExecutableFile().SetFile(pathname, FileSpec::Style::native);
else
process_info.GetExecutableFile().SetFile(cstr, FileSpec::Style::native);
if (!(match_info_ptr == NULL ||
NameMatches(process_info.GetExecutableFile().GetFilename().GetCString(),
match_info_ptr->GetNameMatchType(),
match_info_ptr->GetProcessInfo().GetName())))
return false;
Args &proc_args = process_info.GetArguments();
while (1) {
const uint8_t *p = data.PeekData(offset, 1);
while ((p != NULL) && (*p == '\0') && offset < arg_data_size) {
++offset;
p = data.PeekData(offset, 1);
}
if (p == NULL || offset >= arg_data_size)
break;
cstr = data.GetCStr(&offset);
if (!cstr)
break;
proc_args.AppendArgument(llvm::StringRef(cstr));
}
return true;
}
static bool GetFreeBSDProcessCPUType(ProcessInstanceInfo &process_info) {
if (process_info.ProcessIDIsValid()) {
process_info.GetArchitecture() =
HostInfo::GetArchitecture(HostInfo::eArchKindDefault);
return true;
}
process_info.GetArchitecture().Clear();
return false;
}
static bool GetFreeBSDProcessUserAndGroup(ProcessInstanceInfo &process_info) {
struct kinfo_proc proc_kinfo;
size_t proc_kinfo_size;
const int pid = process_info.GetProcessID();
int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, pid};
if (!process_info.ProcessIDIsValid())
goto error;
proc_kinfo_size = sizeof(struct kinfo_proc);
if (::sysctl(mib, 4, &proc_kinfo, &proc_kinfo_size, NULL, 0) != 0)
goto error;
if (proc_kinfo_size == 0)
goto error;
process_info.SetParentProcessID(proc_kinfo.ki_ppid);
process_info.SetUserID(proc_kinfo.ki_ruid);
process_info.SetGroupID(proc_kinfo.ki_rgid);
process_info.SetEffectiveUserID(proc_kinfo.ki_uid);
if (proc_kinfo.ki_ngroups > 0)
process_info.SetEffectiveGroupID(proc_kinfo.ki_groups[0]);
else
process_info.SetEffectiveGroupID(UINT32_MAX);
return true;
error:
process_info.SetParentProcessID(LLDB_INVALID_PROCESS_ID);
process_info.SetUserID(UINT32_MAX);
process_info.SetGroupID(UINT32_MAX);
process_info.SetEffectiveUserID(UINT32_MAX);
process_info.SetEffectiveGroupID(UINT32_MAX);
return false;
}
uint32_t Host::FindProcesses(const ProcessInstanceInfoMatch &match_info,
ProcessInstanceInfoList &process_infos) {
const ::pid_t our_pid = ::getpid();
const ::uid_t our_uid = ::getuid();
std::vector<struct kinfo_proc> kinfos;
// Special case, if lldb is being run as root we can attach to anything.
bool all_users = match_info.GetMatchAllUsers() || (our_uid == 0);
int mib[3] = {CTL_KERN, KERN_PROC, KERN_PROC_ALL};
size_t pid_data_size = 0;
if (::sysctl(mib, 3, NULL, &pid_data_size, NULL, 0) != 0)
return 0;
// Add a few extra in case a few more show up
const size_t estimated_pid_count =
(pid_data_size / sizeof(struct kinfo_proc)) + 10;
kinfos.resize(estimated_pid_count);
pid_data_size = kinfos.size() * sizeof(struct kinfo_proc);
if (::sysctl(mib, 3, &kinfos[0], &pid_data_size, NULL, 0) != 0)
return 0;
const size_t actual_pid_count = (pid_data_size / sizeof(struct kinfo_proc));
for (size_t i = 0; i < actual_pid_count; i++) {
const struct kinfo_proc &kinfo = kinfos[i];
/* Make sure the user is acceptable */
if (!all_users && kinfo.ki_ruid != our_uid)
continue;
if (kinfo.ki_pid == our_pid || // Skip this process
kinfo.ki_pid == 0 || // Skip kernel (kernel pid is 0)
kinfo.ki_stat == SZOMB || // Zombies are bad
kinfo.ki_flag & P_TRACED || // Being debugged?
kinfo.ki_flag & P_WEXIT) // Working on exiting
continue;
// Every thread is a process in FreeBSD, but all the threads of a single
// process have the same pid. Do not store the process info in the result
// list if a process with given identifier is already registered there.
bool already_registered = false;
for (uint32_t pi = 0;
!already_registered && (const int)kinfo.ki_numthreads > 1 &&
pi < (const uint32_t)process_infos.GetSize();
pi++)
already_registered =
(process_infos.GetProcessIDAtIndex(pi) == (uint32_t)kinfo.ki_pid);
if (already_registered)
continue;
ProcessInstanceInfo process_info;
process_info.SetProcessID(kinfo.ki_pid);
process_info.SetParentProcessID(kinfo.ki_ppid);
process_info.SetUserID(kinfo.ki_ruid);
process_info.SetGroupID(kinfo.ki_rgid);
process_info.SetEffectiveUserID(kinfo.ki_svuid);
process_info.SetEffectiveGroupID(kinfo.ki_svgid);
// Make sure our info matches before we go fetch the name and cpu type
if (match_info.Matches(process_info) &&
GetFreeBSDProcessArgs(&match_info, process_info)) {
GetFreeBSDProcessCPUType(process_info);
if (match_info.Matches(process_info))
process_infos.Append(process_info);
}
}
return process_infos.GetSize();
}
bool Host::GetProcessInfo(lldb::pid_t pid, ProcessInstanceInfo &process_info) {
process_info.SetProcessID(pid);
if (GetFreeBSDProcessArgs(NULL, process_info)) {
// should use libprocstat instead of going right into sysctl?
GetFreeBSDProcessCPUType(process_info);
GetFreeBSDProcessUserAndGroup(process_info);
return true;
}
process_info.Clear();
return false;
}
Environment Host::GetEnvironment() { return Environment(environ); }
Status Host::ShellExpandArguments(ProcessLaunchInfo &launch_info) {
return Status("unimplemented");
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2016 Zubax, zubax.com
* Distributed under the MIT License, available in the file LICENSE.
* Author: Pavel Kirienko <pavel.kirienko@zubax.com>
*/
/*
* Collection of heap-less containers and functions.
*/
#pragma once
#include <type_traits>
#include <algorithm>
#include <cassert>
#include <cstdarg>
#include <cstring>
#include <cstdlib>
#include <cstdint>
#include <cstdio>
#include <limits>
namespace os
{
namespace heapless
{
/**
* Converts any signed or unsigned integer or boolean to string and returns it by value.
* The argument must be of integral type, otherwise the call will be rejected by SFINAE.
* Usage examples:
* intToString(var)
* intToString<16>(var)
* intToString<2>(var).c_str()
* It is safe to obtain a reference to the returned string and pass it to another function as an argument,
* which enables use cases like this (this example is somewhat made up, but it conveys the idea nicely):
* print("%s", intToString(123).c_str());
* More info on rvalue references:
* https://herbsutter.com/2008/01/01/gotw-88-a-candidate-for-the-most-important-const/
* http://stackoverflow.com/questions/584824/guaranteed-lifetime-of-temporary-in-c
*/
template <
int Radix = 10,
typename T,
typename std::enable_if<std::is_integral<T>::value>::type...
>
inline auto intToString(T number)
{
constexpr char Alphabet[] = "0123456789abcdefghijklmnopqrstuvwxyz";
static_assert(Radix >= 1, "Radix must be positive");
static_assert(Radix <= (sizeof(Alphabet) / sizeof(Alphabet[0])), "Radix is too large");
// Plus 1 to round up, see the standard for details.
constexpr unsigned MaxChars =
((Radix >= 10) ? std::numeric_limits<T>::digits10 : std::numeric_limits<T>::digits) +
1 + (std::is_signed<T>::value ? 1 : 0);
class Container
{
std::uint_fast16_t offset_;
char storage_[MaxChars + 1]; // Plus 1 because of zero termination.
public:
Container(T x) :
offset_(MaxChars) // Field initialization is not working in GCC in this context, not sure why.
{
storage_[offset_] = '\0';
do
{
assert(offset_ > 0);
if (std::is_signed<T>::value) // Should be converted to constexpr if.
{
// We can't just do "x = -x", because it would break on int8_t(-128), int16_t(-32768), etc.
auto residual = std::int_fast8_t(x % Radix);
if (residual < 0)
{
// Should never happen - since C++11, neg % pos --> pos
residual = -residual;
}
storage_[--offset_] = Alphabet[residual];
// Signed integers are really tricky sometimes.
// We must not mix negative with positive to avoid implementation-defined behaviors.
x = (x < 0) ? -(x / -Radix) : (x / Radix);
}
else
{
// Fast branch for unsigned arguments.
storage_[--offset_] = Alphabet[x % Radix];
x /= Radix;
}
}
while (x != 0);
if (std::is_signed<T>::value && (x < 0)) // Should be optimized with constexpr if.
{
assert(offset_ > 0);
storage_[--offset_] = '-';
}
assert(offset_ < MaxChars); // Making sure there was no overflow.
}
const char* c_str() const { return &storage_[offset_]; }
operator const char* () const { return this->c_str(); }
};
return Container(number);
}
/**
* The default capacity is optimal for most embedded use cases.
*/
constexpr unsigned DefaultStringCapacity = 100;
/**
* Heapless string that keeps all data inside a fixed length buffer.
* The capacity of the buffer can be specified via template arguments.
* The interface is similar to that of std::string and other standard containers.
*/
template <unsigned Capacity_ = DefaultStringCapacity>
class String
{
static_assert(Capacity_ > 0, "Capacity must be positive");
template <unsigned C>
friend class String;
public:
static constexpr unsigned Capacity = Capacity_;
private:
unsigned len_ = 0;
char buf_[Capacity + 1] = {};
public:
constexpr String() { }
String(const char* const initializer) { append(initializer); }
template <unsigned C>
String(const String<C>& initializer) { append(initializer); }
/*
* Formatting
*/
template <typename... Args>
auto format(Args... format_args) const
{
String<(DefaultStringCapacity > Capacity) ? DefaultStringCapacity : Capacity> output;
using namespace std;
const int res = snprintf(output.begin(), output.capacity(), this->c_str(), format_args...);
if (res > 0)
{
output.len_ = std::min(output.capacity(), unsigned(res));
}
return output;
}
/*
* std::string API
*/
constexpr unsigned capacity() const { return Capacity; }
constexpr unsigned max_size() const { return Capacity; }
unsigned size() const { return len_; }
unsigned length() const { return len_; }
bool empty() const { return len_ == 0; }
const char* c_str() const { return &buf_[0]; }
void clear() { len_ = 0; }
template <unsigned C>
void append(const String<C>& s)
{
append(s.c_str());
}
void append(const char* p)
{
while ((*p != '\0') && (len_ < Capacity))
{
buf_[len_++] = *p++;
}
buf_[len_] = '\0';
assert(buf_[Capacity] == '\0');
}
void append(char p)
{
if (len_ < Capacity)
{
buf_[len_++] = p;
}
buf_[len_] = '\0';
assert(buf_[Capacity] == '\0');
}
template <typename T>
typename std::enable_if<std::is_integral<T>::value>::type append(const T& value)
{
append(intToString(value).c_str());
}
template <typename T>
typename std::enable_if<std::is_floating_point<T>::value>::type append(const T& value)
{
constexpr int Precision = std::numeric_limits<T>::digits10 + 1;
static_assert(Precision > 1, "Invalid floating point type?");
char buffer[20];
using namespace std;
(void) snprintf(buffer, sizeof(buffer), "%.*g", Precision, double(value));
append(static_cast<const char*>(&buffer[0]));
}
template <typename T>
void concatenate(const T& head)
{
this->append(head);
}
template <typename T, typename... Args>
void concatenate(const T& head, Args... tail)
{
this->append(head);
this->concatenate(tail...);
}
char& front() { return operator[](0); }
const char& front() const { return operator[](0); }
char& back()
{
if (len_ > 0)
{
return buf_[len_ - 1U];
}
else
{
assert(false);
return buf_[0];
}
}
const char& back() const { return const_cast<String*>(this)->back(); }
template <unsigned C>
bool compare(const String<C>& s) const
{
return compare(s.c_str());
}
bool compare(const char* s) const
{
return 0 == std::strncmp(this->c_str(), s, Capacity);
}
/*
* Iterators
*/
const char* begin() const { return &buf_[0]; }
const char* end() const { return &buf_[len_]; }
char* begin() { return &buf_[0]; }
char* end() { return &buf_[len_]; }
/*
* Operators
*/
template <typename T>
String& operator=(const T& s)
{
clear();
append(s);
return *this;
}
template <typename T>
String& operator+=(const T& s)
{
append(s);
return *this;
}
char& operator[](unsigned index)
{
if (index < len_)
{
return buf_[index];
}
else
{
assert(false);
return back();
}
}
const char& operator[](unsigned index) const { return const_cast<String*>(this)->operator[](index); }
template <typename T>
bool operator==(const T& s) const { return compare(s); }
/*
* Helpers
*/
template <typename Left, typename Right>
static auto join(const Left& left, const Right& right)
{
String<(DefaultStringCapacity > Capacity) ? DefaultStringCapacity : Capacity> output(left);
output.append(right);
return output;
}
struct Formatter
{
String<Capacity> format_string;
Formatter(const char* format_string) : format_string(format_string) { }
template <typename... Args>
auto operator()(Args... format_args)
{
return format_string.format(format_args...);
}
};
};
/**
* Operators for String<>.
* @{
*/
template <unsigned LeftCapacity, unsigned RightCapacity>
inline auto operator+(const String<LeftCapacity>& left, const String<RightCapacity>& right)
{
return String<LeftCapacity + RightCapacity>::join(left, right);
}
template <unsigned Capacity>
inline auto operator+(const String<Capacity>& left, const char* right)
{
return String<Capacity>::join(left, right);
}
template <unsigned Capacity>
inline auto operator+(const char* left, const String<Capacity>& right)
{
return String<Capacity>::join(left, right);
}
template <unsigned Capacity>
inline bool operator==(const char* left, const String<Capacity>& right)
{
return right.compare(left);
}
/**
* @}
*/
/**
* Converts a string literal into String<>.
* Usage example:
* auto len = "Hello world!"_heapless.length();
*/
inline auto operator "" _heapless(const char* str, std::size_t)
{
return String<>(str);
}
/**
* Formats a string literal using heapless string.
* Usage example:
* auto str = "The %s answer is %d!"_format("Great", 42);
*/
inline auto operator "" _format(const char* str, std::size_t)
{
return String<>::Formatter(str);
}
/**
* Formats an arbitrary string and returns it as a heapless string instance.
* Usage example:
* conat auto str = format("The %s answer is %d!", "Great", 42);
*/
template<unsigned FormatLength, typename... Args>
inline auto format(const char (&format_string)[FormatLength], Args... format_args)
{
return String<FormatLength>(format_string).format(format_args...);
}
/**
* Like Python's print(), except that it returns the string by value as a heapless instance instead of
* printing it.
* Usage example:
* auto str = concatenate("The Great Answer is", 42, "!\n");
*/
template <unsigned Capacity = DefaultStringCapacity, typename... Args>
inline auto concatenate(Args... arguments)
{
String<Capacity> s;
s.concatenate(arguments...);
return s;
}
/**
* Compatibility with standard streams, nothing special here.
*/
template <typename Stream, unsigned Capacity>
inline Stream& operator<<(Stream& stream, const String<Capacity>& obj)
{
stream << obj.c_str();
return stream;
}
}
}
<commit_msg>Increased default string capacity<commit_after>/*
* Copyright (c) 2016 Zubax, zubax.com
* Distributed under the MIT License, available in the file LICENSE.
* Author: Pavel Kirienko <pavel.kirienko@zubax.com>
*/
/*
* Collection of heap-less containers and functions.
*/
#pragma once
#include <type_traits>
#include <algorithm>
#include <cassert>
#include <cstdarg>
#include <cstring>
#include <cstdlib>
#include <cstdint>
#include <cstdio>
#include <limits>
namespace os
{
namespace heapless
{
/**
* Converts any signed or unsigned integer or boolean to string and returns it by value.
* The argument must be of integral type, otherwise the call will be rejected by SFINAE.
* Usage examples:
* intToString(var)
* intToString<16>(var)
* intToString<2>(var).c_str()
* It is safe to obtain a reference to the returned string and pass it to another function as an argument,
* which enables use cases like this (this example is somewhat made up, but it conveys the idea nicely):
* print("%s", intToString(123).c_str());
* More info on rvalue references:
* https://herbsutter.com/2008/01/01/gotw-88-a-candidate-for-the-most-important-const/
* http://stackoverflow.com/questions/584824/guaranteed-lifetime-of-temporary-in-c
*/
template <
int Radix = 10,
typename T,
typename std::enable_if<std::is_integral<T>::value>::type...
>
inline auto intToString(T number)
{
constexpr char Alphabet[] = "0123456789abcdefghijklmnopqrstuvwxyz";
static_assert(Radix >= 1, "Radix must be positive");
static_assert(Radix <= (sizeof(Alphabet) / sizeof(Alphabet[0])), "Radix is too large");
// Plus 1 to round up, see the standard for details.
constexpr unsigned MaxChars =
((Radix >= 10) ? std::numeric_limits<T>::digits10 : std::numeric_limits<T>::digits) +
1 + (std::is_signed<T>::value ? 1 : 0);
class Container
{
std::uint_fast16_t offset_;
char storage_[MaxChars + 1]; // Plus 1 because of zero termination.
public:
Container(T x) :
offset_(MaxChars) // Field initialization is not working in GCC in this context, not sure why.
{
storage_[offset_] = '\0';
do
{
assert(offset_ > 0);
if (std::is_signed<T>::value) // Should be converted to constexpr if.
{
// We can't just do "x = -x", because it would break on int8_t(-128), int16_t(-32768), etc.
auto residual = std::int_fast8_t(x % Radix);
if (residual < 0)
{
// Should never happen - since C++11, neg % pos --> pos
residual = -residual;
}
storage_[--offset_] = Alphabet[residual];
// Signed integers are really tricky sometimes.
// We must not mix negative with positive to avoid implementation-defined behaviors.
x = (x < 0) ? -(x / -Radix) : (x / Radix);
}
else
{
// Fast branch for unsigned arguments.
storage_[--offset_] = Alphabet[x % Radix];
x /= Radix;
}
}
while (x != 0);
if (std::is_signed<T>::value && (x < 0)) // Should be optimized with constexpr if.
{
assert(offset_ > 0);
storage_[--offset_] = '-';
}
assert(offset_ < MaxChars); // Making sure there was no overflow.
}
const char* c_str() const { return &storage_[offset_]; }
operator const char* () const { return this->c_str(); }
};
return Container(number);
}
/**
* The default capacity is optimal for most embedded use cases.
*/
constexpr unsigned DefaultStringCapacity = 200;
/**
* Heapless string that keeps all data inside a fixed length buffer.
* The capacity of the buffer can be specified via template arguments.
* The interface is similar to that of std::string and other standard containers.
*/
template <unsigned Capacity_ = DefaultStringCapacity>
class String
{
static_assert(Capacity_ > 0, "Capacity must be positive");
template <unsigned C>
friend class String;
public:
static constexpr unsigned Capacity = Capacity_;
private:
unsigned len_ = 0;
char buf_[Capacity + 1] = {};
public:
constexpr String() { }
String(const char* const initializer) { append(initializer); }
template <unsigned C>
String(const String<C>& initializer) { append(initializer); }
/*
* Formatting
*/
template <typename... Args>
auto format(Args... format_args) const
{
String<(DefaultStringCapacity > Capacity) ? DefaultStringCapacity : Capacity> output;
using namespace std;
const int res = snprintf(output.begin(), output.capacity(), this->c_str(), format_args...);
if (res > 0)
{
output.len_ = std::min(output.capacity(), unsigned(res));
}
return output;
}
/*
* std::string API
*/
constexpr unsigned capacity() const { return Capacity; }
constexpr unsigned max_size() const { return Capacity; }
unsigned size() const { return len_; }
unsigned length() const { return len_; }
bool empty() const { return len_ == 0; }
const char* c_str() const { return &buf_[0]; }
void clear() { len_ = 0; }
template <unsigned C>
void append(const String<C>& s)
{
append(s.c_str());
}
void append(const char* p)
{
while ((*p != '\0') && (len_ < Capacity))
{
buf_[len_++] = *p++;
}
buf_[len_] = '\0';
assert(buf_[Capacity] == '\0');
}
void append(char p)
{
if (len_ < Capacity)
{
buf_[len_++] = p;
}
buf_[len_] = '\0';
assert(buf_[Capacity] == '\0');
}
template <typename T>
typename std::enable_if<std::is_integral<T>::value>::type append(const T& value)
{
append(intToString(value).c_str());
}
template <typename T>
typename std::enable_if<std::is_floating_point<T>::value>::type append(const T& value)
{
constexpr int Precision = std::numeric_limits<T>::digits10 + 1;
static_assert(Precision > 1, "Invalid floating point type?");
char buffer[20];
using namespace std;
(void) snprintf(buffer, sizeof(buffer), "%.*g", Precision, double(value));
append(static_cast<const char*>(&buffer[0]));
}
template <typename T>
void concatenate(const T& head)
{
this->append(head);
}
template <typename T, typename... Args>
void concatenate(const T& head, Args... tail)
{
this->append(head);
this->concatenate(tail...);
}
char& front() { return operator[](0); }
const char& front() const { return operator[](0); }
char& back()
{
if (len_ > 0)
{
return buf_[len_ - 1U];
}
else
{
assert(false);
return buf_[0];
}
}
const char& back() const { return const_cast<String*>(this)->back(); }
template <unsigned C>
bool compare(const String<C>& s) const
{
return compare(s.c_str());
}
bool compare(const char* s) const
{
return 0 == std::strncmp(this->c_str(), s, Capacity);
}
/*
* Iterators
*/
const char* begin() const { return &buf_[0]; }
const char* end() const { return &buf_[len_]; }
char* begin() { return &buf_[0]; }
char* end() { return &buf_[len_]; }
/*
* Operators
*/
template <typename T>
String& operator=(const T& s)
{
clear();
append(s);
return *this;
}
template <typename T>
String& operator+=(const T& s)
{
append(s);
return *this;
}
char& operator[](unsigned index)
{
if (index < len_)
{
return buf_[index];
}
else
{
assert(false);
return back();
}
}
const char& operator[](unsigned index) const { return const_cast<String*>(this)->operator[](index); }
template <typename T>
bool operator==(const T& s) const { return compare(s); }
/*
* Helpers
*/
template <typename Left, typename Right>
static auto join(const Left& left, const Right& right)
{
String<(DefaultStringCapacity > Capacity) ? DefaultStringCapacity : Capacity> output(left);
output.append(right);
return output;
}
struct Formatter
{
String<Capacity> format_string;
Formatter(const char* format_string) : format_string(format_string) { }
template <typename... Args>
auto operator()(Args... format_args)
{
return format_string.format(format_args...);
}
};
};
/**
* Operators for String<>.
* @{
*/
template <unsigned LeftCapacity, unsigned RightCapacity>
inline auto operator+(const String<LeftCapacity>& left, const String<RightCapacity>& right)
{
return String<LeftCapacity + RightCapacity>::join(left, right);
}
template <unsigned Capacity>
inline auto operator+(const String<Capacity>& left, const char* right)
{
return String<Capacity>::join(left, right);
}
template <unsigned Capacity>
inline auto operator+(const char* left, const String<Capacity>& right)
{
return String<Capacity>::join(left, right);
}
template <unsigned Capacity>
inline bool operator==(const char* left, const String<Capacity>& right)
{
return right.compare(left);
}
/**
* @}
*/
/**
* Converts a string literal into String<>.
* Usage example:
* auto len = "Hello world!"_heapless.length();
*/
inline auto operator "" _heapless(const char* str, std::size_t)
{
return String<>(str);
}
/**
* Formats a string literal using heapless string.
* Usage example:
* auto str = "The %s answer is %d!"_format("Great", 42);
*/
inline auto operator "" _format(const char* str, std::size_t)
{
return String<>::Formatter(str);
}
/**
* Formats an arbitrary string and returns it as a heapless string instance.
* Usage example:
* conat auto str = format("The %s answer is %d!", "Great", 42);
*/
template<unsigned FormatLength, typename... Args>
inline auto format(const char (&format_string)[FormatLength], Args... format_args)
{
return String<FormatLength>(format_string).format(format_args...);
}
/**
* Like Python's print(), except that it returns the string by value as a heapless instance instead of
* printing it.
* Usage example:
* auto str = concatenate("The Great Answer is", 42, "!\n");
*/
template <unsigned Capacity = DefaultStringCapacity, typename... Args>
inline auto concatenate(Args... arguments)
{
String<Capacity> s;
s.concatenate(arguments...);
return s;
}
/**
* Compatibility with standard streams, nothing special here.
*/
template <typename Stream, unsigned Capacity>
inline Stream& operator<<(Stream& stream, const String<Capacity>& obj)
{
stream << obj.c_str();
return stream;
}
}
}
<|endoftext|>
|
<commit_before>/*
* teleop_pr2
* Copyright (c) 2009, 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 <ORGANIZATION> 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: Blaise Gassend
#include <unistd.h>
#include <math.h>
#include <linux/joystick.h>
#include <fcntl.h>
#include <ros/ros.h>
#include <diagnostic_updater/diagnostic_updater.h>
#include <sensor_msgs/Joy.h>
///\brief Opens, reads from and publishes joystick events
class Joystick
{
private:
ros::NodeHandle nh_;
bool open_;
std::string joy_dev_;
double deadzone_;
double autorepeat_rate_; // in Hz. 0 for no repeat.
double coalesce_interval_; // Defaults to 100 Hz rate limit.
int event_count_;
int pub_count_;
ros::Publisher pub_;
double lastDiagTime_;
diagnostic_updater::Updater diagnostic_;
///\brief Publishes diagnostics and status
void diagnostics(diagnostic_updater::DiagnosticStatusWrapper& stat)
{
double now = ros::Time::now().toSec();
double interval = now - lastDiagTime_;
if (open_)
stat.summary(0, "OK");
else
stat.summary(2, "Joystick not open.");
stat.add("topic", pub_.getTopic());
stat.add("device", joy_dev_);
stat.add("dead zone", deadzone_);
stat.add("autorepeat rate (Hz)", autorepeat_rate_);
stat.add("coalesce interval (s)", coalesce_interval_);
stat.add("recent joystick event rate (Hz)", event_count_ / interval);
stat.add("recent publication rate (Hz)", pub_count_ / interval);
stat.add("subscribers", pub_.getNumSubscribers());
event_count_ = 0;
pub_count_ = 0;
lastDiagTime_ = now;
}
public:
Joystick() : nh_(), diagnostic_()
{}
///\brief Opens joystick port, reads from port and publishes while node is active
int main(int argc, char **argv)
{
diagnostic_.add("Joystick Driver Status", this, &Joystick::diagnostics);
diagnostic_.setHardwareID("none");
// Parameters
ros::NodeHandle nh_param("~");
std::string pub_topic;
nh_param.param<std::string>("topic", pub_topic, "joy");
pub_ = nh_.advertise<sensor_msgs::Joy>(pub_topic, 1);
nh_param.param<std::string>("dev", joy_dev_, "/dev/input/js0");
nh_param.param<double>("deadzone", deadzone_, 0.05);
nh_param.param<double>("autorepeat_rate", autorepeat_rate_, 0);
nh_param.param<double>("coalesce_interval", coalesce_interval_, 0.001);
// Checks on parameters
if (autorepeat_rate_ > 1 / coalesce_interval_)
ROS_WARN("joy_node: autorepeat_rate (%f Hz) > 1/coalesce_interval (%f Hz) does not make sense. Timing behavior is not well defined.", autorepeat_rate_, 1/coalesce_interval_);
if (deadzone_ >= 1)
{
ROS_WARN("joy_node: deadzone greater than 1 was requested. The semantics of deadzone have changed. It is now related to the range [-1:1] instead of [-32767:32767]. For now I am dividing your deadzone by 32767, but this behavior is deprecated so you need to update your launch file.");
deadzone_ /= 32767;
}
if (deadzone_ > 0.9)
{
ROS_WARN("joy_node: deadzone (%f) greater than 0.9, setting it to 0.9", deadzone_);
deadzone_ = 0.9;
}
if (deadzone_ < 0)
{
ROS_WARN("joy_node: deadzone_ (%f) less than 0, setting to 0.", deadzone_);
deadzone_ = 0;
}
if (autorepeat_rate_ < 0)
{
ROS_WARN("joy_node: autorepeat_rate (%f) less than 0, setting to 0.", autorepeat_rate_);
autorepeat_rate_ = 0;
}
if (coalesce_interval_ < 0)
{
ROS_WARN("joy_node: coalesce_interval (%f) less than 0, setting to 0.", coalesce_interval_);
coalesce_interval_ = 0;
}
// Parameter conversions
double autorepeat_interval = 1 / autorepeat_rate_;
double scale = -1. / (1. - deadzone_) / 32767.;
double unscaled_deadzone = 32767. * deadzone_;
js_event event;
struct timeval tv;
fd_set set;
int joy_fd;
event_count_ = 0;
pub_count_ = 0;
lastDiagTime_ = ros::Time::now().toSec();
// Big while loop opens, publishes
while (nh_.ok())
{
open_ = false;
diagnostic_.force_update();
bool first_fault = true;
while (true)
{
ros::spinOnce();
if (!nh_.ok())
goto cleanup;
joy_fd = open(joy_dev_.c_str(), O_RDONLY);
if (joy_fd != -1)
{
// There seems to be a bug in the driver or something where the
// initial events that are to define the initial state of the
// joystick are not the values of the joystick when it was opened
// but rather the values of the joystick when it was last closed.
// Opening then closing and opening again is a hack to get more
// accurate initial state data.
close(joy_fd);
joy_fd = open(joy_dev_.c_str(), O_RDONLY);
}
if (joy_fd != -1)
break;
if (first_fault)
{
ROS_ERROR("Couldn't open joystick %s. Will retry every second.", joy_dev_.c_str());
first_fault = false;
}
sleep(1.0);
diagnostic_.update();
}
ROS_INFO("Opened joystick: %s. deadzone_: %f.", joy_dev_.c_str(), deadzone_);
open_ = true;
diagnostic_.force_update();
bool tv_set = false;
bool publication_pending = false;
tv.tv_sec = 1;
tv.tv_usec = 0;
sensor_msgs::Joy joy_msg; // Here because we want to reset it on device close.
while (nh_.ok())
{
ros::spinOnce();
bool publish_now = false;
bool publish_soon = false;
FD_ZERO(&set);
FD_SET(joy_fd, &set);
//ROS_INFO("Select...");
int select_out = select(joy_fd+1, &set, NULL, NULL, &tv);
//ROS_INFO("Tick...");
if (select_out == -1)
{
tv.tv_sec = 0;
tv.tv_usec = 0;
//ROS_INFO("Select returned negative. %i", ros::isShuttingDown());
continue;
// break; // Joystick is probably closed. Not sure if this case is useful.
}
if (FD_ISSET(joy_fd, &set))
{
if (read(joy_fd, &event, sizeof(js_event)) == -1 && errno != EAGAIN)
break; // Joystick is probably closed. Definitely occurs.
//ROS_INFO("Read data...");
joy_msg.header.stamp = ros::Time().now();
event_count_++;
switch(event.type)
{
case JS_EVENT_BUTTON:
case JS_EVENT_BUTTON | JS_EVENT_INIT:
if(event.number >= joy_msg.buttons.size())
{
int old_size = joy_msg.buttons.size();
joy_msg.buttons.resize(event.number+1);
for(unsigned int i=old_size;i<joy_msg.buttons.size();i++)
joy_msg.buttons[i] = 0.0;
}
joy_msg.buttons[event.number] = (event.value ? 1 : 0);
// For initial events, wait a bit before sending to try to catch
// all the initial events.
if (!(event.type & JS_EVENT_INIT))
publish_now = true;
else
publish_soon = true;
break;
case JS_EVENT_AXIS:
case JS_EVENT_AXIS | JS_EVENT_INIT:
if(event.number >= joy_msg.axes.size())
{
int old_size = joy_msg.axes.size();
joy_msg.axes.resize(event.number+1);
for(unsigned int i=old_size;i<joy_msg.axes.size();i++)
joy_msg.axes[i] = 0.0;
}
if (!(event.type & JS_EVENT_INIT)) // Init event.value is wrong.
{
double val = event.value;
// Allows deadzone to be "smooth"
if (val > unscaled_deadzone)
val -= unscaled_deadzone;
else if (val < -unscaled_deadzone)
val += unscaled_deadzone;
else
val = 0;
joy_msg.axes[event.number] = val * scale;
}
// Will wait a bit before sending to try to combine events.
publish_soon = true;
break;
default:
ROS_WARN("joy_node: Unknown event type. Please file a ticket. time=%u, value=%d, type=%Xh, number=%d", event.time, event.value, event.type, event.number);
break;
}
}
else if (tv_set) // Assume that the timer has expired.
publish_now = true;
if (publish_now)
{
// Assume that all the JS_EVENT_INIT messages have arrived already.
// This should be the case as the kernel sends them along as soon as
// the device opens.
//ROS_INFO("Publish...");
pub_.publish(joy_msg);
publish_now = false;
tv_set = false;
publication_pending = false;
publish_soon = false;
pub_count_++;
}
// If an axis event occurred, start a timer to combine with other
// events.
if (!publication_pending && publish_soon)
{
tv.tv_sec = trunc(coalesce_interval_);
tv.tv_usec = (coalesce_interval_ - tv.tv_sec) * 1e6;
publication_pending = true;
tv_set = true;
//ROS_INFO("Pub pending...");
}
// If nothing is going on, start a timer to do autorepeat.
if (!tv_set && autorepeat_rate_ > 0)
{
tv.tv_sec = trunc(autorepeat_interval);
tv.tv_usec = (autorepeat_interval - tv.tv_sec) * 1e6;
tv_set = true;
//ROS_INFO("Autorepeat pending... %i %i", tv.tv_sec, tv.tv_usec);
}
if (!tv_set)
{
tv.tv_sec = 1;
tv.tv_usec = 0;
}
diagnostic_.update();
} // End of joystick open loop.
close(joy_fd);
ros::spinOnce();
if (nh_.ok())
ROS_ERROR("Connection to joystick device lost unexpectedly. Will reopen.");
}
cleanup:
ROS_INFO("joy_node shut down.");
return 0;
}
};
int main(int argc, char **argv)
{
ros::init(argc, argv, "joy_node");
Joystick j;
return j.main(argc, argv);
}
<commit_msg>Joystick node publishes Twist message directly<commit_after>/*
* teleop_pr2
* Copyright (c) 2009, 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 <ORGANIZATION> 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: Blaise Gassend
#include <unistd.h>
#include <math.h>
#include <linux/joystick.h>
#include <fcntl.h>
#include <ros/ros.h>
#include <sensor_msgs/Joy.h>
#include <geometry_msgs/Twist.h>
///\brief Opens, reads from and publishes joystick events
class Joystick
{
private:
ros::NodeHandle nh_;
bool open_;
std::string joy_dev_;
double deadzone_;
double autorepeat_rate_; // in Hz. 0 for no repeat.
double coalesce_interval_; // Defaults to 100 Hz rate limit.
int event_count_;
int pub_count_;
double lastDiagTime_;
double a_scale_;
double l_scale_;
ros::Publisher velocity_publisher_;
ros::Timer velocity_publish_timer_;
sensor_msgs::Joy current_joy_message_;
void publish_velocity(ros::TimerEvent event) {
geometry_msgs::Twist vel;
vel.angular.z = a_scale_ * current_joy_message_.axes[3];
vel.linear.x = l_scale_ * current_joy_message_.axes[4];
velocity_publisher_.publish(vel);
}
public:
Joystick() : nh_() {}
///\brief Opens joystick port, reads from port and publishes while node is active
int main(int argc, char **argv)
{
// diagnostic_.add("Joystick Driver Status", this, &Joystick::diagnostics);
// diagnostic_.setHardwareID("none");
// Parameters
ros::NodeHandle nh_param("~");
std::string pub_topic;
nh_param.param<std::string>("topic", pub_topic, "joy");
// pub_ = nh_.advertise<sensor_msgs::Joy>(pub_topic, 1);
velocity_publisher_ = nh_.advertise<geometry_msgs::Twist>("/joy_cmd_vel", 100, false);
velocity_publish_timer_ = nh_.createTimer(ros::Duration(0.1), boost::bind(&Joystick::publish_velocity, this, _1));
nh_param.param<std::string>("dev", joy_dev_, "/dev/input/js0");
nh_param.param<double>("deadzone", deadzone_, 0.05);
nh_param.param<double>("autorepeat_rate", autorepeat_rate_, 0);
nh_param.param<double>("coalesce_interval", coalesce_interval_, 0.001);
nh_param.param("scale_angular", a_scale_, 0.9);
nh_param.param("scale_linear" , l_scale_, 2.0);
// Checks on parameters
if (autorepeat_rate_ > 1 / coalesce_interval_)
ROS_WARN("joy_node: autorepeat_rate (%f Hz) > 1/coalesce_interval (%f Hz) does not make sense. Timing behavior is not well defined.", autorepeat_rate_, 1/coalesce_interval_);
if (deadzone_ >= 1)
{
ROS_WARN("joy_node: deadzone greater than 1 was requested. The semantics of deadzone have changed. It is now related to the range [-1:1] instead of [-32767:32767]. For now I am dividing your deadzone by 32767, but this behavior is deprecated so you need to update your launch file.");
deadzone_ /= 32767;
}
if (deadzone_ > 0.9)
{
ROS_WARN("joy_node: deadzone (%f) greater than 0.9, setting it to 0.9", deadzone_);
deadzone_ = 0.9;
}
if (deadzone_ < 0)
{
ROS_WARN("joy_node: deadzone_ (%f) less than 0, setting to 0.", deadzone_);
deadzone_ = 0;
}
if (autorepeat_rate_ < 0)
{
ROS_WARN("joy_node: autorepeat_rate (%f) less than 0, setting to 0.", autorepeat_rate_);
autorepeat_rate_ = 0;
}
if (coalesce_interval_ < 0)
{
ROS_WARN("joy_node: coalesce_interval (%f) less than 0, setting to 0.", coalesce_interval_);
coalesce_interval_ = 0;
}
// Parameter conversions
double autorepeat_interval = 1 / autorepeat_rate_;
double scale = -1. / (1. - deadzone_) / 32767.;
double unscaled_deadzone = 32767. * deadzone_;
js_event event;
struct timeval tv;
fd_set set;
int joy_fd;
event_count_ = 0;
pub_count_ = 0;
lastDiagTime_ = ros::Time::now().toSec();
// Big while loop opens, publishes
while (nh_.ok())
{
open_ = false;
// diagnostic_.force_update();
bool first_fault = true;
while (true)
{
ros::spinOnce();
if (!nh_.ok())
goto cleanup;
joy_fd = open(joy_dev_.c_str(), O_RDONLY);
if (joy_fd != -1)
{
// There seems to be a bug in the driver or something where the
// initial events that are to define the initial state of the
// joystick are not the values of the joystick when it was opened
// but rather the values of the joystick when it was last closed.
// Opening then closing and opening again is a hack to get more
// accurate initial state data.
close(joy_fd);
joy_fd = open(joy_dev_.c_str(), O_RDONLY);
}
if (joy_fd != -1)
break;
if (first_fault)
{
ROS_ERROR("Couldn't open joystick %s. Will retry every second.", joy_dev_.c_str());
first_fault = false;
}
sleep(1.0);
// diagnostic_.update();
}
ROS_INFO("Opened joystick: %s. deadzone_: %f.", joy_dev_.c_str(), deadzone_);
open_ = true;
// diagnostic_.force_update();
bool tv_set = false;
bool publication_pending = false;
tv.tv_sec = 1;
tv.tv_usec = 0;
sensor_msgs::Joy joy_msg; // Here because we want to reset it on device close.
while (nh_.ok())
{
ros::spinOnce();
bool publish_now = false;
bool publish_soon = false;
FD_ZERO(&set);
FD_SET(joy_fd, &set);
//ROS_INFO("Select...");
int select_out = select(joy_fd+1, &set, NULL, NULL, &tv);
//ROS_INFO("Tick...");
if (select_out == -1)
{
tv.tv_sec = 0;
tv.tv_usec = 0;
//ROS_INFO("Select returned negative. %i", ros::isShuttingDown());
continue;
// break; // Joystick is probably closed. Not sure if this case is useful.
}
if (FD_ISSET(joy_fd, &set))
{
if (read(joy_fd, &event, sizeof(js_event)) == -1 && errno != EAGAIN)
break; // Joystick is probably closed. Definitely occurs.
//ROS_INFO("Read data...");
joy_msg.header.stamp = ros::Time().now();
event_count_++;
switch(event.type)
{
case JS_EVENT_BUTTON:
case JS_EVENT_BUTTON | JS_EVENT_INIT:
if(event.number >= joy_msg.buttons.size())
{
int old_size = joy_msg.buttons.size();
joy_msg.buttons.resize(event.number+1);
for(unsigned int i=old_size;i<joy_msg.buttons.size();i++)
joy_msg.buttons[i] = 0.0;
}
joy_msg.buttons[event.number] = (event.value ? 1 : 0);
// For initial events, wait a bit before sending to try to catch
// all the initial events.
if (!(event.type & JS_EVENT_INIT))
publish_now = true;
else
publish_soon = true;
break;
case JS_EVENT_AXIS:
case JS_EVENT_AXIS | JS_EVENT_INIT:
if(event.number >= joy_msg.axes.size())
{
int old_size = joy_msg.axes.size();
joy_msg.axes.resize(event.number+1);
for(unsigned int i=old_size;i<joy_msg.axes.size();i++)
joy_msg.axes[i] = 0.0;
}
if (!(event.type & JS_EVENT_INIT)) // Init event.value is wrong.
{
double val = event.value;
// Allows deadzone to be "smooth"
if (val > unscaled_deadzone)
val -= unscaled_deadzone;
else if (val < -unscaled_deadzone)
val += unscaled_deadzone;
else
val = 0;
joy_msg.axes[event.number] = val * scale;
}
// Will wait a bit before sending to try to combine events.
publish_soon = true;
break;
default:
ROS_WARN("joy_node: Unknown event type. Please file a ticket. time=%u, value=%d, type=%Xh, number=%d", event.time, event.value, event.type, event.number);
break;
}
}
else if (tv_set) // Assume that the timer has expired.
publish_now = true;
if (publish_now)
{
// Assume that all the JS_EVENT_INIT messages have arrived already.
// This should be the case as the kernel sends them along as soon as
// the device opens.
//ROS_INFO("Publish...");
// pub_.publish(joy_msg);
current_joy_message_ = joy_msg;
publish_now = false;
tv_set = false;
publication_pending = false;
publish_soon = false;
pub_count_++;
}
// If an axis event occurred, start a timer to combine with other
// events.
if (!publication_pending && publish_soon)
{
tv.tv_sec = trunc(coalesce_interval_);
tv.tv_usec = (coalesce_interval_ - tv.tv_sec) * 1e6;
publication_pending = true;
tv_set = true;
//ROS_INFO("Pub pending...");
}
// If nothing is going on, start a timer to do autorepeat.
if (!tv_set && autorepeat_rate_ > 0)
{
tv.tv_sec = trunc(autorepeat_interval);
tv.tv_usec = (autorepeat_interval - tv.tv_sec) * 1e6;
tv_set = true;
//ROS_INFO("Autorepeat pending... %i %i", tv.tv_sec, tv.tv_usec);
}
if (!tv_set)
{
tv.tv_sec = 1;
tv.tv_usec = 0;
}
// diagnostic_.update();
} // End of joystick open loop.
close(joy_fd);
ros::spinOnce();
if (nh_.ok())
ROS_ERROR("Connection to joystick device lost unexpectedly. Will reopen.");
}
cleanup:
ROS_INFO("joy_node shut down.");
return 0;
}
};
int main(int argc, char **argv)
{
ros::init(argc, argv, "joy_node");
Joystick j;
return j.main(argc, argv);
}
<|endoftext|>
|
<commit_before>/***************************************************************************
**
** Copyright (C) 2010, 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** 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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include "ut_mtapandholdrecognizer.h"
#include "mtapandholdrecognizer.h"
#include "mtapandholdrecognizer_p.h"
#include "mtapandholdgesture_p.h"
#include "mapplication.h"
#include <QGraphicsView>
#include <QMouseEvent>
#include <QtTest/QtTest>
int startTimerInterval;
int QObject::startTimer(int interval)
{
startTimerInterval = interval;
return 1;
}
Qt::GestureState currentGestureState = Qt::NoGesture;
Qt::GestureState QGesture::state() const
{
return currentGestureState;
}
//Mocking MThemePrivate, because the style object is private to library
//and we need to compile some functionality into the unittest.
#include "mtheme_p.h"
void MThemePrivate::unregisterStyleContainer(MStyleContainer*)
{
}
void MThemePrivate::registerStyleContainer(MStyleContainer *)
{
}
#include "mtheme.h"
//Filling the values of the style object.
static const int MTapAndHoldSetTimeout = 200; /* miliseconds */
static const int MTapAndHoldStyleTimeout = 500; /* miliseconds */
static const qreal MTapAndHoldMovementThreshold = 20; /* pixels */
MTapAndHoldRecognizerStyle recognizerStyle;
const MStyle *MTheme::style(const char *,
const QString &) {
recognizerStyle.setTimeout(MTapAndHoldStyleTimeout);
recognizerStyle.setMovementThreshold(MTapAndHoldMovementThreshold);
return &recognizerStyle;
}
void MTheme::releaseStyle(const MStyle *)
{
}
MApplication *app;
QGraphicsView *view;
void Ut_MTapAndHoldRecognizer::initTestCase()
{
static int argc = 1;
static char *app_name[1] = { (char *) "./ut_mtapandholdrecognizer" };
app = new MApplication(argc, app_name);
view = new QGraphicsView();
view->show();
}
void Ut_MTapAndHoldRecognizer::cleanupTestCase()
{
delete app;
}
void Ut_MTapAndHoldRecognizer::init()
{
startTimerInterval = -1;
recognizer = new MTapAndHoldRecognizer();
}
void Ut_MTapAndHoldRecognizer::cleanup()
{
delete recognizer;
}
void Ut_MTapAndHoldRecognizer::testCreateGesture()
{
tapAndHoldGesture = static_cast<MTapAndHoldGesture*>(recognizer->create(view));
}
void Ut_MTapAndHoldRecognizer::testRecognize()
{
QMouseEvent *pressEvent = new QMouseEvent(QEvent::MouseButtonPress, QPoint(0,0), QPoint(0,0), Qt::LeftButton, Qt::LeftButton, 0);
QGestureRecognizer::Result currentState;
currentState = recognizer->recognize(tapAndHoldGesture, 0, pressEvent);
QCOMPARE( currentState, QGestureRecognizer::TriggerGesture);
QTimerEvent fakeTimerEvent(tapAndHoldGesture->timerId);
currentState = recognizer->recognize(tapAndHoldGesture, tapAndHoldGesture, &fakeTimerEvent);
QCOMPARE( currentState, QGestureRecognizer::FinishGesture | QGestureRecognizer::ConsumeEventHint );
delete pressEvent;
}
void Ut_MTapAndHoldRecognizer::testFastTap()
{
QMouseEvent *pressEvent = new QMouseEvent(QEvent::MouseButtonPress, QPoint(0,0), Qt::LeftButton, Qt::LeftButton, 0);
QMouseEvent *releaseEvent = new QMouseEvent(QEvent::MouseButtonRelease, QPoint(0,0), Qt::LeftButton, Qt::LeftButton, 0);
QGestureRecognizer::Result currentState;
currentState = recognizer->recognize(tapAndHoldGesture, 0, pressEvent);
QCOMPARE( currentState, QGestureRecognizer::TriggerGesture);
//Setting timerId as would happen in real life scenario
tapAndHoldGesture->timerId = 1;
currentState = recognizer->recognize(tapAndHoldGesture, 0, releaseEvent);
QCOMPARE( currentState, QGestureRecognizer::CancelGesture);
delete pressEvent;
delete releaseEvent;
}
void Ut_MTapAndHoldRecognizer::testMovePointerInsideThreshold()
{
QMouseEvent *pressEvent = new QMouseEvent(QEvent::MouseButtonPress, QPoint(0,0), Qt::LeftButton, Qt::LeftButton, 0);
QMouseEvent *moveEvent = new QMouseEvent(QEvent::MouseMove, QPoint(3,0), Qt::LeftButton, Qt::LeftButton, 0);
QGestureRecognizer::Result currentState;
currentState = recognizer->recognize(tapAndHoldGesture, 0, pressEvent);
QCOMPARE( currentState, QGestureRecognizer::TriggerGesture);
currentGestureState = Qt::GestureStarted;
currentState = recognizer->recognize(tapAndHoldGesture, 0, moveEvent);
QCOMPARE( currentState, QGestureRecognizer::TriggerGesture);
QTimerEvent fakeTimerEvent(tapAndHoldGesture->timerId);
currentState = recognizer->recognize(tapAndHoldGesture, tapAndHoldGesture, &fakeTimerEvent);
QCOMPARE( currentState, QGestureRecognizer::FinishGesture | QGestureRecognizer::ConsumeEventHint );
delete pressEvent;
delete moveEvent;
}
void Ut_MTapAndHoldRecognizer::testMovePointerBeyondThreshold()
{
QMouseEvent *pressEvent = new QMouseEvent(QEvent::MouseButtonPress, QPoint(0,0), Qt::LeftButton, Qt::LeftButton, 0);
QMouseEvent *moveEvent = new QMouseEvent(QEvent::MouseMove, QPoint(50,0), Qt::LeftButton, Qt::LeftButton, 0);
QGestureRecognizer::Result currentState;
currentState = recognizer->recognize(tapAndHoldGesture, 0, pressEvent);
QCOMPARE( currentState, QGestureRecognizer::TriggerGesture);
currentGestureState = Qt::GestureStarted;
currentState = recognizer->recognize(tapAndHoldGesture, 0, moveEvent);
QCOMPARE( currentState, QGestureRecognizer::CancelGesture);
delete pressEvent;
delete moveEvent;
}
void Ut_MTapAndHoldRecognizer::testUsingStyleTimeout()
{
QMouseEvent pressEvent(QEvent::MouseButtonPress, QPoint(0,0), QPoint(0,0), Qt::LeftButton, Qt::LeftButton, 0);
QGestureRecognizer::Result currentState = recognizer->recognize(tapAndHoldGesture, 0, &pressEvent);
// Verify that timeout from style is used when no timeout is set
QCOMPARE(startTimerInterval, MTapAndHoldStyleTimeout);
}
void Ut_MTapAndHoldRecognizer::testSetTimeout()
{
QTapAndHoldGesture::setTimeout(MTapAndHoldSetTimeout);
QMouseEvent pressEvent(QEvent::MouseButtonPress, QPoint(0,0), QPoint(0,0), Qt::LeftButton, Qt::LeftButton, 0);
QGestureRecognizer::Result currentState = recognizer->recognize(tapAndHoldGesture, 0, &pressEvent);
// Verify that timeout that was set is used
QCOMPARE(startTimerInterval, MTapAndHoldSetTimeout);
}
void Ut_MTapAndHoldRecognizer::testResetTimeout()
{
QTapAndHoldGesture::setTimeout(MTapAndHoldSetTimeout);
// Reset timeout
QTapAndHoldGesture::setTimeout(-1);
QMouseEvent pressEvent(QEvent::MouseButtonPress, QPoint(0,0), QPoint(0,0), Qt::LeftButton, Qt::LeftButton, 0);
QGestureRecognizer::Result currentState = recognizer->recognize(tapAndHoldGesture, 0, &pressEvent);
// Verify that as timeout was resetted then timeout from style is used
QCOMPARE(startTimerInterval, MTapAndHoldStyleTimeout);
}
QTEST_APPLESS_MAIN(Ut_MTapAndHoldRecognizer)
<commit_msg>Changes: More sensitive build in OBS forces unused variables check RevBy:TrustMe Details:<commit_after>/***************************************************************************
**
** Copyright (C) 2010, 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** 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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include "ut_mtapandholdrecognizer.h"
#include "mtapandholdrecognizer.h"
#include "mtapandholdrecognizer_p.h"
#include "mtapandholdgesture_p.h"
#include "mapplication.h"
#include <QGraphicsView>
#include <QMouseEvent>
#include <QtTest/QtTest>
int startTimerInterval;
int QObject::startTimer(int interval)
{
startTimerInterval = interval;
return 1;
}
Qt::GestureState currentGestureState = Qt::NoGesture;
Qt::GestureState QGesture::state() const
{
return currentGestureState;
}
//Mocking MThemePrivate, because the style object is private to library
//and we need to compile some functionality into the unittest.
#include "mtheme_p.h"
void MThemePrivate::unregisterStyleContainer(MStyleContainer*)
{
}
void MThemePrivate::registerStyleContainer(MStyleContainer *)
{
}
#include "mtheme.h"
//Filling the values of the style object.
static const int MTapAndHoldSetTimeout = 200; /* miliseconds */
static const int MTapAndHoldStyleTimeout = 500; /* miliseconds */
static const qreal MTapAndHoldMovementThreshold = 20; /* pixels */
MTapAndHoldRecognizerStyle recognizerStyle;
const MStyle *MTheme::style(const char *,
const QString &) {
recognizerStyle.setTimeout(MTapAndHoldStyleTimeout);
recognizerStyle.setMovementThreshold(MTapAndHoldMovementThreshold);
return &recognizerStyle;
}
void MTheme::releaseStyle(const MStyle *)
{
}
MApplication *app;
QGraphicsView *view;
void Ut_MTapAndHoldRecognizer::initTestCase()
{
static int argc = 1;
static char *app_name[1] = { (char *) "./ut_mtapandholdrecognizer" };
app = new MApplication(argc, app_name);
view = new QGraphicsView();
view->show();
}
void Ut_MTapAndHoldRecognizer::cleanupTestCase()
{
delete app;
}
void Ut_MTapAndHoldRecognizer::init()
{
startTimerInterval = -1;
recognizer = new MTapAndHoldRecognizer();
}
void Ut_MTapAndHoldRecognizer::cleanup()
{
delete recognizer;
}
void Ut_MTapAndHoldRecognizer::testCreateGesture()
{
tapAndHoldGesture = static_cast<MTapAndHoldGesture*>(recognizer->create(view));
}
void Ut_MTapAndHoldRecognizer::testRecognize()
{
QMouseEvent *pressEvent = new QMouseEvent(QEvent::MouseButtonPress, QPoint(0,0), QPoint(0,0), Qt::LeftButton, Qt::LeftButton, 0);
QGestureRecognizer::Result currentState;
currentState = recognizer->recognize(tapAndHoldGesture, 0, pressEvent);
QCOMPARE( currentState, QGestureRecognizer::TriggerGesture);
QTimerEvent fakeTimerEvent(tapAndHoldGesture->timerId);
currentState = recognizer->recognize(tapAndHoldGesture, tapAndHoldGesture, &fakeTimerEvent);
QCOMPARE( currentState, QGestureRecognizer::FinishGesture | QGestureRecognizer::ConsumeEventHint );
delete pressEvent;
}
void Ut_MTapAndHoldRecognizer::testFastTap()
{
QMouseEvent *pressEvent = new QMouseEvent(QEvent::MouseButtonPress, QPoint(0,0), Qt::LeftButton, Qt::LeftButton, 0);
QMouseEvent *releaseEvent = new QMouseEvent(QEvent::MouseButtonRelease, QPoint(0,0), Qt::LeftButton, Qt::LeftButton, 0);
QGestureRecognizer::Result currentState;
currentState = recognizer->recognize(tapAndHoldGesture, 0, pressEvent);
QCOMPARE( currentState, QGestureRecognizer::TriggerGesture);
//Setting timerId as would happen in real life scenario
tapAndHoldGesture->timerId = 1;
currentState = recognizer->recognize(tapAndHoldGesture, 0, releaseEvent);
QCOMPARE( currentState, QGestureRecognizer::CancelGesture);
delete pressEvent;
delete releaseEvent;
}
void Ut_MTapAndHoldRecognizer::testMovePointerInsideThreshold()
{
QMouseEvent *pressEvent = new QMouseEvent(QEvent::MouseButtonPress, QPoint(0,0), Qt::LeftButton, Qt::LeftButton, 0);
QMouseEvent *moveEvent = new QMouseEvent(QEvent::MouseMove, QPoint(3,0), Qt::LeftButton, Qt::LeftButton, 0);
QGestureRecognizer::Result currentState;
currentState = recognizer->recognize(tapAndHoldGesture, 0, pressEvent);
QCOMPARE( currentState, QGestureRecognizer::TriggerGesture);
currentGestureState = Qt::GestureStarted;
currentState = recognizer->recognize(tapAndHoldGesture, 0, moveEvent);
QCOMPARE( currentState, QGestureRecognizer::TriggerGesture);
QTimerEvent fakeTimerEvent(tapAndHoldGesture->timerId);
currentState = recognizer->recognize(tapAndHoldGesture, tapAndHoldGesture, &fakeTimerEvent);
QCOMPARE( currentState, QGestureRecognizer::FinishGesture | QGestureRecognizer::ConsumeEventHint );
delete pressEvent;
delete moveEvent;
}
void Ut_MTapAndHoldRecognizer::testMovePointerBeyondThreshold()
{
QMouseEvent *pressEvent = new QMouseEvent(QEvent::MouseButtonPress, QPoint(0,0), Qt::LeftButton, Qt::LeftButton, 0);
QMouseEvent *moveEvent = new QMouseEvent(QEvent::MouseMove, QPoint(50,0), Qt::LeftButton, Qt::LeftButton, 0);
QGestureRecognizer::Result currentState;
currentState = recognizer->recognize(tapAndHoldGesture, 0, pressEvent);
QCOMPARE( currentState, QGestureRecognizer::TriggerGesture);
currentGestureState = Qt::GestureStarted;
currentState = recognizer->recognize(tapAndHoldGesture, 0, moveEvent);
QCOMPARE( currentState, QGestureRecognizer::CancelGesture);
delete pressEvent;
delete moveEvent;
}
void Ut_MTapAndHoldRecognizer::testUsingStyleTimeout()
{
QMouseEvent pressEvent(QEvent::MouseButtonPress, QPoint(0,0), QPoint(0,0), Qt::LeftButton, Qt::LeftButton, 0);
QGestureRecognizer::Result currentState = recognizer->recognize(tapAndHoldGesture, 0, &pressEvent);
Q_UNUSED(currentState);
// Verify that timeout from style is used when no timeout is set
QCOMPARE(startTimerInterval, MTapAndHoldStyleTimeout);
}
void Ut_MTapAndHoldRecognizer::testSetTimeout()
{
QTapAndHoldGesture::setTimeout(MTapAndHoldSetTimeout);
QMouseEvent pressEvent(QEvent::MouseButtonPress, QPoint(0,0), QPoint(0,0), Qt::LeftButton, Qt::LeftButton, 0);
QGestureRecognizer::Result currentState = recognizer->recognize(tapAndHoldGesture, 0, &pressEvent);
Q_UNUSED(currentState);
// Verify that timeout that was set is used
QCOMPARE(startTimerInterval, MTapAndHoldSetTimeout);
}
void Ut_MTapAndHoldRecognizer::testResetTimeout()
{
QTapAndHoldGesture::setTimeout(MTapAndHoldSetTimeout);
// Reset timeout
QTapAndHoldGesture::setTimeout(-1);
QMouseEvent pressEvent(QEvent::MouseButtonPress, QPoint(0,0), QPoint(0,0), Qt::LeftButton, Qt::LeftButton, 0);
QGestureRecognizer::Result currentState = recognizer->recognize(tapAndHoldGesture, 0, &pressEvent);
Q_UNUSED(currentState);
// Verify that as timeout was resetted then timeout from style is used
QCOMPARE(startTimerInterval, MTapAndHoldStyleTimeout);
}
QTEST_APPLESS_MAIN(Ut_MTapAndHoldRecognizer)
<|endoftext|>
|
<commit_before>// Time: O(nlogw)
// Space: O(w)
class Solution {
public:
vector<double> medianSlidingWindow(vector<int>& nums, int k) {
multiset<int, less<int>> min_bst;
multiset<int, greater<int>> max_bst;
vector<double> result;
for (int i = 0; i < nums.size(); ++i) {
if (i >= k) {
if (max_bst.find(nums[i - k]) != max_bst.cend()) {
max_bst.erase(max_bst.find(nums[i - k]));
} else {
min_bst.erase(min_bst.find(nums[i - k]));
}
}
if (max_bst.empty() || nums[i] > *max_bst.cbegin()) {
min_bst.emplace(nums[i]);
if (min_bst.size() > max_bst.size() + 1) {
max_bst.emplace(*min_bst.cbegin());
min_bst.erase(min_bst.cbegin());
}
} else {
max_bst.emplace(nums[i]);
if (max_bst.size() > min_bst.size()) {
min_bst.emplace(*max_bst.cbegin());
max_bst.erase(max_bst.cbegin());
}
}
if (i >= k - 1) {
result.emplace_back(min_bst.size() == max_bst.size() ?
*max_bst.cbegin() / 2.0 + *min_bst.cbegin() / 2.0 : *min_bst.cbegin());
}
}
return result;
}
};
<commit_msg>Update sliding-window-median.cpp<commit_after>// Time: O(nlogk)
// Space: O(k)
class Solution {
public:
vector<double> medianSlidingWindow(vector<int>& nums, int k) {
multiset<int, less<int>> min_bst;
multiset<int, greater<int>> max_bst;
vector<double> result;
for (int i = 0; i < nums.size(); ++i) {
if (i >= k) {
if (max_bst.find(nums[i - k]) != max_bst.cend()) {
max_bst.erase(max_bst.find(nums[i - k]));
} else {
min_bst.erase(min_bst.find(nums[i - k]));
}
}
if (max_bst.empty() || nums[i] > *max_bst.cbegin()) {
min_bst.emplace(nums[i]);
if (min_bst.size() > max_bst.size() + 1) {
max_bst.emplace(*min_bst.cbegin());
min_bst.erase(min_bst.cbegin());
}
} else {
max_bst.emplace(nums[i]);
if (max_bst.size() > min_bst.size()) {
min_bst.emplace(*max_bst.cbegin());
max_bst.erase(max_bst.cbegin());
}
}
if (i >= k - 1) {
result.emplace_back(min_bst.size() == max_bst.size() ?
*max_bst.cbegin() / 2.0 + *min_bst.cbegin() / 2.0 : *min_bst.cbegin());
}
}
return result;
}
};
<|endoftext|>
|
<commit_before>/*******************************************************
* Copyright (c) 2016, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#pragma once
#include <Param.hpp>
#include <common/dispatch.hpp>
#include <common/kernel_cache.hpp>
#include <debug_opencl.hpp>
#include <kernel/config.hpp>
#include <kernel/reduce.hpp>
#include <kernel/scan_dim.hpp>
#include <kernel/scan_first.hpp>
#include <kernel_headers/csrmm.hpp>
#include <traits.hpp>
#include <af/opencl.h>
#include <string>
#include <vector>
namespace opencl {
namespace kernel {
template<typename T>
void csrmm_nt(Param out, const Param &values, const Param &rowIdx,
const Param &colIdx, const Param &rhs, const T alpha,
const T beta) {
constexpr int MAX_CSRMM_GROUPS = 4096;
// Using greedy indexing is causing performance issues on many platforms
// FIXME: Figure out why
constexpr bool use_greedy = false;
const bool use_alpha = (alpha != scalar<T>(1.0));
const bool use_beta = (beta != scalar<T>(0.0));
std::vector<TemplateArg> targs = {
TemplateTypename<T>(),
TemplateArg(use_alpha),
TemplateArg(use_beta),
TemplateArg(use_greedy),
};
std::vector<std::string> options = {
DefineKeyValue(T, dtype_traits<T>::getName()),
DefineKeyValue(USE_ALPHA, use_alpha),
DefineKeyValue(USE_BETA, use_beta),
DefineKeyValue(USE_GREEDY, use_greedy),
DefineValue(THREADS_PER_GROUP),
DefineKeyValue(IS_CPLX, (af::iscplx<T>() ? 1 : 0)),
};
options.emplace_back(getTypeBuildDefinition<T>());
// FIXME: Switch to perf (thread vs block) baesd kernel
auto csrmm_nt_func =
common::getKernel("csrmm_nt", {csrmm_cl_src}, targs, options);
cl::NDRange local(THREADS_PER_GROUP, 1);
int M = rowIdx.info.dims[0] - 1;
int N = rhs.info.dims[0];
int groups_x = divup(N, local[0]);
int groups_y = divup(M, REPEAT);
groups_y = std::min(groups_y, MAX_CSRMM_GROUPS);
cl::NDRange global(local[0] * groups_x, local[1] * groups_y);
std::vector<int> count(groups_x);
cl::Buffer *counter = bufferAlloc(count.size() * sizeof(int));
getQueue().enqueueWriteBuffer(
*counter, CL_TRUE, 0, count.size() * sizeof(int), (void *)count.data());
csrmm_nt_func(cl::EnqueueArgs(getQueue(), global, local), *out.data,
*values.data, *rowIdx.data, *colIdx.data, M, N, *rhs.data,
rhs.info, alpha, beta, *counter);
bufferFree(counter);
}
} // namespace kernel
} // namespace opencl
<commit_msg>Use CL fill buffer instead of host allocation in csrmm kernel<commit_after>/*******************************************************
* Copyright (c) 2016, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#pragma once
#include <Param.hpp>
#include <common/dispatch.hpp>
#include <common/kernel_cache.hpp>
#include <debug_opencl.hpp>
#include <kernel/config.hpp>
#include <kernel/reduce.hpp>
#include <kernel/scan_dim.hpp>
#include <kernel/scan_first.hpp>
#include <kernel_headers/csrmm.hpp>
#include <traits.hpp>
#include <af/opencl.h>
#include <string>
#include <vector>
namespace opencl {
namespace kernel {
template<typename T>
void csrmm_nt(Param out, const Param &values, const Param &rowIdx,
const Param &colIdx, const Param &rhs, const T alpha,
const T beta) {
constexpr int MAX_CSRMM_GROUPS = 4096;
// Using greedy indexing is causing performance issues on many platforms
// FIXME: Figure out why
constexpr bool use_greedy = false;
const bool use_alpha = (alpha != scalar<T>(1.0));
const bool use_beta = (beta != scalar<T>(0.0));
std::vector<TemplateArg> targs = {
TemplateTypename<T>(),
TemplateArg(use_alpha),
TemplateArg(use_beta),
TemplateArg(use_greedy),
};
std::vector<std::string> options = {
DefineKeyValue(T, dtype_traits<T>::getName()),
DefineKeyValue(USE_ALPHA, use_alpha),
DefineKeyValue(USE_BETA, use_beta),
DefineKeyValue(USE_GREEDY, use_greedy),
DefineValue(THREADS_PER_GROUP),
DefineKeyValue(IS_CPLX, (af::iscplx<T>() ? 1 : 0)),
};
options.emplace_back(getTypeBuildDefinition<T>());
// FIXME: Switch to perf (thread vs block) baesd kernel
auto csrmm_nt_func =
common::getKernel("csrmm_nt", {csrmm_cl_src}, targs, options);
cl::NDRange local(THREADS_PER_GROUP, 1);
int M = rowIdx.info.dims[0] - 1;
int N = rhs.info.dims[0];
int groups_x = divup(N, local[0]);
int groups_y = divup(M, REPEAT);
groups_y = std::min(groups_y, MAX_CSRMM_GROUPS);
cl::NDRange global(local[0] * groups_x, local[1] * groups_y);
cl::Buffer *counter = bufferAlloc(groups_x * sizeof(int));
getQueue().enqueueFillBuffer(*counter, 0, 0, groups_x * sizeof(int));
csrmm_nt_func(cl::EnqueueArgs(getQueue(), global, local), *out.data,
*values.data, *rowIdx.data, *colIdx.data, M, N, *rhs.data,
rhs.info, alpha, beta, *counter);
bufferFree(counter);
}
} // namespace kernel
} // namespace opencl
<|endoftext|>
|
<commit_before>// Copyright 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 "base/logging.h"
#include <stdio.h>
#include <stdlib.h>
#include <iomanip>
#if defined(OS_POSIX)
#include <paths.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <unistd.h>
#include "base/posix/safe_strerror.h"
#endif // OS_POSIX
#if defined(OS_MACOSX)
#include <AvailabilityMacros.h>
#include <CoreFoundation/CoreFoundation.h>
#include <pthread.h>
#if !defined(MAC_OS_X_VERSION_10_12) || \
MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_12
#include <asl.h>
#else
#include <os/log.h>
#endif
#elif defined(OS_LINUX)
#include <sys/syscall.h>
#include <sys/types.h>
#elif defined(OS_WIN)
#include <windows.h>
#endif
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
namespace logging {
namespace {
const char* const log_severity_names[] = {
"INFO",
"WARNING",
"ERROR",
"ERROR_REPORT",
"FATAL"
};
LogMessageHandlerFunction g_log_message_handler = nullptr;
} // namespace
void SetLogMessageHandler(LogMessageHandlerFunction log_message_handler) {
g_log_message_handler = log_message_handler;
}
LogMessageHandlerFunction GetLogMessageHandler() {
return g_log_message_handler;
}
#if defined(OS_WIN)
std::string SystemErrorCodeToString(unsigned long error_code) {
wchar_t msgbuf[256];
DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS |
FORMAT_MESSAGE_MAX_WIDTH_MASK;
DWORD len = FormatMessage(
flags, nullptr, error_code, 0, msgbuf, arraysize(msgbuf), nullptr);
if (len) {
// Most system messages end in a period and a space. Remove the space if
// it’s there, because the following StringPrintf() includes one.
if (len >= 1 && msgbuf[len - 1] == ' ') {
msgbuf[len - 1] = '\0';
}
return base::StringPrintf("%s (%u)",
base::UTF16ToUTF8(msgbuf).c_str(), error_code);
}
return base::StringPrintf("Error %u while retrieving error %u",
GetLastError(),
error_code);
}
#endif // OS_WIN
LogMessage::LogMessage(const char* function,
const char* file_path,
int line,
LogSeverity severity)
: stream_(),
file_path_(file_path),
message_start_(0),
line_(line),
severity_(severity) {
Init(function);
}
LogMessage::LogMessage(const char* function,
const char* file_path,
int line,
std::string* result)
: stream_(),
file_path_(file_path),
message_start_(0),
line_(line),
severity_(LOG_FATAL) {
Init(function);
stream_ << "Check failed: " << *result << ". ";
delete result;
}
LogMessage::~LogMessage() {
stream_ << std::endl;
std::string str_newline(stream_.str());
if (g_log_message_handler &&
g_log_message_handler(
severity_, file_path_, line_, message_start_, str_newline)) {
return;
}
fprintf(stderr, "%s", str_newline.c_str());
fflush(stderr);
#if defined(OS_MACOSX)
const bool log_to_system = []() {
struct stat stderr_stat;
if (fstat(fileno(stderr), &stderr_stat) == -1) {
return true;
}
if (!S_ISCHR(stderr_stat.st_mode)) {
return false;
}
struct stat dev_null_stat;
if (stat(_PATH_DEVNULL, &dev_null_stat) == -1) {
return true;
}
return !S_ISCHR(dev_null_stat.st_mode) ||
stderr_stat.st_rdev == dev_null_stat.st_rdev;
}();
if (log_to_system) {
CFBundleRef main_bundle = CFBundleGetMainBundle();
CFStringRef main_bundle_id_cf =
main_bundle ? CFBundleGetIdentifier(main_bundle) : nullptr;
std::string main_bundle_id_buf;
const char* main_bundle_id = nullptr;
if (main_bundle_id_cf) {
main_bundle_id =
CFStringGetCStringPtr(main_bundle_id_cf, kCFStringEncodingUTF8);
if (!main_bundle_id) {
// 1024 is from 10.10.5 CF-1153.18/CFBundle.c __CFBundleMainID__ (at
// the point of use, not declaration).
main_bundle_id_buf.resize(1024);
if (!CFStringGetCString(main_bundle_id_cf,
&main_bundle_id_buf[0],
main_bundle_id_buf.size(),
kCFStringEncodingUTF8)) {
main_bundle_id_buf.clear();
} else {
main_bundle_id = &main_bundle_id_buf[0];
}
}
}
#if !defined(MAC_OS_X_VERSION_10_12) || \
MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_12
// Use ASL when this might run on pre-10.12 systems. Unified Logging
// (os_log) was introduced in 10.12.
const class ASLClient {
public:
explicit ASLClient(const char* asl_facility)
: client_(asl_open(nullptr, asl_facility, ASL_OPT_NO_DELAY)) {}
~ASLClient() { asl_close(client_); }
aslclient get() const { return client_; }
private:
aslclient client_;
DISALLOW_COPY_AND_ASSIGN(ASLClient);
} asl_client(main_bundle_id ? main_bundle_id : "com.apple.console");
const class ASLMessage {
public:
ASLMessage() : message_(asl_new(ASL_TYPE_MSG)) {}
~ASLMessage() { asl_free(message_); }
aslmsg get() const { return message_; }
private:
aslmsg message_;
DISALLOW_COPY_AND_ASSIGN(ASLMessage);
} asl_message;
// By default, messages are only readable by the admin group. Explicitly
// make them readable by the user generating the messages.
char euid_string[12];
snprintf(euid_string, arraysize(euid_string), "%d", geteuid());
asl_set(asl_message.get(), ASL_KEY_READ_UID, euid_string);
// Map Chrome log severities to ASL log levels.
const char* const asl_level_string = [](LogSeverity severity) {
#define ASL_LEVEL_STR(level) ASL_LEVEL_STR_X(level)
#define ASL_LEVEL_STR_X(level) #level
switch (severity) {
case LOG_INFO:
return ASL_LEVEL_STR(ASL_LEVEL_INFO);
case LOG_WARNING:
return ASL_LEVEL_STR(ASL_LEVEL_WARNING);
case LOG_ERROR:
return ASL_LEVEL_STR(ASL_LEVEL_ERR);
case LOG_FATAL:
return ASL_LEVEL_STR(ASL_LEVEL_CRIT);
default:
return severity < 0 ? ASL_LEVEL_STR(ASL_LEVEL_DEBUG)
: ASL_LEVEL_STR(ASL_LEVEL_NOTICE);
}
#undef ASL_LEVEL_STR
#undef ASL_LEVEL_STR_X
}(severity_);
asl_set(asl_message.get(), ASL_KEY_LEVEL, asl_level_string);
asl_set(asl_message.get(), ASL_KEY_MSG, str_newline.c_str());
asl_send(asl_client.get(), asl_message.get());
#else
// Use Unified Logging (os_log) when this will only run on 10.12 and later.
// ASL is deprecated in 10.12.
const class OSLog {
public:
explicit OSLog(const char* subsystem)
: os_log_(subsystem ? os_log_create(subsystem, "chromium_logging")
: OS_LOG_DEFAULT) {}
~OSLog() {
if (os_log_ != OS_LOG_DEFAULT) {
os_release(os_log_);
}
}
os_log_t get() const { return os_log_; }
private:
os_log_t os_log_;
DISALLOW_COPY_AND_ASSIGN(OSLog);
} log(main_bundle_id);
const os_log_type_t os_log_type = [](LogSeverity severity) {
switch (severity) {
case LOG_INFO:
return OS_LOG_TYPE_INFO;
case LOG_WARNING:
return OS_LOG_TYPE_DEFAULT;
case LOG_ERROR:
return OS_LOG_TYPE_ERROR;
case LOG_FATAL:
return OS_LOG_TYPE_FAULT;
default:
return severity < 0 ? OS_LOG_TYPE_DEBUG : OS_LOG_TYPE_DEFAULT;
}
}(severity_);
os_log_with_type(log.get(), os_log_type, "%{public}s", str_newline.c_str());
#endif
}
#elif defined(OS_WIN)
OutputDebugString(base::UTF8ToUTF16(str_newline).c_str());
#endif // OS_MACOSX
if (severity_ == LOG_FATAL) {
#if defined(COMPILER_MSVC)
__debugbreak();
__ud2();
#elif defined(ARCH_CPU_X86_FAMILY)
asm("int3; ud2;");
#elif defined(ARCH_CPU_ARMEL)
asm("bkpt #0; udf #0;");
#elif defined(ARCH_CPU_ARM64)
asm("brk #0; hlt #0;");
#else
__builtin_trap();
#endif
}
}
void LogMessage::Init(const char* function) {
std::string file_name(file_path_);
#if defined(OS_WIN)
size_t last_slash = file_name.find_last_of("\\/");
#else
size_t last_slash = file_name.find_last_of('/');
#endif
if (last_slash != std::string::npos) {
file_name.assign(file_name.substr(last_slash + 1));
}
#if defined(OS_POSIX)
pid_t pid = getpid();
#elif defined(OS_WIN)
DWORD pid = GetCurrentProcessId();
#endif
#if defined(OS_MACOSX)
uint64_t thread;
pthread_threadid_np(pthread_self(), &thread);
#elif defined(OS_ANDROID)
pid_t thread = gettid();
#elif defined(OS_LINUX)
pid_t thread = syscall(__NR_gettid);
#elif defined(OS_WIN)
DWORD thread = GetCurrentThreadId();
#endif
stream_ << '['
<< pid
<< ':'
<< thread
<< ':'
<< std::setfill('0');
#if defined(OS_POSIX)
timeval tv;
gettimeofday(&tv, nullptr);
tm local_time;
localtime_r(&tv.tv_sec, &local_time);
stream_ << std::setw(4) << local_time.tm_year + 1900
<< std::setw(2) << local_time.tm_mon + 1
<< std::setw(2) << local_time.tm_mday
<< ','
<< std::setw(2) << local_time.tm_hour
<< std::setw(2) << local_time.tm_min
<< std::setw(2) << local_time.tm_sec
<< '.'
<< std::setw(6) << tv.tv_usec;
#elif defined(OS_WIN)
SYSTEMTIME local_time;
GetLocalTime(&local_time);
stream_ << std::setw(4) << local_time.wYear
<< std::setw(2) << local_time.wMonth
<< std::setw(2) << local_time.wDay
<< ','
<< std::setw(2) << local_time.wHour
<< std::setw(2) << local_time.wMinute
<< std::setw(2) << local_time.wSecond
<< '.'
<< std::setw(3) << local_time.wMilliseconds;
#endif
stream_ << ':';
if (severity_ >= 0) {
stream_ << log_severity_names[severity_];
} else {
stream_ << "VERBOSE" << -severity_;
}
stream_ << ' '
<< file_name
<< ':'
<< line_
<< "] ";
message_start_ = stream_.str().size();
}
#if defined(OS_WIN)
unsigned long GetLastSystemErrorCode() {
return GetLastError();
}
Win32ErrorLogMessage::Win32ErrorLogMessage(const char* function,
const char* file_path,
int line,
LogSeverity severity,
unsigned long err)
: LogMessage(function, file_path, line, severity), err_(err) {
}
Win32ErrorLogMessage::~Win32ErrorLogMessage() {
stream() << ": " << SystemErrorCodeToString(err_);
}
#elif defined(OS_POSIX)
ErrnoLogMessage::ErrnoLogMessage(const char* function,
const char* file_path,
int line,
LogSeverity severity,
int err)
: LogMessage(function, file_path, line, severity),
err_(err) {
}
ErrnoLogMessage::~ErrnoLogMessage() {
stream() << ": "
<< base::safe_strerror(err_)
<< " ("
<< err_
<< ")";
}
#endif // OS_POSIX
} // namespace logging
<commit_msg>win: MSVS 2017 (15)/C++ 14.1/C 19.10 compatibility<commit_after>// Copyright 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 "base/logging.h"
#include <stdio.h>
#include <stdlib.h>
#include <iomanip>
#if defined(OS_POSIX)
#include <paths.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <unistd.h>
#include "base/posix/safe_strerror.h"
#endif // OS_POSIX
#if defined(OS_MACOSX)
#include <AvailabilityMacros.h>
#include <CoreFoundation/CoreFoundation.h>
#include <pthread.h>
#if !defined(MAC_OS_X_VERSION_10_12) || \
MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_12
#include <asl.h>
#else
#include <os/log.h>
#endif
#elif defined(OS_LINUX)
#include <sys/syscall.h>
#include <sys/types.h>
#elif defined(OS_WIN)
#include <intrin.h>
#include <windows.h>
#endif
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
namespace logging {
namespace {
const char* const log_severity_names[] = {
"INFO",
"WARNING",
"ERROR",
"ERROR_REPORT",
"FATAL"
};
LogMessageHandlerFunction g_log_message_handler = nullptr;
} // namespace
void SetLogMessageHandler(LogMessageHandlerFunction log_message_handler) {
g_log_message_handler = log_message_handler;
}
LogMessageHandlerFunction GetLogMessageHandler() {
return g_log_message_handler;
}
#if defined(OS_WIN)
std::string SystemErrorCodeToString(unsigned long error_code) {
wchar_t msgbuf[256];
DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS |
FORMAT_MESSAGE_MAX_WIDTH_MASK;
DWORD len = FormatMessage(
flags, nullptr, error_code, 0, msgbuf, arraysize(msgbuf), nullptr);
if (len) {
// Most system messages end in a period and a space. Remove the space if
// it’s there, because the following StringPrintf() includes one.
if (len >= 1 && msgbuf[len - 1] == ' ') {
msgbuf[len - 1] = '\0';
}
return base::StringPrintf("%s (%u)",
base::UTF16ToUTF8(msgbuf).c_str(), error_code);
}
return base::StringPrintf("Error %u while retrieving error %u",
GetLastError(),
error_code);
}
#endif // OS_WIN
LogMessage::LogMessage(const char* function,
const char* file_path,
int line,
LogSeverity severity)
: stream_(),
file_path_(file_path),
message_start_(0),
line_(line),
severity_(severity) {
Init(function);
}
LogMessage::LogMessage(const char* function,
const char* file_path,
int line,
std::string* result)
: stream_(),
file_path_(file_path),
message_start_(0),
line_(line),
severity_(LOG_FATAL) {
Init(function);
stream_ << "Check failed: " << *result << ". ";
delete result;
}
LogMessage::~LogMessage() {
stream_ << std::endl;
std::string str_newline(stream_.str());
if (g_log_message_handler &&
g_log_message_handler(
severity_, file_path_, line_, message_start_, str_newline)) {
return;
}
fprintf(stderr, "%s", str_newline.c_str());
fflush(stderr);
#if defined(OS_MACOSX)
const bool log_to_system = []() {
struct stat stderr_stat;
if (fstat(fileno(stderr), &stderr_stat) == -1) {
return true;
}
if (!S_ISCHR(stderr_stat.st_mode)) {
return false;
}
struct stat dev_null_stat;
if (stat(_PATH_DEVNULL, &dev_null_stat) == -1) {
return true;
}
return !S_ISCHR(dev_null_stat.st_mode) ||
stderr_stat.st_rdev == dev_null_stat.st_rdev;
}();
if (log_to_system) {
CFBundleRef main_bundle = CFBundleGetMainBundle();
CFStringRef main_bundle_id_cf =
main_bundle ? CFBundleGetIdentifier(main_bundle) : nullptr;
std::string main_bundle_id_buf;
const char* main_bundle_id = nullptr;
if (main_bundle_id_cf) {
main_bundle_id =
CFStringGetCStringPtr(main_bundle_id_cf, kCFStringEncodingUTF8);
if (!main_bundle_id) {
// 1024 is from 10.10.5 CF-1153.18/CFBundle.c __CFBundleMainID__ (at
// the point of use, not declaration).
main_bundle_id_buf.resize(1024);
if (!CFStringGetCString(main_bundle_id_cf,
&main_bundle_id_buf[0],
main_bundle_id_buf.size(),
kCFStringEncodingUTF8)) {
main_bundle_id_buf.clear();
} else {
main_bundle_id = &main_bundle_id_buf[0];
}
}
}
#if !defined(MAC_OS_X_VERSION_10_12) || \
MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_12
// Use ASL when this might run on pre-10.12 systems. Unified Logging
// (os_log) was introduced in 10.12.
const class ASLClient {
public:
explicit ASLClient(const char* asl_facility)
: client_(asl_open(nullptr, asl_facility, ASL_OPT_NO_DELAY)) {}
~ASLClient() { asl_close(client_); }
aslclient get() const { return client_; }
private:
aslclient client_;
DISALLOW_COPY_AND_ASSIGN(ASLClient);
} asl_client(main_bundle_id ? main_bundle_id : "com.apple.console");
const class ASLMessage {
public:
ASLMessage() : message_(asl_new(ASL_TYPE_MSG)) {}
~ASLMessage() { asl_free(message_); }
aslmsg get() const { return message_; }
private:
aslmsg message_;
DISALLOW_COPY_AND_ASSIGN(ASLMessage);
} asl_message;
// By default, messages are only readable by the admin group. Explicitly
// make them readable by the user generating the messages.
char euid_string[12];
snprintf(euid_string, arraysize(euid_string), "%d", geteuid());
asl_set(asl_message.get(), ASL_KEY_READ_UID, euid_string);
// Map Chrome log severities to ASL log levels.
const char* const asl_level_string = [](LogSeverity severity) {
#define ASL_LEVEL_STR(level) ASL_LEVEL_STR_X(level)
#define ASL_LEVEL_STR_X(level) #level
switch (severity) {
case LOG_INFO:
return ASL_LEVEL_STR(ASL_LEVEL_INFO);
case LOG_WARNING:
return ASL_LEVEL_STR(ASL_LEVEL_WARNING);
case LOG_ERROR:
return ASL_LEVEL_STR(ASL_LEVEL_ERR);
case LOG_FATAL:
return ASL_LEVEL_STR(ASL_LEVEL_CRIT);
default:
return severity < 0 ? ASL_LEVEL_STR(ASL_LEVEL_DEBUG)
: ASL_LEVEL_STR(ASL_LEVEL_NOTICE);
}
#undef ASL_LEVEL_STR
#undef ASL_LEVEL_STR_X
}(severity_);
asl_set(asl_message.get(), ASL_KEY_LEVEL, asl_level_string);
asl_set(asl_message.get(), ASL_KEY_MSG, str_newline.c_str());
asl_send(asl_client.get(), asl_message.get());
#else
// Use Unified Logging (os_log) when this will only run on 10.12 and later.
// ASL is deprecated in 10.12.
const class OSLog {
public:
explicit OSLog(const char* subsystem)
: os_log_(subsystem ? os_log_create(subsystem, "chromium_logging")
: OS_LOG_DEFAULT) {}
~OSLog() {
if (os_log_ != OS_LOG_DEFAULT) {
os_release(os_log_);
}
}
os_log_t get() const { return os_log_; }
private:
os_log_t os_log_;
DISALLOW_COPY_AND_ASSIGN(OSLog);
} log(main_bundle_id);
const os_log_type_t os_log_type = [](LogSeverity severity) {
switch (severity) {
case LOG_INFO:
return OS_LOG_TYPE_INFO;
case LOG_WARNING:
return OS_LOG_TYPE_DEFAULT;
case LOG_ERROR:
return OS_LOG_TYPE_ERROR;
case LOG_FATAL:
return OS_LOG_TYPE_FAULT;
default:
return severity < 0 ? OS_LOG_TYPE_DEBUG : OS_LOG_TYPE_DEFAULT;
}
}(severity_);
os_log_with_type(log.get(), os_log_type, "%{public}s", str_newline.c_str());
#endif
}
#elif defined(OS_WIN)
OutputDebugString(base::UTF8ToUTF16(str_newline).c_str());
#endif // OS_MACOSX
if (severity_ == LOG_FATAL) {
#if defined(COMPILER_MSVC)
__debugbreak();
__ud2();
#elif defined(ARCH_CPU_X86_FAMILY)
asm("int3; ud2;");
#elif defined(ARCH_CPU_ARMEL)
asm("bkpt #0; udf #0;");
#elif defined(ARCH_CPU_ARM64)
asm("brk #0; hlt #0;");
#else
__builtin_trap();
#endif
}
}
void LogMessage::Init(const char* function) {
std::string file_name(file_path_);
#if defined(OS_WIN)
size_t last_slash = file_name.find_last_of("\\/");
#else
size_t last_slash = file_name.find_last_of('/');
#endif
if (last_slash != std::string::npos) {
file_name.assign(file_name.substr(last_slash + 1));
}
#if defined(OS_POSIX)
pid_t pid = getpid();
#elif defined(OS_WIN)
DWORD pid = GetCurrentProcessId();
#endif
#if defined(OS_MACOSX)
uint64_t thread;
pthread_threadid_np(pthread_self(), &thread);
#elif defined(OS_ANDROID)
pid_t thread = gettid();
#elif defined(OS_LINUX)
pid_t thread = syscall(__NR_gettid);
#elif defined(OS_WIN)
DWORD thread = GetCurrentThreadId();
#endif
stream_ << '['
<< pid
<< ':'
<< thread
<< ':'
<< std::setfill('0');
#if defined(OS_POSIX)
timeval tv;
gettimeofday(&tv, nullptr);
tm local_time;
localtime_r(&tv.tv_sec, &local_time);
stream_ << std::setw(4) << local_time.tm_year + 1900
<< std::setw(2) << local_time.tm_mon + 1
<< std::setw(2) << local_time.tm_mday
<< ','
<< std::setw(2) << local_time.tm_hour
<< std::setw(2) << local_time.tm_min
<< std::setw(2) << local_time.tm_sec
<< '.'
<< std::setw(6) << tv.tv_usec;
#elif defined(OS_WIN)
SYSTEMTIME local_time;
GetLocalTime(&local_time);
stream_ << std::setw(4) << local_time.wYear
<< std::setw(2) << local_time.wMonth
<< std::setw(2) << local_time.wDay
<< ','
<< std::setw(2) << local_time.wHour
<< std::setw(2) << local_time.wMinute
<< std::setw(2) << local_time.wSecond
<< '.'
<< std::setw(3) << local_time.wMilliseconds;
#endif
stream_ << ':';
if (severity_ >= 0) {
stream_ << log_severity_names[severity_];
} else {
stream_ << "VERBOSE" << -severity_;
}
stream_ << ' '
<< file_name
<< ':'
<< line_
<< "] ";
message_start_ = stream_.str().size();
}
#if defined(OS_WIN)
unsigned long GetLastSystemErrorCode() {
return GetLastError();
}
Win32ErrorLogMessage::Win32ErrorLogMessage(const char* function,
const char* file_path,
int line,
LogSeverity severity,
unsigned long err)
: LogMessage(function, file_path, line, severity), err_(err) {
}
Win32ErrorLogMessage::~Win32ErrorLogMessage() {
stream() << ": " << SystemErrorCodeToString(err_);
}
#elif defined(OS_POSIX)
ErrnoLogMessage::ErrnoLogMessage(const char* function,
const char* file_path,
int line,
LogSeverity severity,
int err)
: LogMessage(function, file_path, line, severity),
err_(err) {
}
ErrnoLogMessage::~ErrnoLogMessage() {
stream() << ": "
<< base::safe_strerror(err_)
<< " ("
<< err_
<< ")";
}
#endif // OS_POSIX
} // namespace logging
<|endoftext|>
|
<commit_before>/*!
* \file hyo_utilities_tests.cpp
* \author Robert 'Bob' Caddy (rvc@pitt.edu), Helena Richie (helenarichie@pitt.edu)
* \brief Tests for the contents of hydro_utilities.h and hydro_utilities.cpp
*
*/
// STL Includes
#include <vector>
#include <string>
#include <iostream>
// External Includes
#include <gtest/gtest.h> // Include GoogleTest and related libraries/headers
// Local Includes
#include "../utils/testing_utilities.h"
#include "../utils/hydro_utilities.h"
#include "../global/global.h"
// =============================================================================
// Local helper functions
/*!
* INDEX OF VARIABLES
* p : pressure
* vx, vy, vz : x, y, and z velocity
* d : density
* E : energy
* T : temperature
* px, py, pz : x, y, and z momentum
* n : number density
*/
namespace
{
struct TestParams
{
double gamma = 5./3.;
std::vector<double> d {8.4087201154e-100, 1.6756968986e2, 5.4882403847e100};
std::vector<double> vx {7.0378624601e-100, 7.0829278656e2, 1.8800514112e100};
std::vector<double> vy {7.3583469014e-100, 5.9283073464e2, 5.2725717864e100};
std::vector<double> vz {1.7182972216e-100, 8.8417748226e2, 1.5855352639e100};
std::vector<double> px {8.2340416681e-100, 8.1019429453e2, 5.5062596954e100};
std::vector<double> py {4.9924582299e-100, 7.1254780684e2, 6.5939640992e100};
std::vector<double> pz {3.6703192739e-100, 7.5676716066e2, 7.2115881803e100};
std::vector<double> E {3.0342082433e-100, 7.6976906577e2, 1.9487120853e100};
std::vector<double> p {2.2244082909e-100, 8.6772951021e2, 6.7261085663e100};
std::vector<std::string> names{"Small number case", "Medium number case", "Large number case"};
};
}
TEST(tHYDROSYSTEMHydroUtilsCalcPressureConserved, CorrectInputExpectCorrectOutput) {
TestParams parameters;
std::vector<double> fiducial_ps {3.3366124363499995e-100, 9.9999999999999995e-21, 2.4282508238146436e+100};
for (size_t i = 0; i < parameters.names.size(); i++)
{
Real test_ps = hydro_utilities::Calc_Pressure_Conserved(parameters.E.at(i), parameters.d.at(i), parameters.px.at(i), parameters.py.at(i), parameters.pz.at(i), parameters.gamma);
testingUtilities::checkResults(fiducial_ps.at(i), test_ps, parameters.names.at(i));
}
}
TEST(tHYDROSYSTEMHydroUtilsCalcPressurePrimitive, CorrectInputExpectCorrectOutput) {
TestParams parameters;
std::vector<double> fiducial_pressures{3.3366124363499995e-100, 9.9999999999999995e-21, 2.4282508238146436e+100};
for (size_t i = 0; i < parameters.names.size(); i++)
{
Real test_p = hydro_utilities::Calc_Pressure_Conserved(parameters.p.at(i), parameters.d.at(i), parameters.vx.at(i), parameters.vy.at(i), parameters.vz.at(i), parameters.gamma);
testingUtilities::checkResults(fiducial_pressures.at(i), test_p, parameters.names.at(i));
}
}<commit_msg>add hydro utility function testing<commit_after>/*!
* \file hyo_utilities_tests.cpp
* \author Robert 'Bob' Caddy (rvc@pitt.edu), Helena Richie (helenarichie@pitt.edu)
* \brief Tests for the contents of hydro_utilities.h and hydro_utilities.cpp
*
*/
// STL Includes
#include <vector>
#include <string>
#include <iostream>
// External Includes
#include <gtest/gtest.h> // Include GoogleTest and related libraries/headers
// Local Includes
#include "../utils/testing_utilities.h"
#include "../utils/hydro_utilities.h"
#include "../global/global.h"
// =============================================================================
// Local helper functions
/*!
* INDEX OF VARIABLES
* p : pressure
* vx, vy, vz : x, y, and z velocity
* d : density
* E : energy
* T : temperature
* px, py, pz : x, y, and z momentum
* n : number density
*/
namespace
{
struct TestParams
{
double gamma = 5./3.;
std::vector<double> d {8.4087201154e-100, 1.6756968986e2, 5.4882403847e100};
std::vector<double> vx {7.0378624601e-100, 7.0829278656e2, 1.8800514112e100};
std::vector<double> vy {7.3583469014e-100, 5.9283073464e2, 5.2725717864e100};
std::vector<double> vz {1.7182972216e-100, 8.8417748226e2, 1.5855352639e100};
std::vector<double> px {8.2340416681e-100, 8.1019429453e2, 5.5062596954e100};
std::vector<double> py {4.9924582299e-100, 7.1254780684e2, 6.5939640992e100};
std::vector<double> pz {3.6703192739e-100, 7.5676716066e2, 7.2115881803e100};
std::vector<double> E {3.0342082433e-100, 7.6976906577e2, 1.9487120853e100};
std::vector<double> p {2.2244082909e-100, 8.6772951021e2, 6.7261085663e100};
std::vector<std::string> names{"Small number case", "Medium number case", "Large number case"};
};
}
TEST(tHYDROSYSTEMHydroUtilsCalcPressureConserved, CorrectInputExpectCorrectOutput) {
TestParams parameters;
std::vector<double> fiducial_ps {5, 5, 5};
for (size_t i = 0; i < parameters.names.size(); i++)
{
Real test_ps = hydro_utilities::Calc_Pressure_Conserved(parameters.E.at(i), parameters.d.at(i), parameters.px.at(i), parameters.py.at(i), parameters.pz.at(i), parameters.gamma);
testingUtilities::checkResults(fiducial_ps.at(i), test_ps, parameters.names.at(i));
}
}<|endoftext|>
|
<commit_before>/*
This file is part of Akregator.
Copyright (C) 2005 Frank Osterfeld <frank.osterfeld@kdemail.net>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include "dragobjects.h"
#include "feed.h"
#include <q3cstring.h>
//Added by qt3to4:
#include <QList>
namespace Akregator {
class Article;
ArticleDrag::ArticleDrag(const QList<Article>& articles, QWidget* dragSource, const char* name)
: K3URLDrag(articleURLs(articles), dragSource), m_items(articlesToDragItems(articles))
{
setObjectName(name);
}
bool ArticleDrag::canDecode(const QMimeSource* e)
{
return e->provides("akregator/articles");
}
bool ArticleDrag::decode(const QMimeSource* e, QList<ArticleDragItem>& articles)
{
articles.clear();
QByteArray array = e->encodedData("akregator/articles");
QDataStream stream( &array,QIODevice::ReadOnly);
stream.setVersion(QDataStream::Qt_3_1);
while (!stream.atEnd())
{
ArticleDragItem i;
stream >> i.feedURL;
stream >> i.guid;
articles.append(i);
}
return true;
}
const char* ArticleDrag::format(int i) const
{
if (i == 0)
return "text/uri-list";
else if (i == 1)
return "akregator/articles";
return 0;
}
QByteArray ArticleDrag::encodedData(const char* mime) const
{
Q3CString mimetype(mime);
if (mimetype == "akregator/articles")
{
QByteArray ba;
QDataStream stream( &ba,QIODevice::WriteOnly);
stream.setVersion(QDataStream::Qt_3_1);
QList<ArticleDragItem>::ConstIterator end = m_items.end();
for (QList<ArticleDragItem>::ConstIterator it = m_items.begin(); it != end; ++it)
{
stream << (*it).feedURL;
stream << (*it).guid;
}
return ba;
}
else
{
return K3URLDrag::encodedData(mime);
}
}
QList<ArticleDragItem> ArticleDrag::articlesToDragItems(const QList<Article>& articles)
{
QList<ArticleDragItem> items;
QList<Article>::ConstIterator end(articles.end());
for (QList<Article>::ConstIterator it = articles.begin(); it != end; ++it)
{
ArticleDragItem i;
i.feedURL = (*it).feed() ? (*it).feed()->xmlUrl() : "";
i.guid = (*it).guid();
items.append(i);
}
return items;
}
KURL::List ArticleDrag::articleURLs(const QList<Article>& articles)
{
KURL::List urls;
QList<Article>::ConstIterator end(articles.end());
for (QList<Article>::ConstIterator it = articles.begin(); it != end; ++it)
urls.append((*it).link());
return urls;
}
} // namespace Akregator
<commit_msg>Q3CString--<commit_after>/*
This file is part of Akregator.
Copyright (C) 2005 Frank Osterfeld <frank.osterfeld@kdemail.net>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include "dragobjects.h"
#include "feed.h"
#include <q3cstring.h>
//Added by qt3to4:
#include <QList>
namespace Akregator {
class Article;
ArticleDrag::ArticleDrag(const QList<Article>& articles, QWidget* dragSource, const char* name)
: K3URLDrag(articleURLs(articles), dragSource), m_items(articlesToDragItems(articles))
{
setObjectName(name);
}
bool ArticleDrag::canDecode(const QMimeSource* e)
{
return e->provides("akregator/articles");
}
bool ArticleDrag::decode(const QMimeSource* e, QList<ArticleDragItem>& articles)
{
articles.clear();
QByteArray array = e->encodedData("akregator/articles");
QDataStream stream( &array,QIODevice::ReadOnly);
stream.setVersion(QDataStream::Qt_3_1);
while (!stream.atEnd())
{
ArticleDragItem i;
stream >> i.feedURL;
stream >> i.guid;
articles.append(i);
}
return true;
}
const char* ArticleDrag::format(int i) const
{
if (i == 0)
return "text/uri-list";
else if (i == 1)
return "akregator/articles";
return 0;
}
QByteArray ArticleDrag::encodedData(const char* mime) const
{
QByteArray mimetype(mime);
if (mimetype == "akregator/articles")
{
QByteArray ba;
QDataStream stream( &ba,QIODevice::WriteOnly);
stream.setVersion(QDataStream::Qt_3_1);
QList<ArticleDragItem>::ConstIterator end = m_items.end();
for (QList<ArticleDragItem>::ConstIterator it = m_items.begin(); it != end; ++it)
{
stream << (*it).feedURL;
stream << (*it).guid;
}
return ba;
}
else
{
return K3URLDrag::encodedData(mime);
}
}
QList<ArticleDragItem> ArticleDrag::articlesToDragItems(const QList<Article>& articles)
{
QList<ArticleDragItem> items;
QList<Article>::ConstIterator end(articles.end());
for (QList<Article>::ConstIterator it = articles.begin(); it != end; ++it)
{
ArticleDragItem i;
i.feedURL = (*it).feed() ? (*it).feed()->xmlUrl() : "";
i.guid = (*it).guid();
items.append(i);
}
return items;
}
KURL::List ArticleDrag::articleURLs(const QList<Article>& articles)
{
KURL::List urls;
QList<Article>::ConstIterator end(articles.end());
for (QList<Article>::ConstIterator it = articles.begin(); it != end; ++it)
urls.append((*it).link());
return urls;
}
} // namespace Akregator
<|endoftext|>
|
<commit_before><commit_msg>Base: Active RenderContext in Surface extraction to be able to download GL representations (closes #348)<commit_after><|endoftext|>
|
<commit_before>//
// Copyright(c) 2015 Gabi Melman.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
//
// bench.cpp : spdlog benchmarks
//
#include "spdlog/spdlog.h"
#include "spdlog/async.h"
#include "spdlog/sinks/basic_file_sink.h"
#include "spdlog/sinks/daily_file_sink.h"
#include "spdlog/sinks/null_sink.h"
#include "spdlog/sinks/rotating_file_sink.h"
#include "utils.h"
#include <atomic>
#include <cstdlib> // EXIT_FAILURE
#include <memory>
#include <string>
#include <thread>
using namespace std;
using namespace std::chrono;
using namespace spdlog;
using namespace spdlog::sinks;
using namespace utils;
void bench(int howmany, std::shared_ptr<spdlog::logger> log);
void bench_mt(int howmany, std::shared_ptr<spdlog::logger> log, int thread_count);
void bench_default_api(int howmany, std::shared_ptr<spdlog::logger> log);
void bench_c_string(int howmany, std::shared_ptr<spdlog::logger> log);
int main(int argc, char *argv[])
{
spdlog::default_logger()->set_pattern("[%^%l%$] %v");
int howmany = 1000000;
int queue_size = howmany + 2;
int threads = 10;
size_t file_size = 30 * 1024 * 1024;
size_t rotating_files = 5;
try
{
if (argc > 1)
howmany = atoi(argv[1]);
if (argc > 2)
threads = atoi(argv[2]);
if (argc > 3)
queue_size = atoi(argv[3]);
spdlog::info("**************************************************************");
spdlog::info("Single thread, {:n} iterations", howmany);
spdlog::info("**************************************************************");
auto basic_st = spdlog::basic_logger_st("basic_st", "logs/basic_st.log", true);
bench(howmany, std::move(basic_st));
basic_st.reset();
auto rotating_st = spdlog::rotating_logger_st("rotating_st", "logs/rotating_st.log", file_size, rotating_files);
bench(howmany, std::move(rotating_st));
auto daily_st = spdlog::daily_logger_st("daily_st", "logs/daily_st.log");
bench(howmany, std::move(daily_st));
bench(howmany, spdlog::create<null_sink_st>("null_st"));
spdlog::info("**************************************************************");
spdlog::info("Default API. Single thread, {:n} iterations", howmany);
spdlog::info("**************************************************************");
basic_st = spdlog::basic_logger_st("basic_st", "logs/basic_st.log", true);
bench_default_api(howmany, std::move(basic_st));
rotating_st = spdlog::rotating_logger_st("rotating_st", "logs/rotating_st.log", file_size, rotating_files);
bench_default_api(howmany, std::move(rotating_st));
daily_st = spdlog::daily_logger_st("daily_st", "logs/daily_st.log");
bench_default_api(howmany, std::move(daily_st));
bench_default_api(howmany, spdlog::create<null_sink_st>("null_st"));
spdlog::info("**************************************************************");
spdlog::info("C-string. Single thread, {:n} iterations", howmany);
spdlog::info("**************************************************************");
basic_st = spdlog::basic_logger_st("basic_st", "logs/basic_cs.log", true);
bench_c_string(howmany, std::move(basic_st));
rotating_st = spdlog::rotating_logger_st("rotating_st", "logs/rotating_cs.log", file_size, rotating_files);
bench_c_string(howmany, std::move(rotating_st));
daily_st = spdlog::daily_logger_st("daily_st", "logs/daily_cs.log");
bench_c_string(howmany, std::move(daily_st));
bench_c_string(howmany, spdlog::create<null_sink_st>("null_st"));
spdlog::info("**************************************************************");
spdlog::info("{:n} threads sharing same logger, {:n} iterations", threads, howmany);
spdlog::info("**************************************************************");
auto basic_mt = spdlog::basic_logger_mt("basic_mt", "logs/basic_mt.log", true);
bench_mt(howmany, std::move(basic_mt), threads);
auto rotating_mt = spdlog::rotating_logger_mt("rotating_mt", "logs/rotating_mt.log", file_size, rotating_files);
bench_mt(howmany, std::move(rotating_mt), threads);
auto daily_mt = spdlog::daily_logger_mt("daily_mt", "logs/daily_mt.log");
bench_mt(howmany, std::move(daily_mt), threads);
bench_mt(howmany, spdlog::create<null_sink_mt>("null_mt"), threads);
spdlog::info("**************************************************************");
spdlog::info("Asyncronous.. {:n} threads sharing same logger, {:n} iterations", threads, howmany);
spdlog::info("**************************************************************");
for (int i = 0; i < 3; ++i)
{
spdlog::init_thread_pool(static_cast<size_t>(queue_size), 1);
auto as = spdlog::basic_logger_mt<spdlog::async_factory>("async", "logs/basic_async.log", true);
bench_mt(howmany, std::move(as), threads);
}
}
catch (std::exception &ex)
{
spdlog::error(ex.what());
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
void bench(int howmany, std::shared_ptr<spdlog::logger> log)
{
using std::chrono::high_resolution_clock;
auto start = high_resolution_clock::now();
for (auto i = 0; i < howmany; ++i)
{
log->info("Hello logger: msg number {}", i);
}
auto delta = high_resolution_clock::now() - start;
auto delta_d = duration_cast<duration<double>>(delta).count();
spdlog::info("{:<16} Elapsed: {:0.2f} secs {:>16n}/sec", log->name(), delta_d, int(howmany / delta_d));
spdlog::drop(log->name());
}
void bench_mt(int howmany, std::shared_ptr<spdlog::logger> log, int thread_count)
{
using std::chrono::high_resolution_clock;
vector<thread> threads;
auto start = high_resolution_clock::now();
for (int t = 0; t < thread_count; ++t)
{
threads.push_back(std::thread([&]() {
for (int j = 0; j < howmany / thread_count; j++)
{
log->info("Hello logger: msg number {}", j);
}
}));
}
for (auto &t : threads)
{
t.join();
};
auto delta = high_resolution_clock::now() - start;
auto delta_d = duration_cast<duration<double>>(delta).count();
spdlog::info("{:<16} Elapsed: {:0.2f} secs {:>16n}/sec", log->name(), delta_d, int(howmany / delta_d));
spdlog::drop(log->name());
}
void bench_default_api(int howmany, std::shared_ptr<spdlog::logger> log)
{
using std::chrono::high_resolution_clock;
auto orig_default = spdlog::default_logger();
spdlog::set_default_logger(log);
auto start = high_resolution_clock::now();
for (auto i = 0; i < howmany; ++i)
{
spdlog::info("Hello logger: msg number {}", i);
}
auto delta = high_resolution_clock::now() - start;
auto delta_d = duration_cast<duration<double>>(delta).count();
spdlog::drop(log->name());
spdlog::set_default_logger(std::move(orig_default));
spdlog::info("{:<16} Elapsed: {:0.2f} secs {:>16n}/sec", log->name(), delta_d, int(howmany / delta_d));
}
void bench_c_string(int howmany, std::shared_ptr<spdlog::logger> log)
{
const char *msg = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum pharetra metus cursus "
"lacus placerat congue. Nulla egestas, mauris a tincidunt tempus, enim lectus volutpat mi, eu consequat sem "
"libero nec massa. In dapibus ipsum a diam rhoncus gravida. Etiam non dapibus eros. Donec fringilla dui sed "
"augue pretium, nec scelerisque est maximus. Nullam convallis, sem nec blandit maximus, nisi turpis ornare "
"nisl, sit amet volutpat neque massa eu odio. Maecenas malesuada quam ex, posuere congue nibh turpis duis.";
using std::chrono::high_resolution_clock;
auto orig_default = spdlog::default_logger();
spdlog::set_default_logger(log);
auto start = high_resolution_clock::now();
for (auto i = 0; i < howmany; ++i)
{
spdlog::log(level::info, msg);
}
auto delta = high_resolution_clock::now() - start;
auto delta_d = duration_cast<duration<double>>(delta).count();
spdlog::drop(log->name());
spdlog::set_default_logger(std::move(orig_default));
spdlog::info("{:<16} Elapsed: {:0.2f} secs {:>16n}/sec", log->name(), delta_d, int(howmany / delta_d));
}
<commit_msg>bench C-string title<commit_after>//
// Copyright(c) 2015 Gabi Melman.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
//
// bench.cpp : spdlog benchmarks
//
#include "spdlog/spdlog.h"
#include "spdlog/async.h"
#include "spdlog/sinks/basic_file_sink.h"
#include "spdlog/sinks/daily_file_sink.h"
#include "spdlog/sinks/null_sink.h"
#include "spdlog/sinks/rotating_file_sink.h"
#include "utils.h"
#include <atomic>
#include <cstdlib> // EXIT_FAILURE
#include <memory>
#include <string>
#include <thread>
using namespace std;
using namespace std::chrono;
using namespace spdlog;
using namespace spdlog::sinks;
using namespace utils;
void bench(int howmany, std::shared_ptr<spdlog::logger> log);
void bench_mt(int howmany, std::shared_ptr<spdlog::logger> log, int thread_count);
void bench_default_api(int howmany, std::shared_ptr<spdlog::logger> log);
void bench_c_string(int howmany, std::shared_ptr<spdlog::logger> log);
int main(int argc, char *argv[])
{
spdlog::default_logger()->set_pattern("[%^%l%$] %v");
int howmany = 1000000;
int queue_size = howmany + 2;
int threads = 10;
size_t file_size = 30 * 1024 * 1024;
size_t rotating_files = 5;
try
{
if (argc > 1)
howmany = atoi(argv[1]);
if (argc > 2)
threads = atoi(argv[2]);
if (argc > 3)
queue_size = atoi(argv[3]);
spdlog::info("**************************************************************");
spdlog::info("Single thread, {:n} iterations", howmany);
spdlog::info("**************************************************************");
auto basic_st = spdlog::basic_logger_st("basic_st", "logs/basic_st.log", true);
bench(howmany, std::move(basic_st));
basic_st.reset();
auto rotating_st = spdlog::rotating_logger_st("rotating_st", "logs/rotating_st.log", file_size, rotating_files);
bench(howmany, std::move(rotating_st));
auto daily_st = spdlog::daily_logger_st("daily_st", "logs/daily_st.log");
bench(howmany, std::move(daily_st));
bench(howmany, spdlog::create<null_sink_st>("null_st"));
spdlog::info("**************************************************************");
spdlog::info("Default API. Single thread, {:n} iterations", howmany);
spdlog::info("**************************************************************");
basic_st = spdlog::basic_logger_st("basic_st", "logs/basic_st.log", true);
bench_default_api(howmany, std::move(basic_st));
rotating_st = spdlog::rotating_logger_st("rotating_st", "logs/rotating_st.log", file_size, rotating_files);
bench_default_api(howmany, std::move(rotating_st));
daily_st = spdlog::daily_logger_st("daily_st", "logs/daily_st.log");
bench_default_api(howmany, std::move(daily_st));
bench_default_api(howmany, spdlog::create<null_sink_st>("null_st"));
spdlog::info("**************************************************************");
spdlog::info("C-string (500 bytes). Single thread, {:n} iterations", howmany);
spdlog::info("**************************************************************");
basic_st = spdlog::basic_logger_st("basic_st", "logs/basic_cs.log", true);
bench_c_string(howmany, std::move(basic_st));
rotating_st = spdlog::rotating_logger_st("rotating_st", "logs/rotating_cs.log", file_size, rotating_files);
bench_c_string(howmany, std::move(rotating_st));
daily_st = spdlog::daily_logger_st("daily_st", "logs/daily_cs.log");
bench_c_string(howmany, std::move(daily_st));
bench_c_string(howmany, spdlog::create<null_sink_st>("null_st"));
spdlog::info("**************************************************************");
spdlog::info("{:n} threads sharing same logger, {:n} iterations", threads, howmany);
spdlog::info("**************************************************************");
auto basic_mt = spdlog::basic_logger_mt("basic_mt", "logs/basic_mt.log", true);
bench_mt(howmany, std::move(basic_mt), threads);
auto rotating_mt = spdlog::rotating_logger_mt("rotating_mt", "logs/rotating_mt.log", file_size, rotating_files);
bench_mt(howmany, std::move(rotating_mt), threads);
auto daily_mt = spdlog::daily_logger_mt("daily_mt", "logs/daily_mt.log");
bench_mt(howmany, std::move(daily_mt), threads);
bench_mt(howmany, spdlog::create<null_sink_mt>("null_mt"), threads);
spdlog::info("**************************************************************");
spdlog::info("Asyncronous.. {:n} threads sharing same logger, {:n} iterations", threads, howmany);
spdlog::info("**************************************************************");
for (int i = 0; i < 3; ++i)
{
spdlog::init_thread_pool(static_cast<size_t>(queue_size), 1);
auto as = spdlog::basic_logger_mt<spdlog::async_factory>("async", "logs/basic_async.log", true);
bench_mt(howmany, std::move(as), threads);
}
}
catch (std::exception &ex)
{
spdlog::error(ex.what());
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
void bench(int howmany, std::shared_ptr<spdlog::logger> log)
{
using std::chrono::high_resolution_clock;
auto start = high_resolution_clock::now();
for (auto i = 0; i < howmany; ++i)
{
log->info("Hello logger: msg number {}", i);
}
auto delta = high_resolution_clock::now() - start;
auto delta_d = duration_cast<duration<double>>(delta).count();
spdlog::info("{:<16} Elapsed: {:0.2f} secs {:>16n}/sec", log->name(), delta_d, int(howmany / delta_d));
spdlog::drop(log->name());
}
void bench_mt(int howmany, std::shared_ptr<spdlog::logger> log, int thread_count)
{
using std::chrono::high_resolution_clock;
vector<thread> threads;
auto start = high_resolution_clock::now();
for (int t = 0; t < thread_count; ++t)
{
threads.push_back(std::thread([&]() {
for (int j = 0; j < howmany / thread_count; j++)
{
log->info("Hello logger: msg number {}", j);
}
}));
}
for (auto &t : threads)
{
t.join();
};
auto delta = high_resolution_clock::now() - start;
auto delta_d = duration_cast<duration<double>>(delta).count();
spdlog::info("{:<16} Elapsed: {:0.2f} secs {:>16n}/sec", log->name(), delta_d, int(howmany / delta_d));
spdlog::drop(log->name());
}
void bench_default_api(int howmany, std::shared_ptr<spdlog::logger> log)
{
using std::chrono::high_resolution_clock;
auto orig_default = spdlog::default_logger();
spdlog::set_default_logger(log);
auto start = high_resolution_clock::now();
for (auto i = 0; i < howmany; ++i)
{
spdlog::info("Hello logger: msg number {}", i);
}
auto delta = high_resolution_clock::now() - start;
auto delta_d = duration_cast<duration<double>>(delta).count();
spdlog::drop(log->name());
spdlog::set_default_logger(std::move(orig_default));
spdlog::info("{:<16} Elapsed: {:0.2f} secs {:>16n}/sec", log->name(), delta_d, int(howmany / delta_d));
}
void bench_c_string(int howmany, std::shared_ptr<spdlog::logger> log)
{
const char *msg = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum pharetra metus cursus "
"lacus placerat congue. Nulla egestas, mauris a tincidunt tempus, enim lectus volutpat mi, eu consequat sem "
"libero nec massa. In dapibus ipsum a diam rhoncus gravida. Etiam non dapibus eros. Donec fringilla dui sed "
"augue pretium, nec scelerisque est maximus. Nullam convallis, sem nec blandit maximus, nisi turpis ornare "
"nisl, sit amet volutpat neque massa eu odio. Maecenas malesuada quam ex, posuere congue nibh turpis duis.";
using std::chrono::high_resolution_clock;
auto orig_default = spdlog::default_logger();
spdlog::set_default_logger(log);
auto start = high_resolution_clock::now();
for (auto i = 0; i < howmany; ++i)
{
spdlog::log(level::info, msg);
}
auto delta = high_resolution_clock::now() - start;
auto delta_d = duration_cast<duration<double>>(delta).count();
spdlog::drop(log->name());
spdlog::set_default_logger(std::move(orig_default));
spdlog::info("{:<16} Elapsed: {:0.2f} secs {:>16n}/sec", log->name(), delta_d, int(howmany / delta_d));
}
<|endoftext|>
|
<commit_before>/* ---------------------------------------------------------------------
* Numenta Platform for Intelligent Computing (NuPIC)
* Copyright (C) 2013, Numenta, Inc. Unless you have an agreement
* with Numenta, Inc., for a separate license for this software code, the
* following terms and conditions apply:
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*
* http://numenta.org/licenses/
* ----------------------------------------------------------------------
*/
/** @file
* Definitions for the Spatial Pooler
*/
#ifndef NTA_spatial_pooler_HPP
#define NTA_spatial_pooler_HPP
#include <cstring>
#include <iostream>
#include <nta/math/SparseBinaryMatrix.hpp>
#include <nta/math/SparseMatrix.hpp>
#include <nta/types/types.hpp>
#include <string>
#include <vector>
using namespace std;
namespace nta {
namespace algorithms {
namespace spatial_pooler {
/////////////////////////////////////////////////////////////////////////
/// CLA spatial pooler implementation in C++.
///
/// @b Responsibility
/// The Spatial Pooler is responsible for creating a sparse distributed
/// representation of the input. It computes the set of active columns.
/// It maintains the state of the proximal dendrites between the columns
/// and the inputs bits and keeps track of the activity and overlap
/// duty cycles
///
/// @b Description
/// Todo.
///
/////////////////////////////////////////////////////////////////////////
class SpatialPooler {
public:
SpatialPooler();
~SpatialPooler() {}
virtual UInt version() const {
return version_;
};
virtual void compute(UInt inputVector[], bool learn,
UInt activeVector[]);
virtual void save(ostream& outStream);
virtual void load(istream& inStream);
virtual UInt persistentSize();
UInt getNumColumns();
UInt getNumInputs();
UInt getPotentialRadius();
void setPotentialRadius(UInt potentialRadius);
Real getPotentialPct();
void setPotentialPct(Real potentialPct);
bool getGlobalInhibition();
void setGlobalInhibition(bool globalInhibition);
Int getNumActiveColumnsPerInhArea();
void setNumActiveColumnsPerInhArea(UInt numActiveColumnsPerInhArea);
Real getLocalAreaDensity();
void setLocalAreaDensity(Real localAreaDensity);
UInt getStimulusThreshold();
void setStimulusThreshold(UInt stimulusThreshold);
UInt getInhibitionRadius();
void setInhibitionRadius(UInt inhibitionRadius);
UInt getDutyCyclePeriod();
void setDutyCyclePeriod(UInt dutyCyclePeriod);
Real getMaxBoost();
void setMaxBoost(Real maxBoost);
UInt getIterationNum();
void setIterationNum(UInt iterationNum);
UInt getIterationLearnNum();
void setIterationLearnNum(UInt iterationLearnNum);
UInt getSpVerbosity();
void setSpVerbosity(UInt spVerbosity);
UInt getUpdatePeriod();
void setUpdatePeriod(UInt updatePeriod);
Real getSynPermTrimThreshold();
void setSynPermTrimThreshold(Real synPermTrimThreshold);
Real getSynPermActiveInc();
void setSynPermActiveInc(Real synPermActiveInc);
Real getSynPermInactiveDec();
void setSynPermInactiveDec(Real synPermInactiveDec);
Real getSynPermBelowStimulusInc();
void setSynPermBelowStimulusInc(Real synPermBelowStimulusInc);
Real getSynPermConnected();
void setSynPermConnected(Real setSynPermConnected);
Real getMinPctOverlapDutyCycles();
void setMinPctOverlapDutyCycles(Real minPctOverlapDutyCycles);
Real getMinPctActiveDutyCycles();
void setMinPctActiveDutyCycles(Real minPctActiveDutyCycles);
void getBoostFactors(Real boostFactors[]);
void setBoostFactors(Real boostFactors[]);
void getOverlapDutyCycles(Real overlapDutyCycles[]);
void setOverlapDutyCycles(Real overlapDutyCycles[]);
void getActiveDutyCycles(Real activeDutyCycles[]);
void setActiveDutyCycles(Real activeDutyCycles[]);
void getMinOverlapDutyCycles(Real minOverlapDutyCycles[]);
void setMinOverlapDutyCycles(Real minOverlapDutyCycles[]);
void getMinActiveDutyCycles(Real minActiveDutyCycles[]);
void setMinActiveDutyCycles(Real minActiveDutyCycles[]);
void getPotential(UInt column, UInt potential[]);
void setPotential(UInt column, UInt potential[]);
void getPermanence(UInt column, Real permanence[]);
void setPermanence(UInt column, Real permanence[]);
void getConnectedSynapses(UInt column, UInt connectedSynapses[]);
void getConnectedCounts(UInt connectedCounts[]);
// Implementation methods. all methods below this line are
// NOT part of the public API
void stripNeverLearned_(UInt activeArray[]);
void toDense_(vector<UInt>& sparse,
UInt dense[],
UInt n);
void boostOverlaps_(vector<UInt>& overlaps,
vector<Real>& boostedOverlaps);
void range_(Int start, Int end, UInt ubound, bool wrapAround,
vector<UInt>& rangeVector);
vector<UInt> mapPotential1D_(UInt column, bool wrapAround);
Real initPermConnected_();
Real initPermNonConnected_();
vector<Real> initPermanence_(vector<UInt>& potential,
Real connectedPct);
void clip_(vector<Real>& perm, bool trim);
void updatePermanencesForColumn_(vector<Real>& perm, UInt column,
bool raisePerm=true);
UInt countConnected_(vector<Real>& perm);
UInt raisePermanencesToThreshold_(vector<Real>& perm,
vector<UInt>& potential);
void calculateOverlap_(UInt inputVector[],
vector<UInt>& overlap);
void calculateOverlapPct_(vector<UInt>& overlaps,
vector<Real>& overlapPct);
bool isWinner_(Real score, vector<pair<UInt, Real> >& winners,
UInt numWinners);
void addToWinners_(UInt index, Real score,
vector<pair<UInt, Real> >& winners);
void inhibitColumns_(vector<Real>& overlaps,
vector<UInt>& activeColumns);
void inhibitColumnsGlobal_(vector<Real>& overlaps, Real density,
vector<UInt>& activeColumns);
void inhibitColumnsLocal_(vector<Real>& overlaps, Real density,
vector<UInt>& activeColumns);
void getNeighbors1D_(UInt column, vector<UInt>& dimensions,
UInt radius, bool wrapAround,
vector<UInt>& neighbors);
void getNeighbors2D_(UInt column, vector<UInt>& dimensions,
UInt radius, bool wrapAround,
vector<UInt>& neighbors);
void cartesianProduct_(vector<vector<UInt> >& vecs,
vector<vector<UInt> >& product);
void getNeighborsND_(UInt column, vector<UInt>& dimensions,
UInt radius, bool wrapAround,
vector<UInt>& neighbors);
void adaptSynapses_(UInt inputVector[],
vector<UInt>& activeColumns);
void bumpUpWeakColumns_();
void updateInhibitionRadius_();
Real avgColumnsPerInput_();
Real avgConnectedSpanForColumn1D_(UInt column);
Real avgConnectedSpanForColumn2D_(UInt column);
Real avgConnectedSpanForColumnND_(UInt column);
void updateMinDutyCycles_();
void updateMinDutyCyclesGlobal_();
void updateMinDutyCyclesLocal_();
static void updateDutyCyclesHelper_(vector<Real>& dutyCycles,
vector<UInt>& newValues,
UInt period);
void updateDutyCycles_(vector<UInt>& overlaps,
UInt activeArray[]);
void updateBoostFactors_();
void updateBookeepingVars_(bool learn);
bool isUpdateRound_();
virtual void initialize(vector<UInt> inputDimensions,
vector<UInt> columnDimensions,
UInt potentialRadius=16,
Real potentialPct=0.5,
bool globalInhibition=true,
Real localAreaDensity=-1.0,
UInt numActiveColumnsPerInhArea=10,
UInt stimulusThreshold=0,
Real synPermInactiveDec=0.01,
Real synPermActiveInc=0.1,
Real synPermConnected=0.1,
Real minPctOverlapDutyCycles=0.001,
Real minPctActiveDutyCycles=0.001,
UInt dutyCyclePeriod=1000,
Real maxBoost=10.0,
Int seed=1,
UInt spVerbosity=0);
void seed_(UInt64 seed);
//-------------------------------------------------------------------
// Debugging helpers
//-------------------------------------------------------------------
// Print the main SP creation parameters
void printParameters();
// Print the given UInt array in a nice format
void printState(vector<UInt> &state);
// Print the given Real array in a nice format
void printState(vector<Real> &state);
protected:
UInt numInputs_;
UInt numColumns_;
vector<UInt> columnDimensions_;
vector<UInt> inputDimensions_;
UInt potentialRadius_;
Real potentialPct_;
Real initConnectedPct_;
bool globalInhibition_;
Int numActiveColumnsPerInhArea_;
Real localAreaDensity_;
UInt stimulusThreshold_;
UInt inhibitionRadius_;
UInt dutyCyclePeriod_;
Real maxBoost_;
UInt iterationNum_;
UInt iterationLearnNum_;
UInt spVerbosity_;
UInt updatePeriod_;
Real synPermMin_;
Real synPermMax_;
Real synPermTrimThreshold_;
Real synPermInactiveDec_;
Real synPermActiveInc_;
Real synPermBelowStimulusInc_;
Real synPermConnected_;
vector<Real> boostFactors_;
vector<Real> overlapDutyCycles_;
vector<Real> activeDutyCycles_;
vector<Real> minOverlapDutyCycles_;
vector<Real> minActiveDutyCycles_;
Real minPctOverlapDutyCycles_;
Real minPctActiveDutyCycles_;
SparseMatrix<UInt,Real,Int,Real64> permanences_;
SparseBinaryMatrix<UInt,UInt> potentialPools_;
SparseBinaryMatrix<UInt, UInt> connectedSynapses_;
vector<UInt> connectedCounts_;
vector<UInt> overlaps_;
vector<Real> overlapsPct_;
vector<Real> boostedOverlaps_;
vector<UInt> activeColumns_;
vector<Real> tieBreaker_;
UInt version_;
Random rng_;
};
} // end namespace spatial_pooler
} // end namespace algorithms
} // end namespace nta
#endif // NTA_spatial_pooler_HPP
<commit_msg>Added initial documentation<commit_after>/* ---------------------------------------------------------------------
* Numenta Platform for Intelligent Computing (NuPIC)
* Copyright (C) 2013, Numenta, Inc. Unless you have an agreement
* with Numenta, Inc., for a separate license for this software code, the
* following terms and conditions apply:
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*
* http://numenta.org/licenses/
* ----------------------------------------------------------------------
*/
/** @file
* Definitions for the Spatial Pooler
*/
#ifndef NTA_spatial_pooler_HPP
#define NTA_spatial_pooler_HPP
#include <cstring>
#include <iostream>
#include <nta/math/SparseBinaryMatrix.hpp>
#include <nta/math/SparseMatrix.hpp>
#include <nta/types/types.hpp>
#include <string>
#include <vector>
using namespace std;
namespace nta {
namespace algorithms {
namespace spatial_pooler {
/**
* CLA spatial pooler implementation in C++.
*
* ### Description
* The Spatial Pooler is responsible for creating a sparse distributed
* representation of the input. Given an input it computes a set of sparse
* active columns and simultaneously updates its permanences, duty cycles,
* etc.
*
* The primary public interfaces to this function are the "initialize"
* and "compute" methods.
*
* Example usage:
*
* SpatialPooler sp;
* sp.initialize(inputDimensions, columnDimensions, <parameters>);
* while (true) {
* <get input vector>
* sp.compute(inputVector, learn, activeColumns)
* <do something with output>
* }
*
*/
class SpatialPooler {
public:
SpatialPooler();
~SpatialPooler() {}
/**
Initialize the spatial pooler using the given parameters.
@param inputDimensions A list of integers representing the
dimensions of the input vector. Format is [height, width,
depth, ...], where each value represents the size of the
dimension. For a topology of one dimesion with 100 inputs
use [100]. For a two dimensional topology of 10x5
use [10,5].
@param columnDimensions A list of integers representing the
dimensions of the columns in the region. Format is [height,
width, depth, ...], where each value represents the size of
the dimension. For a topology of one dimesion with 2000
columns use 2000, or [2000]. For a three dimensional
topology of 32x64x16 use [32, 64, 16].
@param potentialRadius This parameter deteremines the extent of the
input that each column can potentially be connected to. This
can be thought of as the input bits that are visible to each
column, or a 'receptive field' of the field of vision. A large
enough value will result in global coverage, meaning
that each column can potentially be connected to every input
bit. This parameter defines a square (or hyper square) area: a
column will have a max square potential pool with sides of
length (2 * potentialRadius + 1).
@param potentialPct The percent of the inputs, within a column's
potential radius, that a column can be connected to. If set to
1, the column will be connected to every input within its
potential radius. This parameter is used to give each column a
unique potential pool when a large potentialRadius causes
overlap between the columns. At initialization time we choose
((2*potentialRadius + 1)^(# inputDimensions) * potentialPct)
input bits to comprise the column's potential pool.
@param globalInhibition If true, then during inhibition phase the
winning columns are selected as the most active columns from the
region as a whole. Otherwise, the winning columns are selected
with resepct to their local neighborhoods. Global inhibition
boosts performance significantly but there is no topology at the
output.
@param localAreaDensity The desired density of active columns within
a local inhibition area (the size of which is set by the
internally calculated inhibitionRadius, which is in turn
determined from the average size of the connected potential
pools of all columns). The inhibition logic will insure that at
most N columns remain ON within a local inhibition area, where
N = localAreaDensity * (total number of columns in inhibition
area). If localAreaDensity is set to a negative value output
sparsity will be determined by the numActivePerInhArea.
@param numActivePerInhArea An alternate way to control the sparsity of
active columns. If numActivePerInhArea is specified then
localAreaDensity must less than 0, and vice versa. When
numActivePerInhArea > 0, the inhibition logic will insure that
at most 'numActivePerInhArea' columns remain ON within a local
inhibition area (the size of which is set by the internally
calculated inhibitionRadius). When using this method, as columns
learn and grow their effective receptive fields, the
inhibitionRadius will grow, and hence the net density of the
active columns will *decrease*. This is in contrast to the
localAreaDensity method, which keeps the density of active
columns the same regardless of the size of their receptive
fields.
@param stimulusThreshold This is a number specifying the minimum
number of synapses that must be active in order for a column to
turn ON. The purpose of this is to prevent noisy input from
activating columns.
@param synPermInactiveDec The amount by which the permanence of an
inactive synapse is decremented in each learning step.
@param synPermActiveInc The amount by which the permanence of an
active synapse is incremented in each round.
@param synPermConnected The default connected threshold. Any synapse
whose permanence value is above the connected threshold is
a "connected synapse", meaning it can contribute to
the cell's firing.
@param minPctOvlerapDutyCycle A number between 0 and 1.0, used to set
a floor on how often a column should have at least
stimulusThreshold active inputs. Periodically, each column looks
at the overlap duty cycle of all other column within its
inhibition radius and sets its own internal minimal acceptable
duty cycle to: minPctDutyCycleBeforeInh * max(other columns'
duty cycles). On each iteration, any column whose overlap duty
cycle falls below this computed value will get all of its
permanence values boosted up by synPermActiveInc. Raising all
permanences in response to a sub-par duty cycle before
inhibition allows a cell to search for new inputs when either
its previously learned inputs are no longer ever active, or when
the vast majority of them have been "hijacked" by other columns.
@param minPctActiveDutyCycle A number between 0 and 1.0, used to set
a floor on how often a column should be activate. Periodically,
each column looks at the activity duty cycle of all other
columns within its inhibition radius and sets its own internal
minimal acceptable duty cycle to:
minPctDutyCycleAfterInh * max(other columns' duty cycles).
On each iteration, any column whose duty cycle after inhibition
falls below this computed value will get its internal boost
factor increased.
@param dutyCyclePeriod The period used to calculate duty cycles.
Higher values make it take longer to respond to changes in
boost. Shorter values make it potentially more unstable and
likely to oscillate.
@param maxBoost The maximum overlap boost factor. Each column's
overlap gets multiplied by a boost factor before it gets
considered for inhibition. The actual boost factor for a column
is a number between 1.0 and maxBoost. A boost factor of 1.0 is
used if the duty cycle is >= minOverlapDutyCycle, maxBoost is
used if the duty cycle is 0, and any duty cycle in between is
linearly extrapolated from these 2 endpoints.
@param seed Seed for our random number generator. If seed is < 0
a randomly generated seed is used. The behavior of the spatial
pooler is deterministic once the seed is set.
@param spVerbosity spVerbosity level: 0, 1, 2, or 3
*/
virtual void initialize(vector<UInt> inputDimensions,
vector<UInt> columnDimensions,
UInt potentialRadius=16,
Real potentialPct=0.5,
bool globalInhibition=true,
Real localAreaDensity=-1.0,
UInt numActiveColumnsPerInhArea=10,
UInt stimulusThreshold=0,
Real synPermInactiveDec=0.01,
Real synPermActiveInc=0.1,
Real synPermConnected=0.1,
Real minPctOverlapDutyCycles=0.001,
Real minPctActiveDutyCycles=0.001,
UInt dutyCyclePeriod=1000,
Real maxBoost=10.0,
Int seed=1,
UInt spVerbosity=0);
/**
This is the main workshorse method of the SpatialPooler class. This
method takes an input vector and computes the set of output active
columns. If 'learn' is set to True, this method also performs
learning.
@param inputVector An array of integer 0's and 1's that comprises
the input to the spatial pooler. The length of the
array must match the total number of input bits implied by
the constructor (also returned by the method getNumInputs). In
cases where the input is multi-dimensional, inputVector is a
flattened array of inputs.
@param learn A boolean value indicating whether learning should be
performed. Learning entails updating the permanence values of
the synapses, duty cycles, etc. Learning is typically on but
setting learning to 'off' is useful for analyzing the current
state of the SP. For example, you might want to feed in various
inputs and examine the resulting SDR's. Note that if learning
is off, boosting is turned off and columns that have never won
will be removed from activeVector. TODO: we may want to keep
boosting on even when learning is off.
@param activeArray An array representing the winning columns after
inhinition. The size of the array is equal to the number of
columns (also returned by the method getNumColumns). This array
will be populated with 1's at the indices of the active columns,
and 0's everywhere else. In the case where the output is
multi-dimensional, activeVector represents a flattened array
of outputs.
*/
virtual void compute(UInt inputVector[], bool learn,
UInt activeVector[]);
/**
* Get the version number of this spatial pooler
* @returns Integer version number
*/
virtual UInt version() const {
return version_;
};
/**
Save (serialize) the current state of the spatial pooler to the
specified output stream.
@param outStream A valid ostream.
*/
virtual void save(ostream& outStream);
/**
Load (deserialize) and initialize the spatial pooler from the
specified input stream.
@param inStream A valid istream.
*/
virtual void load(istream& inStream);
/**
Returns the number of bytes that a save operation would result in.
Note: this method is currently somewhat inefficient as it just does
a full save into an ostream and counts the resulting size.
@returns Integer number of bytes
*/
virtual UInt persistentSize();
UInt getNumColumns();
UInt getNumInputs();
UInt getPotentialRadius();
void setPotentialRadius(UInt potentialRadius);
Real getPotentialPct();
void setPotentialPct(Real potentialPct);
bool getGlobalInhibition();
void setGlobalInhibition(bool globalInhibition);
Int getNumActiveColumnsPerInhArea();
void setNumActiveColumnsPerInhArea(UInt numActiveColumnsPerInhArea);
Real getLocalAreaDensity();
void setLocalAreaDensity(Real localAreaDensity);
UInt getStimulusThreshold();
void setStimulusThreshold(UInt stimulusThreshold);
UInt getInhibitionRadius();
void setInhibitionRadius(UInt inhibitionRadius);
UInt getDutyCyclePeriod();
void setDutyCyclePeriod(UInt dutyCyclePeriod);
Real getMaxBoost();
void setMaxBoost(Real maxBoost);
UInt getIterationNum();
void setIterationNum(UInt iterationNum);
UInt getIterationLearnNum();
void setIterationLearnNum(UInt iterationLearnNum);
UInt getSpVerbosity();
void setSpVerbosity(UInt spVerbosity);
UInt getUpdatePeriod();
void setUpdatePeriod(UInt updatePeriod);
Real getSynPermTrimThreshold();
void setSynPermTrimThreshold(Real synPermTrimThreshold);
Real getSynPermActiveInc();
void setSynPermActiveInc(Real synPermActiveInc);
Real getSynPermInactiveDec();
void setSynPermInactiveDec(Real synPermInactiveDec);
Real getSynPermBelowStimulusInc();
void setSynPermBelowStimulusInc(Real synPermBelowStimulusInc);
Real getSynPermConnected();
void setSynPermConnected(Real setSynPermConnected);
Real getMinPctOverlapDutyCycles();
void setMinPctOverlapDutyCycles(Real minPctOverlapDutyCycles);
Real getMinPctActiveDutyCycles();
void setMinPctActiveDutyCycles(Real minPctActiveDutyCycles);
void getBoostFactors(Real boostFactors[]);
void setBoostFactors(Real boostFactors[]);
void getOverlapDutyCycles(Real overlapDutyCycles[]);
void setOverlapDutyCycles(Real overlapDutyCycles[]);
void getActiveDutyCycles(Real activeDutyCycles[]);
void setActiveDutyCycles(Real activeDutyCycles[]);
void getMinOverlapDutyCycles(Real minOverlapDutyCycles[]);
void setMinOverlapDutyCycles(Real minOverlapDutyCycles[]);
void getMinActiveDutyCycles(Real minActiveDutyCycles[]);
void setMinActiveDutyCycles(Real minActiveDutyCycles[]);
void getPotential(UInt column, UInt potential[]);
void setPotential(UInt column, UInt potential[]);
void getPermanence(UInt column, Real permanence[]);
void setPermanence(UInt column, Real permanence[]);
void getConnectedSynapses(UInt column, UInt connectedSynapses[]);
void getConnectedCounts(UInt connectedCounts[]);
/**
Print the main SP creation parameters to stdout.
*/
void printParameters();
///////////////////////////////////////////////////////////
//
// Implementation methods. all methods below this line are
// NOT part of the public API
void stripNeverLearned_(UInt activeArray[]);
void toDense_(vector<UInt>& sparse,
UInt dense[],
UInt n);
void boostOverlaps_(vector<UInt>& overlaps,
vector<Real>& boostedOverlaps);
void range_(Int start, Int end, UInt ubound, bool wrapAround,
vector<UInt>& rangeVector);
vector<UInt> mapPotential1D_(UInt column, bool wrapAround);
Real initPermConnected_();
Real initPermNonConnected_();
vector<Real> initPermanence_(vector<UInt>& potential,
Real connectedPct);
void clip_(vector<Real>& perm, bool trim);
void updatePermanencesForColumn_(vector<Real>& perm, UInt column,
bool raisePerm=true);
UInt countConnected_(vector<Real>& perm);
UInt raisePermanencesToThreshold_(vector<Real>& perm,
vector<UInt>& potential);
void calculateOverlap_(UInt inputVector[],
vector<UInt>& overlap);
void calculateOverlapPct_(vector<UInt>& overlaps,
vector<Real>& overlapPct);
bool isWinner_(Real score, vector<pair<UInt, Real> >& winners,
UInt numWinners);
void addToWinners_(UInt index, Real score,
vector<pair<UInt, Real> >& winners);
void inhibitColumns_(vector<Real>& overlaps,
vector<UInt>& activeColumns);
void inhibitColumnsGlobal_(vector<Real>& overlaps, Real density,
vector<UInt>& activeColumns);
void inhibitColumnsLocal_(vector<Real>& overlaps, Real density,
vector<UInt>& activeColumns);
void getNeighbors1D_(UInt column, vector<UInt>& dimensions,
UInt radius, bool wrapAround,
vector<UInt>& neighbors);
void getNeighbors2D_(UInt column, vector<UInt>& dimensions,
UInt radius, bool wrapAround,
vector<UInt>& neighbors);
void cartesianProduct_(vector<vector<UInt> >& vecs,
vector<vector<UInt> >& product);
void getNeighborsND_(UInt column, vector<UInt>& dimensions,
UInt radius, bool wrapAround,
vector<UInt>& neighbors);
void adaptSynapses_(UInt inputVector[],
vector<UInt>& activeColumns);
void bumpUpWeakColumns_();
void updateInhibitionRadius_();
Real avgColumnsPerInput_();
Real avgConnectedSpanForColumn1D_(UInt column);
Real avgConnectedSpanForColumn2D_(UInt column);
Real avgConnectedSpanForColumnND_(UInt column);
void updateMinDutyCycles_();
void updateMinDutyCyclesGlobal_();
void updateMinDutyCyclesLocal_();
static void updateDutyCyclesHelper_(vector<Real>& dutyCycles,
vector<UInt>& newValues,
UInt period);
void updateDutyCycles_(vector<UInt>& overlaps,
UInt activeArray[]);
void updateBoostFactors_();
void updateBookeepingVars_(bool learn);
bool isUpdateRound_();
void seed_(UInt64 seed);
//-------------------------------------------------------------------
// Debugging helpers
//-------------------------------------------------------------------
// Print the given UInt array in a nice format
void printState(vector<UInt> &state);
// Print the given Real array in a nice format
void printState(vector<Real> &state);
protected:
UInt numInputs_;
UInt numColumns_;
vector<UInt> columnDimensions_;
vector<UInt> inputDimensions_;
UInt potentialRadius_;
Real potentialPct_;
Real initConnectedPct_;
bool globalInhibition_;
Int numActiveColumnsPerInhArea_;
Real localAreaDensity_;
UInt stimulusThreshold_;
UInt inhibitionRadius_;
UInt dutyCyclePeriod_;
Real maxBoost_;
UInt iterationNum_;
UInt iterationLearnNum_;
UInt spVerbosity_;
UInt updatePeriod_;
Real synPermMin_;
Real synPermMax_;
Real synPermTrimThreshold_;
Real synPermInactiveDec_;
Real synPermActiveInc_;
Real synPermBelowStimulusInc_;
Real synPermConnected_;
vector<Real> boostFactors_;
vector<Real> overlapDutyCycles_;
vector<Real> activeDutyCycles_;
vector<Real> minOverlapDutyCycles_;
vector<Real> minActiveDutyCycles_;
Real minPctOverlapDutyCycles_;
Real minPctActiveDutyCycles_;
SparseMatrix<UInt,Real,Int,Real64> permanences_;
SparseBinaryMatrix<UInt,UInt> potentialPools_;
SparseBinaryMatrix<UInt, UInt> connectedSynapses_;
vector<UInt> connectedCounts_;
vector<UInt> overlaps_;
vector<Real> overlapsPct_;
vector<Real> boostedOverlaps_;
vector<UInt> activeColumns_;
vector<Real> tieBreaker_;
UInt version_;
Random rng_;
};
} // end namespace spatial_pooler
} // end namespace algorithms
} // end namespace nta
#endif // NTA_spatial_pooler_HPP
<|endoftext|>
|
<commit_before>#if defined(_QT_GUI_USED_)
#include <QPainter>
#include <QDebug>
#endif
#include <math.h>
#include "zcircle.h"
#include "tz_math.h"
#include "zintpoint.h"
const ZCircle::TVisualEffect ZCircle::VE_NONE = 0;
const ZCircle::TVisualEffect ZCircle::VE_DASH_PATTERN = 1;
const ZCircle::TVisualEffect ZCircle::VE_BOUND_BOX = 2;
const ZCircle::TVisualEffect ZCircle::VE_NO_CIRCLE = 4;
const ZCircle::TVisualEffect ZCircle::VE_NO_FILL = 8;
const ZCircle::TVisualEffect ZCircle::VE_GRADIENT_FILL = 16;
const ZCircle::TVisualEffect ZCircle::VE_OUT_FOCUS_DIM = 32;
ZCircle::ZCircle() : m_visualEffect(ZCircle::VE_NONE)
{
set(0, 0, 0, 1);
}
ZCircle::ZCircle(double x, double y, double z, double r) :
m_visualEffect(ZCircle::VE_NONE)
{
set(x, y, z, r);
}
void ZCircle::set(double x, double y, double z, double r)
{
m_center.set(x, y, z);
m_r = r;
}
void ZCircle::set(const ZIntPoint ¢er, double r)
{
set(center.getX(), center.getY(), center.getZ(), r);
}
void ZCircle::set(const ZPoint ¢er, double r)
{
set(center.x(), center.y(), center.z(), r);
}
//void ZCircle::display(QImage *image, int n, Display_Style style) const
//{
//#if defined(_QT_GUI_USED_)
// QPainter painter(image);
// painter.setPen(m_color);
// display(&painter, n, style);
//#endif
//}
void ZCircle::display(ZPainter &painter, int n,
ZStackObject::Display_Style style) const
{
if (!isVisible()) {
return;
}
UNUSED_PARAMETER(style);
#if _QT_GUI_USED_
QPen pen(m_color, getPenWidth());
pen.setCosmetic(m_usingCosmeticPen);
if (hasVisualEffect(VE_DASH_PATTERN)) {
pen.setStyle(Qt::DotLine);
}
painter.setPen(pen);
//qDebug() << "Internal color: " << m_color;
const QBrush &oldBrush = painter.brush();
if (hasVisualEffect(VE_GRADIENT_FILL)) {
QRadialGradient gradient(50, 50, 50, 50, 50);
gradient.setColorAt(0, QColor::fromRgbF(0, 1, 0, 1));
gradient.setColorAt(1, QColor::fromRgbF(0, 0, 0, 0));
/*
QBrush brush(gradient);
brush.setColor(m_color);
brush.setStyle(Qt::RadialGradientPattern);
painter.setBrush(brush);
*/
//painter.setBrush(m_color);
//painter.setBrush(QBrush(m_color, Qt::RadialGradientPattern));
} else {
if (hasVisualEffect(VE_NO_FILL)) {
painter.setBrush(Qt::NoBrush);
}
}
displayHelper(&painter, n, style);
painter.setBrush(oldBrush);
#endif
}
bool ZCircle::isCuttingPlane(double z, double r, double n)
{
double h = fabs(z - n);
if (r > h) {
return true;
} else if (iround(z) == iround(n)) {
return true;
}
return false;
}
bool ZCircle::isCuttingPlane(double n)
{
return isCuttingPlane(m_center.z(), m_r, n);
}
double ZCircle::getAdjustedRadius(double r) const
{
double adjustedRadius = r;
if (!m_usingCosmeticPen) {
adjustedRadius += getPenWidth() * 0.5;
}
return adjustedRadius;
}
void ZCircle::displayHelper(ZPainter *painter, int stackFocus, Display_Style style) const
{
UNUSED_PARAMETER(style);
#if defined(_QT_GUI_USED_)
double adjustedRadius = getAdjustedRadius(m_r);
double dataFocus = stackFocus - painter->getOffset().z();
bool visible = false;
double alpha = 1.0;
if (stackFocus == -1) {
visible = true;
} else {
if (isCuttingPlane(m_center.z(), m_r, dataFocus)) {
double h = fabs(m_center.z() - dataFocus);
double r = 0.0;
if (m_r > h) {
r = sqrt(m_r * m_r - h * h);
adjustedRadius = getAdjustedRadius(r);
//adjustedRadius = r + getPenWidth() * 0.5;
visible = true;
} else { //too small, show at least one plane
//adjustedRadius = getPenWidth() * 0.5;
r = 0.1;
adjustedRadius = getAdjustedRadius(r);
visible = true;
}
if (hasVisualEffect(VE_OUT_FOCUS_DIM)) {
alpha = r / m_r;
alpha *= alpha;
}
}
}
if (visible) {
if (!hasVisualEffect(VE_NO_CIRCLE)) {
//qDebug() << painter->brush().color();
QColor color = painter->pen().color();
color.setAlphaF(alpha);
painter->setPen(color);
painter->drawEllipse(QPointF(m_center.x(), m_center.y()),
adjustedRadius, adjustedRadius);
}
}
if (hasVisualEffect(VE_BOUND_BOX)) {
QRectF rect;
rect.setLeft(m_center.x() - adjustedRadius);
rect.setTop(m_center.y() - adjustedRadius);
rect.setWidth(adjustedRadius + adjustedRadius);
rect.setHeight(adjustedRadius + adjustedRadius);
const QBrush &oldBrush = painter->brush();
const QPen &oldPen = painter->pen();
painter->setBrush(Qt::NoBrush);
QPen pen = oldPen;
pen.setStyle(Qt::SolidLine);
pen.setCosmetic(m_usingCosmeticPen);
painter->setPen(pen);
#if 0 //for future versions
QPen pen = oldPen;
QVector<qreal> pattern;
pattern << 1 << 2;
pen.setDashPattern(pattern);
painter->setPen(pen);
painter->drawRect(rect);
pen.setColor(Qt::black);
pen.setDashOffset(1.5);
painter->setPen(pen);
#endif
//QPainter::CompositionMode oldMode = painter->compositionMode();
//painter->setCompositionMode(QPainter::RasterOp_SourceXorDestination);
painter->drawRect(rect);
//painter->setCompositionMode(oldMode);
painter->setBrush(oldBrush);
painter->setPen(oldPen);
}
#endif
}
void ZCircle::save(const char *filePath)
{
UNUSED_PARAMETER(filePath);
}
bool ZCircle::load(const char *filePath)
{
UNUSED_PARAMETER(filePath);
return false;
}
ZSTACKOBJECT_DEFINE_CLASS_NAME(ZCircle)
<commit_msg>fix color bug<commit_after>#if defined(_QT_GUI_USED_)
#include <QPainter>
#include <QDebug>
#endif
#include <math.h>
#include "zcircle.h"
#include "tz_math.h"
#include "zintpoint.h"
const ZCircle::TVisualEffect ZCircle::VE_NONE = 0;
const ZCircle::TVisualEffect ZCircle::VE_DASH_PATTERN = 1;
const ZCircle::TVisualEffect ZCircle::VE_BOUND_BOX = 2;
const ZCircle::TVisualEffect ZCircle::VE_NO_CIRCLE = 4;
const ZCircle::TVisualEffect ZCircle::VE_NO_FILL = 8;
const ZCircle::TVisualEffect ZCircle::VE_GRADIENT_FILL = 16;
const ZCircle::TVisualEffect ZCircle::VE_OUT_FOCUS_DIM = 32;
ZCircle::ZCircle() : m_visualEffect(ZCircle::VE_NONE)
{
set(0, 0, 0, 1);
}
ZCircle::ZCircle(double x, double y, double z, double r) :
m_visualEffect(ZCircle::VE_NONE)
{
set(x, y, z, r);
}
void ZCircle::set(double x, double y, double z, double r)
{
m_center.set(x, y, z);
m_r = r;
}
void ZCircle::set(const ZIntPoint ¢er, double r)
{
set(center.getX(), center.getY(), center.getZ(), r);
}
void ZCircle::set(const ZPoint ¢er, double r)
{
set(center.x(), center.y(), center.z(), r);
}
//void ZCircle::display(QImage *image, int n, Display_Style style) const
//{
//#if defined(_QT_GUI_USED_)
// QPainter painter(image);
// painter.setPen(m_color);
// display(&painter, n, style);
//#endif
//}
void ZCircle::display(ZPainter &painter, int n,
ZStackObject::Display_Style style) const
{
if (!isVisible()) {
return;
}
UNUSED_PARAMETER(style);
#if _QT_GUI_USED_
QPen pen(m_color, getPenWidth());
pen.setCosmetic(m_usingCosmeticPen);
if (hasVisualEffect(VE_DASH_PATTERN)) {
pen.setStyle(Qt::DotLine);
}
painter.setPen(pen);
//qDebug() << "Internal color: " << m_color;
const QBrush &oldBrush = painter.brush();
if (hasVisualEffect(VE_GRADIENT_FILL)) {
QRadialGradient gradient(50, 50, 50, 50, 50);
gradient.setColorAt(0, QColor::fromRgbF(0, 1, 0, 1));
gradient.setColorAt(1, QColor::fromRgbF(0, 0, 0, 0));
/*
QBrush brush(gradient);
brush.setColor(m_color);
brush.setStyle(Qt::RadialGradientPattern);
painter.setBrush(brush);
*/
//painter.setBrush(m_color);
//painter.setBrush(QBrush(m_color, Qt::RadialGradientPattern));
} else {
if (hasVisualEffect(VE_NO_FILL)) {
painter.setBrush(Qt::NoBrush);
}
}
displayHelper(&painter, n, style);
painter.setBrush(oldBrush);
#endif
}
bool ZCircle::isCuttingPlane(double z, double r, double n)
{
double h = fabs(z - n);
if (r > h) {
return true;
} else if (iround(z) == iround(n)) {
return true;
}
return false;
}
bool ZCircle::isCuttingPlane(double n)
{
return isCuttingPlane(m_center.z(), m_r, n);
}
double ZCircle::getAdjustedRadius(double r) const
{
double adjustedRadius = r;
if (!m_usingCosmeticPen) {
adjustedRadius += getPenWidth() * 0.5;
}
return adjustedRadius;
}
void ZCircle::displayHelper(ZPainter *painter, int stackFocus, Display_Style style) const
{
UNUSED_PARAMETER(style);
#if defined(_QT_GUI_USED_)
double adjustedRadius = getAdjustedRadius(m_r);
double dataFocus = stackFocus - painter->getOffset().z();
bool visible = false;
const QBrush &oldBrush = painter->brush();
const QPen &oldPen = painter->pen();
double alpha = oldPen.color().alphaF();
if (stackFocus == -1) {
visible = true;
} else {
if (isCuttingPlane(m_center.z(), m_r, dataFocus)) {
double h = fabs(m_center.z() - dataFocus);
double r = 0.0;
if (m_r > h) {
r = sqrt(m_r * m_r - h * h);
adjustedRadius = getAdjustedRadius(r);
//adjustedRadius = r + getPenWidth() * 0.5;
visible = true;
} else { //too small, show at least one plane
//adjustedRadius = getPenWidth() * 0.5;
r = 0.1;
adjustedRadius = getAdjustedRadius(r);
visible = true;
}
if (hasVisualEffect(VE_OUT_FOCUS_DIM)) {
alpha *= r * r / m_r / m_r;
//alpha *= alpha;
}
}
}
if (visible) {
if (!hasVisualEffect(VE_NO_CIRCLE)) {
//qDebug() << painter->brush().color();
QColor color = painter->pen().color();
color.setAlphaF(alpha);
painter->setPen(color);
painter->drawEllipse(QPointF(m_center.x(), m_center.y()),
adjustedRadius, adjustedRadius);
}
}
if (hasVisualEffect(VE_BOUND_BOX)) {
QRectF rect;
rect.setLeft(m_center.x() - adjustedRadius);
rect.setTop(m_center.y() - adjustedRadius);
rect.setWidth(adjustedRadius + adjustedRadius);
rect.setHeight(adjustedRadius + adjustedRadius);
painter->setBrush(Qt::NoBrush);
QPen pen = oldPen;
pen.setStyle(Qt::SolidLine);
pen.setCosmetic(m_usingCosmeticPen);
painter->setPen(pen);
#if 0 //for future versions
QPen pen = oldPen;
QVector<qreal> pattern;
pattern << 1 << 2;
pen.setDashPattern(pattern);
painter->setPen(pen);
painter->drawRect(rect);
pen.setColor(Qt::black);
pen.setDashOffset(1.5);
painter->setPen(pen);
#endif
//QPainter::CompositionMode oldMode = painter->compositionMode();
//painter->setCompositionMode(QPainter::RasterOp_SourceXorDestination);
painter->drawRect(rect);
//painter->setCompositionMode(oldMode);
}
painter->setBrush(oldBrush);
painter->setPen(oldPen);
#endif
}
void ZCircle::save(const char *filePath)
{
UNUSED_PARAMETER(filePath);
}
bool ZCircle::load(const char *filePath)
{
UNUSED_PARAMETER(filePath);
return false;
}
ZSTACKOBJECT_DEFINE_CLASS_NAME(ZCircle)
<|endoftext|>
|
<commit_before>// Copyright 2019 The SwiftShader 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 "VkStringify.hpp"
#include "System/Debug.hpp"
#include <vulkan/vk_ext_provoking_vertex.h>
#include <vulkan/vk_google_filtering_precision.h>
#define VULKAN_HPP_NO_EXCEPTIONS
#define VULKAN_HPP_NAMESPACE vkhpp
#include <vulkan/vulkan.hpp>
#include <iostream>
#include <map>
#include <sstream>
#include <string>
namespace vk {
std::string Stringify(VkStructureType value)
{
#ifndef NDEBUG
std::string ret = "";
switch(static_cast<int>(value))
{
case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROVOKING_VERTEX_FEATURES_EXT:
ret = "PhysicalDeviceProvokingVertexFeaturesEXT";
break;
case VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_PROVOKING_VERTEX_STATE_CREATE_INFO_EXT:
ret = "PipelineRasterizationProvokingVertexStateCreateInfoEXT";
break;
case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROVOKING_VERTEX_PROPERTIES_EXT:
ret = "PhysicalDeviceProvokingVertexPropertiesEXT";
break;
case VK_STRUCTURE_TYPE_SAMPLER_FILTERING_PRECISION_GOOGLE:
ret = "SamplerFilteringPrecisionGOOGLE";
break;
default:
ret = vkhpp::to_string(static_cast<vkhpp::StructureType>(value));
break;
}
std::ostringstream stringStream;
stringStream << ret << " (" << static_cast<int>(value) << ")";
return stringStream.str();
#else
return std::to_string(static_cast<int>(value));
#endif
}
} // namespace vk
<commit_msg>Don't auto append value of stringified enums<commit_after>// Copyright 2019 The SwiftShader 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 "VkStringify.hpp"
#include "System/Debug.hpp"
#include <vulkan/vk_ext_provoking_vertex.h>
#include <vulkan/vk_google_filtering_precision.h>
#define VULKAN_HPP_NO_EXCEPTIONS
#define VULKAN_HPP_NAMESPACE vkhpp
#include <vulkan/vulkan.hpp>
namespace vk {
std::string Stringify(VkStructureType value)
{
#ifndef NDEBUG
std::string ret = "";
switch(static_cast<int>(value))
{
case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROVOKING_VERTEX_FEATURES_EXT:
ret = "PhysicalDeviceProvokingVertexFeaturesEXT";
break;
case VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_PROVOKING_VERTEX_STATE_CREATE_INFO_EXT:
ret = "PipelineRasterizationProvokingVertexStateCreateInfoEXT";
break;
case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROVOKING_VERTEX_PROPERTIES_EXT:
ret = "PhysicalDeviceProvokingVertexPropertiesEXT";
break;
case VK_STRUCTURE_TYPE_SAMPLER_FILTERING_PRECISION_GOOGLE:
ret = "SamplerFilteringPrecisionGOOGLE";
break;
default:
ret = vkhpp::to_string(static_cast<vkhpp::StructureType>(value));
break;
}
return ret;
#else
return std::to_string(static_cast<int>(value));
#endif
}
} // namespace vk
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.