text
stringlengths 54
60.6k
|
---|
<commit_before>/*************************************************************************
*
* $RCSfile: changes.cxx,v $
*
* $Revision: 1.16 $
*
* last change: $Author: jb $ $Date: 2002-03-28 08:24:29 $
*
* 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>
#include "change.hxx"
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
namespace configmgr
{
//==========================================================================
//= ValueChange
//==========================================================================
// works reliably only if old value is set and the value really changes
uno::Type implGetValueType(uno::Any const & _aValue, uno::Any const & _aOldValue)
{
if (_aValue.hasValue())
{
OSL_ENSURE(!_aOldValue.hasValue() || _aOldValue.getValueType() == _aValue.getValueType(),
"ERROR: Type mismatch in value change");
return _aValue.getValueType();
}
else
{
OSL_ENSURE(_aOldValue.hasValue(),"WARNING: Cannot determine value type of change");
return _aOldValue.getValueType();
}
}
// -------------------------------------------------------------------------
static inline bool isDefaultMode(ValueChange::Mode _eMode)
{ return (_eMode == ValueChange::setToDefault) || (_eMode == ValueChange::changeDefault); }
// -------------------------------------------------------------------------
static inline bool isLayerChangeMode(ValueChange::Mode _eMode)
{ return (_eMode == ValueChange::setToDefault) || (_eMode == ValueChange::wasDefault); }
// -----------------------------------------------------------------------------
ValueChange::ValueChange(OUString const& _rName,
const node::Attributes& _rAttributes,
Mode _eMode,
uno::Any const & aNewValue, uno::Any const & aOldValue)
: Change(_rName, isDefaultMode(_eMode))
,m_aValueType( implGetValueType(aNewValue,aOldValue) )
,m_aValue(aNewValue)
,m_aOldValue(aOldValue)
,m_eMode(_eMode)
,m_aAttributes(_rAttributes)
{
m_aAttributes.markAsDefault(Change::isToDefault());
}
// -----------------------------------------------------------------------------
ValueChange::ValueChange(OUString const& _rName,
const node::Attributes& _rAttributes,
Mode _eMode,
uno::Type const & aValueType)
: Change(_rName, isDefaultMode(_eMode))
,m_aValueType( aValueType )
,m_aValue()
,m_aOldValue()
,m_eMode(_eMode)
,m_aAttributes(_rAttributes)
{
m_aAttributes.markAsDefault(Change::isToDefault());
}
// -------------------------------------------------------------------------
ValueChange::ValueChange(uno::Any const & aNewValue, ValueNode const& aOldValue)
: Change(aOldValue.getName(),false)
,m_aValueType( aOldValue.getValueType() )
,m_aValue(aNewValue)
,m_aOldValue(aOldValue.getValue())
,m_aAttributes(aOldValue.getAttributes())
{
OSL_ENSURE(aNewValue.getValueType() == m_aValueType || !aNewValue.hasValue(),
"ValueChange: Type mismatch in new value" );
m_eMode = aOldValue.isDefault() ? wasDefault : changeValue;
m_aAttributes.markAsDefault(false);
}
// -------------------------------------------------------------------------
ValueChange::ValueChange(SetToDefault, ValueNode const& aOldValue)
: Change(aOldValue.getName(),true)
,m_aValueType( aOldValue.getValueType() )
,m_aValue(aOldValue.getDefault())
,m_aOldValue(aOldValue.getValue())
,m_eMode(setToDefault)
,m_aAttributes(aOldValue.getAttributes())
{
m_aAttributes.markAsDefault(true);
}
// -----------------------------------------------------------------------------
void ValueChange::setNewValue(const uno::Any& _rNewVal)
{
OSL_ENSURE(_rNewVal.getValueType() == m_aValueType || !_rNewVal.hasValue(),
"ValueChange: Type mismatch in setNewValue" );
m_aValue = _rNewVal;
}
// -----------------------------------------------------------------------------
std::auto_ptr<Change> ValueChange::clone() const
{
return std::auto_ptr<Change>(new ValueChange(*this));
}
// -----------------------------------------------------------------------------
bool ValueChange::isChange() const // makes sense only if old value is set
{
return isLayerChangeMode(m_eMode) || (m_aOldValue != m_aValue);
}
// -------------------------------------------------------------------------
namespace tree_changes_internal {
inline void doAdjust(uno::Any& aActual, uno::Any const& aTarget)
{
// If set - it should already match
OSL_ASSERT(!aActual.hasValue() || aTarget == aActual);
aActual = aTarget;
}
}
using namespace tree_changes_internal;
// -------------------------------------------------------------------------
void ValueChange::applyTo(ValueNode& aValue)
{
switch (getMode())
{
case wasDefault:
OSL_ASSERT(aValue.isDefault());
case changeValue:
doAdjust( m_aOldValue, aValue.getValue());
aValue.setValue(getNewValue());
break;
case setToDefault:
doAdjust( m_aOldValue, aValue.getValue());
doAdjust( m_aValue, aValue.getDefault());
aValue.setDefault();
break;
case changeDefault:
doAdjust( m_aOldValue, aValue.getDefault());
aValue.changeDefault(getNewValue());
break;
default:
OSL_ENSURE(0, "Unknown mode found for ValueChange");
break;
}
}
// -------------------------------------------------------------------------
void ValueChange::applyChangeNoRecover(ValueNode& aValue) const
{
switch (getMode())
{
case wasDefault:
OSL_ASSERT(aValue.isDefault());
case changeValue:
aValue.setValue(getNewValue());
break;
case setToDefault:
aValue.setDefault();
break;
case changeDefault:
aValue.changeDefault(getNewValue());
break;
default:
OSL_ENSURE(0, "Unknown mode found for ValueChange");
break;
}
}
// -------------------------------------------------------------------------
::rtl::OUString ValueChange::getModeAsString() const
{
::rtl::OUString aRet;
switch(m_eMode)
{
case wasDefault:
aRet = ::rtl::OUString::createFromAscii("wasDefault");
break;
case changeValue:
aRet = ::rtl::OUString::createFromAscii("changeValue");
break;
case setToDefault:
aRet = ::rtl::OUString::createFromAscii("setToDefault");
break;
case changeDefault:
aRet = ::rtl::OUString::createFromAscii("changeDefault");
break;
default:
OSL_ENSURE(0,"getModeAsString: Wrong mode!");
}
return aRet;
}
// -------------------------------------------------------------------------
void ValueChange::setModeAsString(const ::rtl::OUString& _rMode)
{
if(_rMode == ::rtl::OUString::createFromAscii("wasDefault")) m_eMode = wasDefault;
else if(_rMode == ::rtl::OUString::createFromAscii("changeValue")) m_eMode = changeValue;
else if(_rMode == ::rtl::OUString::createFromAscii("setToDefault")) m_eMode = setToDefault;
else if(_rMode == ::rtl::OUString::createFromAscii("changeDefault"))m_eMode = changeDefault;
else
{
OSL_ENSURE(0,"setModeAsString: Wrong mode!");
}
}
//==========================================================================
//= AddNode
//==========================================================================
using data::TreeSegment;
//------------------------------------------0--------------------------------
AddNode::AddNode(TreeSegment const & _aAddedTree, OUString const& _rName, bool _bToDefault)
:Change(_rName,_bToDefault)
,m_aOwnNewNode(_aAddedTree)
,m_aOwnOldNode()
,m_aInsertedTree()
,m_bReplacing(false)
{
}
//--------------------------------------------------------------------------
AddNode::~AddNode()
{
}
// -----------------------------------------------------------------------------
AddNode::AddNode(const AddNode& _aObj)
: Change(_aObj)
, m_bReplacing(_aObj.m_bReplacing)
, m_aOwnNewNode(_aObj.m_aOwnNewNode.cloneSegment())
, m_aOwnOldNode(_aObj.m_aOwnOldNode.cloneSegment())
, m_aInsertedTree(_aObj.m_aInsertedTree)
{
}
// -----------------------------------------------------------------------------
std::auto_ptr<Change> AddNode::clone() const
{
return std::auto_ptr<Change>(new AddNode(*this));
}
//--------------------------------------------------------------------------
void AddNode::setInsertedAddress(data::TreeAddress const & _aInsertedTree)
{
OSL_ENSURE( !m_aInsertedTree.is(), "AddNode already was applied - inserted a second time ?");
m_aInsertedTree = _aInsertedTree;
}
//--------------------------------------------------------------------------
#if 0
void AddNode::expectReplacedNode(INode const* pOldNode)
{
if (pOldNode != m_aOwnOldNode.getRoot())
{
OSL_ENSURE(!m_aOwnOldNode.is(), "This AddNode already owns a replaced Node - throwing that away");
m_aOwnOldNode.clear();
}
m_pOldNode = pOldNode;
}
#endif
//--------------------------------------------------------------------------
void AddNode::takeReplacedTree(TreeSegment const & _aReplacedTree)
{
m_aOwnOldNode = _aReplacedTree;
if (m_aOwnOldNode.is()) m_bReplacing = true;
}
//==========================================================================
//= RemoveNode
//==========================================================================
RemoveNode::RemoveNode(OUString const& _rName, bool _bToDefault)
:Change(_rName,_bToDefault)
,m_aOwnOldNode()
{
}
//--------------------------------------------------------------------------
RemoveNode::~RemoveNode()
{
}
// -----------------------------------------------------------------------------
RemoveNode::RemoveNode(const RemoveNode& _aObj)
: Change(_aObj)
, m_aOwnOldNode(_aObj.m_aOwnOldNode.cloneSegment())
{
}
// -----------------------------------------------------------------------------
std::auto_ptr<Change> RemoveNode::clone() const
{
return std::auto_ptr<Change>(new RemoveNode(*this));
}
//--------------------------------------------------------------------------
#if 0
void RemoveNode::expectRemovedNode(INode const* pOldNode)
{
if (pOldNode != m_aOwnOldNode.getRoot())
{
OSL_ENSURE(!m_aOwnOldNode.is(), "This RemoveNode already owns a Node - throwing that away");
m_aOwnOldNode.clear();
}
m_pOldNode = pOldNode;
}
#endif
//--------------------------------------------------------------------------
void RemoveNode::takeRemovedTree(data::TreeSegment const & _aRemovedTree)
{
m_aOwnOldNode = _aRemovedTree;
}
//--------------------------------------------------------------------------
} // namespace configmgr
<commit_msg>INTEGRATION: CWS cfgcleanup (1.16.98); FILE MERGED 2004/02/09 15:30:28 jb 1.16.98.1: #i25025# Eliminate warnings from gcc<commit_after>/*************************************************************************
*
* $RCSfile: changes.cxx,v $
*
* $Revision: 1.17 $
*
* last change: $Author: kz $ $Date: 2004-03-23 10:29:04 $
*
* 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>
#include "change.hxx"
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
namespace configmgr
{
//==========================================================================
//= ValueChange
//==========================================================================
// works reliably only if old value is set and the value really changes
uno::Type implGetValueType(uno::Any const & _aValue, uno::Any const & _aOldValue)
{
if (_aValue.hasValue())
{
OSL_ENSURE(!_aOldValue.hasValue() || _aOldValue.getValueType() == _aValue.getValueType(),
"ERROR: Type mismatch in value change");
return _aValue.getValueType();
}
else
{
OSL_ENSURE(_aOldValue.hasValue(),"WARNING: Cannot determine value type of change");
return _aOldValue.getValueType();
}
}
// -------------------------------------------------------------------------
static inline bool isDefaultMode(ValueChange::Mode _eMode)
{ return (_eMode == ValueChange::setToDefault) || (_eMode == ValueChange::changeDefault); }
// -------------------------------------------------------------------------
static inline bool isLayerChangeMode(ValueChange::Mode _eMode)
{ return (_eMode == ValueChange::setToDefault) || (_eMode == ValueChange::wasDefault); }
// -----------------------------------------------------------------------------
ValueChange::ValueChange(OUString const& _rName,
const node::Attributes& _rAttributes,
Mode _eMode,
uno::Any const & aNewValue, uno::Any const & aOldValue)
: Change(_rName, isDefaultMode(_eMode))
,m_aValueType( implGetValueType(aNewValue,aOldValue) )
,m_aValue(aNewValue)
,m_aOldValue(aOldValue)
,m_aAttributes(_rAttributes)
,m_eMode(_eMode)
{
m_aAttributes.markAsDefault(Change::isToDefault());
}
// -----------------------------------------------------------------------------
ValueChange::ValueChange(OUString const& _rName,
const node::Attributes& _rAttributes,
Mode _eMode,
uno::Type const & aValueType)
: Change(_rName, isDefaultMode(_eMode))
,m_aValueType( aValueType )
,m_aValue()
,m_aOldValue()
,m_aAttributes(_rAttributes)
,m_eMode(_eMode)
{
m_aAttributes.markAsDefault(Change::isToDefault());
}
// -------------------------------------------------------------------------
ValueChange::ValueChange(uno::Any const & aNewValue, ValueNode const& aOldValue)
: Change(aOldValue.getName(),false)
,m_aValueType( aOldValue.getValueType() )
,m_aValue(aNewValue)
,m_aOldValue(aOldValue.getValue())
,m_aAttributes(aOldValue.getAttributes())
{
OSL_ENSURE(aNewValue.getValueType() == m_aValueType || !aNewValue.hasValue(),
"ValueChange: Type mismatch in new value" );
m_eMode = aOldValue.isDefault() ? wasDefault : changeValue;
m_aAttributes.markAsDefault(false);
}
// -------------------------------------------------------------------------
ValueChange::ValueChange(SetToDefault, ValueNode const& aOldValue)
: Change(aOldValue.getName(),true)
,m_aValueType( aOldValue.getValueType() )
,m_aValue(aOldValue.getDefault())
,m_aOldValue(aOldValue.getValue())
,m_aAttributes(aOldValue.getAttributes())
,m_eMode(setToDefault)
{
m_aAttributes.markAsDefault(true);
}
// -----------------------------------------------------------------------------
void ValueChange::setNewValue(const uno::Any& _rNewVal)
{
OSL_ENSURE(_rNewVal.getValueType() == m_aValueType || !_rNewVal.hasValue(),
"ValueChange: Type mismatch in setNewValue" );
m_aValue = _rNewVal;
}
// -----------------------------------------------------------------------------
std::auto_ptr<Change> ValueChange::clone() const
{
return std::auto_ptr<Change>(new ValueChange(*this));
}
// -----------------------------------------------------------------------------
bool ValueChange::isChange() const // makes sense only if old value is set
{
return isLayerChangeMode(m_eMode) || (m_aOldValue != m_aValue);
}
// -------------------------------------------------------------------------
namespace tree_changes_internal {
inline void doAdjust(uno::Any& aActual, uno::Any const& aTarget)
{
// If set - it should already match
OSL_ASSERT(!aActual.hasValue() || aTarget == aActual);
aActual = aTarget;
}
}
using namespace tree_changes_internal;
// -------------------------------------------------------------------------
void ValueChange::applyTo(ValueNode& aValue)
{
switch (getMode())
{
case wasDefault:
OSL_ASSERT(aValue.isDefault());
case changeValue:
doAdjust( m_aOldValue, aValue.getValue());
aValue.setValue(getNewValue());
break;
case setToDefault:
doAdjust( m_aOldValue, aValue.getValue());
doAdjust( m_aValue, aValue.getDefault());
aValue.setDefault();
break;
case changeDefault:
doAdjust( m_aOldValue, aValue.getDefault());
aValue.changeDefault(getNewValue());
break;
default:
OSL_ENSURE(0, "Unknown mode found for ValueChange");
break;
}
}
// -------------------------------------------------------------------------
void ValueChange::applyChangeNoRecover(ValueNode& aValue) const
{
switch (getMode())
{
case wasDefault:
OSL_ASSERT(aValue.isDefault());
case changeValue:
aValue.setValue(getNewValue());
break;
case setToDefault:
aValue.setDefault();
break;
case changeDefault:
aValue.changeDefault(getNewValue());
break;
default:
OSL_ENSURE(0, "Unknown mode found for ValueChange");
break;
}
}
// -------------------------------------------------------------------------
::rtl::OUString ValueChange::getModeAsString() const
{
::rtl::OUString aRet;
switch(m_eMode)
{
case wasDefault:
aRet = ::rtl::OUString::createFromAscii("wasDefault");
break;
case changeValue:
aRet = ::rtl::OUString::createFromAscii("changeValue");
break;
case setToDefault:
aRet = ::rtl::OUString::createFromAscii("setToDefault");
break;
case changeDefault:
aRet = ::rtl::OUString::createFromAscii("changeDefault");
break;
default:
OSL_ENSURE(0,"getModeAsString: Wrong mode!");
}
return aRet;
}
// -------------------------------------------------------------------------
void ValueChange::setModeAsString(const ::rtl::OUString& _rMode)
{
if(_rMode == ::rtl::OUString::createFromAscii("wasDefault")) m_eMode = wasDefault;
else if(_rMode == ::rtl::OUString::createFromAscii("changeValue")) m_eMode = changeValue;
else if(_rMode == ::rtl::OUString::createFromAscii("setToDefault")) m_eMode = setToDefault;
else if(_rMode == ::rtl::OUString::createFromAscii("changeDefault"))m_eMode = changeDefault;
else
{
OSL_ENSURE(0,"setModeAsString: Wrong mode!");
}
}
//==========================================================================
//= AddNode
//==========================================================================
using data::TreeSegment;
//------------------------------------------0--------------------------------
AddNode::AddNode(TreeSegment const & _aAddedTree, OUString const& _rName, bool _bToDefault)
:Change(_rName,_bToDefault)
,m_aOwnNewNode(_aAddedTree)
,m_aOwnOldNode()
,m_aInsertedTree()
,m_bReplacing(false)
{
}
//--------------------------------------------------------------------------
AddNode::~AddNode()
{
}
// -----------------------------------------------------------------------------
AddNode::AddNode(const AddNode& _aObj)
: Change(_aObj)
, m_aOwnNewNode(_aObj.m_aOwnNewNode.cloneSegment())
, m_aOwnOldNode(_aObj.m_aOwnOldNode.cloneSegment())
, m_aInsertedTree(_aObj.m_aInsertedTree)
, m_bReplacing(_aObj.m_bReplacing)
{
}
// -----------------------------------------------------------------------------
std::auto_ptr<Change> AddNode::clone() const
{
return std::auto_ptr<Change>(new AddNode(*this));
}
//--------------------------------------------------------------------------
void AddNode::setInsertedAddress(data::TreeAddress const & _aInsertedTree)
{
OSL_ENSURE( !m_aInsertedTree.is(), "AddNode already was applied - inserted a second time ?");
m_aInsertedTree = _aInsertedTree;
}
//--------------------------------------------------------------------------
#if 0
void AddNode::expectReplacedNode(INode const* pOldNode)
{
if (pOldNode != m_aOwnOldNode.getRoot())
{
OSL_ENSURE(!m_aOwnOldNode.is(), "This AddNode already owns a replaced Node - throwing that away");
m_aOwnOldNode.clear();
}
m_pOldNode = pOldNode;
}
#endif
//--------------------------------------------------------------------------
void AddNode::takeReplacedTree(TreeSegment const & _aReplacedTree)
{
m_aOwnOldNode = _aReplacedTree;
if (m_aOwnOldNode.is()) m_bReplacing = true;
}
//==========================================================================
//= RemoveNode
//==========================================================================
RemoveNode::RemoveNode(OUString const& _rName, bool _bToDefault)
:Change(_rName,_bToDefault)
,m_aOwnOldNode()
{
}
//--------------------------------------------------------------------------
RemoveNode::~RemoveNode()
{
}
// -----------------------------------------------------------------------------
RemoveNode::RemoveNode(const RemoveNode& _aObj)
: Change(_aObj)
, m_aOwnOldNode(_aObj.m_aOwnOldNode.cloneSegment())
{
}
// -----------------------------------------------------------------------------
std::auto_ptr<Change> RemoveNode::clone() const
{
return std::auto_ptr<Change>(new RemoveNode(*this));
}
//--------------------------------------------------------------------------
#if 0
void RemoveNode::expectRemovedNode(INode const* pOldNode)
{
if (pOldNode != m_aOwnOldNode.getRoot())
{
OSL_ENSURE(!m_aOwnOldNode.is(), "This RemoveNode already owns a Node - throwing that away");
m_aOwnOldNode.clear();
}
m_pOldNode = pOldNode;
}
#endif
//--------------------------------------------------------------------------
void RemoveNode::takeRemovedTree(data::TreeSegment const & _aRemovedTree)
{
m_aOwnOldNode = _aRemovedTree;
}
//--------------------------------------------------------------------------
} // namespace configmgr
<|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 "ash/system/chromeos/session/tray_session_length_limit.h"
#include "ash/root_window_controller.h"
#include "ash/shell.h"
#include "ash/system/tray/system_tray.h"
#include "ash/test/ash_test_base.h"
#include "ash/test/test_system_tray_delegate.h"
#include "base/time/time.h"
#include "ui/message_center/message_center.h"
#include "ui/message_center/notification.h"
#include "ui/message_center/notification_types.h"
namespace ash {
namespace test {
class TraySessionLengthLimitTest : public AshTestBase {
public:
TraySessionLengthLimitTest() {}
~TraySessionLengthLimitTest() override {}
void SetUp() override {
AshTestBase::SetUp();
SystemTray* system_tray =
Shell::GetPrimaryRootWindowController()->GetSystemTray();
tray_session_length_limit_ = new TraySessionLengthLimit(system_tray);
system_tray->AddTrayItem(tray_session_length_limit_);
}
void TearDown() override { AshTestBase::TearDown(); }
protected:
void UpdateSessionLengthLimitInMin(int mins) {
GetSystemTrayDelegate()->SetSessionLengthLimitForTest(
base::TimeDelta::FromMinutes(mins));
tray_session_length_limit_->OnSessionLengthLimitChanged();
}
message_center::Notification* GetNotification() {
const message_center::NotificationList::Notifications& notifications =
message_center::MessageCenter::Get()->GetVisibleNotifications();
for (message_center::NotificationList::Notifications::const_iterator iter =
notifications.begin(); iter != notifications.end(); ++iter) {
if ((*iter)->id() == TraySessionLengthLimit::kNotificationId)
return *iter;
}
return NULL;
}
void ClearSessionLengthLimit() {
GetSystemTrayDelegate()->ClearSessionLengthLimit();
tray_session_length_limit_->OnSessionLengthLimitChanged();
}
void RemoveNotification() {
message_center::MessageCenter::Get()->RemoveNotification(
TraySessionLengthLimit::kNotificationId, false /* by_user */);
}
TraySessionLengthLimit* tray_session_length_limit() {
return tray_session_length_limit_;
}
private:
// Weak reference, owned by the SystemTray.
TraySessionLengthLimit* tray_session_length_limit_;
DISALLOW_COPY_AND_ASSIGN(TraySessionLengthLimitTest);
};
TEST_F(TraySessionLengthLimitTest, Notification) {
// No notifications when no session limit.
EXPECT_FALSE(GetNotification());
// Limit is 15 min.
UpdateSessionLengthLimitInMin(15);
message_center::Notification* notification = GetNotification();
EXPECT_TRUE(notification);
EXPECT_EQ(message_center::SYSTEM_PRIORITY, notification->priority());
base::string16 first_content = notification->message();
// Should read the content.
EXPECT_TRUE(notification->rich_notification_data().
should_make_spoken_feedback_for_popup_updates);
// Limit is 10 min.
UpdateSessionLengthLimitInMin(10);
notification = GetNotification();
EXPECT_TRUE(notification);
EXPECT_EQ(message_center::SYSTEM_PRIORITY, notification->priority());
// The content should be updated.
EXPECT_NE(first_content, notification->message());
// Should NOT read, because just update the remaining time.
EXPECT_FALSE(notification->rich_notification_data().
should_make_spoken_feedback_for_popup_updates);
// Limit is 3 min.
UpdateSessionLengthLimitInMin(3);
notification = GetNotification();
EXPECT_TRUE(notification);
EXPECT_EQ(message_center::SYSTEM_PRIORITY, notification->priority());
// Should read the content again because the state has changed.
EXPECT_TRUE(notification->rich_notification_data().
should_make_spoken_feedback_for_popup_updates);
// Session length limit is updated to longer: 15 min.
UpdateSessionLengthLimitInMin(15);
notification = GetNotification();
EXPECT_TRUE(notification);
EXPECT_EQ(message_center::SYSTEM_PRIORITY, notification->priority());
// Should read again because an increase of the remaining time is noteworthy.
EXPECT_TRUE(notification->rich_notification_data().
should_make_spoken_feedback_for_popup_updates);
// Clears the limit: the notification should be gone.
ClearSessionLengthLimit();
EXPECT_FALSE(GetNotification());
}
TEST_F(TraySessionLengthLimitTest, RemoveNotification) {
message_center::Notification* notification;
// Limit is 15 min.
UpdateSessionLengthLimitInMin(15);
EXPECT_TRUE(GetNotification());
// Removes the notification.
RemoveNotification();
EXPECT_FALSE(GetNotification());
// Limit is 10 min. The notification should not re-appear.
UpdateSessionLengthLimitInMin(10);
EXPECT_FALSE(GetNotification());
// Limit is 3 min. The notification should re-appear and should be re-read
// because of state change.
UpdateSessionLengthLimitInMin(3);
notification = GetNotification();
EXPECT_TRUE(notification);
EXPECT_TRUE(notification->rich_notification_data().
should_make_spoken_feedback_for_popup_updates);
RemoveNotification();
// Session length limit is updated to longer state. Notification should
// re-appear and be re-read.
UpdateSessionLengthLimitInMin(15);
notification = GetNotification();
EXPECT_TRUE(notification);
EXPECT_TRUE(notification->rich_notification_data().
should_make_spoken_feedback_for_popup_updates);
}
} // namespace test
} // namespace ash
<commit_msg>Fixes tray_session_length_limit_unittest timeout on valgrind.<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 "ash/system/chromeos/session/tray_session_length_limit.h"
#include "ash/root_window_controller.h"
#include "ash/shell.h"
#include "ash/system/tray/system_tray.h"
#include "ash/test/ash_test_base.h"
#include "ash/test/test_system_tray_delegate.h"
#include "base/time/time.h"
#include "ui/message_center/message_center.h"
#include "ui/message_center/notification.h"
#include "ui/message_center/notification_types.h"
namespace ash {
namespace test {
class TraySessionLengthLimitTest : public AshTestBase {
public:
TraySessionLengthLimitTest() {}
~TraySessionLengthLimitTest() override {}
void SetUp() override {
AshTestBase::SetUp();
SystemTray* system_tray =
Shell::GetPrimaryRootWindowController()->GetSystemTray();
tray_session_length_limit_ = new TraySessionLengthLimit(system_tray);
system_tray->AddTrayItem(tray_session_length_limit_);
}
void TearDown() override {
ClearSessionLengthLimit();
AshTestBase::TearDown();
}
protected:
void UpdateSessionLengthLimitInMin(int mins) {
GetSystemTrayDelegate()->SetSessionLengthLimitForTest(
base::TimeDelta::FromMinutes(mins));
tray_session_length_limit_->OnSessionLengthLimitChanged();
}
message_center::Notification* GetNotification() {
const message_center::NotificationList::Notifications& notifications =
message_center::MessageCenter::Get()->GetVisibleNotifications();
for (message_center::NotificationList::Notifications::const_iterator iter =
notifications.begin(); iter != notifications.end(); ++iter) {
if ((*iter)->id() == TraySessionLengthLimit::kNotificationId)
return *iter;
}
return nullptr;
}
void ClearSessionLengthLimit() {
GetSystemTrayDelegate()->ClearSessionLengthLimit();
tray_session_length_limit_->OnSessionLengthLimitChanged();
}
void RemoveNotification() {
message_center::MessageCenter::Get()->RemoveNotification(
TraySessionLengthLimit::kNotificationId, false /* by_user */);
}
TraySessionLengthLimit* tray_session_length_limit() {
return tray_session_length_limit_;
}
private:
// Weak reference, owned by the SystemTray.
TraySessionLengthLimit* tray_session_length_limit_;
DISALLOW_COPY_AND_ASSIGN(TraySessionLengthLimitTest);
};
TEST_F(TraySessionLengthLimitTest, Notification) {
// No notifications when no session limit.
EXPECT_FALSE(GetNotification());
// Limit is 15 min.
UpdateSessionLengthLimitInMin(15);
message_center::Notification* notification = GetNotification();
EXPECT_TRUE(notification);
EXPECT_EQ(message_center::SYSTEM_PRIORITY, notification->priority());
base::string16 first_content = notification->message();
// Should read the content.
EXPECT_TRUE(notification->rich_notification_data().
should_make_spoken_feedback_for_popup_updates);
// Limit is 10 min.
UpdateSessionLengthLimitInMin(10);
notification = GetNotification();
EXPECT_TRUE(notification);
EXPECT_EQ(message_center::SYSTEM_PRIORITY, notification->priority());
// The content should be updated.
EXPECT_NE(first_content, notification->message());
// Should NOT read, because just update the remaining time.
EXPECT_FALSE(notification->rich_notification_data().
should_make_spoken_feedback_for_popup_updates);
// Limit is 3 min.
UpdateSessionLengthLimitInMin(3);
notification = GetNotification();
EXPECT_TRUE(notification);
EXPECT_EQ(message_center::SYSTEM_PRIORITY, notification->priority());
// Should read the content again because the state has changed.
EXPECT_TRUE(notification->rich_notification_data().
should_make_spoken_feedback_for_popup_updates);
// Session length limit is updated to longer: 15 min.
UpdateSessionLengthLimitInMin(15);
notification = GetNotification();
EXPECT_TRUE(notification);
EXPECT_EQ(message_center::SYSTEM_PRIORITY, notification->priority());
// Should read again because an increase of the remaining time is noteworthy.
EXPECT_TRUE(notification->rich_notification_data().
should_make_spoken_feedback_for_popup_updates);
// Clears the limit: the notification should be gone.
ClearSessionLengthLimit();
EXPECT_FALSE(GetNotification());
}
TEST_F(TraySessionLengthLimitTest, RemoveNotification) {
// Limit is 15 min.
UpdateSessionLengthLimitInMin(15);
EXPECT_TRUE(GetNotification());
// Removes the notification.
RemoveNotification();
EXPECT_FALSE(GetNotification());
// Limit is 10 min. The notification should not re-appear.
UpdateSessionLengthLimitInMin(10);
EXPECT_FALSE(GetNotification());
// Limit is 3 min. The notification should re-appear and should be re-read
// because of state change.
UpdateSessionLengthLimitInMin(3);
message_center::Notification* notification = GetNotification();
EXPECT_TRUE(notification);
EXPECT_TRUE(notification->rich_notification_data().
should_make_spoken_feedback_for_popup_updates);
RemoveNotification();
// Session length limit is updated to longer state. Notification should
// re-appear and be re-read.
UpdateSessionLengthLimitInMin(15);
notification = GetNotification();
EXPECT_TRUE(notification);
EXPECT_TRUE(notification->rich_notification_data().
should_make_spoken_feedback_for_popup_updates);
}
} // namespace test
} // namespace ash
<|endoftext|> |
<commit_before>/**
*
* @copyright
* ========================================================================
* Copyright 2007 FLWOR Foundation
*
* 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.
* ========================================================================
*
* @author Sorin Nasoi (sorin.nasoi@ipdevel.ro)
* @file functions/StringsImpl.cpp
*
*/
#include "StringsImpl.h"
#include "util/tracer.h"
#include <iostream>
using namespace std;
namespace xqp {
/**
*______________________________________________________________________
*
* 7.2.1 fn:codepoints-to-string
*
* fn:codepoints-to-string($arg as xs:integer*) as xs:string
*
* Summary:Creates an xs:string from a sequence of code points.
*Returns the zero-length string if $arg is the empty sequence.
*If any of the code points in $arg is not a legal XML character,
*an error is raised [err:FOCH0001] ("Code point not valid.").
*_______________________________________________________________________*/
std::ostream& CodepointsToStringIterator::_show(std::ostream& os) const{
argv->show(os);
return os;
}
item_t CodepointsToStringIterator::nextImpl(){
item_t item;
const numericValue* n0;
sequence_type_t type0;
//xqpString test;
STACK_INIT();
while(true){
item = this->consumeNext(argv);
if(&*item == NULL) {
//test = (uint)23;
//STACK_PUSH(new stringValue(xs_string, test));
STACK_PUSH(new stringValue(xs_string, res));
STACK_PUSH(NULL);
}
else {
n0 = dynamic_cast<const numericValue*>(&*item);
seq[0] = 0;
seq[1] = 0;
seq[2] = 0;
seq[3] = 0;
EncodeUtf8((uint32_t)n0->val(), seq);
res.append(seq);
}
}
STACK_PUSH(NULL);
STACK_END();
}
void CodepointsToStringIterator::resetImpl(){
this->resetChild(argv);
}
void CodepointsToStringIterator::releaseResourcesImpl() {
this->releaseChildResources(argv);
}
/**
*______________________________________________________________________
*
* 7.2.2 fn:string-to-codepoints
*
* fn:string-to-codepoints($arg as xs:string?) as xs:integer*
*
* Summary: Returns the sequence of code points that constitute an
*xs:string.
*If $arg is a zero-length string or the empty sequence,
*the empty sequence is returned.
*_______________________________________________________________________*/
std::ostream& StringToCodepointsIterator::_show(std::ostream& os) const{
argv->show(os);
return os;
}
item_t StringToCodepointsIterator::nextImpl(){
item_t item;
const stringValue* n0;
STACK_INIT();
item = this->consumeNext(argv);
if(&*item == NULL) {
STACK_PUSH(NULL);
}
else
{
n0 = dynamic_cast<const stringValue*>(&*item);
vLength = (n0->val().length()) + 1;
v.reserve(vLength);
std::strcpy(&v[0], n0->val().c_str());
c = &v[0];
while( --vLength > 0 ){
cp = DecodeUtf8(c);
STACK_PUSH(new numericValue(xs_long, cp));
}
}
STACK_PUSH(NULL);
STACK_END();
}
void StringToCodepointsIterator::resetImpl(){
this->resetChild(argv);
}
void StringToCodepointsIterator::releaseResourcesImpl() {
this->releaseChildResources(argv);
}
/**
*______________________________________________________________________
* 7.3.2 fn:compare
* fn:compare($comparand1 as xs:string?,
* $comparand2 as xs:string?) as xs:integer
*
* fn:compare( $comparand1 as xs:string?,
* $comparand2 as xs:string?,
* $collation as xs:string) as xs:integer?
*
* Summary: Returns -1, 0, or 1, depending on whether the value of
* the $comparand1 is respectively less than, equal to, or greater
* than the value of $comparand2, according to the rules of
* the collation that is used.
*
* If either argument is the empty sequence, the result is the empty sequence.
*_______________________________________________________________________*/
/**
*______________________________________________________________________
*
* 7.3.3 fn:codepoint-equal
*
* fn:codepoint-equal( $comparand1 as xs:string?,
* $comparand2 as xs:string?) as xs:boolean?
*
* Summary: Returns true or false depending on whether the value
* of $comparand1 is equal to the value of $comparand2, according to
* the Unicode code point collation
* (http://www.w3.org/2005/xpath-functions/collation/codepoint).
*
* If either argument is the empty sequence, the result is the empty sequence.
*
* Note: This function allows xs:anyURI values to be compared
* without having to specify the Unicode code point collation.
*_______________________________________________________________________*/
std::ostream& CodepointEqualIterator::_show(std::ostream& os) const{
argv0->show(os);
argv1->show(os);
return os;
}
item_t CodepointEqualIterator::nextImpl(){
item_t item0;
item_t item1;
const stringValue* n0;
const stringValue* n1;
STACK_INIT();
item0 = this->consumeNext(argv0);
item1 = this->consumeNext(argv1);
finish = false;
if(&*item0 == NULL || &*item1 == NULL) {
STACK_PUSH(NULL);
}
else
{
n0 = dynamic_cast<const stringValue*>(&*item0);
n1 = dynamic_cast<const stringValue*>(&*item1);
vLength = (n0->val().length());
if(vLength != n1->val().length())
STACK_PUSH(new booleanValue(false));
else
{
v0.reserve(vLength);
std::strcpy(&v0[0], n0->val().c_str());
c0 = &v0[0];
v1.reserve(vLength);
std::strcpy(&v1[0], n1->val().c_str());
c1 = &v1[0];
while( !finish && (vLength > 0) ){
if(DecodeUtf8(c0) != DecodeUtf8(c1))
{
finish = true;
STACK_PUSH(new booleanValue(false));
}
vLength--;
}
if(!finish)
STACK_PUSH(new booleanValue(true));
}
}
STACK_PUSH(NULL);
STACK_END();
}
void CodepointEqualIterator::resetImpl(){
this->resetChild(argv0);
this->resetChild(argv1);
}
void CodepointEqualIterator::releaseResourcesImpl() {
this->releaseChildResources(argv0);
this->releaseChildResources(argv1);
}
/**
*______________________________________________________________________
*
* 7.4.1 fn:concat
*
* fn:concat( $arg1 as xs:anyAtomicType?,
* $arg2 as xs:anyAtomicType?,
* ... ) as xs:string
*
* Summary:
* Accepts two or more xs:anyAtomicType arguments and casts them to xs:string.
* Returns the xs:string that is the concatenation of the values of its
* arguments after conversion.
* If any of the arguments is the empty sequence, the argument is treated
* as the zero-length string.
*
* The fn:concat function is specified to allow an two or more arguments
* that are concatenated together.
*
* Note:
* Unicode normalization is not automatically applied to the result
* of fn:concat. If a normalized result is required, fn:normalize-unicode
* can be applied to the xs:string returned by fn:concat.
*_______________________________________________________________________*/
std::ostream& ConcatFnIterator::_show(std::ostream& os)
const
{
std::vector<iterator_t>::const_iterator iter = this->argv.begin();
for(; iter != this->argv.end(); ++iter) {
(*iter)->show(os);
}
return os;
}
item_t ConcatFnIterator::nextImpl() {
item_t item;
iterator_t currit_str;
item_t item_str;
const stringValue* n;
STACK_INIT();
this->cursor = 0;
for (; this->cursor < this->argv.size (); this->cursor++) {;
this->currit_h = this->argv[this->cursor];
item = this->consumeNext(this->currit_h);
//if the item is not a node => it's a xs:anyAtomicType
if((item->type() & NODE_MASK) == NOT_NODE)
{
currit_str = item->string_value(loc);
item_str = this->consumeNext(currit_str);
n = dynamic_cast<const stringValue*>(&*item_str);
res.append(n->val());
//res.append("1");
}
}
STACK_PUSH(new stringValue(xs_string, res));
STACK_PUSH(NULL);
STACK_END();
}
void ConcatFnIterator::resetImpl() {
std::vector<iterator_t>::iterator iter = this->argv.begin();
for(; iter != this->argv.end(); ++iter) {
this->resetChild(*iter);
}
}
void ConcatFnIterator::releaseResourcesImpl() {
std::vector<iterator_t>::iterator iter = this->argv.begin();
for(; iter != this->argv.end(); ++iter) {
this->releaseChildResources(*iter);
}
}
/**
*______________________________________________________________________
*
* 7.4.2 fn:string-join
*
* fn:string-join($arg1 as xs:string*,
* $arg2 as xs:string) as xs:string
*
*
*
* Summary: Returns a xs:string created by concatenating the members
* of the $arg1 sequence using $arg2 as a separator.
*
* If the value of $arg2 is the zero-length string,
* then the members of $arg1 are concatenated without a separator.
*
* If the value of $arg1 is the empty sequence,
* the zero-length string is returned.
*_______________________________________________________________________*/
std::ostream& StringJoinIterator::_show(std::ostream& os)
const
{
std::vector<iterator_t>::const_iterator iter = this->argv.begin();
for(; iter != this->argv.end(); ++iter) {
(*iter)->show(os);
}
return os;
}
item_t StringJoinIterator::nextImpl() {
STACK_INIT();
STACK_PUSH(new stringValue(xs_string, "result"));
STACK_PUSH(NULL);
STACK_END();
}
void StringJoinIterator::resetImpl() {
std::vector<iterator_t>::iterator iter = this->argv.begin();
for(; iter != this->argv.end(); ++iter) {
this->resetChild(*iter);
}
}
void StringJoinIterator::releaseResourcesImpl() {
std::vector<iterator_t>::iterator iter = this->argv.begin();
for(; iter != this->argv.end(); ++iter) {
this->releaseChildResources(*iter);
}
}
} /* namespace xqp */
<commit_msg>Added a TODO tag.<commit_after>/**
*
* @copyright
* ========================================================================
* Copyright 2007 FLWOR Foundation
*
* 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.
* ========================================================================
*
* @author Sorin Nasoi (sorin.nasoi@ipdevel.ro)
* @file functions/StringsImpl.cpp
*
*/
#include "StringsImpl.h"
#include "util/tracer.h"
#include <iostream>
using namespace std;
namespace xqp {
/**
*______________________________________________________________________
*
* 7.2.1 fn:codepoints-to-string
*
* fn:codepoints-to-string($arg as xs:integer*) as xs:string
*
* Summary:Creates an xs:string from a sequence of code points.
*Returns the zero-length string if $arg is the empty sequence.
*If any of the code points in $arg is not a legal XML character,
*an error is raised [err:FOCH0001] ("Code point not valid.").
*_______________________________________________________________________*/
std::ostream& CodepointsToStringIterator::_show(std::ostream& os) const{
argv->show(os);
return os;
}
item_t CodepointsToStringIterator::nextImpl(){
item_t item;
const numericValue* n0;
sequence_type_t type0;
//xqpString test;
STACK_INIT();
while(true){
item = this->consumeNext(argv);
if(&*item == NULL) {
//test = (uint)23;
//STACK_PUSH(new stringValue(xs_string, test));
STACK_PUSH(new stringValue(xs_string, res));
STACK_PUSH(NULL);
}
else {
n0 = dynamic_cast<const numericValue*>(&*item);
seq[0] = 0;
seq[1] = 0;
seq[2] = 0;
seq[3] = 0;
EncodeUtf8((uint32_t)n0->val(), seq);
res.append(seq);
}
}
STACK_PUSH(NULL);
STACK_END();
}
void CodepointsToStringIterator::resetImpl(){
this->resetChild(argv);
}
void CodepointsToStringIterator::releaseResourcesImpl() {
this->releaseChildResources(argv);
}
/**
*______________________________________________________________________
*
* 7.2.2 fn:string-to-codepoints
*
* fn:string-to-codepoints($arg as xs:string?) as xs:integer*
*
* Summary: Returns the sequence of code points that constitute an
*xs:string.
*If $arg is a zero-length string or the empty sequence,
*the empty sequence is returned.
*_______________________________________________________________________*/
std::ostream& StringToCodepointsIterator::_show(std::ostream& os) const{
argv->show(os);
return os;
}
item_t StringToCodepointsIterator::nextImpl(){
item_t item;
const stringValue* n0;
STACK_INIT();
item = this->consumeNext(argv);
if(&*item == NULL) {
STACK_PUSH(NULL);
}
else
{
n0 = dynamic_cast<const stringValue*>(&*item);
vLength = (n0->val().length()) + 1;
v.reserve(vLength);
std::strcpy(&v[0], n0->val().c_str());
c = &v[0];
while( --vLength > 0 ){
cp = DecodeUtf8(c);
STACK_PUSH(new numericValue(xs_long, cp));
}
}
STACK_PUSH(NULL);
STACK_END();
}
void StringToCodepointsIterator::resetImpl(){
this->resetChild(argv);
}
void StringToCodepointsIterator::releaseResourcesImpl() {
this->releaseChildResources(argv);
}
/**
*______________________________________________________________________
* 7.3.2 fn:compare
* fn:compare($comparand1 as xs:string?,
* $comparand2 as xs:string?) as xs:integer
*
* fn:compare( $comparand1 as xs:string?,
* $comparand2 as xs:string?,
* $collation as xs:string) as xs:integer?
*
* Summary: Returns -1, 0, or 1, depending on whether the value of
* the $comparand1 is respectively less than, equal to, or greater
* than the value of $comparand2, according to the rules of
* the collation that is used.
*
* If either argument is the empty sequence, the result is the empty sequence.
*_______________________________________________________________________*/
/**
*______________________________________________________________________
*
* 7.3.3 fn:codepoint-equal
*
* fn:codepoint-equal( $comparand1 as xs:string?,
* $comparand2 as xs:string?) as xs:boolean?
*
* Summary: Returns true or false depending on whether the value
* of $comparand1 is equal to the value of $comparand2, according to
* the Unicode code point collation
* (http://www.w3.org/2005/xpath-functions/collation/codepoint).
*
* If either argument is the empty sequence, the result is the empty sequence.
*
* Note: This function allows xs:anyURI values to be compared
* without having to specify the Unicode code point collation.
*_______________________________________________________________________*/
std::ostream& CodepointEqualIterator::_show(std::ostream& os) const{
argv0->show(os);
argv1->show(os);
return os;
}
item_t CodepointEqualIterator::nextImpl(){
item_t item0;
item_t item1;
const stringValue* n0;
const stringValue* n1;
STACK_INIT();
item0 = this->consumeNext(argv0);
item1 = this->consumeNext(argv1);
finish = false;
if(&*item0 == NULL || &*item1 == NULL) {
STACK_PUSH(NULL);
}
else
{
n0 = dynamic_cast<const stringValue*>(&*item0);
n1 = dynamic_cast<const stringValue*>(&*item1);
vLength = (n0->val().length());
if(vLength != n1->val().length())
STACK_PUSH(new booleanValue(false));
else
{
v0.reserve(vLength);
std::strcpy(&v0[0], n0->val().c_str());
c0 = &v0[0];
v1.reserve(vLength);
std::strcpy(&v1[0], n1->val().c_str());
c1 = &v1[0];
while( !finish && (vLength > 0) ){
if(DecodeUtf8(c0) != DecodeUtf8(c1))
{
finish = true;
STACK_PUSH(new booleanValue(false));
}
vLength--;
}
if(!finish)
STACK_PUSH(new booleanValue(true));
}
}
STACK_PUSH(NULL);
STACK_END();
}
void CodepointEqualIterator::resetImpl(){
this->resetChild(argv0);
this->resetChild(argv1);
}
void CodepointEqualIterator::releaseResourcesImpl() {
this->releaseChildResources(argv0);
this->releaseChildResources(argv1);
}
/**
*______________________________________________________________________
*
* 7.4.1 fn:concat
*
* fn:concat( $arg1 as xs:anyAtomicType?,
* $arg2 as xs:anyAtomicType?,
* ... ) as xs:string
*
* Summary:
* Accepts two or more xs:anyAtomicType arguments and casts them to xs:string.
* Returns the xs:string that is the concatenation of the values of its
* arguments after conversion.
* If any of the arguments is the empty sequence, the argument is treated
* as the zero-length string.
*
* The fn:concat function is specified to allow an two or more arguments
* that are concatenated together.
*
* Note:
* Unicode normalization is not automatically applied to the result
* of fn:concat. If a normalized result is required, fn:normalize-unicode
* can be applied to the xs:string returned by fn:concat.
*_______________________________________________________________________*/
std::ostream& ConcatFnIterator::_show(std::ostream& os)
const
{
std::vector<iterator_t>::const_iterator iter = this->argv.begin();
for(; iter != this->argv.end(); ++iter) {
(*iter)->show(os);
}
return os;
}
item_t ConcatFnIterator::nextImpl() {
item_t item;
iterator_t currit_str;
item_t item_str;
const stringValue* n;
STACK_INIT();
this->cursor = 0;
for (; this->cursor < this->argv.size (); this->cursor++) {;
this->currit_h = this->argv[this->cursor];
item = this->consumeNext(this->currit_h);
//TODO use a more high level function provided by the type system
//if the item is not a node => it's a xs:anyAtomicType
if((item->type() & NODE_MASK) == NOT_NODE)
{
currit_str = item->string_value(loc);
item_str = this->consumeNext(currit_str);
n = dynamic_cast<const stringValue*>(&*item_str);
res.append(n->val());
//res.append("1");
}
}
STACK_PUSH(new stringValue(xs_string, res));
STACK_PUSH(NULL);
STACK_END();
}
void ConcatFnIterator::resetImpl() {
std::vector<iterator_t>::iterator iter = this->argv.begin();
for(; iter != this->argv.end(); ++iter) {
this->resetChild(*iter);
}
}
void ConcatFnIterator::releaseResourcesImpl() {
std::vector<iterator_t>::iterator iter = this->argv.begin();
for(; iter != this->argv.end(); ++iter) {
this->releaseChildResources(*iter);
}
}
/**
*______________________________________________________________________
*
* 7.4.2 fn:string-join
*
* fn:string-join($arg1 as xs:string*,
* $arg2 as xs:string) as xs:string
*
*
*
* Summary: Returns a xs:string created by concatenating the members
* of the $arg1 sequence using $arg2 as a separator.
*
* If the value of $arg2 is the zero-length string,
* then the members of $arg1 are concatenated without a separator.
*
* If the value of $arg1 is the empty sequence,
* the zero-length string is returned.
*_______________________________________________________________________*/
std::ostream& StringJoinIterator::_show(std::ostream& os)
const
{
std::vector<iterator_t>::const_iterator iter = this->argv.begin();
for(; iter != this->argv.end(); ++iter) {
(*iter)->show(os);
}
return os;
}
item_t StringJoinIterator::nextImpl() {
STACK_INIT();
STACK_PUSH(new stringValue(xs_string, "result"));
STACK_PUSH(NULL);
STACK_END();
}
void StringJoinIterator::resetImpl() {
std::vector<iterator_t>::iterator iter = this->argv.begin();
for(; iter != this->argv.end(); ++iter) {
this->resetChild(*iter);
}
}
void StringJoinIterator::releaseResourcesImpl() {
std::vector<iterator_t>::iterator iter = this->argv.begin();
for(; iter != this->argv.end(); ++iter) {
this->releaseChildResources(*iter);
}
}
} /* namespace xqp */
<|endoftext|> |
<commit_before>//===- InputSegment.cpp ---------------------------------------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "InputChunks.h"
#include "Config.h"
#include "OutputSegment.h"
#include "lld/Common/ErrorHandler.h"
#include "lld/Common/LLVM.h"
#include "llvm/Support/LEB128.h"
#define DEBUG_TYPE "lld"
using namespace llvm;
using namespace llvm::wasm;
using namespace lld;
using namespace lld::wasm;
uint32_t InputSegment::translateVA(uint32_t Address) const {
assert(Address >= startVA() && Address < endVA());
int32_t Delta = OutputSeg->StartVA + OutputSegmentOffset - startVA();
DEBUG(dbgs() << "translateVA: " << getName() << " Delta=" << Delta
<< " Address=" << Address << "\n");
return Address + Delta;
}
void InputChunk::copyRelocations(const WasmSection &Section) {
if (Section.Relocations.empty())
return;
size_t Start = getInputSectionOffset();
size_t Size = getSize();
for (const WasmRelocation &R : Section.Relocations)
if (R.Offset >= Start && R.Offset < Start + Size)
Relocations.push_back(R);
}
static void applyRelocation(uint8_t *Buf, const OutputRelocation &Reloc) {
DEBUG(dbgs() << "write reloc: type=" << Reloc.Reloc.Type
<< " index=" << Reloc.Reloc.Index << " value=" << Reloc.Value
<< " offset=" << Reloc.Reloc.Offset << "\n");
Buf += Reloc.Reloc.Offset;
int64_t ExistingValue;
switch (Reloc.Reloc.Type) {
case R_WEBASSEMBLY_TYPE_INDEX_LEB:
case R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
ExistingValue = decodeULEB128(Buf);
if (ExistingValue != Reloc.Reloc.Index) {
DEBUG(dbgs() << "existing value: " << decodeULEB128(Buf) << "\n");
assert(decodeULEB128(Buf) == Reloc.Reloc.Index);
}
LLVM_FALLTHROUGH;
case R_WEBASSEMBLY_MEMORY_ADDR_LEB:
case R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
encodeULEB128(Reloc.Value, Buf, 5);
break;
case R_WEBASSEMBLY_TABLE_INDEX_SLEB:
ExistingValue = decodeSLEB128(Buf);
if (ExistingValue != Reloc.Reloc.Index) {
DEBUG(dbgs() << "existing value: " << decodeSLEB128(Buf) << "\n");
assert(decodeSLEB128(Buf) == Reloc.Reloc.Index);
}
LLVM_FALLTHROUGH;
case R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
encodeSLEB128(static_cast<int32_t>(Reloc.Value), Buf, 5);
break;
case R_WEBASSEMBLY_TABLE_INDEX_I32:
case R_WEBASSEMBLY_MEMORY_ADDR_I32:
support::endian::write32<support::little>(Buf, Reloc.Value);
break;
default:
llvm_unreachable("unknown relocation type");
}
}
static void applyRelocations(uint8_t *Buf, ArrayRef<OutputRelocation> Relocs) {
if (!Relocs.size())
return;
DEBUG(dbgs() << "applyRelocations: count=" << Relocs.size() << "\n");
for (const OutputRelocation &Reloc : Relocs)
applyRelocation(Buf, Reloc);
}
void InputChunk::writeTo(uint8_t *SectionStart) const {
memcpy(SectionStart + getOutputOffset(), getData(), getSize());
applyRelocations(SectionStart, OutRelocations);
}
// Populate OutRelocations based on the input relocations and offset within the
// output section. Calculates the updated index and offset for each relocation
// as well as the value to write out in the final binary.
void InputChunk::calcRelocations() {
if (Relocations.empty())
return;
int32_t Off = getOutputOffset() - getInputSectionOffset();
DEBUG(dbgs() << "calcRelocations: " << File->getName()
<< " offset=" << Twine(Off) << "\n");
for (const WasmRelocation &Reloc : Relocations) {
OutputRelocation NewReloc;
NewReloc.Reloc = Reloc;
assert(Reloc.Offset + Off > 0);
NewReloc.Reloc.Offset += Off;
DEBUG(dbgs() << "reloc: type=" << Reloc.Type << " index=" << Reloc.Index
<< " offset=" << Reloc.Offset
<< " newOffset=" << NewReloc.Reloc.Offset << "\n");
if (Config->EmitRelocs)
NewReloc.NewIndex = File->calcNewIndex(Reloc);
switch (Reloc.Type) {
case R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
case R_WEBASSEMBLY_MEMORY_ADDR_I32:
case R_WEBASSEMBLY_MEMORY_ADDR_LEB:
NewReloc.Value = File->getRelocatedAddress(Reloc.Index) + Reloc.Addend;
break;
default:
NewReloc.Value = File->calcNewIndex(Reloc);
break;
}
OutRelocations.emplace_back(NewReloc);
}
}
void InputFunction::setOutputIndex(uint32_t Index) {
DEBUG(dbgs() << "InputFunction::setOutputIndex: " << Index << "\n");
assert(!hasOutputIndex());
OutputIndex = Index;
};
<commit_msg>[WebAssembly] Fix typo in file header<commit_after>//===- InputChunks.cpp ----------------------------------------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "InputChunks.h"
#include "Config.h"
#include "OutputSegment.h"
#include "lld/Common/ErrorHandler.h"
#include "lld/Common/LLVM.h"
#include "llvm/Support/LEB128.h"
#define DEBUG_TYPE "lld"
using namespace llvm;
using namespace llvm::wasm;
using namespace lld;
using namespace lld::wasm;
uint32_t InputSegment::translateVA(uint32_t Address) const {
assert(Address >= startVA() && Address < endVA());
int32_t Delta = OutputSeg->StartVA + OutputSegmentOffset - startVA();
DEBUG(dbgs() << "translateVA: " << getName() << " Delta=" << Delta
<< " Address=" << Address << "\n");
return Address + Delta;
}
void InputChunk::copyRelocations(const WasmSection &Section) {
if (Section.Relocations.empty())
return;
size_t Start = getInputSectionOffset();
size_t Size = getSize();
for (const WasmRelocation &R : Section.Relocations)
if (R.Offset >= Start && R.Offset < Start + Size)
Relocations.push_back(R);
}
static void applyRelocation(uint8_t *Buf, const OutputRelocation &Reloc) {
DEBUG(dbgs() << "write reloc: type=" << Reloc.Reloc.Type
<< " index=" << Reloc.Reloc.Index << " value=" << Reloc.Value
<< " offset=" << Reloc.Reloc.Offset << "\n");
Buf += Reloc.Reloc.Offset;
int64_t ExistingValue;
switch (Reloc.Reloc.Type) {
case R_WEBASSEMBLY_TYPE_INDEX_LEB:
case R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
ExistingValue = decodeULEB128(Buf);
if (ExistingValue != Reloc.Reloc.Index) {
DEBUG(dbgs() << "existing value: " << decodeULEB128(Buf) << "\n");
assert(decodeULEB128(Buf) == Reloc.Reloc.Index);
}
LLVM_FALLTHROUGH;
case R_WEBASSEMBLY_MEMORY_ADDR_LEB:
case R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
encodeULEB128(Reloc.Value, Buf, 5);
break;
case R_WEBASSEMBLY_TABLE_INDEX_SLEB:
ExistingValue = decodeSLEB128(Buf);
if (ExistingValue != Reloc.Reloc.Index) {
DEBUG(dbgs() << "existing value: " << decodeSLEB128(Buf) << "\n");
assert(decodeSLEB128(Buf) == Reloc.Reloc.Index);
}
LLVM_FALLTHROUGH;
case R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
encodeSLEB128(static_cast<int32_t>(Reloc.Value), Buf, 5);
break;
case R_WEBASSEMBLY_TABLE_INDEX_I32:
case R_WEBASSEMBLY_MEMORY_ADDR_I32:
support::endian::write32<support::little>(Buf, Reloc.Value);
break;
default:
llvm_unreachable("unknown relocation type");
}
}
static void applyRelocations(uint8_t *Buf, ArrayRef<OutputRelocation> Relocs) {
if (!Relocs.size())
return;
DEBUG(dbgs() << "applyRelocations: count=" << Relocs.size() << "\n");
for (const OutputRelocation &Reloc : Relocs)
applyRelocation(Buf, Reloc);
}
void InputChunk::writeTo(uint8_t *SectionStart) const {
memcpy(SectionStart + getOutputOffset(), getData(), getSize());
applyRelocations(SectionStart, OutRelocations);
}
// Populate OutRelocations based on the input relocations and offset within the
// output section. Calculates the updated index and offset for each relocation
// as well as the value to write out in the final binary.
void InputChunk::calcRelocations() {
if (Relocations.empty())
return;
int32_t Off = getOutputOffset() - getInputSectionOffset();
DEBUG(dbgs() << "calcRelocations: " << File->getName()
<< " offset=" << Twine(Off) << "\n");
for (const WasmRelocation &Reloc : Relocations) {
OutputRelocation NewReloc;
NewReloc.Reloc = Reloc;
assert(Reloc.Offset + Off > 0);
NewReloc.Reloc.Offset += Off;
DEBUG(dbgs() << "reloc: type=" << Reloc.Type << " index=" << Reloc.Index
<< " offset=" << Reloc.Offset
<< " newOffset=" << NewReloc.Reloc.Offset << "\n");
if (Config->EmitRelocs)
NewReloc.NewIndex = File->calcNewIndex(Reloc);
switch (Reloc.Type) {
case R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
case R_WEBASSEMBLY_MEMORY_ADDR_I32:
case R_WEBASSEMBLY_MEMORY_ADDR_LEB:
NewReloc.Value = File->getRelocatedAddress(Reloc.Index) + Reloc.Addend;
break;
default:
NewReloc.Value = File->calcNewIndex(Reloc);
break;
}
OutRelocations.emplace_back(NewReloc);
}
}
void InputFunction::setOutputIndex(uint32_t Index) {
DEBUG(dbgs() << "InputFunction::setOutputIndex: " << Index << "\n");
assert(!hasOutputIndex());
OutputIndex = Index;
};
<|endoftext|> |
<commit_before>#include "AliHBTReaderKineTree.h"
//_______________________________________________________________________
/////////////////////////////////////////////////////////////////////////
//
// class AliHBTReaderKineTree
//
// Reader for Kinematics
//
// Piotr.Skowronski@cern.ch
//
/////////////////////////////////////////////////////////////////////////
#include <TString.h>
#include <TParticle.h>
#include <AliRunLoader.h>
#include <AliStack.h>
#include "AliHBTEvent.h"
#include "AliHBTParticle.h"
ClassImp(AliHBTReaderKineTree)
/**********************************************************/
const TString AliHBTReaderKineTree::fgkEventFolderName("HBTReaderKineTree");
AliHBTReaderKineTree::AliHBTReaderKineTree():
fFileName("galice.root"),
fRunLoader(0x0)
{
//ctor
}
/**********************************************************/
AliHBTReaderKineTree::AliHBTReaderKineTree(TString& fname):
fFileName(fname),
fRunLoader(0x0)
{
//ctor
}
/**********************************************************/
AliHBTReaderKineTree::AliHBTReaderKineTree(TObjArray* dirs,const Char_t *filename):
AliHBTReader(dirs),
fFileName(filename),
fRunLoader(0x0)
{
//ctor
}
/**********************************************************/
AliHBTReaderKineTree::AliHBTReaderKineTree(const AliHBTReaderKineTree& in):
AliHBTReader(in),
fFileName(in.fFileName),
fRunLoader(0x0)
{
//cpy ctor
}
/**********************************************************/
AliHBTReaderKineTree::~AliHBTReaderKineTree()
{
//dtor
delete fRunLoader;
}
/**********************************************************/
AliHBTReaderKineTree& AliHBTReaderKineTree::operator=(const AliHBTReaderKineTree& in)
{
//Assiment operator
if (this == &in) return *this;
AliHBTReader::operator=(in);
delete fRunLoader;
fRunLoader = 0x0;
return * this;
}
/**********************************************************/
void AliHBTReaderKineTree::Rewind()
{
//Rewinds to the beginning
delete fRunLoader;
fRunLoader = 0x0;
fCurrentDir = 0;
fNEventsRead= 0;
}
/**********************************************************/
Int_t AliHBTReaderKineTree::ReadNext()
{
//Reads Kinematics Tree
Info("Read","");
if (fParticlesEvent == 0x0) fParticlesEvent = new AliHBTEvent();
fParticlesEvent->Reset();
do //do{}while; is OK even if 0 dirs specified. In that case we try to read from "./"
{
if (fRunLoader == 0x0)
if (OpenNextFile())
{
fCurrentDir++;
continue;
}
if (fCurrentEvent == fRunLoader->GetNumberOfEvents())
{
//read next directory
delete fRunLoader;//close current session
fRunLoader = 0x0;//assure pointer is null
fCurrentDir++;//go to next dir
continue;//directory counter is increased inside in case of error
}
Info("ReadNext","Reading Event %d",fCurrentEvent);
fRunLoader->GetEvent(fCurrentEvent);
AliStack* stack = fRunLoader->Stack();
if (!stack)
{
Error("ReadNext","Can not get stack for event %d",fCurrentEvent);
continue;
}
Int_t npart = stack->GetNtrack();
for (Int_t i = 0;i<npart; i++)
{
TParticle * p = stack->Particle(i);
// if (p->GetFirstMother() >= 0) continue; do not apply with pythia etc
if(Pass(p->GetPdgCode())) continue; //check if we are intersted with particles of this type
//if not take next partilce
AliHBTParticle* part = new AliHBTParticle(*p,i);
if(Pass(part)) { delete part; continue;}//check if meets all criteria of any of our cuts
//if it does not delete it and take next good track
fParticlesEvent->AddParticle(part);//put particle in event
}
Info("ReadNext","Read %d particles from event %d (event %d in dir %d).",
fParticlesEvent->GetNumberOfParticles(),
fNEventsRead,fCurrentEvent,fCurrentDir);
fCurrentEvent++;
fNEventsRead++;
return 0;
}while(fCurrentDir < GetNumberOfDirs());//end of loop over directories specified in fDirs Obj Array
return 1;
}
/**********************************************************/
Int_t AliHBTReaderKineTree::OpenNextFile()
{
//opens file with kine tree
Info("OpenNextFile","________________________________________________________");
const TString& dirname = GetDirName(fCurrentEvent);
if (dirname == "")
{
Error("OpenNextFile","Can not get directory name");
return 1;
}
TString filename = dirname +"/"+ fFileName;
fRunLoader = AliRunLoader::Open(filename.Data(),fgkEventFolderName,"READ");
if ( fRunLoader == 0x0)
{
Error("OpenNextFile","Can't open session from file %s",filename.Data());
return 0x0;
}
if (fRunLoader->GetNumberOfEvents() <= 0)
{
Error("OpenNextFile","There is no events in this directory.");
delete fRunLoader;
fRunLoader = 0x0;
return 1;
}
if (fRunLoader->LoadKinematics())
{
Error("OpenNextFile","Error occured while loading kinematics.");
return 1;
}
fCurrentEvent = 0;
return 0;
}
<commit_msg>Bug Correction<commit_after>#include "AliHBTReaderKineTree.h"
//_______________________________________________________________________
/////////////////////////////////////////////////////////////////////////
//
// class AliHBTReaderKineTree
//
// Reader for Kinematics
//
// Piotr.Skowronski@cern.ch
//
/////////////////////////////////////////////////////////////////////////
#include <TString.h>
#include <TParticle.h>
#include <AliRunLoader.h>
#include <AliStack.h>
#include "AliHBTEvent.h"
#include "AliHBTParticle.h"
ClassImp(AliHBTReaderKineTree)
/**********************************************************/
const TString AliHBTReaderKineTree::fgkEventFolderName("HBTReaderKineTree");
AliHBTReaderKineTree::AliHBTReaderKineTree():
fFileName("galice.root"),
fRunLoader(0x0)
{
//ctor
}
/**********************************************************/
AliHBTReaderKineTree::AliHBTReaderKineTree(TString& fname):
fFileName(fname),
fRunLoader(0x0)
{
//ctor
}
/**********************************************************/
AliHBTReaderKineTree::AliHBTReaderKineTree(TObjArray* dirs,const Char_t *filename):
AliHBTReader(dirs),
fFileName(filename),
fRunLoader(0x0)
{
//ctor
}
/**********************************************************/
AliHBTReaderKineTree::AliHBTReaderKineTree(const AliHBTReaderKineTree& in):
AliHBTReader(in),
fFileName(in.fFileName),
fRunLoader(0x0)
{
//cpy ctor
}
/**********************************************************/
AliHBTReaderKineTree::~AliHBTReaderKineTree()
{
//dtor
delete fRunLoader;
}
/**********************************************************/
AliHBTReaderKineTree& AliHBTReaderKineTree::operator=(const AliHBTReaderKineTree& in)
{
//Assiment operator
if (this == &in) return *this;
AliHBTReader::operator=(in);
delete fRunLoader;
fRunLoader = 0x0;
return * this;
}
/**********************************************************/
void AliHBTReaderKineTree::Rewind()
{
//Rewinds to the beginning
delete fRunLoader;
fRunLoader = 0x0;
fCurrentDir = 0;
fNEventsRead= 0;
}
/**********************************************************/
Int_t AliHBTReaderKineTree::ReadNext()
{
//Reads Kinematics Tree
Info("Read","");
if (fParticlesEvent == 0x0) fParticlesEvent = new AliHBTEvent();
fParticlesEvent->Reset();
do //do{}while; is OK even if 0 dirs specified. In that case we try to read from "./"
{
if (fRunLoader == 0x0)
if (OpenNextFile())
{
fCurrentDir++;
continue;
}
if (fCurrentEvent == fRunLoader->GetNumberOfEvents())
{
//read next directory
delete fRunLoader;//close current session
fRunLoader = 0x0;//assure pointer is null
fCurrentDir++;//go to next dir
continue;//directory counter is increased inside in case of error
}
Info("ReadNext","Reading Event %d",fCurrentEvent);
fRunLoader->GetEvent(fCurrentEvent);
AliStack* stack = fRunLoader->Stack();
if (!stack)
{
Error("ReadNext","Can not get stack for event %d",fCurrentEvent);
continue;
}
Int_t npart = stack->GetNtrack();
for (Int_t i = 0;i<npart; i++)
{
TParticle * p = stack->Particle(i);
// if (p->GetFirstMother() >= 0) continue; do not apply with pythia etc
if(Pass(p->GetPdgCode())) continue; //check if we are intersted with particles of this type
//if not take next partilce
AliHBTParticle* part = new AliHBTParticle(*p,i);
if(Pass(part)) { delete part; continue;}//check if meets all criteria of any of our cuts
//if it does not delete it and take next good track
fParticlesEvent->AddParticle(part);//put particle in event
}
Info("ReadNext","Read %d particles from event %d (event %d in dir %d).",
fParticlesEvent->GetNumberOfParticles(),
fNEventsRead,fCurrentEvent,fCurrentDir);
fCurrentEvent++;
fNEventsRead++;
return 0;
}while(fCurrentDir < GetNumberOfDirs());//end of loop over directories specified in fDirs Obj Array
return 1;
}
/**********************************************************/
Int_t AliHBTReaderKineTree::OpenNextFile()
{
//opens file with kine tree
Info("OpenNextFile","________________________________________________________");
const TString& dirname = GetDirName(fCurrentEvent);
if (dirname == "")
{
Error("OpenNextFile","Can not get directory name");
return 1;
}
TString filename = dirname +"/"+ fFileName;
fRunLoader = AliRunLoader::Open(filename.Data(),fgkEventFolderName,"READ");
if ( fRunLoader == 0x0)
{
Error("OpenNextFile","Can't open session from file %s",filename.Data());
return 1;
}
if (fRunLoader->GetNumberOfEvents() <= 0)
{
Error("OpenNextFile","There is no events in this directory.");
delete fRunLoader;
fRunLoader = 0x0;
return 2;
}
if (fRunLoader->LoadKinematics())
{
Error("OpenNextFile","Error occured while loading kinematics.");
return 3;
}
fCurrentEvent = 0;
return 0;
}
<|endoftext|> |
<commit_before>// $Id$
//**************************************************************************
//* This file is property of and copyright by the ALICE HLT Project *
//* ALICE Experiment at CERN, All rights reserved. *
//* *
//* Primary Authors: Matthias Richter <Matthias.Richter@ift.uib.no> *
//* for The ALICE HLT Project. *
//* *
//* Permission to use, copy, modify and distribute this software and its *
//* documentation strictly for non-commercial purposes is hereby granted *
//* without fee, provided that the above copyright notice appears in all *
//* copies and that both the copyright notice and this permission notice *
//* appear in the supporting documentation. The authors make no claims *
//* about the suitability of this software for any purpose. It is *
//* provided "as is" without express or implied warranty. *
//**************************************************************************
/** @file AliHLTAltroEncoder.cxx
@author Matthias Richter
@date
@brief Encoder class for 10/40bit Altro Data format
*/
#include <cassert>
#include <cerrno>
#include "AliHLTAltroEncoder.h"
#include "TArrayC.h"
/** ROOT macro for the implementation of ROOT specific class methods */
ClassImp(AliHLTAltroEncoder)
AliHLTAltroEncoder::AliHLTAltroEncoder()
:
fpBuffer(NULL),
fBufferSize(0),
fPrevTimebin(AliHLTUInt16MAX),
fBunchLength(0),
fChannelStart(0),
fChannel(AliHLTUInt16MAX),
fChannels(),
fOffset(0),
f10bitWords(0),
fOrder(kUnknownOrder),
fpCDH(NULL),
fpRCUTrailer(NULL)
{
// see header file for class documentation
// or
// refer to README to build package
// or
// visit http://web.ift.uib.no/~kjeks/doc/alice-hlt
}
AliHLTAltroEncoder::AliHLTAltroEncoder(AliHLTUInt8_t* pBuffer, int iSize)
:
fpBuffer(pBuffer),
fBufferSize(iSize),
fPrevTimebin(AliHLTUInt16MAX),
fBunchLength(0),
fChannelStart(0),
fChannel(AliHLTUInt16MAX),
fChannels(),
fOffset(0),
f10bitWords(0),
fOrder(kUnknownOrder),
fpCDH(NULL),
fpRCUTrailer(NULL)
{
// see header file for class documentation
}
AliHLTAltroEncoder::~AliHLTAltroEncoder()
{
// see header file for class documentation
if (fpCDH) delete fpCDH;
fpCDH=NULL;
if (fpRCUTrailer) delete fpRCUTrailer;
fpRCUTrailer=NULL;
}
int AliHLTAltroEncoder::SetBuffer(AliHLTUInt8_t* pBuffer, int iSize)
{
// see header file for class documentation
fpBuffer=pBuffer;
fBufferSize=iSize;
return 0;
}
int AliHLTAltroEncoder::AddSignal(AliHLTUInt16_t signal, AliHLTUInt16_t timebin)
{
// see header file for class documentation
int iResult=0;
if (fPrevTimebin!=AliHLTUInt16MAX) {
assert(fPrevTimebin!=timebin);
if (fOrder==kUnknownOrder) {
if (fPrevTimebin+1==timebin) fOrder=kAscending;
else if (fPrevTimebin==timebin+1) fOrder=kDescending;
}
if ((fOrder!=kAscending || fPrevTimebin+1!=timebin) &&
(fOrder!=kDescending || fPrevTimebin!=timebin+1)) {
// Finalize bunch and start new one
iResult=SetBunch();
}
}
if (iResult>=0 && (iResult=Add10BitValue(signal))>=0) {
fBunchLength++;
}
// HLTDebug("fOffset: %d (fOffset-32)*4: %d f10bitWords*5 %d", fOffset,(fOffset-32)*4,f10bitWords*5);
assert((fOffset-(fpCDH?fpCDH->GetSize():0)*4)<=f10bitWords*5);//32 is here size of CDH 8 32bit words
fPrevTimebin=timebin;
return iResult;
}
int AliHLTAltroEncoder::SetChannel(AliHLTUInt16_t hwaddress)
{
// see header file for class documentation
int iResult=0;
int added10BitWords=0;
if (!fpBuffer) return -ENODEV;
if (fOffset+5>=fBufferSize-(fpRCUTrailer?fpRCUTrailer->GetSize():0)) {
HLTWarning("buffer too small too finalize channel: %d of %d byte(s) already used", fOffset, fBufferSize);
return -ENOSPC;
}
if (iResult>=0 &&
(iResult=SetBunch())>=0) {
AliHLTUInt16_t length=f10bitWords-fChannelStart;
if ((iResult=Pad40Bit())<0) return iResult;
// 2 words for the SetBunch (end time and length) and the
// padded words to fill 40bit word
added10BitWords=iResult+2;
assert((length+iResult)%4==0);
//HLTInfo("%d %x", hwaddress, hwaddress);
fpBuffer[fOffset++]=hwaddress&0xff;
fpBuffer[fOffset++]=0xa0 | (hwaddress>>8)&0xf;
fpBuffer[fOffset++]=length&0xff;
fpBuffer[fOffset++]=0xa8 | (length>>8)&0x3;
fpBuffer[fOffset++]=0xaa;
f10bitWords+=4;
fChannelStart=f10bitWords;
fChannels.push_back(hwaddress);
fPrevTimebin=AliHLTUInt16MAX;
}
if (iResult<0) return iResult;
return added10BitWords;
}
int AliHLTAltroEncoder::AddChannelSignal(AliHLTUInt16_t signal, AliHLTUInt16_t timebin, AliHLTUInt16_t hwaddress)
{
// see header file for class documentation
int iResult=0;
int added10BitWords=0;
if (fChannel==AliHLTUInt16MAX) {
fChannel=hwaddress;
} else if (fChannel!=hwaddress) {
iResult=SetChannel(fChannel);
added10BitWords=iResult;
fChannel=hwaddress;
}
if (iResult>=0) {
if ((iResult=AddSignal(signal, timebin))>=0)
added10BitWords++;
}
if (iResult<0) return iResult;
return added10BitWords;
}
int AliHLTAltroEncoder::GetTotal40bitWords()
{
// see header file for class documentation
if (fChannelStart!=f10bitWords) {
HLTWarning("unterminated channel found, check calling sequence");
}
assert(fChannelStart%4==0);
return fChannelStart;
}
int AliHLTAltroEncoder::SetBunch()
{
// see header file for class documentation
int iResult=0;
// return if the bunch has already been set
if (fBunchLength==0) return 0;
// fill time bin and bunch length
if ((iResult=Add10BitValue(fPrevTimebin))>=0) {
iResult=Add10BitValue(fBunchLength+2);
fBunchLength=0;
iResult=2;
}
return iResult;
}
int AliHLTAltroEncoder::Add10BitValue(AliHLTUInt16_t value)
{
// see header file for class documentation
int iResult=0;
if (!fpBuffer) return -ENODEV;
if (fOffset+2>=fBufferSize-(fpRCUTrailer?fpRCUTrailer->GetSize():0)) {
HLTWarning("buffer too small too add 10bit word: %d of %d byte(s) already used", fOffset, fBufferSize);
return -ENOSPC;
}
int bit=(f10bitWords%4)*10;
int shift=bit%8;
unsigned short maskLow=~((0xff<<shift)>>8);
//unsigned short maskHigh=~((0xff<<((bit+10)%8))>>8);
fpBuffer[fOffset++]|=maskLow&(value<<shift);
fpBuffer[fOffset]=(value&0x3ff)>>(8-shift);
f10bitWords++;
if (f10bitWords%4==0) fOffset++;
return iResult;
}
int AliHLTAltroEncoder::Pad40Bit()
{
// see header file for class documentation
int iResult=0;
int added10BitWords=0;
while (iResult>=0 && f10bitWords%4!=0) {
if ((iResult=Add10BitValue(0x2aa))>=0) {
added10BitWords++;
}
}
if (iResult<0) return iResult;
return added10BitWords;
}
int AliHLTAltroEncoder::SetCDH(AliHLTUInt8_t* pCDH,int size)
{
// see header file for class documentation
int iResult=0;
if (fOffset>0) {
HLTError("CDH can only be set prior to data");
iResult=-EFAULT;
}
if (size>0 && pCDH){
if (fpCDH == NULL){
fpCDH = new TArrayC(0);
}
if (fpCDH){
fpCDH->Set(0);
fpCDH->Set(size, (const char*)pCDH);
fOffset=size;
} else {
iResult=-ENOMEM;
}
} else {
iResult=-EINVAL;
}
return iResult;
}
int AliHLTAltroEncoder::SetRCUTrailer(AliHLTUInt8_t* pRCUTrailer,int size)
{
// see header file for class documentation
int iResult=0;
if (size>0 && pRCUTrailer){
if (fpRCUTrailer == NULL){
fpRCUTrailer = new TArrayC(0);
}
if (fpRCUTrailer){
fpRCUTrailer->Set(0);
fpRCUTrailer->Set(size, (const char*)pRCUTrailer);
} else {
iResult=-ENOMEM;
}
} else {
iResult=-EINVAL;
}
return iResult;
}
int AliHLTAltroEncoder::SetLength()
{
// see header file for class documentation
int iResult=0;
if (fChannel!=AliHLTUInt16MAX && (iResult=SetChannel(fChannel))<0) {
HLTError("error finalizing channel");
return iResult;
}
if (fpRCUTrailer && fOffset+fpRCUTrailer->GetSize()<fBufferSize) {
// copy the trailer
AliHLTUInt32_t* pTgt=reinterpret_cast<AliHLTUInt32_t*>(fpBuffer+fOffset);
memcpy(pTgt, fpRCUTrailer->GetArray(), fpRCUTrailer->GetSize());
// set number of 10bit words
*pTgt=GetTotal40bitWords();
fOffset+=fpRCUTrailer->GetSize();
}
if (fpCDH && fOffset>fpCDH->GetSize()) {
memcpy(fpBuffer, fpCDH->GetArray(), fpCDH->GetSize());
AliHLTUInt32_t* pCdhSize=reinterpret_cast<AliHLTUInt32_t*>(fpBuffer);
*pCdhSize=fOffset;//set the first word in the header to be the fOffset(number of bytes added)
HLTDebug("Size set in the header: %d",*pCdhSize);
}
return fOffset;
}
<commit_msg>bugfix: initialize each byte starting a new 40bit word with zero, due to bitwise OR the signal was spoiled by remnants in the buffer; handling of subsequent signals with identical time<commit_after>// $Id$
//**************************************************************************
//* This file is property of and copyright by the ALICE HLT Project *
//* ALICE Experiment at CERN, All rights reserved. *
//* *
//* Primary Authors: Matthias Richter <Matthias.Richter@ift.uib.no> *
//* for The ALICE HLT Project. *
//* *
//* Permission to use, copy, modify and distribute this software and its *
//* documentation strictly for non-commercial purposes is hereby granted *
//* without fee, provided that the above copyright notice appears in all *
//* copies and that both the copyright notice and this permission notice *
//* appear in the supporting documentation. The authors make no claims *
//* about the suitability of this software for any purpose. It is *
//* provided "as is" without express or implied warranty. *
//**************************************************************************
/** @file AliHLTAltroEncoder.cxx
@author Matthias Richter
@date
@brief Encoder class for 10/40bit Altro Data format
*/
#include <cassert>
#include <cerrno>
#include "AliHLTAltroEncoder.h"
#include "TArrayC.h"
/** ROOT macro for the implementation of ROOT specific class methods */
ClassImp(AliHLTAltroEncoder)
AliHLTAltroEncoder::AliHLTAltroEncoder()
:
fpBuffer(NULL),
fBufferSize(0),
fPrevTimebin(AliHLTUInt16MAX),
fBunchLength(0),
fChannelStart(0),
fChannel(AliHLTUInt16MAX),
fChannels(),
fOffset(0),
f10bitWords(0),
fOrder(kUnknownOrder),
fpCDH(NULL),
fpRCUTrailer(NULL)
{
// see header file for class documentation
// or
// refer to README to build package
// or
// visit http://web.ift.uib.no/~kjeks/doc/alice-hlt
}
AliHLTAltroEncoder::AliHLTAltroEncoder(AliHLTUInt8_t* pBuffer, int iSize)
:
fpBuffer(pBuffer),
fBufferSize(iSize),
fPrevTimebin(AliHLTUInt16MAX),
fBunchLength(0),
fChannelStart(0),
fChannel(AliHLTUInt16MAX),
fChannels(),
fOffset(0),
f10bitWords(0),
fOrder(kUnknownOrder),
fpCDH(NULL),
fpRCUTrailer(NULL)
{
// see header file for class documentation
}
AliHLTAltroEncoder::~AliHLTAltroEncoder()
{
// see header file for class documentation
if (fpCDH) delete fpCDH;
fpCDH=NULL;
if (fpRCUTrailer) delete fpRCUTrailer;
fpRCUTrailer=NULL;
}
int AliHLTAltroEncoder::SetBuffer(AliHLTUInt8_t* pBuffer, int iSize)
{
// see header file for class documentation
fpBuffer=pBuffer;
fBufferSize=iSize;
return 0;
}
int AliHLTAltroEncoder::AddSignal(AliHLTUInt16_t signal, AliHLTUInt16_t timebin)
{
// see header file for class documentation
int iResult=0;
if (fPrevTimebin!=AliHLTUInt16MAX) {
if (fPrevTimebin==timebin){
HLTWarning("timebin missmatch, two subsequent signals with identical time added, ignoring signal %d at time %d", signal, timebin);
return -EINVAL;
}
//assert(fPrevTimebin!=timebin);
if (fOrder==kUnknownOrder) {
if (fPrevTimebin+1==timebin) fOrder=kAscending;
else if (fPrevTimebin==timebin+1) fOrder=kDescending;
}
if ((fOrder!=kAscending || fPrevTimebin+1!=timebin) &&
(fOrder!=kDescending || fPrevTimebin!=timebin+1)) {
// Finalize bunch and start new one
iResult=SetBunch();
}
}
if (iResult>=0 && (iResult=Add10BitValue(signal))>=0) {
fBunchLength++;
}
// HLTDebug("fOffset: %d (fOffset-32)*4: %d f10bitWords*5 %d", fOffset,(fOffset-32)*4,f10bitWords*5);
assert((fOffset-(fpCDH?fpCDH->GetSize():0)*4)<=f10bitWords*5);//32 is here size of CDH 8 32bit words
fPrevTimebin=timebin;
return iResult;
}
int AliHLTAltroEncoder::SetChannel(AliHLTUInt16_t hwaddress)
{
// see header file for class documentation
int iResult=0;
int added10BitWords=0;
if (!fpBuffer) return -ENODEV;
if (fOffset+5>=fBufferSize-(fpRCUTrailer?fpRCUTrailer->GetSize():0)) {
HLTWarning("buffer too small too finalize channel: %d of %d byte(s) already used", fOffset, fBufferSize);
return -ENOSPC;
}
if (iResult>=0 &&
(iResult=SetBunch())>=0) {
AliHLTUInt16_t length=f10bitWords-fChannelStart;
if ((iResult=Pad40Bit())<0) return iResult;
// 2 words for the SetBunch (end time and length) and the
// padded words to fill 40bit word
added10BitWords=iResult+2;
assert((length+iResult)%4==0);
//HLTInfo("%d %x", hwaddress, hwaddress);
fpBuffer[fOffset++]=hwaddress&0xff;
fpBuffer[fOffset++]=0xa0 | (hwaddress>>8)&0xf;
fpBuffer[fOffset++]=length&0xff;
fpBuffer[fOffset++]=0xa8 | (length>>8)&0x3;
fpBuffer[fOffset++]=0xaa;
f10bitWords+=4;
fChannelStart=f10bitWords;
fChannels.push_back(hwaddress);
fPrevTimebin=AliHLTUInt16MAX;
}
if (iResult<0) return iResult;
return added10BitWords;
}
int AliHLTAltroEncoder::AddChannelSignal(AliHLTUInt16_t signal, AliHLTUInt16_t timebin, AliHLTUInt16_t hwaddress)
{
// see header file for class documentation
int iResult=0;
int added10BitWords=0;
if (fChannel==AliHLTUInt16MAX) {
fChannel=hwaddress;
} else if (fChannel!=hwaddress) {
iResult=SetChannel(fChannel);
added10BitWords=iResult;
fChannel=hwaddress;
}
if (iResult>=0) {
if ((iResult=AddSignal(signal, timebin))>=0)
added10BitWords++;
}
if (iResult<0) return iResult;
return added10BitWords;
}
int AliHLTAltroEncoder::GetTotal40bitWords()
{
// see header file for class documentation
if (fChannelStart!=f10bitWords) {
HLTWarning("unterminated channel found, check calling sequence");
}
assert(fChannelStart%4==0);
return fChannelStart;
}
int AliHLTAltroEncoder::SetBunch()
{
// see header file for class documentation
int iResult=0;
// return if the bunch has already been set
if (fBunchLength==0) return 0;
// fill time bin and bunch length
if ((iResult=Add10BitValue(fPrevTimebin))>=0) {
iResult=Add10BitValue(fBunchLength+2);
fBunchLength=0;
iResult=2;
}
return iResult;
}
int AliHLTAltroEncoder::Add10BitValue(AliHLTUInt16_t value)
{
// see header file for class documentation
int iResult=0;
if (!fpBuffer) return -ENODEV;
if (fOffset+2>=fBufferSize-(fpRCUTrailer?fpRCUTrailer->GetSize():0)) {
HLTWarning("buffer too small too add 10bit word: %d of %d byte(s) already used", fOffset, fBufferSize);
return -ENOSPC;
}
int bit=(f10bitWords%4)*10;
int shift=bit%8;
unsigned short maskLow=~((0xff<<shift)>>8);
//unsigned short maskHigh=~((0xff<<((bit+10)%8))>>8);
if (bit==0) fpBuffer[fOffset]=0;
fpBuffer[fOffset++]|=maskLow&(value<<shift);
fpBuffer[fOffset]=(value&0x3ff)>>(8-shift);
f10bitWords++;
if (f10bitWords%4==0) fOffset++;
return iResult;
}
int AliHLTAltroEncoder::Pad40Bit()
{
// see header file for class documentation
int iResult=0;
int added10BitWords=0;
while (iResult>=0 && f10bitWords%4!=0) {
if ((iResult=Add10BitValue(0x2aa))>=0) {
added10BitWords++;
}
}
if (iResult<0) return iResult;
return added10BitWords;
}
int AliHLTAltroEncoder::SetCDH(AliHLTUInt8_t* pCDH,int size)
{
// see header file for class documentation
int iResult=0;
if (fOffset>0) {
HLTError("CDH can only be set prior to data");
iResult=-EFAULT;
}
if (size>0 && pCDH){
if (fpCDH == NULL){
fpCDH = new TArrayC(0);
}
if (fpCDH){
fpCDH->Set(0);
fpCDH->Set(size, (const char*)pCDH);
fOffset=size;
} else {
iResult=-ENOMEM;
}
} else {
iResult=-EINVAL;
}
return iResult;
}
int AliHLTAltroEncoder::SetRCUTrailer(AliHLTUInt8_t* pRCUTrailer,int size)
{
// see header file for class documentation
int iResult=0;
if (size>0 && pRCUTrailer){
if (fpRCUTrailer == NULL){
fpRCUTrailer = new TArrayC(0);
}
if (fpRCUTrailer){
fpRCUTrailer->Set(0);
fpRCUTrailer->Set(size, (const char*)pRCUTrailer);
} else {
iResult=-ENOMEM;
}
} else {
iResult=-EINVAL;
}
return iResult;
}
int AliHLTAltroEncoder::SetLength()
{
// see header file for class documentation
int iResult=0;
if (fChannel!=AliHLTUInt16MAX && (iResult=SetChannel(fChannel))<0) {
HLTError("error finalizing channel");
return iResult;
}
if (fpRCUTrailer && fOffset+fpRCUTrailer->GetSize()<fBufferSize) {
// copy the trailer
AliHLTUInt32_t* pTgt=reinterpret_cast<AliHLTUInt32_t*>(fpBuffer+fOffset);
memcpy(pTgt, fpRCUTrailer->GetArray(), fpRCUTrailer->GetSize());
// set number of 10bit words
*pTgt=GetTotal40bitWords();
fOffset+=fpRCUTrailer->GetSize();
}
if (fpCDH && fOffset>fpCDH->GetSize()) {
memcpy(fpBuffer, fpCDH->GetArray(), fpCDH->GetSize());
AliHLTUInt32_t* pCdhSize=reinterpret_cast<AliHLTUInt32_t*>(fpBuffer);
*pCdhSize=fOffset;//set the first word in the header to be the fOffset(number of bytes added)
HLTDebug("Size set in the header: %d",*pCdhSize);
}
return fOffset;
}
<|endoftext|> |
<commit_before>#include "Halide.h"
#include <tiramisu/utils.h>
#include <cstdlib>
#include <iostream>
#include "mkl_cblas.h"
#include "sgemm_wrapper.h"
#include "benchmarks.h"
#ifdef __cplusplus
extern "C" {
#endif
#ifdef __cplusplus
} // extern "C"
#endif
int main(int, char **)
{
std::vector<std::chrono::duration<double,std::milli>> duration_vector_1;
std::vector<std::chrono::duration<double,std::milli>> duration_vector_2;
float a = 3, b = 3;
#if 1
bool run_mkl = false;
bool run_tiramisu = false;
const char* env_mkl = std::getenv("RUN_REF");
if ((env_mkl != NULL) && (env_mkl[0] == '1'))
run_mkl = true;
const char* env_tira = std::getenv("RUN_TIRAMISU");
if ((env_tira != NULL) && (env_tira[0] == '1'))
run_tiramisu = true;
#else
bool run_mkl = true;
bool run_tiramisu = true;
#endif
int sizes[27][4], D = 1060 * 1060;
/************ SIZE_IS_MULTIPLE_OF_TILE 1 ******************/
sizes[0][0] = 4096;
sizes[0][1] = 4096;
sizes[0][2] = 4096;
sizes[0][3] = 65536 * 4096;
sizes[1][0] = 128;
sizes[1][1] = 128;
sizes[1][2] = 128;
sizes[1][3] = 128;
sizes[2][0] = 512;
sizes[2][1] = 512;
sizes[2][2] = 512;
sizes[2][3] = 1024;
sizes[3][0] = 1024;
sizes[3][1] = 1024;
sizes[3][2] = 1024;
sizes[3][3] = 1024 * 1024;
sizes[4][0] = 128;
sizes[4][1] = 128;
sizes[4][2] = 256;
sizes[4][3] = D;
sizes[5][0] = 2048;
sizes[5][1] = 2048;
sizes[5][2] = 2048;
sizes[5][3] = D;
sizes[6][0] = 2048;
sizes[6][1] = 2048;
sizes[6][2] = 1024;
sizes[6][3] = D;
sizes[7][0] = 1024;
sizes[7][1] = 1024;
sizes[7][2] = 2048;
sizes[7][3] = D;
sizes[8][0] = 1024;
sizes[8][1] = 1024;
sizes[8][2] = 512;
sizes[8][3] = D;
sizes[9][0] = 512;
sizes[9][1] = 512;
sizes[9][2] = 1024;
sizes[9][3] = D;
sizes[10][0] = 512;
sizes[10][1] = 512;
sizes[10][2] = 256;
sizes[10][3] = D;
sizes[11][0] = 128;
sizes[11][1] = 128;
sizes[11][2] = 2048;
sizes[11][3] = D;
sizes[12][0] = 256;
sizes[12][1] = 256;
sizes[12][2] = 256;
sizes[12][3] = D;
sizes[13][0] = 128;
sizes[13][1] = 128;
sizes[13][2] = 512;
sizes[13][3] = D;
sizes[14][0] = 128;
sizes[14][1] = 128;
sizes[14][2] = 1024;
sizes[14][3] = D;
sizes[15][0] = 128;
sizes[15][1] = 128;
sizes[15][2] = 64;
sizes[15][3] = D;
/************** SIZE_IS_MULTIPLE_OF_TILE 0 ****************/
sizes[16][0] = 1060;
sizes[16][1] = 1060;
sizes[16][2] = 1060;
sizes[16][3] = D;
sizes[17][0] = 4;
sizes[17][1] = 4;
sizes[17][2] = 4;
sizes[17][3] = D;
sizes[18][0] = 8;
sizes[18][1] = 8;
sizes[18][2] = 4;
sizes[18][3] = D;
sizes[19][0] = 16;
sizes[19][1] = 16;
sizes[19][2] = 4;
sizes[19][3] = D;
sizes[20][0] = 16;
sizes[20][1] = 16;
sizes[20][2] = 16;
sizes[20][3] = D;
sizes[21][0] = 8;
sizes[21][1] = 8;
sizes[21][2] = 16;
sizes[21][3] = D;
int p, q;
if (SIZE_IS_MULTIPLE_OF_TILE)
{
p = 0;
q = 16;
}
else
{
p = 16;
q = 22;
}
for (int j = p; j < q; j++)
{
int local_N = sizes[j][0];
int local_M = sizes[j][1];
int local_K = sizes[j][2];
int local_size = sizes[j][3];
Halide::Buffer<int> SIZES(3, "SIZES");
Halide::Buffer<float> alpha(1, "alpha");
Halide::Buffer<float> beta(1, "beta");
Halide::Buffer<float> A(local_N, local_K, "A");
Halide::Buffer<float> B(local_K, local_M, "B");
Halide::Buffer<float> C(local_N, local_M, "C");
Halide::Buffer<float> C_mkl(local_N, local_M, "C_mkl");
SIZES(0) = local_N; SIZES(1) = local_M; SIZES(2) = local_K;
alpha(0) = a; beta(0) = b;
init_buffer(A, (float)1);
init_buffer(B, (float)1);
init_buffer(C, (float)1);
init_buffer(C_mkl, (float)1);
// Calling MKL
{
long long int lda, ldb, ldc;
long long int rmaxa, cmaxa, rmaxb, cmaxb, rmaxc, cmaxc;
CBLAS_LAYOUT layout = CblasRowMajor;
CBLAS_TRANSPOSE transA = CblasNoTrans, transB = CblasNoTrans;
long long int ma, na, mb, nb;
if( transA == CblasNoTrans ) {
rmaxa = local_M + 1;
cmaxa = local_K;
ma = local_M;
na = local_K;
} else {
rmaxa = local_K + 1;
cmaxa = local_M;
ma = local_K;
na = local_M;
}
if( transB == CblasNoTrans ) {
rmaxb = local_K + 1;
cmaxb = local_N;
mb = local_K;
nb = local_N;
} else {
rmaxb = local_N + 1;
cmaxb = local_K;
mb = local_N;
nb = local_K;
}
rmaxc = local_M + 1;
cmaxc = local_N;
if (layout == CblasRowMajor) {
lda=cmaxa;
ldb=cmaxb;
ldc=cmaxc;
} else {
lda=rmaxa;
ldb=rmaxb;
ldc=rmaxc;
}
for (int i = 0; i < NB_TESTS; i++)
{
init_buffer(C_mkl, (float)1);
auto start1 = std::chrono::high_resolution_clock::now();
if (run_mkl == true)
cblas_sgemm(layout, transA, transB, local_M, local_N, local_K, a, (float *) A.raw_buffer()->host, lda, (float *) B.raw_buffer()->host, ldb, b, (float *) C_mkl.raw_buffer()->host, ldc);
auto end1 = std::chrono::high_resolution_clock::now();
std::chrono::duration<double,std::milli> duration1 = end1 - start1;
duration_vector_1.push_back(duration1);
}
}
for (int i = 0; i < NB_TESTS; i++)
{
init_buffer(C, (float)1);
auto start2 = std::chrono::high_resolution_clock::now();
if (run_tiramisu == true)
sgemm_tiramisu(SIZES.raw_buffer(), alpha.raw_buffer(), beta.raw_buffer(), A.raw_buffer(), B.raw_buffer(), C.raw_buffer());
auto end2 = std::chrono::high_resolution_clock::now();
std::chrono::duration<double,std::milli> duration2 = end2 - start2;
duration_vector_2.push_back(duration2);
}
print_time("performance_CPU.csv", "sgemm",
{"MKL", "Tiramisu"},
{median(duration_vector_1), median(duration_vector_2)});
if (CHECK_CORRECTNESS)
if (run_mkl == 1 && run_tiramisu == 1)
{
compare_buffers("sgemm", C, C_mkl);
}
if (PRINT_OUTPUT)
{
std::cout << "Tiramisu sgemm " << std::endl;
print_buffer(C);
std::cout << "MKL sgemm " << std::endl;
print_buffer(C_mkl);
}
}
return 0;
}
<commit_msg>Update sgemm_wrapper.cpp<commit_after>#include "Halide.h"
#include <tiramisu/utils.h>
#include <cstdlib>
#include <iostream>
#include "mkl_cblas.h"
#include "sgemm_wrapper.h"
#include "benchmarks.h"
#ifdef __cplusplus
extern "C" {
#endif
#ifdef __cplusplus
} // extern "C"
#endif
int main(int, char **)
{
std::vector<std::chrono::duration<double,std::milli>> duration_vector_1;
std::vector<std::chrono::duration<double,std::milli>> duration_vector_2;
float a = 3, b = 3;
#if 1
bool run_mkl = false;
bool run_tiramisu = false;
const char* env_mkl = std::getenv("RUN_REF");
if ((env_mkl != NULL) && (env_mkl[0] == '1'))
run_mkl = true;
const char* env_tira = std::getenv("RUN_TIRAMISU");
if ((env_tira != NULL) && (env_tira[0] == '1'))
run_tiramisu = true;
#else
bool run_mkl = true;
bool run_tiramisu = true;
#endif
int sizes[27][4], D = 1060 * 1060;
/************ SIZE_IS_MULTIPLE_OF_TILE 1 ******************/
sizes[0][0] = 4096;
sizes[0][1] = 4096;
sizes[0][2] = 4096;
sizes[0][3] = 65536 * 4096;
sizes[1][0] = 128;
sizes[1][1] = 128;
sizes[1][2] = 128;
sizes[1][3] = 128;
sizes[2][0] = 512;
sizes[2][1] = 512;
sizes[2][2] = 512;
sizes[2][3] = 1024;
sizes[3][0] = 1024;
sizes[3][1] = 1024;
sizes[3][2] = 1024;
sizes[3][3] = 1024 * 1024;
sizes[4][0] = 128;
sizes[4][1] = 128;
sizes[4][2] = 256;
sizes[4][3] = D;
sizes[5][0] = 2048;
sizes[5][1] = 2048;
sizes[5][2] = 2048;
sizes[5][3] = D;
sizes[6][0] = 2048;
sizes[6][1] = 2048;
sizes[6][2] = 1024;
sizes[6][3] = D;
sizes[7][0] = 1024;
sizes[7][1] = 1024;
sizes[7][2] = 2048;
sizes[7][3] = D;
sizes[8][0] = 1024;
sizes[8][1] = 1024;
sizes[8][2] = 512;
sizes[8][3] = D;
sizes[9][0] = 512;
sizes[9][1] = 512;
sizes[9][2] = 1024;
sizes[9][3] = D;
sizes[10][0] = 512;
sizes[10][1] = 512;
sizes[10][2] = 256;
sizes[10][3] = D;
sizes[11][0] = 128;
sizes[11][1] = 128;
sizes[11][2] = 2048;
sizes[11][3] = D;
sizes[12][0] = 256;
sizes[12][1] = 256;
sizes[12][2] = 256;
sizes[12][3] = D;
sizes[13][0] = 128;
sizes[13][1] = 128;
sizes[13][2] = 512;
sizes[13][3] = D;
sizes[14][0] = 128;
sizes[14][1] = 128;
sizes[14][2] = 1024;
sizes[14][3] = D;
sizes[15][0] = 128;
sizes[15][1] = 128;
sizes[15][2] = 64;
sizes[15][3] = D;
/************** SIZE_IS_MULTIPLE_OF_TILE 0 ****************/
sizes[16][0] = 1060;
sizes[16][1] = 1060;
sizes[16][2] = 1060;
sizes[16][3] = D;
sizes[17][0] = 4;
sizes[17][1] = 4;
sizes[17][2] = 4;
sizes[17][3] = D;
sizes[18][0] = 8;
sizes[18][1] = 8;
sizes[18][2] = 4;
sizes[18][3] = D;
sizes[19][0] = 16;
sizes[19][1] = 16;
sizes[19][2] = 4;
sizes[19][3] = D;
sizes[20][0] = 16;
sizes[20][1] = 16;
sizes[20][2] = 16;
sizes[20][3] = D;
sizes[21][0] = 8;
sizes[21][1] = 8;
sizes[21][2] = 16;
sizes[21][3] = D;
int p, q;
if (SIZE_IS_MULTIPLE_OF_TILE)
{
p = 0;
q = 16;
}
else
{
p = 16;
q = 22;
}
for (int j = p; j < q; j++)
{
int local_N = sizes[j][0];
int local_M = sizes[j][1];
int local_K = sizes[j][2];
int local_size = sizes[j][3];
Halide::Buffer<int> SIZES(3, "SIZES");
Halide::Buffer<float> alpha(1, "alpha");
Halide::Buffer<float> beta(1, "beta");
Halide::Buffer<float> A(local_N, local_K, "A");
Halide::Buffer<float> B(local_K, local_M, "B");
Halide::Buffer<float> C(local_N, local_M, "C");
Halide::Buffer<float> C_mkl(local_N, local_M, "C_mkl");
SIZES(0) = local_N; SIZES(1) = local_M; SIZES(2) = local_K;
alpha(0) = a; beta(0) = b;
init_buffer(A, (float)1);
init_buffer(B, (float)1);
init_buffer(C, (float)1);
init_buffer(C_mkl, (float)1);
// Calling MKL
{
long long int lda, ldb, ldc;
long long int rmaxa, cmaxa, rmaxb, cmaxb, rmaxc, cmaxc;
CBLAS_LAYOUT layout = CblasRowMajor;
CBLAS_TRANSPOSE transA = CblasNoTrans, transB = CblasNoTrans;
long long int ma, na, mb, nb;
if( transA == CblasNoTrans ) {
rmaxa = local_M + 1;
cmaxa = local_K;
ma = local_M;
na = local_K;
} else {
rmaxa = local_K + 1;
cmaxa = local_M;
ma = local_K;
na = local_M;
}
if( transB == CblasNoTrans ) {
rmaxb = local_K + 1;
cmaxb = local_N;
mb = local_K;
nb = local_N;
} else {
rmaxb = local_N + 1;
cmaxb = local_K;
mb = local_N;
nb = local_K;
}
rmaxc = local_M + 1;
cmaxc = local_N;
if (layout == CblasRowMajor) {
lda=cmaxa;
ldb=cmaxb;
ldc=cmaxc;
} else {
lda=rmaxa;
ldb=rmaxb;
ldc=rmaxc;
}
for (int i = 0; i < NB_TESTS; i++)
{
init_buffer(C_mkl, (float)1);
auto start1 = std::chrono::high_resolution_clock::now();
if (run_mkl == true)
cblas_sgemm(layout, transA, transB, local_M, local_N, local_K, a, (float *) A.raw_buffer()->host, lda, (float *) B.raw_buffer()->host, ldb, b, (float *) C_mkl.raw_buffer()->host, ldc);
auto end1 = std::chrono::high_resolution_clock::now();
std::chrono::duration<double,std::milli> duration1 = end1 - start1;
duration_vector_1.push_back(duration1);
}
}
for (int i = 0; i < NB_TESTS; i++)
{
init_buffer(C, (float)1);
auto start2 = std::chrono::high_resolution_clock::now();
if (run_tiramisu == true)
sgemm_tiramisu(SIZES.raw_buffer(), alpha.raw_buffer(), beta.raw_buffer(), A.raw_buffer(), B.raw_buffer(), C.raw_buffer());
auto end2 = std::chrono::high_resolution_clock::now();
std::chrono::duration<double,std::milli> duration2 = end2 - start2;
duration_vector_2.push_back(duration2);
}
print_time("performance_CPU.csv", "sgemm",
{"MKL", "Tiramisu"},
{median(duration_vector_1), median(duration_vector_2)});
if (CHECK_CORRECTNESS)
if (run_mkl == 1 && run_tiramisu == 1)
{
compare_buffers("sgemm", C, C_mkl);
}
if (PRINT_OUTPUT)
{
std::cout << "Tiramisu sgemm " << std::endl;
print_buffer(C);
std::cout << "MKL sgemm " << std::endl;
print_buffer(C_mkl);
}
}
return 0;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <sstream>
#include <string>
#include "pegmatite.hh"
// This is very bad style, but it's okay for a short example...
using namespace std;
using namespace pegmatite;
/**
* The AST namespace contains the abstract syntax tree for this grammar.
*/
namespace AST
{
/**
* The base class for expressions in our language.
*/
class Expression : public ASTContainer
{
public:
/**
* Evaluate this expression. Returns a `double` representing the result of
* the evaluation.
*/
virtual double eval() const = 0;
/**
* Print the node, at the specified indent depth.
*/
virtual void print(size_t depth = 0) const = 0;
PEGMATITE_RTTI(Expression, ASTContainer)
};
/**
* AST node representing a number.
*/
class Number : public Expression
{
/**
* The parsed value for this number.
*/
double value;
public:
/**
* Construct the numerical value from the text in the input range.
*/
void construct(const pegmatite::InputRange &r, pegmatite::ASTStack &) override
{
stringstream stream;
for_each(r.begin(), r.end(), [&](char c) {stream << c;});
stream >> value;
}
double eval() const override
{
return value;
}
void print(size_t depth) const override
{
cout << string(depth, '\t') << value << endl;
}
};
/**
* Superclass for all of the binary expressions. Contains pointers to the left
* and right children. Subclasses encode the operation type.
*/
template<class func, char op>
class BinaryExpression : public Expression
{
/**
* The pointers to the left and right nodes. The `ASTPtr` class will
* automatically fill these in when this node is constructed, popping the
* two top values from the AST stack.
*/
ASTPtr<Expression> left, right;
public:
double eval() const override
{
func f;
return f(left->eval(), right->eval());
}
void print(size_t depth) const override
{
cout << string(depth, '\t') << op << endl;
left->print(depth+1);
right->print(depth+1);
}
};
}
namespace Parser
{
/**
* The (singleton) calculator grammar.
*/
struct CalculatorGrammar
{
/**
* Only spaces are recognised as whitespace in this toy example.
*/
Rule ws = " \t\n"_E;
/**
* Digits are things in the range 0-9.
*/
Rule digits = "[0-9]+"_R;
/**
* Numbers are one or more digits, optionally followed by a decimal point,
* and one or more digits, optionally followed by an exponent (which may
* also be negative.
*/
Rule num = digits >> -('.'_E >> digits >> -("eE"_S >> -("+-"_S) >> digits));
/**
* Values are either numbers or expressions in brackets (highest precedence).
*/
Rule val = num | '(' >> expr >> ')';
/**
* Multiply operations are values or multiply, or divide operations,
* followed by a multiply symbol, followed by a values, or multiply or
* divide operations. The sides can never be add or subtract operations,
* because they have lower precedence and so can only be parents of
* multiply or divide operations (or children via parenthetical
* expressions), not direct children.
*/
Rule mul_op = mul >> '*' >> mul;
/**
* Divide operations follow the same syntax as multiply.
*/
Rule div_op = mul >> '/' >> mul;
/**
* Multiply-precedence operations are either multiply or divide operations,
* or simple values (numbers of parenthetical expressions).
*/
Rule mul = mul_op | div_op | val;
/**
* Add operations can have any expression on the left (including other add
* expressions), but only higher-precedence operations on the right.
*/
Rule add_op = expr >> '+' >> expr;
/**
* Subtract operations follow the same structure as add.
*/
Rule sub_op = expr >> '-' >> expr;
/**
* Expressions can be any of the other types.
*/
Rule expr = add_op | sub_op | mul;
/**
* Returns a singleton instance of this grammar.
*/
static const CalculatorGrammar& get()
{
static CalculatorGrammar g;
return g;
}
private:
/**
* Private constructor. This class is immutable, and so only the `get()`
* method should be used to return the singleton instance.
*/
CalculatorGrammar() {}
};
/**
* CalculatorParser, constructs an AST from an input string.
*/
class CalculatorParser : public ASTParserDelegate
{
public:
const CalculatorGrammar &g = CalculatorGrammar::get();
BindAST<AST::Number> num = g.num;
BindAST<AST::BinaryExpression<plus<double>,'+'>> add = g.add_op;
BindAST<AST::BinaryExpression<minus<double>,'-'>> sub = g.sub_op;
BindAST<AST::BinaryExpression<multiplies<double>,'*'>> mul = g.mul_op;
BindAST<AST::BinaryExpression<divides<double>,'/'>> div = g.div_op;
};
}
int main()
{
Parser::CalculatorParser p;
for (;;)
{
string s;
cout << "enter a math expression (+ - * /, floats, parentheses) or enter to exit:\n";
getline(cin, s);
if (s.empty()) break;
//convert the string to input
StringInput i(move(s));
//parse
ErrorReporter er = [](const InputRange &ir, const string &str)
{
cout << "line " << ir.start.line << ", col " << ir.finish.col << ": " << str;
};
unique_ptr<AST::Expression> root = 0;
p.parse(i, p.g.expr, p.g.ws, er, root);
//on success
if (root)
{
double v = root->eval();
cout << "success\n";
cout << "result = " << v << endl;
cout << "parse tree:\n";
root->print(0);
}
//next input
cout << endl;
}
return 0;
}
<commit_msg>Add a default value to print.<commit_after>#include <iostream>
#include <sstream>
#include <string>
#include "pegmatite.hh"
// This is very bad style, but it's okay for a short example...
using namespace std;
using namespace pegmatite;
/**
* The AST namespace contains the abstract syntax tree for this grammar.
*/
namespace AST
{
/**
* The base class for expressions in our language.
*/
class Expression : public ASTContainer
{
public:
/**
* Evaluate this expression. Returns a `double` representing the result of
* the evaluation.
*/
virtual double eval() const = 0;
/**
* Print the node, at the specified indent depth.
*/
virtual void print(size_t depth = 0) const = 0;
PEGMATITE_RTTI(Expression, ASTContainer)
};
/**
* AST node representing a number.
*/
class Number : public Expression
{
/**
* The parsed value for this number.
*/
double value;
public:
/**
* Construct the numerical value from the text in the input range.
*/
void construct(const pegmatite::InputRange &r, pegmatite::ASTStack &) override
{
stringstream stream;
for_each(r.begin(), r.end(), [&](char c) {stream << c;});
stream >> value;
}
double eval() const override
{
return value;
}
void print(size_t depth) const override
{
cout << string(depth, '\t') << value << endl;
}
};
/**
* Superclass for all of the binary expressions. Contains pointers to the left
* and right children. Subclasses encode the operation type.
*/
template<class func, char op>
class BinaryExpression : public Expression
{
/**
* The pointers to the left and right nodes. The `ASTPtr` class will
* automatically fill these in when this node is constructed, popping the
* two top values from the AST stack.
*/
ASTPtr<Expression> left, right;
public:
double eval() const override
{
func f;
return f(left->eval(), right->eval());
}
void print(size_t depth=0) const override
{
cout << string(depth, '\t') << op << endl;
left->print(depth+1);
right->print(depth+1);
}
};
}
namespace Parser
{
/**
* The (singleton) calculator grammar.
*/
struct CalculatorGrammar
{
/**
* Only spaces are recognised as whitespace in this toy example.
*/
Rule ws = " \t\n"_E;
/**
* Digits are things in the range 0-9.
*/
Rule digits = "[0-9]+"_R;
/**
* Numbers are one or more digits, optionally followed by a decimal point,
* and one or more digits, optionally followed by an exponent (which may
* also be negative.
*/
Rule num = digits >> -('.'_E >> digits >> -("eE"_S >> -("+-"_S) >> digits));
/**
* Values are either numbers or expressions in brackets (highest precedence).
*/
Rule val = num | '(' >> expr >> ')';
/**
* Multiply operations are values or multiply, or divide operations,
* followed by a multiply symbol, followed by a values, or multiply or
* divide operations. The sides can never be add or subtract operations,
* because they have lower precedence and so can only be parents of
* multiply or divide operations (or children via parenthetical
* expressions), not direct children.
*/
Rule mul_op = mul >> '*' >> mul;
/**
* Divide operations follow the same syntax as multiply.
*/
Rule div_op = mul >> '/' >> mul;
/**
* Multiply-precedence operations are either multiply or divide operations,
* or simple values (numbers of parenthetical expressions).
*/
Rule mul = mul_op | div_op | val;
/**
* Add operations can have any expression on the left (including other add
* expressions), but only higher-precedence operations on the right.
*/
Rule add_op = expr >> '+' >> expr;
/**
* Subtract operations follow the same structure as add.
*/
Rule sub_op = expr >> '-' >> expr;
/**
* Expressions can be any of the other types.
*/
Rule expr = add_op | sub_op | mul;
/**
* Returns a singleton instance of this grammar.
*/
static const CalculatorGrammar& get()
{
static CalculatorGrammar g;
return g;
}
private:
/**
* Private constructor. This class is immutable, and so only the `get()`
* method should be used to return the singleton instance.
*/
CalculatorGrammar() {}
};
/**
* CalculatorParser, constructs an AST from an input string.
*/
class CalculatorParser : public ASTParserDelegate
{
public:
const CalculatorGrammar &g = CalculatorGrammar::get();
BindAST<AST::Number> num = g.num;
BindAST<AST::BinaryExpression<plus<double>,'+'>> add = g.add_op;
BindAST<AST::BinaryExpression<minus<double>,'-'>> sub = g.sub_op;
BindAST<AST::BinaryExpression<multiplies<double>,'*'>> mul = g.mul_op;
BindAST<AST::BinaryExpression<divides<double>,'/'>> div = g.div_op;
};
}
int main()
{
Parser::CalculatorParser p;
for (;;)
{
string s;
cout << "enter a math expression (+ - * /, floats, parentheses) or enter to exit:\n";
getline(cin, s);
if (s.empty()) break;
//convert the string to input
StringInput i(move(s));
//parse
ErrorReporter er = [](const InputRange &ir, const string &str)
{
cout << "line " << ir.start.line << ", col " << ir.finish.col << ": " << str;
};
unique_ptr<AST::Expression> root = 0;
p.parse(i, p.g.expr, p.g.ws, er, root);
//on success
if (root)
{
double v = root->eval();
cout << "success\n";
cout << "result = " << v << endl;
cout << "parse tree:\n";
root->print();
}
//next input
cout << endl;
}
return 0;
}
<|endoftext|> |
<commit_before>/// @file demo_multilayer_iris.cpp -- A multilayer perceptron on Iris dataset
///
/// usage: demo_multilayer_iris [path_to_data (default: ../data/iris.csv)]
#include <iostream>
#include <fstream>
#include <ostream>
#include <string>
#include <iomanip>
#include "notch.hpp"
#include "notch_io.hpp"
#include "notch_pre.hpp"
using namespace std;
ostream &operator<<(ostream &out, const Dataset &d) {
for (auto v : d) {
out << v << "\n";
}
return out;
}
int main(int argc, char *argv[]) {
string csvFile("../data/iris.csv");
if (argc == 2) {
csvFile = string(argv[1]);
}
cout << "reading dataset from CSV " << csvFile << "\n";
ifstream f(csvFile);
if (!f.is_open()) {
cerr << "cannot open " << csvFile << "\n";
exit(-1);
}
LabeledDataset trainSet = CSVReader<>::read(f);
OneHotEncoder labelEnc(trainSet.getLabels());
trainSet.transformLabels(labelEnc);
//cout << ArrowFormat(trainSet);
MultilayerPerceptron net({4, 6, 3}, scaledTanh);
unique_ptr<RNG> rng(newRNG());
net.init(rng);
cout << net << "\n\n";
cout << "initial loss: " << totalLoss(L2_loss, net, trainSet) << "\n";
for (int j = 0; j < 1000; ++j) {
// training cycle
for (auto sample : trainSet) {
Array actualOutput = net.forwardPass(sample.data);
Array err = sample.label - actualOutput;
net.backwardPass(err, 0.01f);
}
if (j % 50 == 49) {
cout << "epoch " << j+1
<< " loss: " << totalLoss(L2_loss, net, trainSet) << "\n";
}
}
cout << "\n";
cout << net << "\n";
for (auto s : trainSet) {
cout << s.data << " -> ";
cout << labelEnc.inverse_transform(net.forwardPass(s.data)) << "\n";
}
cout << "\n";
}
<commit_msg>update demo_multilayer_iris to use new MultilayerPerceptron<commit_after>/// @file demo_multilayer_iris.cpp -- A multilayer perceptron on Iris dataset
///
/// usage: demo_multilayer_iris [path_to_data (default: ../data/iris.csv)]
#include <iostream>
#include <fstream>
#include <ostream>
#include <string>
#include <iomanip>
#include "notch.hpp"
#include "notch_io.hpp"
#include "notch_pre.hpp"
using namespace std;
ostream &operator<<(ostream &out, const Dataset &d) {
for (auto v : d) {
out << v << "\n";
}
return out;
}
int main(int argc, char *argv[]) {
string csvFile("../data/iris.csv");
if (argc == 2) {
csvFile = string(argv[1]);
}
cout << "reading dataset from CSV " << csvFile << "\n";
ifstream f(csvFile);
if (!f.is_open()) {
cerr << "cannot open " << csvFile << "\n";
exit(-1);
}
LabeledDataset trainSet = CSVReader<>::read(f);
OneHotEncoder labelEnc(trainSet.getLabels());
trainSet.transformLabels(labelEnc);
//cout << ArrowFormat(trainSet);
MultilayerPerceptron net({4, 6, 3}, scaledTanh);
unique_ptr<RNG> rng(newRNG());
net.init(rng);
cout << net << "\n\n";
cout << "initial loss: " << totalLoss(L2_loss, net, trainSet) << "\n";
float learningRate = 0.01f;
for (int j = 0; j < 1000; ++j) {
// training cycle
for (auto sample : trainSet) {
Array actualOutput = *net.output(sample.data);
Array err = sample.label - actualOutput;
auto backpropResult = net.backprop(err);
net.adjustWeights(learningRate);
}
if (j % 50 == 49) {
cout << "epoch " << j+1
<< " loss: " << totalLoss(L2_loss, net, trainSet) << "\n";
}
}
cout << "\n";
cout << net << "\n";
for (auto s : trainSet) {
cout << s.data << " -> ";
cout << labelEnc.inverse_transform(*net.output(s.data)) << "\n";
}
cout << "\n";
}
<|endoftext|> |
<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// 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 <os>
#include <net/inet4>
#include <net/dhcp/dh4client.hpp>
#include <math.h> // rand()
#include <sstream>
// An IP-stack object
std::unique_ptr<net::Inet4<VirtioNet> > inet;
using namespace std::chrono;
void Service::start() {
// Assign a driver (VirtioNet) to a network interface (eth0)
// @note: We could determine the appropirate driver dynamically, but then we'd
// have to include all the drivers into the image, which we want to avoid.
hw::Nic<VirtioNet>& eth0 = hw::Dev::eth<0,VirtioNet>();
// Bring up a network stack, attached to the nic
// @note : No parameters after 'nic' means we'll use DHCP for IP config.
inet = std::make_unique<net::Inet4<VirtioNet> >(eth0);
// Static IP configuration, until we (possibly) get DHCP
// @note : Mostly to get a robust demo service that it works with and without DHCP
inet->network_config( {{ 10,0,0,42 }}, // IP
{{ 255,255,255,0 }}, // Netmask
{{ 10,0,0,1 }}, // Gateway
{{ 8,8,8,8 }} ); // DNS
srand(OS::cycles_since_boot());
// Set up a TCP server on port 80
auto& server = inet->tcp().bind(80);
hw::PIT::instance().onRepeatedTimeout(30s, []{
printf("<Service> TCP STATUS:\n%s \n", inet->tcp().status().c_str());
});
// Add a TCP connection handler - here a hardcoded HTTP-service
server.onAccept([](auto conn) -> bool {
printf("<Service> @onAccept - Connection attempt from: %s \n",
conn->to_string().c_str());
return true; // allow all connections
}).onConnect([](auto) {
printf("<Service> @onConnect - Connection successfully established.\n");
}).onReceive([](auto conn, bool push) {
std::string data = conn->read(1024);
printf("<Service> @onData - PUSH: %d, Data read: \n%s\n", push, data.c_str());
int color = rand();
std::stringstream stream;
/* HTML Fonts */
std::string ubuntu_medium = "font-family: \'Ubuntu\', sans-serif; font-weight: 500; ";
std::string ubuntu_normal = "font-family: \'Ubuntu\', sans-serif; font-weight: 400; ";
std::string ubuntu_light = "font-family: \'Ubuntu\', sans-serif; font-weight: 300; ";
/* HTML */
stream << "<html><head>"
<< "<link href='https://fonts.googleapis.com/css?family=Ubuntu:500,300' rel='stylesheet' type='text/css'>"
<< "</head><body>"
<< "<h1 style= \"color: " << "#" << std::hex << (color >> 8) << "\">"
<< "<span style=\""+ubuntu_medium+"\">Include</span><span style=\""+ubuntu_light+"\">OS</span> </h1>"
<< "<h2>Now speaks TCP!</h2>"
// .... generate more dynamic content
<< "<p> ...and can improvise http. With limitations of course, but it's been easier than expected so far </p>"
<< "<footer><hr /> © 2015, Oslo and Akershus University College of Applied Sciences </footer>"
<< "</body></html>\n";
/* HTTP-header */
std::string html = stream.str();
std::string header="HTTP/1.1 200 OK \n " \
"Date: Mon, 01 Jan 1970 00:00:01 GMT \n" \
"Server: IncludeOS prototype 4.0 \n" \
"Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT \n" \
"Content-Type: text/html; charset=UTF-8 \n" \
"Content-Length: "+std::to_string(html.size())+"\n" \
"Accept-Ranges: bytes\n" \
"Connection: close\n\n";
std::string output{header + html};
conn->write(output.data(), output.size());
}).onDisconnect([](auto, auto reason) {
printf("<Service> @onDisconnect - Reason: %s \n", reason.to_string().c_str());
});
printf("*** TEST SERVICE STARTED *** \n");
}
<commit_msg>example: repaired demo example<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// 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 <os>
#include <net/inet4>
#include <net/dhcp/dh4client.hpp>
#include <math.h> // rand()
#include <sstream>
// An IP-stack object
std::unique_ptr<net::Inet4<VirtioNet> > inet;
using namespace std::chrono;
std::string HTML_RESPONSE() {
int color = rand();
std::stringstream stream;
/* HTML Fonts */
std::string ubuntu_medium = "font-family: \'Ubuntu\', sans-serif; font-weight: 500; ";
std::string ubuntu_normal = "font-family: \'Ubuntu\', sans-serif; font-weight: 400; ";
std::string ubuntu_light = "font-family: \'Ubuntu\', sans-serif; font-weight: 300; ";
/* HTML */
stream << "<html><head>"
<< "<link href='https://fonts.googleapis.com/css?family=Ubuntu:500,300' rel='stylesheet' type='text/css'>"
<< "</head><body>"
<< "<h1 style= \"color: " << "#" << std::hex << (color >> 8) << "\">"
<< "<span style=\""+ubuntu_medium+"\">Include</span><span style=\""+ubuntu_light+"\">OS</span> </h1>"
<< "<h2>Now speaks TCP!</h2>"
// .... generate more dynamic content
<< "<p> ...and can improvise http. With limitations of course, but it's been easier than expected so far </p>"
<< "<footer><hr /> © 2015, Oslo and Akershus University College of Applied Sciences </footer>"
<< "</body></html>\n";
std::string html = stream.str();
std::string header="HTTP/1.1 200 OK \n " \
"Date: Mon, 01 Jan 1970 00:00:01 GMT \n" \
"Server: IncludeOS prototype 4.0 \n" \
"Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT \n" \
"Content-Type: text/html; charset=UTF-8 \n" \
"Content-Length: "+std::to_string(html.size())+"\n" \
"Accept-Ranges: bytes\n" \
"Connection: close\n\n";
return header + html;
}
void Service::start() {
// Assign a driver (VirtioNet) to a network interface (eth0)
// @note: We could determine the appropirate driver dynamically, but then we'd
// have to include all the drivers into the image, which we want to avoid.
hw::Nic<VirtioNet>& eth0 = hw::Dev::eth<0,VirtioNet>();
// Bring up a network stack, attached to the nic
// @note : No parameters after 'nic' means we'll use DHCP for IP config.
inet = std::make_unique<net::Inet4<VirtioNet> >(eth0);
// Static IP configuration, until we (possibly) get DHCP
// @note : Mostly to get a robust demo service that it works with and without DHCP
inet->network_config( {{ 10,0,0,42 }}, // IP
{{ 255,255,255,0 }}, // Netmask
{{ 10,0,0,1 }}, // Gateway
{{ 8,8,8,8 }} ); // DNS
srand(OS::cycles_since_boot());
// Set up a TCP server on port 80
auto& server = inet->tcp().bind(80);
hw::PIT::instance().onRepeatedTimeout(30s, []{
printf("<Service> TCP STATUS:\n%s \n", inet->tcp().status().c_str());
});
// Add a TCP connection handler - here a hardcoded HTTP-service
server.onAccept([](auto conn) -> bool {
printf("<Service> @onAccept - Connection attempt from: %s \n",
conn->to_string().c_str());
return true; // allow all connections
}).onConnect([](auto conn) {
printf("<Service> @onConnect - Connection successfully established.\n");
// read async with a buffer size of 1024 bytes
// define what to do when data is read
conn->read(1024, [conn](net::TCP::buffer_t buf, size_t n) {
// create string from buffer
std::string data { (char*)buf.get(), n };
printf("<Service> @read:\n%s\n", data.c_str());
// create response
std::string response = HTML_RESPONSE();
// write the data from the string with the strings size
conn->write(response.data(), response.size(), [](size_t n) {
printf("<Service> @write: %u bytes written\n", n);
});
});
}).onDisconnect([](auto, auto reason) {
printf("<Service> @onDisconnect - Reason: %s \n", reason.to_string().c_str());
});
printf("*** TEST SERVICE STARTED *** \n");
}
<|endoftext|> |
<commit_before>//
// DiskImage.hpp
// Clock Signal
//
// Created by Thomas Harte on 21/09/2017.
// Copyright 2017 Thomas Harte. All rights reserved.
//
#ifndef DiskImage_hpp
#define DiskImage_hpp
#include <map>
#include <memory>
#include "../Disk.hpp"
#include "../Track/Track.hpp"
namespace Storage {
namespace Disk {
enum class Error {
InvalidFormat = -2,
UnknownVersion = -3
};
/*!
Models a disk image as a collection of tracks, plus a range of possible track positions.
The intention is not that tracks necessarily be evenly spaced; a head_position_count of 3 wih track
A appearing in positions 0 and 1, and track B appearing in position 2 is an appropriate use of this API
if it matches the media.
*/
class DiskImage {
public:
virtual ~DiskImage() {}
/*!
@returns the distance at which there stops being any further content.
This is not necessarily a track count. There is no implicit guarantee that every position will
return a distinct track, or, e.g. if the media is holeless, will return any track at all.
*/
virtual HeadPosition get_maximum_head_position() = 0;
/*!
@returns the number of heads (and, therefore, impliedly surfaces) available on this disk.
*/
virtual int get_head_count() { return 1; }
/*!
@returns the @c Track at @c position underneath @c head if there are any detectable events there;
returns @c nullptr otherwise.
*/
virtual std::shared_ptr<Track> get_track_at_position(Track::Address address) = 0;
/*!
Replaces the Tracks indicated by the map, that maps from physical address to track content.
*/
virtual void set_tracks(const std::map<Track::Address, std::shared_ptr<Track>> &) {}
/*!
Communicates that it is likely to be a while before any more tracks are written.
*/
virtual void flush_tracks() {}
/*!
@returns whether the disk image is read only. Defaults to @c true if not overridden.
*/
virtual bool get_is_read_only() { return true; }
/*!
@returns @c true if the tracks at the two addresses are different. @c false if they are the same track.
This can avoid some degree of work when disk images offer sub-head-position precision.
*/
virtual bool tracks_differ(Track::Address lhs, Track::Address rhs) { return lhs != rhs; }
};
class DiskImageHolderBase: public Disk {
protected:
std::set<Track::Address> unwritten_tracks_;
std::map<Track::Address, std::shared_ptr<Track>> cached_tracks_;
std::unique_ptr<Concurrency::AsyncTaskQueue> update_queue_;
};
/*!
Provides a wrapper that wraps a DiskImage to make it into a Disk, providing caching and,
thereby, an intermediate store for modified tracks so that mutable disk images can either
update on the fly or perform a block update on closure, as appropriate.
*/
template <typename T> class DiskImageHolder: public DiskImageHolderBase {
public:
template <typename... Ts> DiskImageHolder(Ts&&... args) :
disk_image_(args...) {}
~DiskImageHolder();
HeadPosition get_maximum_head_position();
int get_head_count();
std::shared_ptr<Track> get_track_at_position(Track::Address address);
void set_track_at_position(Track::Address address, const std::shared_ptr<Track> &track);
void flush_tracks();
bool get_is_read_only();
bool tracks_differ(Track::Address lhs, Track::Address rhs);
private:
T disk_image_;
};
#include "DiskImageImplementation.hpp"
}
}
#endif /* DiskImage_hpp */
<commit_msg>Fix through route to `TargetPlatform::TypeDistinguisher`.<commit_after>//
// DiskImage.hpp
// Clock Signal
//
// Created by Thomas Harte on 21/09/2017.
// Copyright 2017 Thomas Harte. All rights reserved.
//
#ifndef DiskImage_hpp
#define DiskImage_hpp
#include <map>
#include <memory>
#include "../Disk.hpp"
#include "../Track/Track.hpp"
#include "../../TargetPlatforms.hpp"
namespace Storage {
namespace Disk {
enum class Error {
InvalidFormat = -2,
UnknownVersion = -3
};
/*!
Models a disk image as a collection of tracks, plus a range of possible track positions.
The intention is not that tracks necessarily be evenly spaced; a head_position_count of 3 wih track
A appearing in positions 0 and 1, and track B appearing in position 2 is an appropriate use of this API
if it matches the media.
*/
class DiskImage {
public:
virtual ~DiskImage() {}
/*!
@returns the distance at which there stops being any further content.
This is not necessarily a track count. There is no implicit guarantee that every position will
return a distinct track, or, e.g. if the media is holeless, will return any track at all.
*/
virtual HeadPosition get_maximum_head_position() = 0;
/*!
@returns the number of heads (and, therefore, impliedly surfaces) available on this disk.
*/
virtual int get_head_count() { return 1; }
/*!
@returns the @c Track at @c position underneath @c head if there are any detectable events there;
returns @c nullptr otherwise.
*/
virtual std::shared_ptr<Track> get_track_at_position(Track::Address address) = 0;
/*!
Replaces the Tracks indicated by the map, that maps from physical address to track content.
*/
virtual void set_tracks(const std::map<Track::Address, std::shared_ptr<Track>> &) {}
/*!
Communicates that it is likely to be a while before any more tracks are written.
*/
virtual void flush_tracks() {}
/*!
@returns whether the disk image is read only. Defaults to @c true if not overridden.
*/
virtual bool get_is_read_only() { return true; }
/*!
@returns @c true if the tracks at the two addresses are different. @c false if they are the same track.
This can avoid some degree of work when disk images offer sub-head-position precision.
*/
virtual bool tracks_differ(Track::Address lhs, Track::Address rhs) { return lhs != rhs; }
};
class DiskImageHolderBase: public Disk {
protected:
std::set<Track::Address> unwritten_tracks_;
std::map<Track::Address, std::shared_ptr<Track>> cached_tracks_;
std::unique_ptr<Concurrency::AsyncTaskQueue> update_queue_;
};
/*!
Provides a wrapper that wraps a DiskImage to make it into a Disk, providing caching and,
thereby, an intermediate store for modified tracks so that mutable disk images can either
update on the fly or perform a block update on closure, as appropriate.
Implements TargetPlatform::TypeDistinguisher to return either no information whatsoever, if
the underlying image doesn't implement TypeDistinguisher, or else to pass the call along.
*/
template <typename T> class DiskImageHolder: public DiskImageHolderBase, public TargetPlatform::TypeDistinguisher {
public:
template <typename... Ts> DiskImageHolder(Ts&&... args) :
disk_image_(args...) {}
~DiskImageHolder();
HeadPosition get_maximum_head_position();
int get_head_count();
std::shared_ptr<Track> get_track_at_position(Track::Address address);
void set_track_at_position(Track::Address address, const std::shared_ptr<Track> &track);
void flush_tracks();
bool get_is_read_only();
bool tracks_differ(Track::Address lhs, Track::Address rhs);
private:
T disk_image_;
TargetPlatform::Type target_platform_type() final {
if constexpr (std::is_base_of<TargetPlatform::TypeDistinguisher, T>::value) {
return static_cast<TargetPlatform::TypeDistinguisher *>(&disk_image_)->target_platform_type();
} else {
return TargetPlatform::Type(~0);
}
}
};
#include "DiskImageImplementation.hpp"
}
}
#endif /* DiskImage_hpp */
<|endoftext|> |
<commit_before>// This file is a part of the OpenSurgSim project.
// Copyright 2013-2015, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <vector>
#include "SurgSim/Collision/CollisionPair.h"
#include "SurgSim/Collision/Representation.h"
#include "SurgSim/Physics/ContactFiltering.h"
#include "SurgSim/Physics/PhysicsManagerState.h"
using SurgSim::Collision::CollisionPair;
namespace SurgSim
{
namespace Physics
{
ContactFiltering::ContactFiltering(bool doCopyState) : Computation(doCopyState)
{
m_logger = SurgSim::Framework::Logger::getLogger("ContactFiltering");
}
ContactFiltering::~ContactFiltering()
{
}
std::shared_ptr<PhysicsManagerState> ContactFiltering::doUpdate(
const double& dt,
const std::shared_ptr<PhysicsManagerState>& state)
{
std::shared_ptr<PhysicsManagerState> result = state;
for (auto& pair : result->getCollisionPairs())
{
auto collisionRepresentations = pair->getRepresentations();
auto collisionToPhysicsMap = state->getCollisionToPhysicsMap();
auto foundFirst = collisionToPhysicsMap.find(collisionRepresentations.first);
auto foundSecond = collisionToPhysicsMap.find(collisionRepresentations.second);
if (foundFirst == collisionToPhysicsMap.end() || foundSecond == collisionToPhysicsMap.end())
{
continue;
}
std::pair<std::shared_ptr<Representation>, std::shared_ptr<Representation>> physicsRepresentations;
physicsRepresentations.first = foundFirst->second;
physicsRepresentations.second = foundSecond->second;
if (!(physicsRepresentations.first->isActive() && physicsRepresentations.second->isActive()))
{
continue;
}
for (auto& contact : pair->getContacts())
{
Math::Vector3d normal = contact->normal;
auto loc1 = physicsRepresentations.first->createLocalization(contact->penetrationPoints.first);
auto loc2 = physicsRepresentations.second->createLocalization(contact->penetrationPoints.second);
Math::Vector3d velocity1 = loc1->calculateVelocity(), velocity2 = loc2->calculateVelocity();
Math::Vector3d relativeVelocity = (velocity2 - velocity1);
// If the relative velocity is small, it means that the motion is not strong enough to drive the
// contact filtering...i.e. all contacts are potentially valid and can push the object in any direction.
double relativeVelocityNorm = relativeVelocity.norm();
if (relativeVelocityNorm < 1e-4)
{
continue;
}
relativeVelocity /= relativeVelocityNorm;
// Filter contacts that are opposite to the motion
double criteria = normal.dot(relativeVelocity);
if (criteria < 0.0)
{
contact->active = false;
SURGSIM_LOG(m_logger, DEBUG) << "Contact filtered [normal.relativeVelocity = " <<
criteria << "] < 0 (opposite to the motion)" << std::endl <<
" > normal = " << normal.transpose() << std::endl <<
" > relativeVelocity = " << relativeVelocity.transpose() << std::endl;
}
// Filter contact that are too orthogonal to the motion and would produce inconsitant forces wrt motion
criteria = std::abs(normal.dot(relativeVelocity));
if (criteria < std::cos(5 * M_PI / 12.0))
{
contact->active = false;
SURGSIM_LOG(m_logger, DEBUG) << "Contact filtered [|normal.relativeVelocity| = "<<
criteria << "] < cos(5*PI/12) = " << std::cos(5 * M_PI / 12.0) << std::endl <<
" > normal = " << normal.transpose() << std::endl <<
" > relativeVelocity = " << relativeVelocity.transpose() << std::endl;
}
}
}
return result;
}
}; // Physics
}; // SurgSim
<commit_msg>Remove filtering of contact opposite to the relative motion<commit_after>// This file is a part of the OpenSurgSim project.
// Copyright 2013-2015, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <vector>
#include "SurgSim/Collision/CollisionPair.h"
#include "SurgSim/Collision/Representation.h"
#include "SurgSim/Physics/ContactFiltering.h"
#include "SurgSim/Physics/PhysicsManagerState.h"
using SurgSim::Collision::CollisionPair;
namespace SurgSim
{
namespace Physics
{
ContactFiltering::ContactFiltering(bool doCopyState) : Computation(doCopyState)
{
m_logger = SurgSim::Framework::Logger::getLogger("ContactFiltering");
}
ContactFiltering::~ContactFiltering()
{
}
std::shared_ptr<PhysicsManagerState> ContactFiltering::doUpdate(
const double& dt,
const std::shared_ptr<PhysicsManagerState>& state)
{
std::shared_ptr<PhysicsManagerState> result = state;
for (auto& pair : result->getCollisionPairs())
{
auto collisionRepresentations = pair->getRepresentations();
auto collisionToPhysicsMap = state->getCollisionToPhysicsMap();
auto foundFirst = collisionToPhysicsMap.find(collisionRepresentations.first);
auto foundSecond = collisionToPhysicsMap.find(collisionRepresentations.second);
if (foundFirst == collisionToPhysicsMap.end() || foundSecond == collisionToPhysicsMap.end())
{
continue;
}
std::pair<std::shared_ptr<Representation>, std::shared_ptr<Representation>> physicsRepresentations;
physicsRepresentations.first = foundFirst->second;
physicsRepresentations.second = foundSecond->second;
if (!(physicsRepresentations.first->isActive() && physicsRepresentations.second->isActive()))
{
continue;
}
for (auto& contact : pair->getContacts())
{
// By the contact definition, normal is pointing "in" to body1.
// Moving body1 by normal * depth would solve the contact with body2.
Math::Vector3d normal = contact->normal;
auto loc1 = physicsRepresentations.first->createLocalization(contact->penetrationPoints.first);
auto loc2 = physicsRepresentations.second->createLocalization(contact->penetrationPoints.second);
Math::Vector3d velocity1 = loc1->calculateVelocity(), velocity2 = loc2->calculateVelocity();
Math::Vector3d relativeVelocity = (velocity2 - velocity1);
// If the relative velocity is small, it means that the motion is not strong enough to drive the
// contact filtering...i.e. all contacts are potentially valid and can push the object in any direction.
double relativeVelocityNorm = relativeVelocity.norm();
if (relativeVelocityNorm < 1e-4)
{
continue;
}
relativeVelocity /= relativeVelocityNorm;
// Filter contacts that are too orthogonal to the motion and would produce inconsitant forces wrt motion
double criteria = std::abs(normal.dot(relativeVelocity));
if (criteria < std::cos(M_PI / 3.0))
{
contact->active = false;
SURGSIM_LOG(m_logger, DEBUG) << "Contact filtered [|normal.relativeVelocity| = "<<
criteria << "] < cos(PI/3) = " << std::cos(M_PI / 3.0) << std::endl <<
" > normal = " << normal.transpose() << std::endl <<
" > relativeVelocity = " << relativeVelocity.transpose() << std::endl;
}
}
}
return result;
}
}; // Physics
}; // SurgSim
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2018, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* 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 "mbed.h"
#include "greentea-client/test_env.h"
#include "unity.h"
#include "utest.h"
#include "platform/mbed_wait_api.h"
#include "hal/us_ticker_api.h"
#include "hal/lp_ticker_api.h"
using namespace utest::v1;
/* This test is created based on the test for Timer class.
* Since low power timer is less accurate than regular
* timer we need to adjust delta.
*/
/*
* Define tolerance as follows:
* Timer might be +/-5% out; wait_ns is permitted 20% slow, but not fast.
* Therefore minimum measured time should be 95% of requested, maximum should
* be 125%. Unity doesn't let us specify an asymmetric error though.
*/
#define TOLERANCE_MIN 0.95f
#define TOLERANCE_MAX 1.25f
#define MIDPOINT ((TOLERANCE_MIN+TOLERANCE_MAX)/2)
#define DELTA (MIDPOINT-TOLERANCE_MIN)
/* This test verifies if wait_ns's wait time
* is accurate, according to a timer.
*
* Given timer is created.
* When timer is used to measure delay.
* Then the results are valid (within acceptable range).
*/
template<int wait_val_ms, class CompareTimer>
void test_wait_ns_time_measurement()
{
CompareTimer timer;
float wait_val_s = (float)wait_val_ms / 1000;
/* Start the timer. */
timer.start();
/* Wait <wait_val_ms> ms - arithmetic inside wait_ns will overflow if
* asked for too large a delay, so break it up.
*/
for (int i = 0; i < wait_val_ms; i++) {
wait_ns(1000000);
}
/* Stop the timer. */
timer.stop();
/* Check results - wait_val_us us have elapsed. */
TEST_ASSERT_FLOAT_WITHIN(DELTA * wait_val_s, MIDPOINT * wait_val_s, timer.read());
}
utest::v1::status_t test_setup(const size_t number_of_cases)
{
GREENTEA_SETUP(15, "default_auto");
return verbose_test_setup_handler(number_of_cases);
}
Case cases[] = {
#if DEVICE_LPTICKER
Case("Test: wait_ns - compare with lp_timer 1s", test_wait_ns_time_measurement<1000, LowPowerTimer>),
#endif
Case("Test: wait_ns - compare with us_timer 1s", test_wait_ns_time_measurement<1000, Timer>)
};
Specification specification(test_setup, cases);
int main()
{
return !Harness::run(specification);
}
<commit_msg>Increase wait_ns test tolerance<commit_after>/*
* Copyright (c) 2018, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* 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 "mbed.h"
#include "greentea-client/test_env.h"
#include "unity.h"
#include "utest.h"
#include "platform/mbed_wait_api.h"
#include "hal/us_ticker_api.h"
#include "hal/lp_ticker_api.h"
using namespace utest::v1;
/* This test is created based on the test for Timer class.
* Since low power timer is less accurate than regular
* timer we need to adjust delta.
*/
/*
* Define tolerance as follows:
* Timer might be +/-5% out; wait_ns is permitted 40% slow, but not fast.
* Therefore minimum measured time should be 95% of requested, maximum should
* be 145%. Unity doesn't let us specify an asymmetric error though.
*
* Would be nice to have tighter upper tolerance, but in practice we've seen
* a few devices unable to sustain theoretical throughput - flash wait states?
*/
#define TOLERANCE_MIN 0.95f
#define TOLERANCE_MAX 1.45f
#define MIDPOINT ((TOLERANCE_MIN+TOLERANCE_MAX)/2)
#define DELTA (MIDPOINT-TOLERANCE_MIN)
/* This test verifies if wait_ns's wait time
* is accurate, according to a timer.
*
* Given timer is created.
* When timer is used to measure delay.
* Then the results are valid (within acceptable range).
*/
template<int wait_val_ms, class CompareTimer>
void test_wait_ns_time_measurement()
{
CompareTimer timer;
float wait_val_s = (float)wait_val_ms / 1000;
/* Start the timer. */
timer.start();
/* Wait <wait_val_ms> ms - arithmetic inside wait_ns will overflow if
* asked for too large a delay, so break it up.
*/
for (int i = 0; i < wait_val_ms; i++) {
wait_ns(1000000);
}
/* Stop the timer. */
timer.stop();
/* Check results - wait_val_us us have elapsed. */
TEST_ASSERT_FLOAT_WITHIN(DELTA * wait_val_s, MIDPOINT * wait_val_s, timer.read());
}
utest::v1::status_t test_setup(const size_t number_of_cases)
{
GREENTEA_SETUP(15, "default_auto");
return verbose_test_setup_handler(number_of_cases);
}
Case cases[] = {
#if DEVICE_LPTICKER
Case("Test: wait_ns - compare with lp_timer 1s", test_wait_ns_time_measurement<1000, LowPowerTimer>),
#endif
Case("Test: wait_ns - compare with us_timer 1s", test_wait_ns_time_measurement<1000, Timer>)
};
Specification specification(test_setup, cases);
int main()
{
return !Harness::run(specification);
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://www.qt.io/licensing. For further information
** use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "projectpartcontainer.h"
#include <QDebug>
#include <QDataStream>
#include <ostream>
namespace ClangBackEnd {
ProjectPartContainer::ProjectPartContainer(const Utf8String &projectPathId,
const Utf8StringVector &arguments)
: projectPartId_(projectPathId),
arguments_(arguments)
{
}
const Utf8String &ProjectPartContainer::projectPartId() const
{
return projectPartId_;
}
const Utf8StringVector &ProjectPartContainer::arguments() const
{
return arguments_;
}
QDataStream &operator<<(QDataStream &out, const ProjectPartContainer &container)
{
out << container.projectPartId_;
out << container.arguments_;
return out;
}
QDataStream &operator>>(QDataStream &in, ProjectPartContainer &container)
{
in >> container.projectPartId_;
in >> container.arguments_;
return in;
}
bool operator==(const ProjectPartContainer &first, const ProjectPartContainer &second)
{
return first.projectPartId_ == second.projectPartId_;
}
bool operator<(const ProjectPartContainer &first, const ProjectPartContainer &second)
{
return first.projectPartId_ < second.projectPartId_;
}
QDebug operator<<(QDebug debug, const ProjectPartContainer &container)
{
debug.nospace() << "ProjectPartContainer("
<< container.projectPartId()
<< ","
<< container.arguments()
<< ")";
return debug;
}
void PrintTo(const ProjectPartContainer &container, ::std::ostream* os)
{
*os << "ProjectPartContainer("
<< container.projectPartId().constData()
<< ","
<< container.arguments().constData()
<< ")";
}
} // namespace ClangBackEnd
<commit_msg>Clang: Quote project part arguments for easier debugging<commit_after>/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://www.qt.io/licensing. For further information
** use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "projectpartcontainer.h"
#include <QDebug>
#include <QDataStream>
#include <ostream>
namespace ClangBackEnd {
ProjectPartContainer::ProjectPartContainer(const Utf8String &projectPathId,
const Utf8StringVector &arguments)
: projectPartId_(projectPathId),
arguments_(arguments)
{
}
const Utf8String &ProjectPartContainer::projectPartId() const
{
return projectPartId_;
}
const Utf8StringVector &ProjectPartContainer::arguments() const
{
return arguments_;
}
QDataStream &operator<<(QDataStream &out, const ProjectPartContainer &container)
{
out << container.projectPartId_;
out << container.arguments_;
return out;
}
QDataStream &operator>>(QDataStream &in, ProjectPartContainer &container)
{
in >> container.projectPartId_;
in >> container.arguments_;
return in;
}
bool operator==(const ProjectPartContainer &first, const ProjectPartContainer &second)
{
return first.projectPartId_ == second.projectPartId_;
}
bool operator<(const ProjectPartContainer &first, const ProjectPartContainer &second)
{
return first.projectPartId_ < second.projectPartId_;
}
static Utf8String quotedArguments(const Utf8StringVector &arguments)
{
const Utf8String quote = Utf8String::fromUtf8("\"");
const Utf8String joined = arguments.join(quote + QString::fromUtf8(" ") + quote);
return quote + joined + quote;
}
QDebug operator<<(QDebug debug, const ProjectPartContainer &container)
{
debug.nospace() << "ProjectPartContainer("
<< container.projectPartId()
<< ","
<< quotedArguments(container.arguments())
<< ")";
return debug;
}
void PrintTo(const ProjectPartContainer &container, ::std::ostream* os)
{
*os << "ProjectPartContainer("
<< container.projectPartId().constData()
<< ","
<< container.arguments().constData()
<< ")";
}
} // namespace ClangBackEnd
<|endoftext|> |
<commit_before>#include <cassert>
#include <functional>
#include <sstream>
#include <string>
#include <vector>
#include <sampgdk/core.h>
#include <sampgdk/sdk.h>
#include "ufs.h"
enum LoadState {
WaitLoad,
BeginLoad,
Loaded,
Unloaded
};
extern void *pAMXFunctions;
static LoadState load_state = WaitLoad;
static std::vector<AMX*> normal_scripts;
PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() {
return sampgdk::Supports() | SUPPORTS_PROCESS_TICK | SUPPORTS_AMX_NATIVES;
}
PLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData) {
pAMXFunctions = ppData[PLUGIN_DATA_AMX_EXPORTS];
ufs::UFS::Instance().SetPluginData(ppData);
load_state = BeginLoad;
return sampgdk::Load(ppData);
}
PLUGIN_EXPORT void PLUGIN_CALL Unload() {
assert(load_state == Loaded);
ufs::UFS::Instance().UnloadScripts();
ufs::UFS::Instance().UnloadPlugins();
load_state = Unloaded;
sampgdk::Unload();
}
PLUGIN_EXPORT void PLUGIN_CALL ProcessTick() {
if (load_state == BeginLoad) {
assert(load_state != Loaded);
ufs::UFS::Instance().LoadPlugins();
ufs::UFS::Instance().LoadScripts();
load_state = Loaded;
for (std::vector<AMX*>::iterator it = normal_scripts.begin();
it != normal_scripts.end(); it++) {
AmxUnload(*it);
}
}
ufs::UFS::Instance().ForEachPlugin(
std::mem_fun(&ufs::Plugin::ProcessTick));
sampgdk::ProcessTick();
}
PLUGIN_EXPORT int PLUGIN_CALL AmxLoad(AMX *amx) {
normal_scripts.push_back(amx);
ufs::UFS::Instance().ForEachPlugin(
std::bind2nd(std::mem_fun(&ufs::Plugin::AmxLoad), amx));
return AMX_ERR_NONE;
}
PLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx) {
ufs::UFS::Instance().ForEachPlugin(
std::bind2nd(std::mem_fun(&ufs::Plugin::AmxUnload), amx));
return AMX_ERR_NONE;
}
<commit_msg>UFS: Fix loading of normal scripts<commit_after>#include <cassert>
#include <functional>
#include <sstream>
#include <string>
#include <vector>
#include <sampgdk/core.h>
#include <sampgdk/sdk.h>
#include "ufs.h"
enum LoadState {
WaitLoad,
BeginLoad,
Loaded,
Unloaded
};
extern void *pAMXFunctions;
static LoadState load_state = WaitLoad;
static std::vector<AMX*> normal_scripts;
PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() {
return sampgdk::Supports() | SUPPORTS_PROCESS_TICK | SUPPORTS_AMX_NATIVES;
}
PLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData) {
pAMXFunctions = ppData[PLUGIN_DATA_AMX_EXPORTS];
ufs::UFS::Instance().SetPluginData(ppData);
load_state = BeginLoad;
return sampgdk::Load(ppData);
}
PLUGIN_EXPORT void PLUGIN_CALL Unload() {
assert(load_state == Loaded);
ufs::UFS::Instance().UnloadScripts();
ufs::UFS::Instance().UnloadPlugins();
load_state = Unloaded;
sampgdk::Unload();
}
PLUGIN_EXPORT void PLUGIN_CALL ProcessTick() {
if (load_state == BeginLoad) {
assert(load_state != Loaded);
ufs::UFS::Instance().LoadPlugins();
ufs::UFS::Instance().LoadScripts();
load_state = Loaded;
for (std::vector<AMX*>::iterator it = normal_scripts.begin();
it != normal_scripts.end(); it++) {
ufs::UFS::Instance().ForEachPlugin(
std::bind2nd(std::mem_fun(&ufs::Plugin::AmxLoad), *it));
}
}
ufs::UFS::Instance().ForEachPlugin(
std::mem_fun(&ufs::Plugin::ProcessTick));
sampgdk::ProcessTick();
}
PLUGIN_EXPORT int PLUGIN_CALL AmxLoad(AMX *amx) {
normal_scripts.push_back(amx);
return AMX_ERR_NONE;
}
PLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx) {
ufs::UFS::Instance().ForEachPlugin(
std::bind2nd(std::mem_fun(&ufs::Plugin::AmxUnload), amx));
return AMX_ERR_NONE;
}
<|endoftext|> |
<commit_before>#include <Utils/Age_microprofile.hpp>
#include <Utils/Profiler.hpp>
#include <context/SDL/SdlContext.hh>
#include <Utils/OpenGL.hh>
#include <iostream>
#include <Utils/DependenciesInjector.hpp>
#include <Core/Inputs/Input.hh>
#include <SDL/SDL.h>
#include <Core/Inputs/Input.hh>
#include <Threads/MainThread.hpp>
namespace AGE
{
bool SdlContext::_init()
{
_firstCall = true;
_dependencyManager->setInstance<Input>();
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) != 0 ||
//SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1) != 0 ||
//SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8) != 0 ||
(_window = SDL_CreateWindow(_windowName.c_str(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
_screenSize.x, _screenSize.y, SDL_WINDOW_OPENGL)) == NULL ||
(_glContext = SDL_GL_CreateContext(_window)) == NULL)
{
std::cerr << "SDL_GL_CreateContext Failed : " << SDL_GetError() << std::endl;
return (false);
}
SDL_GL_SetSwapInterval(0);
if (glewInit() != GLEW_OK)
{
std::cerr << "glewInit Failed" << std::endl;
return (false);
}
#ifdef AGE_ENABLE_PROFILING
MicroProfileGpuInitGL();
#endif
return (true);
}
SdlContext::SdlContext() { }
SdlContext::~SdlContext() { }
void SdlContext::swapContext()
{
#ifdef AGE_ENABLE_PROFILING
MicroProfileFlip();
#endif
{
SCOPE_profile_cpu_i("RenderTimer", "swapContext");
SCOPE_profile_gpu_i("SwapContext");
SDL_GL_SwapWindow(_window);
}
}
void SdlContext::refreshInputs()
{
SCOPE_profile_cpu_function("RenderTimer");
SDL_Event events;
auto input = _dependencyManager->getInstance<Input>();
input->frameUpdate();
if (_firstCall)
{
_initJoysticks(*input);
_firstCall = false;
}
while (SDL_PollEvent(&events))
{
switch (events.type)
{
case SDL_KEYDOWN:
input->keyInputPressed(findAgeMappedKey(events.key.keysym.sym), findAgePhysicalKey(events.key.keysym.scancode));
break;
case SDL_KEYUP:
input->keyInputReleased(findAgeMappedKey(events.key.keysym.sym), findAgePhysicalKey(events.key.keysym.scancode));
break;
case SDL_MOUSEBUTTONDOWN:
input->mouseButtonPressed(findAgeMouseButton(events.button.button));
break;
case SDL_MOUSEBUTTONUP:
input->mouseButtonReleased(findAgeMouseButton(events.button.button));
break;
case SDL_MOUSEWHEEL:
input->setMouseWheel(glm::ivec2(events.wheel.x, events.wheel.y));
break;
case SDL_MOUSEMOTION:
input->setMousePosition(glm::ivec2(events.motion.x, events.motion.y), glm::ivec2(events.motion.xrel, events.motion.yrel));
break;
case SDL_JOYDEVICEADDED:
_addJoystick(*input, events.jdevice.which);
break;
case SDL_JOYDEVICEREMOVED:
_removeJoystick(*input, events.jdevice.which);
break;
case SDL_JOYAXISMOTION:
{
uint32_t joyId = _fromSdlJoystickIdToAge(events.jaxis.which);
AgeJoystickAxis joyAxis = findAgeJoystickAxis(events.jaxis.axis);
float value = (float)events.jaxis.value / 32768.0f;
input->setJoystickAxis(joyId, joyAxis, value);
}
break;
case SDL_JOYBUTTONDOWN:
{
uint32_t joyId = _fromSdlJoystickIdToAge(events.jbutton.which);
AgeJoystickButtons joyButton = findAgeJoystickButton(events.jbutton.button);
input->joystickButtonPressed(joyId, joyButton);
}
break;
case SDL_JOYBUTTONUP:
{
uint32_t joyId = _fromSdlJoystickIdToAge(events.jbutton.which);
AgeJoystickButtons joyButton = findAgeJoystickButton(events.jbutton.button);
input->joystickButtonReleased(joyId, joyButton);
}
break;
case SDL_JOYBALLMOTION:
{
uint32_t joyId = _fromSdlJoystickIdToAge(events.jball.which);
input->setJoystickTrackBall(joyId, events.jball.ball, glm::ivec2(events.jball.xrel, events.jball.yrel));
}
break;
case SDL_JOYHATMOTION:
{
uint32_t joyId = _fromSdlJoystickIdToAge(events.jhat.which);
AgeJoystickHatDirections joyHatDir = findAgeJoystickHatDirection(events.jhat.value);
input->setJoystickHat(joyId, events.jhat.hat, joyHatDir);
}
break;
case SDL_WINDOWEVENT:
input->addWindowInput(findAgeWindowInput(events.window.event));
break;
default:
input->addWindowInput(findAgeWindowInput(events.type));
break;
}
}
input->sendMouseStateToIMGUI();
}
const glm::uvec2 &SdlContext::getScreenSize()
{
return _screenSize;
}
void SdlContext::setScreenSize(const glm::uvec2 &screenSize)
{
_screenSize = screenSize;
SDL_SetWindowSize(_window, _screenSize.x, _screenSize.y);
SDL_SetWindowPosition(_window, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED);
}
void SdlContext::grabMouse(bool grabMouse)
{
SDL_SetRelativeMouseMode((SDL_bool)grabMouse);
}
uint32_t SdlContext::_fromSdlJoystickIdToAge(SDL_JoystickID id)
{
uint32_t currentId = 0;
while (currentId != AGE_JOYSTICK_MAX_NUMBER &&
_joysticks[currentId].id != id)
++currentId;
assert(currentId != AGE_JOYSTICK_MAX_NUMBER && "Cannot find the joystick.");
return (currentId);
}
void SdlContext::_initJoysticks(Input &inputs)
{
// Init Joysticks
for (int i = 0; i < AGE_JOYSTICK_MAX_NUMBER; ++i)
{
_joysticks[i].id = -1;
_joysticks[i].handler = NULL;
}
SDL_JoystickEventState(SDL_ENABLE);
for (int i = 0; i < SDL_NumJoysticks(); ++i)
_addJoystick(inputs, i);
}
void SdlContext::_addJoystick(Input &inputs, int joyIdx)
{
SDL_Joystick *current = SDL_JoystickOpen(joyIdx);
if (current)
{
SDL_JoystickID sdlJoyId = SDL_JoystickInstanceID(current);
if (sdlJoyId != -1)
{
uint32_t currentId = 0;
while (currentId != AGE_JOYSTICK_MAX_NUMBER &&
_joysticks[currentId].id != -1)
++currentId;
assert(currentId != AGE_JOYSTICK_MAX_NUMBER && "AGE cannot handle more than 6 joysticks.");
_joysticks[currentId].id = sdlJoyId;
_joysticks[currentId].handler = current;
inputs.addJoystick(SDL_JoystickName(current), currentId);
}
}
}
void SdlContext::_removeJoystick(Input &inputs, SDL_JoystickID joyId)
{
uint32_t currentId = 0;
while (currentId != AGE_JOYSTICK_MAX_NUMBER &&
_joysticks[currentId].id != joyId)
++currentId;
assert(currentId != AGE_JOYSTICK_MAX_NUMBER && "Cannot remove the nonexistent joystick");
SDL_JoystickClose(_joysticks[currentId].handler);
_joysticks[currentId].id = -1;
_joysticks[currentId].handler = NULL;
inputs.removeJoystick(currentId);
}
}
<commit_msg>update arg microprofile<commit_after>#include <Utils/Age_microprofile.hpp>
#include <Utils/Profiler.hpp>
#include <context/SDL/SdlContext.hh>
#include <Utils/OpenGL.hh>
#include <iostream>
#include <Utils/DependenciesInjector.hpp>
#include <Core/Inputs/Input.hh>
#include <SDL/SDL.h>
#include <Core/Inputs/Input.hh>
#include <Threads/MainThread.hpp>
namespace AGE
{
bool SdlContext::_init()
{
_firstCall = true;
_dependencyManager->setInstance<Input>();
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) != 0 ||
//SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1) != 0 ||
//SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8) != 0 ||
(_window = SDL_CreateWindow(_windowName.c_str(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
_screenSize.x, _screenSize.y, SDL_WINDOW_OPENGL)) == NULL ||
(_glContext = SDL_GL_CreateContext(_window)) == NULL)
{
std::cerr << "SDL_GL_CreateContext Failed : " << SDL_GetError() << std::endl;
return (false);
}
SDL_GL_SetSwapInterval(0);
if (glewInit() != GLEW_OK)
{
std::cerr << "glewInit Failed" << std::endl;
return (false);
}
#ifdef AGE_ENABLE_PROFILING
MicroProfileGpuInitGL();
#endif
return (true);
}
SdlContext::SdlContext() { }
SdlContext::~SdlContext() { }
void SdlContext::swapContext()
{
#ifdef AGE_ENABLE_PROFILING
MicroProfileFlip(0);
#endif
{
SCOPE_profile_cpu_i("RenderTimer", "swapContext");
SCOPE_profile_gpu_i("SwapContext");
SDL_GL_SwapWindow(_window);
}
}
void SdlContext::refreshInputs()
{
SCOPE_profile_cpu_function("RenderTimer");
SDL_Event events;
auto input = _dependencyManager->getInstance<Input>();
input->frameUpdate();
if (_firstCall)
{
_initJoysticks(*input);
_firstCall = false;
}
while (SDL_PollEvent(&events))
{
switch (events.type)
{
case SDL_KEYDOWN:
input->keyInputPressed(findAgeMappedKey(events.key.keysym.sym), findAgePhysicalKey(events.key.keysym.scancode));
break;
case SDL_KEYUP:
input->keyInputReleased(findAgeMappedKey(events.key.keysym.sym), findAgePhysicalKey(events.key.keysym.scancode));
break;
case SDL_MOUSEBUTTONDOWN:
input->mouseButtonPressed(findAgeMouseButton(events.button.button));
break;
case SDL_MOUSEBUTTONUP:
input->mouseButtonReleased(findAgeMouseButton(events.button.button));
break;
case SDL_MOUSEWHEEL:
input->setMouseWheel(glm::ivec2(events.wheel.x, events.wheel.y));
break;
case SDL_MOUSEMOTION:
input->setMousePosition(glm::ivec2(events.motion.x, events.motion.y), glm::ivec2(events.motion.xrel, events.motion.yrel));
break;
case SDL_JOYDEVICEADDED:
_addJoystick(*input, events.jdevice.which);
break;
case SDL_JOYDEVICEREMOVED:
_removeJoystick(*input, events.jdevice.which);
break;
case SDL_JOYAXISMOTION:
{
uint32_t joyId = _fromSdlJoystickIdToAge(events.jaxis.which);
AgeJoystickAxis joyAxis = findAgeJoystickAxis(events.jaxis.axis);
float value = (float)events.jaxis.value / 32768.0f;
input->setJoystickAxis(joyId, joyAxis, value);
}
break;
case SDL_JOYBUTTONDOWN:
{
uint32_t joyId = _fromSdlJoystickIdToAge(events.jbutton.which);
AgeJoystickButtons joyButton = findAgeJoystickButton(events.jbutton.button);
input->joystickButtonPressed(joyId, joyButton);
}
break;
case SDL_JOYBUTTONUP:
{
uint32_t joyId = _fromSdlJoystickIdToAge(events.jbutton.which);
AgeJoystickButtons joyButton = findAgeJoystickButton(events.jbutton.button);
input->joystickButtonReleased(joyId, joyButton);
}
break;
case SDL_JOYBALLMOTION:
{
uint32_t joyId = _fromSdlJoystickIdToAge(events.jball.which);
input->setJoystickTrackBall(joyId, events.jball.ball, glm::ivec2(events.jball.xrel, events.jball.yrel));
}
break;
case SDL_JOYHATMOTION:
{
uint32_t joyId = _fromSdlJoystickIdToAge(events.jhat.which);
AgeJoystickHatDirections joyHatDir = findAgeJoystickHatDirection(events.jhat.value);
input->setJoystickHat(joyId, events.jhat.hat, joyHatDir);
}
break;
case SDL_WINDOWEVENT:
input->addWindowInput(findAgeWindowInput(events.window.event));
break;
default:
input->addWindowInput(findAgeWindowInput(events.type));
break;
}
}
input->sendMouseStateToIMGUI();
}
const glm::uvec2 &SdlContext::getScreenSize()
{
return _screenSize;
}
void SdlContext::setScreenSize(const glm::uvec2 &screenSize)
{
_screenSize = screenSize;
SDL_SetWindowSize(_window, _screenSize.x, _screenSize.y);
SDL_SetWindowPosition(_window, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED);
}
void SdlContext::grabMouse(bool grabMouse)
{
SDL_SetRelativeMouseMode((SDL_bool)grabMouse);
}
uint32_t SdlContext::_fromSdlJoystickIdToAge(SDL_JoystickID id)
{
uint32_t currentId = 0;
while (currentId != AGE_JOYSTICK_MAX_NUMBER &&
_joysticks[currentId].id != id)
++currentId;
assert(currentId != AGE_JOYSTICK_MAX_NUMBER && "Cannot find the joystick.");
return (currentId);
}
void SdlContext::_initJoysticks(Input &inputs)
{
// Init Joysticks
for (int i = 0; i < AGE_JOYSTICK_MAX_NUMBER; ++i)
{
_joysticks[i].id = -1;
_joysticks[i].handler = NULL;
}
SDL_JoystickEventState(SDL_ENABLE);
for (int i = 0; i < SDL_NumJoysticks(); ++i)
_addJoystick(inputs, i);
}
void SdlContext::_addJoystick(Input &inputs, int joyIdx)
{
SDL_Joystick *current = SDL_JoystickOpen(joyIdx);
if (current)
{
SDL_JoystickID sdlJoyId = SDL_JoystickInstanceID(current);
if (sdlJoyId != -1)
{
uint32_t currentId = 0;
while (currentId != AGE_JOYSTICK_MAX_NUMBER &&
_joysticks[currentId].id != -1)
++currentId;
assert(currentId != AGE_JOYSTICK_MAX_NUMBER && "AGE cannot handle more than 6 joysticks.");
_joysticks[currentId].id = sdlJoyId;
_joysticks[currentId].handler = current;
inputs.addJoystick(SDL_JoystickName(current), currentId);
}
}
}
void SdlContext::_removeJoystick(Input &inputs, SDL_JoystickID joyId)
{
uint32_t currentId = 0;
while (currentId != AGE_JOYSTICK_MAX_NUMBER &&
_joysticks[currentId].id != joyId)
++currentId;
assert(currentId != AGE_JOYSTICK_MAX_NUMBER && "Cannot remove the nonexistent joystick");
SDL_JoystickClose(_joysticks[currentId].handler);
_joysticks[currentId].id = -1;
_joysticks[currentId].handler = NULL;
inputs.removeJoystick(currentId);
}
}
<|endoftext|> |
<commit_before>// Copyright 2010-2014 RethinkDB, all rights reserved.
#ifndef CONCURRENCY_FIFO_CHECKER_HPP_
#define CONCURRENCY_FIFO_CHECKER_HPP_
#include <map>
#include <string>
#include <utility>
#include "containers/archive/archive.hpp"
#include "containers/uuid.hpp"
#include "rpc/serialize_macros.hpp"
#include "threading.hpp"
struct order_bucket_t {
uuid_u uuid_;
static order_bucket_t invalid() { return order_bucket_t(nil_uuid()); }
static order_bucket_t create() { return order_bucket_t(generate_uuid()); }
bool valid() const;
private:
RDB_MAKE_ME_SERIALIZABLE_1(uuid_);
explicit order_bucket_t(uuid_u uuid) : uuid_(uuid) { }
};
bool operator==(const order_bucket_t &a, const order_bucket_t &b);
bool operator!=(const order_bucket_t &a, const order_bucket_t &b);
bool operator<(const order_bucket_t &a, const order_bucket_t &b);
/* Order tokens of the same bucket need to arrive at order sinks in a
certain order. Pretending that read_mode is always false, they
need to arrive by ascending order of their value -- the same order
that they were created in. This is because write operations cannot
be reordered. However, read operations may be shuffled around, and
so may order_tokens with read_mode set to true.
*/
class order_token_t {
public:
static const order_token_t ignore;
#ifndef NDEBUG
// By default we construct a totally invalid order token, not
// equal to ignore, that must be initialized.
order_token_t();
order_token_t with_read_mode() const;
void assert_read_mode() const;
void assert_write_mode() const;
const std::string &tag() const;
#else
order_token_t() { }
order_token_t with_read_mode() const { return order_token_t(); }
void assert_read_mode() const { }
void assert_write_mode() const { }
std::string tag() const { return ""; }
#endif // ifndef NDEBUG
private:
#ifndef NDEBUG
order_token_t(order_bucket_t bucket, int64_t x, bool read_mode, const std::string &tag);
bool is_invalid() const;
bool is_ignore() const;
// TODO: Make these fields const.
order_bucket_t bucket_;
bool read_mode_;
int64_t value_;
// This tag would be inefficient on VC++ or some other non-GNU
// std::string implementation, since we copy by value.
std::string tag_;
RDB_DECLARE_ME_SERIALIZABLE;
#else
RDB_MAKE_ME_SERIALIZABLE_0(0);
#endif // ifndef NDEBUG
friend class order_source_t;
friend class order_sink_t;
friend class order_checkpoint_t;
friend class plain_sink_t;
};
/* Order sources create order tokens with increasing values for a
specific bucket. */
class order_source_t : public home_thread_mixin_debug_only_t {
public:
#ifndef NDEBUG
order_source_t();
explicit order_source_t(threadnum_t specified_home_thread);
~order_source_t();
// Makes a write-mode order token.
order_token_t check_in(const std::string &tag);
#else
order_source_t() { }
explicit order_source_t(threadnum_t specified_home_thread) : home_thread_mixin_debug_only_t(specified_home_thread) { }
~order_source_t() { }
order_token_t check_in(const std::string&) { return order_token_t(); }
#endif // ndef NDEBUG
private:
#ifndef NDEBUG
order_bucket_t bucket_;
int64_t counter_;
#endif // ifndef NDEBUG
DISABLE_COPYING(order_source_t);
};
struct tagged_seen_t {
int64_t value;
std::string tag;
tagged_seen_t(int64_t _value, const std::string &_tag) : value(_value), tag(_tag) { }
};
/* Eventually order tokens get to an order sink, and those of the same
bucket had better arrive in the right order. */
class order_sink_t : public home_thread_mixin_debug_only_t {
public:
#ifndef NDEBUG
order_sink_t();
void check_out(order_token_t token);
#else
order_sink_t() { }
void check_out(UNUSED order_token_t token) { }
#endif // ifndef NDEBUG
private:
#ifndef NDEBUG
friend class plain_sink_t;
static void verify_token_value_and_update(order_token_t token, std::pair<tagged_seen_t, tagged_seen_t> *ls_pair);
// We keep two last seen values because reads can be reordered.
// .first = last seen write, .second = max(last seen read, last seen write)
typedef std::map<order_bucket_t, std::pair<tagged_seen_t, tagged_seen_t> > last_seens_map_t;
last_seens_map_t last_seens_;
#endif // ifndef NDEBUG
DISABLE_COPYING(order_sink_t);
};
// An order sink with less overhead, for situations where there is
// only one source (like the top of a btree slice) and many sinks. If
// there's one bucket there's no point in instantiating a `std::map`.
// TODO: Is a `std::map` of one item really expensive enough to justify
// having a separate type?
class plain_sink_t : public home_thread_mixin_debug_only_t {
public:
#ifndef NDEBUG
plain_sink_t();
void check_out(order_token_t token);
#else
plain_sink_t() { }
void check_out(UNUSED order_token_t token) { }
#endif // NDEBUG
private:
#ifndef NDEBUG
// The pair of last seen values.
std::pair<tagged_seen_t, tagged_seen_t> ls_pair_;
/* If `have_bucket_`, then `bucket_` is the bucket that we are associated with.
If we get an order token from a different bucket we crap out. */
bool have_bucket_;
order_bucket_t bucket_;
#endif // NDEBUG
};
// `order_checkpoint_t` is an `order_sink_t` plus an `order_source_t`.
class order_checkpoint_t : public home_thread_mixin_debug_only_t {
public:
order_checkpoint_t() { }
#ifndef NDEBUG
explicit order_checkpoint_t(const std::string &tagappend) : tagappend_(tagappend) { }
void set_tagappend(const std::string &tagappend);
order_token_t check_through(order_token_t token);
order_token_t checkpoint_raw_check_in();
#else
explicit order_checkpoint_t(UNUSED const std::string &tagappend) { }
void set_tagappend(UNUSED const std::string &tagappend) { }
order_token_t check_through(UNUSED order_token_t token) { return order_token_t(); }
order_token_t checkpoint_raw_check_in() { return order_token_t(); }
#endif // ndef NDEBUG
private:
#ifndef NDEBUG
order_sink_t sink_;
order_source_t source_;
std::string tagappend_;
#endif
};
#endif // CONCURRENCY_FIFO_CHECKER_HPP_
<commit_msg>Fixed RDB_MAKE_ME_SERIALIZABLE macro that was trying to specify version number in release mode.<commit_after>// Copyright 2010-2014 RethinkDB, all rights reserved.
#ifndef CONCURRENCY_FIFO_CHECKER_HPP_
#define CONCURRENCY_FIFO_CHECKER_HPP_
#include <map>
#include <string>
#include <utility>
#include "containers/archive/archive.hpp"
#include "containers/uuid.hpp"
#include "rpc/serialize_macros.hpp"
#include "threading.hpp"
struct order_bucket_t {
uuid_u uuid_;
static order_bucket_t invalid() { return order_bucket_t(nil_uuid()); }
static order_bucket_t create() { return order_bucket_t(generate_uuid()); }
bool valid() const;
private:
RDB_MAKE_ME_SERIALIZABLE_1(uuid_);
explicit order_bucket_t(uuid_u uuid) : uuid_(uuid) { }
};
bool operator==(const order_bucket_t &a, const order_bucket_t &b);
bool operator!=(const order_bucket_t &a, const order_bucket_t &b);
bool operator<(const order_bucket_t &a, const order_bucket_t &b);
/* Order tokens of the same bucket need to arrive at order sinks in a
certain order. Pretending that read_mode is always false, they
need to arrive by ascending order of their value -- the same order
that they were created in. This is because write operations cannot
be reordered. However, read operations may be shuffled around, and
so may order_tokens with read_mode set to true.
*/
class order_token_t {
public:
static const order_token_t ignore;
#ifndef NDEBUG
// By default we construct a totally invalid order token, not
// equal to ignore, that must be initialized.
order_token_t();
order_token_t with_read_mode() const;
void assert_read_mode() const;
void assert_write_mode() const;
const std::string &tag() const;
#else
order_token_t() { }
order_token_t with_read_mode() const { return order_token_t(); }
void assert_read_mode() const { }
void assert_write_mode() const { }
std::string tag() const { return ""; }
#endif // ifndef NDEBUG
private:
#ifndef NDEBUG
order_token_t(order_bucket_t bucket, int64_t x, bool read_mode, const std::string &tag);
bool is_invalid() const;
bool is_ignore() const;
// TODO: Make these fields const.
order_bucket_t bucket_;
bool read_mode_;
int64_t value_;
// This tag would be inefficient on VC++ or some other non-GNU
// std::string implementation, since we copy by value.
std::string tag_;
RDB_DECLARE_ME_SERIALIZABLE;
#else
RDB_MAKE_ME_SERIALIZABLE_0();
#endif // ifndef NDEBUG
friend class order_source_t;
friend class order_sink_t;
friend class order_checkpoint_t;
friend class plain_sink_t;
};
/* Order sources create order tokens with increasing values for a
specific bucket. */
class order_source_t : public home_thread_mixin_debug_only_t {
public:
#ifndef NDEBUG
order_source_t();
explicit order_source_t(threadnum_t specified_home_thread);
~order_source_t();
// Makes a write-mode order token.
order_token_t check_in(const std::string &tag);
#else
order_source_t() { }
explicit order_source_t(threadnum_t specified_home_thread) : home_thread_mixin_debug_only_t(specified_home_thread) { }
~order_source_t() { }
order_token_t check_in(const std::string&) { return order_token_t(); }
#endif // ndef NDEBUG
private:
#ifndef NDEBUG
order_bucket_t bucket_;
int64_t counter_;
#endif // ifndef NDEBUG
DISABLE_COPYING(order_source_t);
};
struct tagged_seen_t {
int64_t value;
std::string tag;
tagged_seen_t(int64_t _value, const std::string &_tag) : value(_value), tag(_tag) { }
};
/* Eventually order tokens get to an order sink, and those of the same
bucket had better arrive in the right order. */
class order_sink_t : public home_thread_mixin_debug_only_t {
public:
#ifndef NDEBUG
order_sink_t();
void check_out(order_token_t token);
#else
order_sink_t() { }
void check_out(UNUSED order_token_t token) { }
#endif // ifndef NDEBUG
private:
#ifndef NDEBUG
friend class plain_sink_t;
static void verify_token_value_and_update(order_token_t token, std::pair<tagged_seen_t, tagged_seen_t> *ls_pair);
// We keep two last seen values because reads can be reordered.
// .first = last seen write, .second = max(last seen read, last seen write)
typedef std::map<order_bucket_t, std::pair<tagged_seen_t, tagged_seen_t> > last_seens_map_t;
last_seens_map_t last_seens_;
#endif // ifndef NDEBUG
DISABLE_COPYING(order_sink_t);
};
// An order sink with less overhead, for situations where there is
// only one source (like the top of a btree slice) and many sinks. If
// there's one bucket there's no point in instantiating a `std::map`.
// TODO: Is a `std::map` of one item really expensive enough to justify
// having a separate type?
class plain_sink_t : public home_thread_mixin_debug_only_t {
public:
#ifndef NDEBUG
plain_sink_t();
void check_out(order_token_t token);
#else
plain_sink_t() { }
void check_out(UNUSED order_token_t token) { }
#endif // NDEBUG
private:
#ifndef NDEBUG
// The pair of last seen values.
std::pair<tagged_seen_t, tagged_seen_t> ls_pair_;
/* If `have_bucket_`, then `bucket_` is the bucket that we are associated with.
If we get an order token from a different bucket we crap out. */
bool have_bucket_;
order_bucket_t bucket_;
#endif // NDEBUG
};
// `order_checkpoint_t` is an `order_sink_t` plus an `order_source_t`.
class order_checkpoint_t : public home_thread_mixin_debug_only_t {
public:
order_checkpoint_t() { }
#ifndef NDEBUG
explicit order_checkpoint_t(const std::string &tagappend) : tagappend_(tagappend) { }
void set_tagappend(const std::string &tagappend);
order_token_t check_through(order_token_t token);
order_token_t checkpoint_raw_check_in();
#else
explicit order_checkpoint_t(UNUSED const std::string &tagappend) { }
void set_tagappend(UNUSED const std::string &tagappend) { }
order_token_t check_through(UNUSED order_token_t token) { return order_token_t(); }
order_token_t checkpoint_raw_check_in() { return order_token_t(); }
#endif // ndef NDEBUG
private:
#ifndef NDEBUG
order_sink_t sink_;
order_source_t source_;
std::string tagappend_;
#endif
};
#endif // CONCURRENCY_FIFO_CHECKER_HPP_
<|endoftext|> |
<commit_before>/*********************************************************************
*
* Condor ClassAd library
* Copyright (C) 1990-2001, CONDOR Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI, and Rajesh Raman.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of version 2.1 of the GNU Lesser General
* Public License as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
*********************************************************************/
#include "common.h"
#include "exprTree.h"
using namespace std;
BEGIN_NAMESPACE( classad )
ExprList::
ExprList()
{
nodeKind = EXPR_LIST_NODE;
}
ExprList::
~ExprList()
{
Clear( );
}
void ExprList::
Clear ()
{
vector<ExprTree*>::iterator itr;
for( itr = exprList.begin( ); itr != exprList.end( ); itr++ ) {
delete *itr;
}
exprList.clear( );
}
ExprList *ExprList::
Copy( ) const
{
ExprList *newList = new ExprList;
ExprTree *newTree;
if (newList == 0) return 0;
newList->parentScope = parentScope;
vector<ExprTree*>::const_iterator itr;
for( itr = exprList.begin( ); itr != exprList.end( ); itr++ ) {
if( !( newTree = (*itr)->Copy( ) ) ) {
delete newList;
CondorErrno = ERR_MEM_ALLOC_FAILED;
CondorErrMsg = "";
return((ExprList*)NULL);
}
newList->exprList.push_back( newTree );
}
return newList;
}
void ExprList::
_SetParentScope( const ClassAd *parent )
{
vector<ExprTree*>::iterator itr;
for( itr = exprList.begin( ); itr != exprList.end( ); itr++ ) {
(*itr)->SetParentScope( parent );
}
}
ExprList *ExprList::
MakeExprList( const vector<ExprTree*> &exprs )
{
vector<ExprTree*>::const_iterator itr;
ExprList *el = new ExprList;
if( !el ) {
CondorErrno = ERR_MEM_ALLOC_FAILED;
CondorErrMsg = "";
return( NULL );
}
for( itr=exprs.begin( ) ; itr!=exprs.end( ); itr++ ) {
el->exprList.push_back( *itr );
}
return( el );
}
void ExprList::
GetComponents( vector<ExprTree*> &exprs ) const
{
vector<ExprTree*>::const_iterator itr;
exprs.clear( );
for( itr=exprList.begin( ); itr!=exprList.end( ); itr++ ) {
exprs.push_back( *itr );
}
}
bool ExprList::
_Evaluate (EvalState &, Value &val) const
{
val.SetListValue (this);
return( true );
}
bool ExprList::
_Evaluate( EvalState &, Value &val, ExprTree *&sig ) const
{
val.SetListValue( this );
return( ( sig = Copy( ) ) );
}
bool ExprList::
_Flatten( EvalState &state, Value &, ExprTree *&tree, int* ) const
{
vector<ExprTree*>::const_iterator itr;
ExprTree *expr, *nexpr;
Value tempVal;
ExprList *newList;
if( ( newList = new ExprList( ) ) == NULL ) return false;
for( itr = exprList.begin( ); itr != exprList.end( ); itr++ ) {
expr = *itr;
// flatten the constituent expression
if( !expr->Flatten( state, tempVal, nexpr ) ) {
delete newList;
tree = NULL;
return false;
}
// if only a value was obtained, convert to an expression
if( !nexpr ) {
nexpr = Literal::MakeLiteral( tempVal );
if( !nexpr ) {
CondorErrno = ERR_MEM_ALLOC_FAILED;
CondorErrMsg = "";
delete newList;
return false;
}
}
// add the new expression to the flattened list
newList->exprList.push_back( nexpr );
}
tree = newList;
return true;
}
// Iterator implementation
ExprListIterator::
ExprListIterator( )
{
l = NULL;
}
ExprListIterator::
ExprListIterator( const ExprList* l )
{
Initialize( l );
}
ExprListIterator::
~ExprListIterator( )
{
}
void ExprListIterator::
Initialize( const ExprList *el )
{
// initialize eval state
l = el;
state.cache.clear( );
state.curAd = (ClassAd*)l->parentScope;
state.SetRootScope( );
// initialize list iterator
itr = l->exprList.begin( );
}
void ExprListIterator::
ToFirst( )
{
if( l ) itr = l->exprList.begin( );
}
void ExprListIterator::
ToAfterLast( )
{
if( l ) itr = l->exprList.end( );
}
bool ExprListIterator::
ToNth( int n )
{
if( l && n >= 0 && l->exprList.size( ) > (unsigned)n ) {
itr = l->exprList.begin( ) + n;
return( true );
}
itr = l->exprList.begin( );
return( false );
}
const ExprTree* ExprListIterator::
NextExpr( )
{
if( l && itr != l->exprList.end( ) ) {
itr++;
return( itr==l->exprList.end() ? NULL : *itr );
}
return( NULL );
}
const ExprTree* ExprListIterator::
CurrentExpr( ) const
{
return( l && itr != l->exprList.end( ) ? *itr : NULL );
}
const ExprTree* ExprListIterator::
PrevExpr( )
{
if( l && itr != l->exprList.begin( ) ) {
itr++;
return( *itr );
}
return( NULL );
}
bool ExprListIterator::
GetValue( Value& val, const ExprTree *tree, EvalState *es )
{
Value cv;
EvalState *currentState;
EvalCache::iterator itr;
if( !tree ) return false;
// if called from user code, es == NULL so we use &state instead
currentState = es ? es : &state;
// lookup in cache
itr = currentState->cache.find( tree );
// if found, return cached value
if( itr != currentState->cache.end( ) ) {
val.CopyFrom( itr->second );
return true;
}
// temporarily cache value as undef, so any circular refs in
// Evaluate() will eval to undef rather than loop
cv.SetUndefinedValue( );
currentState->cache[ tree ] = cv;
tree->Evaluate( *currentState, val );
// replace temporary cached value (above) with actual evaluation
currentState->cache[ tree ] = val;
return true;
}
bool ExprListIterator::
NextValue( Value& val, EvalState *es )
{
return GetValue( val, NextExpr( ), es );
}
bool ExprListIterator::
CurrentValue( Value& val, EvalState *es )
{
return GetValue( val, CurrentExpr( ), es );
}
bool ExprListIterator::
PrevValue( Value& val, EvalState *es )
{
return GetValue( val, PrevExpr( ), es );
}
bool ExprListIterator::
GetValue( Value& val, ExprTree*& sig, const ExprTree *tree, EvalState *es )
{
Value cv;
EvalState *currentState;
EvalCache::iterator itr;
if( !tree ) return false;
// if called from user code, es == NULL so we use &state instead
currentState = es ? es : &state;
// lookup in cache
itr = currentState->cache.find( tree );
// if found, return cached value
if( itr != currentState->cache.end( ) ) {
val.CopyFrom( itr->second );
return true;
}
// temporarily cache value as undef, so any circular refs in
// Evaluate() will eval to undef rather than loop
cv.SetUndefinedValue( );
currentState->cache[ tree ] = cv;
tree->Evaluate( *currentState, val, sig );
// replace temporary cached value (above) with actual evaluation
currentState->cache[ tree ] = val;
return true;
}
bool ExprListIterator::
NextValue( Value& val, ExprTree*& sig, EvalState *es )
{
return GetValue( val, sig, NextExpr( ), es );
}
bool ExprListIterator::
CurrentValue( Value& val, ExprTree*& sig, EvalState *es )
{
return GetValue( val, sig, CurrentExpr( ), es );
}
bool ExprListIterator::
PrevValue( Value& val, ExprTree*& sig, EvalState *es )
{
return GetValue( val, sig, PrevExpr( ), es );
}
bool ExprListIterator::
IsAtFirst( ) const
{
return( l && itr == l->exprList.begin( ) );
}
bool ExprListIterator::
IsAfterLast( ) const
{
return( l && itr == l->exprList.end( ) );
}
END_NAMESPACE // classad
<commit_msg>fixed bug: in subscript operators, evaluation of the list component expression must be performed in the scope of the list, not the subscript expression. (Contributed by Rajesh)<commit_after>/*********************************************************************
*
* Condor ClassAd library
* Copyright (C) 1990-2001, CONDOR Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI, and Rajesh Raman.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of version 2.1 of the GNU Lesser General
* Public License as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
*********************************************************************/
#include "common.h"
#include "exprTree.h"
using namespace std;
BEGIN_NAMESPACE( classad )
ExprList::
ExprList()
{
nodeKind = EXPR_LIST_NODE;
}
ExprList::
~ExprList()
{
Clear( );
}
void ExprList::
Clear ()
{
vector<ExprTree*>::iterator itr;
for( itr = exprList.begin( ); itr != exprList.end( ); itr++ ) {
delete *itr;
}
exprList.clear( );
}
ExprList *ExprList::
Copy( ) const
{
ExprList *newList = new ExprList;
ExprTree *newTree;
if (newList == 0) return 0;
newList->parentScope = parentScope;
vector<ExprTree*>::const_iterator itr;
for( itr = exprList.begin( ); itr != exprList.end( ); itr++ ) {
if( !( newTree = (*itr)->Copy( ) ) ) {
delete newList;
CondorErrno = ERR_MEM_ALLOC_FAILED;
CondorErrMsg = "";
return((ExprList*)NULL);
}
newList->exprList.push_back( newTree );
}
return newList;
}
void ExprList::
_SetParentScope( const ClassAd *parent )
{
vector<ExprTree*>::iterator itr;
for( itr = exprList.begin( ); itr != exprList.end( ); itr++ ) {
(*itr)->SetParentScope( parent );
}
}
ExprList *ExprList::
MakeExprList( const vector<ExprTree*> &exprs )
{
vector<ExprTree*>::const_iterator itr;
ExprList *el = new ExprList;
if( !el ) {
CondorErrno = ERR_MEM_ALLOC_FAILED;
CondorErrMsg = "";
return( NULL );
}
for( itr=exprs.begin( ) ; itr!=exprs.end( ); itr++ ) {
el->exprList.push_back( *itr );
}
return( el );
}
void ExprList::
GetComponents( vector<ExprTree*> &exprs ) const
{
vector<ExprTree*>::const_iterator itr;
exprs.clear( );
for( itr=exprList.begin( ); itr!=exprList.end( ); itr++ ) {
exprs.push_back( *itr );
}
}
bool ExprList::
_Evaluate (EvalState &, Value &val) const
{
val.SetListValue (this);
return( true );
}
bool ExprList::
_Evaluate( EvalState &, Value &val, ExprTree *&sig ) const
{
val.SetListValue( this );
return( ( sig = Copy( ) ) );
}
bool ExprList::
_Flatten( EvalState &state, Value &, ExprTree *&tree, int* ) const
{
vector<ExprTree*>::const_iterator itr;
ExprTree *expr, *nexpr;
Value tempVal;
ExprList *newList;
if( ( newList = new ExprList( ) ) == NULL ) return false;
for( itr = exprList.begin( ); itr != exprList.end( ); itr++ ) {
expr = *itr;
// flatten the constituent expression
if( !expr->Flatten( state, tempVal, nexpr ) ) {
delete newList;
tree = NULL;
return false;
}
// if only a value was obtained, convert to an expression
if( !nexpr ) {
nexpr = Literal::MakeLiteral( tempVal );
if( !nexpr ) {
CondorErrno = ERR_MEM_ALLOC_FAILED;
CondorErrMsg = "";
delete newList;
return false;
}
}
// add the new expression to the flattened list
newList->exprList.push_back( nexpr );
}
tree = newList;
return true;
}
// Iterator implementation
ExprListIterator::
ExprListIterator( )
{
l = NULL;
}
ExprListIterator::
ExprListIterator( const ExprList* l )
{
Initialize( l );
}
ExprListIterator::
~ExprListIterator( )
{
}
void ExprListIterator::
Initialize( const ExprList *el )
{
// initialize eval state
l = el;
state.cache.clear( );
state.curAd = (ClassAd*)l->parentScope;
state.SetRootScope( );
// initialize list iterator
itr = l->exprList.begin( );
}
void ExprListIterator::
ToFirst( )
{
if( l ) itr = l->exprList.begin( );
}
void ExprListIterator::
ToAfterLast( )
{
if( l ) itr = l->exprList.end( );
}
bool ExprListIterator::
ToNth( int n )
{
if( l && n >= 0 && l->exprList.size( ) > (unsigned)n ) {
itr = l->exprList.begin( ) + n;
return( true );
}
itr = l->exprList.begin( );
return( false );
}
const ExprTree* ExprListIterator::
NextExpr( )
{
if( l && itr != l->exprList.end( ) ) {
itr++;
return( itr==l->exprList.end() ? NULL : *itr );
}
return( NULL );
}
const ExprTree* ExprListIterator::
CurrentExpr( ) const
{
return( l && itr != l->exprList.end( ) ? *itr : NULL );
}
const ExprTree* ExprListIterator::
PrevExpr( )
{
if( l && itr != l->exprList.begin( ) ) {
itr++;
return( *itr );
}
return( NULL );
}
bool ExprListIterator::
GetValue( Value& val, const ExprTree *tree, EvalState *es )
{
Value cv;
EvalState *currentState;
EvalCache::iterator itr;
if( !tree ) return false;
// if called from user code, es == NULL so we use &state instead
currentState = es ? es : &state;
// lookup in cache
itr = currentState->cache.find( tree );
// if found, return cached value
if( itr != currentState->cache.end( ) ) {
val.CopyFrom( itr->second );
return true;
}
// temporarily cache value as undef, so any circular refs in
// Evaluate() will eval to undef rather than loop
cv.SetUndefinedValue( );
currentState->cache[ tree ] = cv;
const ClassAd *tmpScope = es->curAd;
es->curAd = (ClassAd*) tree->GetParentScope();
tree->Evaluate( *currentState, val );
es->curAd = (ClassAd*) tmpScope;
// replace temporary cached value (above) with actual evaluation
currentState->cache[ tree ] = val;
return true;
}
bool ExprListIterator::
NextValue( Value& val, EvalState *es )
{
return GetValue( val, NextExpr( ), es );
}
bool ExprListIterator::
CurrentValue( Value& val, EvalState *es )
{
return GetValue( val, CurrentExpr( ), es );
}
bool ExprListIterator::
PrevValue( Value& val, EvalState *es )
{
return GetValue( val, PrevExpr( ), es );
}
bool ExprListIterator::
GetValue( Value& val, ExprTree*& sig, const ExprTree *tree, EvalState *es )
{
Value cv;
EvalState *currentState;
EvalCache::iterator itr;
if( !tree ) return false;
// if called from user code, es == NULL so we use &state instead
currentState = es ? es : &state;
// lookup in cache
itr = currentState->cache.find( tree );
// if found, return cached value
if( itr != currentState->cache.end( ) ) {
val.CopyFrom( itr->second );
return true;
}
// temporarily cache value as undef, so any circular refs in
// Evaluate() will eval to undef rather than loop
cv.SetUndefinedValue( );
currentState->cache[ tree ] = cv;
const ClassAd *tmpScope = es->curAd;
es->curAd = (ClassAd*) tree->GetParentScope();
tree->Evaluate( *currentState, val, sig );
es->curAd = (ClassAd*) tmpScope;
// replace temporary cached value (above) with actual evaluation
currentState->cache[ tree ] = val;
return true;
}
bool ExprListIterator::
NextValue( Value& val, ExprTree*& sig, EvalState *es )
{
return GetValue( val, sig, NextExpr( ), es );
}
bool ExprListIterator::
CurrentValue( Value& val, ExprTree*& sig, EvalState *es )
{
return GetValue( val, sig, CurrentExpr( ), es );
}
bool ExprListIterator::
PrevValue( Value& val, ExprTree*& sig, EvalState *es )
{
return GetValue( val, sig, PrevExpr( ), es );
}
bool ExprListIterator::
IsAtFirst( ) const
{
return( l && itr == l->exprList.begin( ) );
}
bool ExprListIterator::
IsAfterLast( ) const
{
return( l && itr == l->exprList.end( ) );
}
END_NAMESPACE // classad
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/sync/notifier/chrome_system_resources.h"
#include <cstdlib>
#include <cstring>
#include <string>
#include "base/logging.h"
#include "base/message_loop.h"
#include "base/stl_util-inl.h"
#include "base/string_util.h"
#include "chrome/browser/sync/notifier/invalidation_util.h"
namespace sync_notifier {
ChromeSystemResources::ChromeSystemResources(StateWriter* state_writer)
: state_writer_(state_writer) {
DCHECK(non_thread_safe_.CalledOnValidThread());
DCHECK(state_writer_);
}
ChromeSystemResources::~ChromeSystemResources() {
DCHECK(non_thread_safe_.CalledOnValidThread());
StopScheduler();
}
invalidation::Time ChromeSystemResources::current_time() {
DCHECK(non_thread_safe_.CalledOnValidThread());
return base::Time::Now();
}
void ChromeSystemResources::StartScheduler() {
DCHECK(non_thread_safe_.CalledOnValidThread());
scoped_runnable_method_factory_.reset(
new ScopedRunnableMethodFactory<ChromeSystemResources>(this));
}
void ChromeSystemResources::StopScheduler() {
DCHECK(non_thread_safe_.CalledOnValidThread());
scoped_runnable_method_factory_.reset();
STLDeleteElements(&posted_tasks_);
}
void ChromeSystemResources::ScheduleWithDelay(
invalidation::TimeDelta delay,
invalidation::Closure* task) {
DCHECK(non_thread_safe_.CalledOnValidThread());
Task* task_to_post = MakeTaskToPost(task);
if (!task_to_post) {
return;
}
MessageLoop::current()->PostDelayedTask(
FROM_HERE, task_to_post, delay.InMillisecondsRoundedUp());
}
void ChromeSystemResources::ScheduleImmediately(
invalidation::Closure* task) {
DCHECK(non_thread_safe_.CalledOnValidThread());
Task* task_to_post = MakeTaskToPost(task);
if (!task_to_post) {
return;
}
MessageLoop::current()->PostTask(FROM_HERE, task_to_post);
}
// The listener thread is just our current thread (i.e., the
// notifications thread).
void ChromeSystemResources::ScheduleOnListenerThread(
invalidation::Closure* task) {
DCHECK(non_thread_safe_.CalledOnValidThread());
ScheduleImmediately(task);
}
// 'Internal thread' means 'not the listener thread'. Since the
// listener thread is the notifications thread, always return false.
bool ChromeSystemResources::IsRunningOnInternalThread() {
DCHECK(non_thread_safe_.CalledOnValidThread());
return false;
}
void ChromeSystemResources::Log(
LogLevel level, const char* file, int line,
const char* format, ...) {
DCHECK(non_thread_safe_.CalledOnValidThread());
logging::LogSeverity log_severity = logging::LOG_INFO;
switch (level) {
case INFO_LEVEL:
log_severity = logging::LOG_INFO;
break;
case WARNING_LEVEL:
log_severity = logging::LOG_WARNING;
break;
case SEVERE_LEVEL:
log_severity = logging::LOG_ERROR;
break;
}
// We treat LOG(INFO) as VLOG(1).
if ((log_severity >= logging::GetMinLogLevel()) &&
((log_severity != logging::LOG_INFO) ||
(1 <= logging::GetVlogLevelHelper(file, ::strlen(file))))) {
va_list ap;
va_start(ap, format);
std::string result;
StringAppendV(&result, format, ap);
logging::LogMessage(file, line, log_severity).stream() << result;
va_end(ap);
}
}
void ChromeSystemResources::RunAndDeleteStorageCallback(
invalidation::StorageCallback* callback) {
callback->Run(true);
delete callback;
}
void ChromeSystemResources::WriteState(
const invalidation::string& state,
invalidation::StorageCallback* callback) {
CHECK(state_writer_);
state_writer_->WriteState(state);
// According to the cache invalidation API folks, we can do this as
// long as we make sure to clear the persistent state that we start
// up the cache invalidation client with. However, we musn't do it
// right away, as we may be called under a lock that the callback
// uses.
ScheduleImmediately(
invalidation::NewPermanentCallback(
this, &ChromeSystemResources::RunAndDeleteStorageCallback,
callback));
}
Task* ChromeSystemResources::MakeTaskToPost(
invalidation::Closure* task) {
DCHECK(non_thread_safe_.CalledOnValidThread());
DCHECK(invalidation::IsCallbackRepeatable(task));
if (!scoped_runnable_method_factory_.get()) {
delete task;
return NULL;
}
posted_tasks_.insert(task);
Task* task_to_post =
scoped_runnable_method_factory_->NewRunnableMethod(
&ChromeSystemResources::RunPostedTask, task);
return task_to_post;
}
void ChromeSystemResources::RunPostedTask(invalidation::Closure* task) {
DCHECK(non_thread_safe_.CalledOnValidThread());
RunAndDeleteClosure(task);
posted_tasks_.erase(task);
}
} // namespace sync_notifier
<commit_msg>sync: change some DCHECKs to CHECKs to shed light on a bug.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/sync/notifier/chrome_system_resources.h"
#include <cstdlib>
#include <cstring>
#include <string>
#include "base/logging.h"
#include "base/message_loop.h"
#include "base/stl_util-inl.h"
#include "base/string_util.h"
#include "chrome/browser/sync/notifier/invalidation_util.h"
namespace sync_notifier {
ChromeSystemResources::ChromeSystemResources(StateWriter* state_writer)
: state_writer_(state_writer) {
CHECK(non_thread_safe_.CalledOnValidThread());
DCHECK(state_writer_);
}
ChromeSystemResources::~ChromeSystemResources() {
CHECK(non_thread_safe_.CalledOnValidThread());
StopScheduler();
}
invalidation::Time ChromeSystemResources::current_time() {
CHECK(non_thread_safe_.CalledOnValidThread());
return base::Time::Now();
}
void ChromeSystemResources::StartScheduler() {
CHECK(non_thread_safe_.CalledOnValidThread());
scoped_runnable_method_factory_.reset(
new ScopedRunnableMethodFactory<ChromeSystemResources>(this));
}
void ChromeSystemResources::StopScheduler() {
CHECK(non_thread_safe_.CalledOnValidThread());
scoped_runnable_method_factory_.reset();
STLDeleteElements(&posted_tasks_);
}
void ChromeSystemResources::ScheduleWithDelay(
invalidation::TimeDelta delay,
invalidation::Closure* task) {
CHECK(non_thread_safe_.CalledOnValidThread());
Task* task_to_post = MakeTaskToPost(task);
if (!task_to_post) {
return;
}
MessageLoop::current()->PostDelayedTask(
FROM_HERE, task_to_post, delay.InMillisecondsRoundedUp());
}
void ChromeSystemResources::ScheduleImmediately(
invalidation::Closure* task) {
CHECK(non_thread_safe_.CalledOnValidThread());
Task* task_to_post = MakeTaskToPost(task);
if (!task_to_post) {
return;
}
MessageLoop::current()->PostTask(FROM_HERE, task_to_post);
}
// The listener thread is just our current thread (i.e., the
// notifications thread).
void ChromeSystemResources::ScheduleOnListenerThread(
invalidation::Closure* task) {
CHECK(non_thread_safe_.CalledOnValidThread());
ScheduleImmediately(task);
}
// 'Internal thread' means 'not the listener thread'. Since the
// listener thread is the notifications thread, always return false.
bool ChromeSystemResources::IsRunningOnInternalThread() {
CHECK(non_thread_safe_.CalledOnValidThread());
return false;
}
void ChromeSystemResources::Log(
LogLevel level, const char* file, int line,
const char* format, ...) {
DCHECK(non_thread_safe_.CalledOnValidThread());
logging::LogSeverity log_severity = logging::LOG_INFO;
switch (level) {
case INFO_LEVEL:
log_severity = logging::LOG_INFO;
break;
case WARNING_LEVEL:
log_severity = logging::LOG_WARNING;
break;
case SEVERE_LEVEL:
log_severity = logging::LOG_ERROR;
break;
}
// We treat LOG(INFO) as VLOG(1).
if ((log_severity >= logging::GetMinLogLevel()) &&
((log_severity != logging::LOG_INFO) ||
(1 <= logging::GetVlogLevelHelper(file, ::strlen(file))))) {
va_list ap;
va_start(ap, format);
std::string result;
StringAppendV(&result, format, ap);
logging::LogMessage(file, line, log_severity).stream() << result;
va_end(ap);
}
}
void ChromeSystemResources::RunAndDeleteStorageCallback(
invalidation::StorageCallback* callback) {
callback->Run(true);
delete callback;
}
void ChromeSystemResources::WriteState(
const invalidation::string& state,
invalidation::StorageCallback* callback) {
CHECK(state_writer_);
state_writer_->WriteState(state);
// According to the cache invalidation API folks, we can do this as
// long as we make sure to clear the persistent state that we start
// up the cache invalidation client with. However, we musn't do it
// right away, as we may be called under a lock that the callback
// uses.
ScheduleImmediately(
invalidation::NewPermanentCallback(
this, &ChromeSystemResources::RunAndDeleteStorageCallback,
callback));
}
Task* ChromeSystemResources::MakeTaskToPost(
invalidation::Closure* task) {
CHECK(non_thread_safe_.CalledOnValidThread());
DCHECK(invalidation::IsCallbackRepeatable(task));
if (!scoped_runnable_method_factory_.get()) {
delete task;
return NULL;
}
posted_tasks_.insert(task);
Task* task_to_post =
scoped_runnable_method_factory_->NewRunnableMethod(
&ChromeSystemResources::RunPostedTask, task);
return task_to_post;
}
void ChromeSystemResources::RunPostedTask(invalidation::Closure* task) {
CHECK(non_thread_safe_.CalledOnValidThread());
RunAndDeleteClosure(task);
posted_tasks_.erase(task);
}
} // namespace sync_notifier
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/translate/translate_infobar_delegate2.h"
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/translate/translate_infobar_view.h"
#include "chrome/browser/translate/translate_manager2.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
// static
TranslateInfoBarDelegate2* TranslateInfoBarDelegate2::CreateInstance(
Type type,
TranslateErrors::Type error,
TabContents* tab_contents,
const std::string& original_language,
const std::string& target_language) {
if (!TranslateManager2::IsSupportedLanguage(original_language) ||
!TranslateManager2::IsSupportedLanguage(target_language)) {
return NULL;
}
return new TranslateInfoBarDelegate2(type, error, tab_contents,
original_language, target_language);
}
TranslateInfoBarDelegate2::TranslateInfoBarDelegate2(
Type type,
TranslateErrors::Type error,
TabContents* tab_contents,
const std::string& original_language,
const std::string& target_language)
: InfoBarDelegate(tab_contents),
type_(type),
background_animation_(NONE),
tab_contents_(tab_contents),
original_language_index_(-1),
target_language_index_(-1),
error_(error),
infobar_view_(NULL),
prefs_(tab_contents_->profile()->GetPrefs()) {
DCHECK((type_ != TRANSLATION_ERROR && error == TranslateErrors::NONE) ||
(type_ == TRANSLATION_ERROR && error != TranslateErrors::NONE));
std::vector<std::string> language_codes;
TranslateManager2::GetSupportedLanguages(&language_codes);
languages_.reserve(language_codes.size());
for (std::vector<std::string>::const_iterator iter = language_codes.begin();
iter != language_codes.end(); ++iter) {
std::string language_code = *iter;
if (language_code == original_language)
original_language_index_ = iter - language_codes.begin();
else if (language_code == target_language)
target_language_index_ = iter - language_codes.begin();
string16 language_name = GetLanguageDisplayableName(language_code);
// Insert the language in languages_ in alphabetical order.
std::vector<LanguageNamePair>::iterator iter2;
for (iter2 = languages_.begin(); iter2 != languages_.end(); ++iter2) {
if (language_name.compare(iter2->second) < 0)
break;
}
languages_.insert(iter2, LanguageNamePair(language_code, language_name));
}
DCHECK(original_language_index_ != -1);
DCHECK(target_language_index_ != -1);
}
int TranslateInfoBarDelegate2::GetLanguageCount() const {
return static_cast<int>(languages_.size());
}
const std::string& TranslateInfoBarDelegate2::GetLanguageCodeAt(
int index) const {
DCHECK(index >=0 && index < GetLanguageCount());
return languages_[index].first;
}
const string16& TranslateInfoBarDelegate2::GetLanguageDisplayableNameAt(
int index) const {
DCHECK(index >=0 && index < GetLanguageCount());
return languages_[index].second;
}
const std::string& TranslateInfoBarDelegate2::GetOriginalLanguageCode() const {
return GetLanguageCodeAt(original_language_index());
}
const std::string& TranslateInfoBarDelegate2::GetTargetLanguageCode() const {
return GetLanguageCodeAt(target_language_index());
}
void TranslateInfoBarDelegate2::SetOriginalLanguage(int language_index) {
DCHECK(language_index < static_cast<int>(languages_.size()));
original_language_index_ = language_index;
if (infobar_view_)
infobar_view_->OriginalLanguageChanged();
if (type_ == AFTER_TRANSLATE)
Translate();
}
void TranslateInfoBarDelegate2::SetTargetLanguage(int language_index) {
DCHECK(language_index < static_cast<int>(languages_.size()));
target_language_index_ = language_index;
if (infobar_view_)
infobar_view_->TargetLanguageChanged();
if (type_ == AFTER_TRANSLATE)
Translate();
}
bool TranslateInfoBarDelegate2::IsError() {
return type_ == TRANSLATION_ERROR;
}
void TranslateInfoBarDelegate2::Translate() {
Singleton<TranslateManager2>::get()->TranslatePage(
tab_contents_,
GetLanguageCodeAt(original_language_index()),
GetLanguageCodeAt(target_language_index()));
}
void TranslateInfoBarDelegate2::RevertTranslation() {
Singleton<TranslateManager2>::get()->RevertTranslation(tab_contents_);
tab_contents_->RemoveInfoBar(this);
}
void TranslateInfoBarDelegate2::TranslationDeclined() {
// Remember that the user declined the translation so as to prevent showing a
// translate infobar for that page again. (TranslateManager initiates
// translations when getting a LANGUAGE_DETERMINED from the page, which
// happens when a load stops. That could happen multiple times, including
// after the user already declined the translation.)
tab_contents_->language_state().set_translation_declined(true);
}
void TranslateInfoBarDelegate2::InfoBarDismissed() {
if (type_ != BEFORE_TRANSLATE)
return;
// The user closed the infobar without clicking the translate button.
TranslationDeclined();
UMA_HISTOGRAM_COUNTS("Translate.DeclineTranslateCloseInfobar", 1);
}
SkBitmap* TranslateInfoBarDelegate2::GetIcon() const {
return ResourceBundle::GetSharedInstance().GetBitmapNamed(
IDR_INFOBAR_TRANSLATE);
}
InfoBarDelegate::Type TranslateInfoBarDelegate2::GetInfoBarType() {
return InfoBarDelegate::PAGE_ACTION_TYPE;
}
bool TranslateInfoBarDelegate2::IsLanguageBlacklisted() {
const std::string& original_lang =
GetLanguageCodeAt(original_language_index());
return prefs_.IsLanguageBlacklisted(original_lang);
}
void TranslateInfoBarDelegate2::ToggleLanguageBlacklist() {
const std::string& original_lang =
GetLanguageCodeAt(original_language_index());
if (prefs_.IsLanguageBlacklisted(original_lang)) {
prefs_.RemoveLanguageFromBlacklist(original_lang);
} else {
prefs_.BlacklistLanguage(original_lang);
tab_contents_->RemoveInfoBar(this);
}
}
bool TranslateInfoBarDelegate2::IsSiteBlacklisted() {
std::string host = GetPageHost();
return !host.empty() && prefs_.IsSiteBlacklisted(host);
}
void TranslateInfoBarDelegate2::ToggleSiteBlacklist() {
std::string host = GetPageHost();
if (host.empty())
return;
if (prefs_.IsSiteBlacklisted(host)) {
prefs_.RemoveSiteFromBlacklist(host);
} else {
prefs_.BlacklistSite(host);
tab_contents_->RemoveInfoBar(this);
}
}
bool TranslateInfoBarDelegate2::ShouldAlwaysTranslate() {
return prefs_.IsLanguagePairWhitelisted(GetOriginalLanguageCode(),
GetTargetLanguageCode());
}
void TranslateInfoBarDelegate2::ToggleAlwaysTranslate() {
std::string original_lang = GetOriginalLanguageCode();
std::string target_lang = GetTargetLanguageCode();
if (prefs_.IsLanguagePairWhitelisted(original_lang, target_lang))
prefs_.RemoveLanguagePairFromWhitelist(original_lang, target_lang);
else
prefs_.WhitelistLanguagePair(original_lang, target_lang);
}
string16 TranslateInfoBarDelegate2::GetMessageInfoBarText() {
switch (type_) {
case TRANSLATING:
return l10n_util::GetStringFUTF16(
IDS_TRANSLATE_INFOBAR_TRANSLATING_TO,
GetLanguageDisplayableNameAt(target_language_index_));
case TRANSLATION_ERROR:
switch (error_) {
case TranslateErrors::NETWORK:
return l10n_util::GetStringUTF16(
IDS_TRANSLATE_INFOBAR_ERROR_CANT_CONNECT);
case TranslateErrors::INITIALIZATION_ERROR:
case TranslateErrors::TRANSLATION_ERROR:
return l10n_util::GetStringUTF16(
IDS_TRANSLATE_INFOBAR_ERROR_CANT_TRANSLATE);
default:
NOTREACHED();
return string16();
}
default:
NOTREACHED();
return string16();
}
}
string16 TranslateInfoBarDelegate2::GetMessageInfoBarButtonText() {
switch (type_) {
case TRANSLATING:
return string16();
case TRANSLATION_ERROR:
return l10n_util::GetStringUTF16(IDS_TRANSLATE_INFOBAR_RETRY);
default:
NOTREACHED();
return string16();
}
}
void TranslateInfoBarDelegate2::MessageInfoBarButtonPressed() {
DCHECK(type_ == TRANSLATION_ERROR);
Singleton<TranslateManager2>::get()->TranslatePage(
tab_contents_,
GetLanguageCodeAt(original_language_index()),
GetLanguageCodeAt(target_language_index()));
}
void TranslateInfoBarDelegate2::UpdateBackgroundAnimation(
TranslateInfoBarDelegate2* previous_infobar) {
if (!previous_infobar || previous_infobar->IsError() == IsError()) {
background_animation_ = NONE;
return;
}
background_animation_ = IsError() ? NORMAL_TO_ERROR : ERROR_TO_NORMAL;
}
std::string TranslateInfoBarDelegate2::GetPageHost() {
NavigationEntry* entry = tab_contents_->controller().GetActiveEntry();
return entry ? entry->url().HostNoBrackets() : std::string();
}
// static
string16 TranslateInfoBarDelegate2::GetLanguageDisplayableName(
const std::string& language_code) {
return l10n_util::GetDisplayNameForLocale(
language_code, g_browser_process->GetApplicationLocale(), true);
}
// static
void TranslateInfoBarDelegate2::GetAfterTranslateStrings(
std::vector<string16>* strings, bool* swap_languages) {
DCHECK(strings);
DCHECK(swap_languages);
std::vector<size_t> offsets;
string16 text =
l10n_util::GetStringFUTF16(IDS_TRANSLATE_INFOBAR_AFTER_MESSAGE,
string16(), string16(), &offsets);
DCHECK(offsets.size() == 2U);
if (offsets[0] > offsets[1]) {
// Target language comes before source.
int tmp = offsets[0];
offsets[0] = offsets[0];
offsets[1] = tmp;
*swap_languages = true;
} else {
*swap_languages = false;
}
strings->push_back(text.substr(0, offsets[0]));
strings->push_back(text.substr(offsets[0], offsets[1]));
strings->push_back(text.substr(offsets[1]));
}
#if !defined(OS_WIN) && !defined(OS_CHROMEOS)
// Necessary so we link OK on Mac and Linux while the new translate infobars
// are being ported to these platforms.
InfoBar* TranslateInfoBarDelegate2::CreateInfoBar() {
return NULL;
}
#endif
<commit_msg>Coverity: fix wrong assignment in swap in TranslateInfoBarDelegate2::GetAfterTranslateStrings.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <algorithm>
#include "chrome/browser/translate/translate_infobar_delegate2.h"
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/translate/translate_infobar_view.h"
#include "chrome/browser/translate/translate_manager2.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
// static
TranslateInfoBarDelegate2* TranslateInfoBarDelegate2::CreateInstance(
Type type,
TranslateErrors::Type error,
TabContents* tab_contents,
const std::string& original_language,
const std::string& target_language) {
if (!TranslateManager2::IsSupportedLanguage(original_language) ||
!TranslateManager2::IsSupportedLanguage(target_language)) {
return NULL;
}
return new TranslateInfoBarDelegate2(type, error, tab_contents,
original_language, target_language);
}
TranslateInfoBarDelegate2::TranslateInfoBarDelegate2(
Type type,
TranslateErrors::Type error,
TabContents* tab_contents,
const std::string& original_language,
const std::string& target_language)
: InfoBarDelegate(tab_contents),
type_(type),
background_animation_(NONE),
tab_contents_(tab_contents),
original_language_index_(-1),
target_language_index_(-1),
error_(error),
infobar_view_(NULL),
prefs_(tab_contents_->profile()->GetPrefs()) {
DCHECK((type_ != TRANSLATION_ERROR && error == TranslateErrors::NONE) ||
(type_ == TRANSLATION_ERROR && error != TranslateErrors::NONE));
std::vector<std::string> language_codes;
TranslateManager2::GetSupportedLanguages(&language_codes);
languages_.reserve(language_codes.size());
for (std::vector<std::string>::const_iterator iter = language_codes.begin();
iter != language_codes.end(); ++iter) {
std::string language_code = *iter;
if (language_code == original_language)
original_language_index_ = iter - language_codes.begin();
else if (language_code == target_language)
target_language_index_ = iter - language_codes.begin();
string16 language_name = GetLanguageDisplayableName(language_code);
// Insert the language in languages_ in alphabetical order.
std::vector<LanguageNamePair>::iterator iter2;
for (iter2 = languages_.begin(); iter2 != languages_.end(); ++iter2) {
if (language_name.compare(iter2->second) < 0)
break;
}
languages_.insert(iter2, LanguageNamePair(language_code, language_name));
}
DCHECK(original_language_index_ != -1);
DCHECK(target_language_index_ != -1);
}
int TranslateInfoBarDelegate2::GetLanguageCount() const {
return static_cast<int>(languages_.size());
}
const std::string& TranslateInfoBarDelegate2::GetLanguageCodeAt(
int index) const {
DCHECK(index >=0 && index < GetLanguageCount());
return languages_[index].first;
}
const string16& TranslateInfoBarDelegate2::GetLanguageDisplayableNameAt(
int index) const {
DCHECK(index >=0 && index < GetLanguageCount());
return languages_[index].second;
}
const std::string& TranslateInfoBarDelegate2::GetOriginalLanguageCode() const {
return GetLanguageCodeAt(original_language_index());
}
const std::string& TranslateInfoBarDelegate2::GetTargetLanguageCode() const {
return GetLanguageCodeAt(target_language_index());
}
void TranslateInfoBarDelegate2::SetOriginalLanguage(int language_index) {
DCHECK(language_index < static_cast<int>(languages_.size()));
original_language_index_ = language_index;
if (infobar_view_)
infobar_view_->OriginalLanguageChanged();
if (type_ == AFTER_TRANSLATE)
Translate();
}
void TranslateInfoBarDelegate2::SetTargetLanguage(int language_index) {
DCHECK(language_index < static_cast<int>(languages_.size()));
target_language_index_ = language_index;
if (infobar_view_)
infobar_view_->TargetLanguageChanged();
if (type_ == AFTER_TRANSLATE)
Translate();
}
bool TranslateInfoBarDelegate2::IsError() {
return type_ == TRANSLATION_ERROR;
}
void TranslateInfoBarDelegate2::Translate() {
Singleton<TranslateManager2>::get()->TranslatePage(
tab_contents_,
GetLanguageCodeAt(original_language_index()),
GetLanguageCodeAt(target_language_index()));
}
void TranslateInfoBarDelegate2::RevertTranslation() {
Singleton<TranslateManager2>::get()->RevertTranslation(tab_contents_);
tab_contents_->RemoveInfoBar(this);
}
void TranslateInfoBarDelegate2::TranslationDeclined() {
// Remember that the user declined the translation so as to prevent showing a
// translate infobar for that page again. (TranslateManager initiates
// translations when getting a LANGUAGE_DETERMINED from the page, which
// happens when a load stops. That could happen multiple times, including
// after the user already declined the translation.)
tab_contents_->language_state().set_translation_declined(true);
}
void TranslateInfoBarDelegate2::InfoBarDismissed() {
if (type_ != BEFORE_TRANSLATE)
return;
// The user closed the infobar without clicking the translate button.
TranslationDeclined();
UMA_HISTOGRAM_COUNTS("Translate.DeclineTranslateCloseInfobar", 1);
}
SkBitmap* TranslateInfoBarDelegate2::GetIcon() const {
return ResourceBundle::GetSharedInstance().GetBitmapNamed(
IDR_INFOBAR_TRANSLATE);
}
InfoBarDelegate::Type TranslateInfoBarDelegate2::GetInfoBarType() {
return InfoBarDelegate::PAGE_ACTION_TYPE;
}
bool TranslateInfoBarDelegate2::IsLanguageBlacklisted() {
const std::string& original_lang =
GetLanguageCodeAt(original_language_index());
return prefs_.IsLanguageBlacklisted(original_lang);
}
void TranslateInfoBarDelegate2::ToggleLanguageBlacklist() {
const std::string& original_lang =
GetLanguageCodeAt(original_language_index());
if (prefs_.IsLanguageBlacklisted(original_lang)) {
prefs_.RemoveLanguageFromBlacklist(original_lang);
} else {
prefs_.BlacklistLanguage(original_lang);
tab_contents_->RemoveInfoBar(this);
}
}
bool TranslateInfoBarDelegate2::IsSiteBlacklisted() {
std::string host = GetPageHost();
return !host.empty() && prefs_.IsSiteBlacklisted(host);
}
void TranslateInfoBarDelegate2::ToggleSiteBlacklist() {
std::string host = GetPageHost();
if (host.empty())
return;
if (prefs_.IsSiteBlacklisted(host)) {
prefs_.RemoveSiteFromBlacklist(host);
} else {
prefs_.BlacklistSite(host);
tab_contents_->RemoveInfoBar(this);
}
}
bool TranslateInfoBarDelegate2::ShouldAlwaysTranslate() {
return prefs_.IsLanguagePairWhitelisted(GetOriginalLanguageCode(),
GetTargetLanguageCode());
}
void TranslateInfoBarDelegate2::ToggleAlwaysTranslate() {
std::string original_lang = GetOriginalLanguageCode();
std::string target_lang = GetTargetLanguageCode();
if (prefs_.IsLanguagePairWhitelisted(original_lang, target_lang))
prefs_.RemoveLanguagePairFromWhitelist(original_lang, target_lang);
else
prefs_.WhitelistLanguagePair(original_lang, target_lang);
}
string16 TranslateInfoBarDelegate2::GetMessageInfoBarText() {
switch (type_) {
case TRANSLATING:
return l10n_util::GetStringFUTF16(
IDS_TRANSLATE_INFOBAR_TRANSLATING_TO,
GetLanguageDisplayableNameAt(target_language_index_));
case TRANSLATION_ERROR:
switch (error_) {
case TranslateErrors::NETWORK:
return l10n_util::GetStringUTF16(
IDS_TRANSLATE_INFOBAR_ERROR_CANT_CONNECT);
case TranslateErrors::INITIALIZATION_ERROR:
case TranslateErrors::TRANSLATION_ERROR:
return l10n_util::GetStringUTF16(
IDS_TRANSLATE_INFOBAR_ERROR_CANT_TRANSLATE);
default:
NOTREACHED();
return string16();
}
default:
NOTREACHED();
return string16();
}
}
string16 TranslateInfoBarDelegate2::GetMessageInfoBarButtonText() {
switch (type_) {
case TRANSLATING:
return string16();
case TRANSLATION_ERROR:
return l10n_util::GetStringUTF16(IDS_TRANSLATE_INFOBAR_RETRY);
default:
NOTREACHED();
return string16();
}
}
void TranslateInfoBarDelegate2::MessageInfoBarButtonPressed() {
DCHECK(type_ == TRANSLATION_ERROR);
Singleton<TranslateManager2>::get()->TranslatePage(
tab_contents_,
GetLanguageCodeAt(original_language_index()),
GetLanguageCodeAt(target_language_index()));
}
void TranslateInfoBarDelegate2::UpdateBackgroundAnimation(
TranslateInfoBarDelegate2* previous_infobar) {
if (!previous_infobar || previous_infobar->IsError() == IsError()) {
background_animation_ = NONE;
return;
}
background_animation_ = IsError() ? NORMAL_TO_ERROR : ERROR_TO_NORMAL;
}
std::string TranslateInfoBarDelegate2::GetPageHost() {
NavigationEntry* entry = tab_contents_->controller().GetActiveEntry();
return entry ? entry->url().HostNoBrackets() : std::string();
}
// static
string16 TranslateInfoBarDelegate2::GetLanguageDisplayableName(
const std::string& language_code) {
return l10n_util::GetDisplayNameForLocale(
language_code, g_browser_process->GetApplicationLocale(), true);
}
// static
void TranslateInfoBarDelegate2::GetAfterTranslateStrings(
std::vector<string16>* strings, bool* swap_languages) {
DCHECK(strings);
DCHECK(swap_languages);
std::vector<size_t> offsets;
string16 text =
l10n_util::GetStringFUTF16(IDS_TRANSLATE_INFOBAR_AFTER_MESSAGE,
string16(), string16(), &offsets);
DCHECK(offsets.size() == 2U);
if (offsets[0] > offsets[1]) {
// Target language comes before source.
std::swap(offsets[0], offsets[1]);
*swap_languages = true;
} else {
*swap_languages = false;
}
strings->push_back(text.substr(0, offsets[0]));
strings->push_back(text.substr(offsets[0], offsets[1]));
strings->push_back(text.substr(offsets[1]));
}
#if !defined(OS_WIN) && !defined(OS_CHROMEOS)
// Necessary so we link OK on Mac and Linux while the new translate infobars
// are being ported to these platforms.
InfoBar* TranslateInfoBarDelegate2::CreateInfoBar() {
return NULL;
}
#endif
<|endoftext|> |
<commit_before>#include <ros/ros.h>
#include <geometry_msgs/Twist.h>
#include <sensor_msgs/PointCloud2.h>
#include <sensor_msgs/PointCloud.h>
#include <sensor_msgs/point_cloud_conversion.h>
#include <tf/transform_listener.h>
#include <octomap/octomap.h>
#include <octomap/OcTree.h>
#include <octomap_msgs/Octomap.h>
#include <octomap_msgs/conversions.h>
#include <geometry_msgs/PointStamped.h>
#include <string>
#include <math.h>
#include <vector>
#include "dmath/geometry.h"
class ArtificialPotentialField{
public:
ArtificialPotentialField(ros::NodeHandle &node) :
base_link_("base_link"),
cmd_pub_(node.advertise<geometry_msgs::Twist>("cmd_vel", 10)),
obs_sub_(node.subscribe("octomap_full", 10, &ArtificialPotentialField::obstacleCallback, this))
{
collision_map_.header.stamp = ros::Time(0);
}
void spin(){
ros::Rate r(10);
ros::Duration(1).sleep();
geometry_msgs::Twist cmd;
cmd.linear.z = 0.15;
cmd_pub_.publish(cmd);
ros::Duration(3).sleep();
cmd.linear.z = 0;
cmd_pub_.publish(cmd);
ros::Duration(3).sleep();
const double force = 0.025;
while(ros::ok()){
if(collision_map_.header.stamp != ros::Time(0)){
std::vector<dmath::Vector3D> obstacles_lc;
std::string map_frame = collision_map_.header.frame_id;
octomap::OcTree *tree = dynamic_cast<octomap::OcTree*>(octomap_msgs::msgToMap(collision_map_));
octomap::OcTree::leaf_iterator const end_it = tree->end_leafs();
for(octomap::OcTree::leaf_iterator it = tree->begin_leafs(0); it != end_it; it++){
geometry_msgs::PointStamped p_in, p_out;
p_in.header.frame_id = map_frame;
p_in.point.x = it.getX();
p_in.point.y = it.getY();
p_in.point.z = it.getZ();
try{
tf_listener_.transformPoint(base_link_, p_in, p_out);
}catch(tf::TransformException &ex){
ROS_ERROR_STREAM("Exception trying to transform octomap: " << ex.what());
}
obstacles_lc.push_back(dmath::Vector3D(p_out.point.x, p_out.point.y, p_out.point.z));
}
ROS_INFO_STREAM("size = " << obstacles_lc.size());
dmath::Vector3D Fs;
for(int i=0; i < obstacles_lc.size(); i++){
Fs += get_potential_force(obstacles_lc[i], 0, 0.5, 1.0, 1.5);
}
//dmath::Vector3D g;
//Fs += get_potential_force(g, 2, 0, 1.5, 1);
dmath::Vector3D vel = Fs * force;
cmd.linear.x = vel.y;
cmd.linear.y = vel.x;
cmd.linear.z = vel.z;
ROS_INFO_STREAM("cmd = " << cmd);
cmd_pub_.publish(cmd);
}
r.sleep();
ros::spinOnce();
}
}
private:
dmath::Vector3D get_potential_force(const dmath::Vector3D &dest_lc, double A = 1, double B = 1, double n = 1, double m = 1){
dmath::Vector3D u = dest_lc;
u = normalize(u);
const double d = magnitude(dest_lc);
double U = 0;
if(fabs(d) > dmath::tol){
U = -A/pow(d, n) + B/pow(d, m);
}
return U * u;
}
void obstacleCallback(const octomap_msgs::OctomapPtr &obs_msg){
collision_map_ = *obs_msg;
}
octomap_msgs::Octomap collision_map_;
ros::Publisher cmd_pub_;
ros::Subscriber obs_sub_;
tf::TransformListener tf_listener_;
std::string base_link_;
};
int main(int argc, char *argv[]){
ros::init(argc, argv, "apf_planner");
ros::NodeHandle node;
ArtificialPotentialField apf(node);
apf.spin();
return 0;
}
<commit_msg>Fix a problem that calculate missing the distance<commit_after>#include <ros/ros.h>
#include <geometry_msgs/Twist.h>
#include <sensor_msgs/PointCloud2.h>
#include <sensor_msgs/PointCloud.h>
#include <sensor_msgs/point_cloud_conversion.h>
#include <tf/transform_listener.h>
#include <octomap/octomap.h>
#include <octomap/OcTree.h>
#include <octomap_msgs/Octomap.h>
#include <octomap_msgs/conversions.h>
#include <geometry_msgs/PointStamped.h>
#include <string>
#include <math.h>
#include <vector>
#include "dmath/geometry.h"
class ArtificialPotentialField{
public:
ArtificialPotentialField(ros::NodeHandle &node) :
base_link_("base_link"),
cmd_pub_(node.advertise<geometry_msgs::Twist>("cmd_vel", 10)),
obs_sub_(node.subscribe("octomap_full", 10, &ArtificialPotentialField::obstacleCallback, this))
{
collision_map_.header.stamp = ros::Time(0);
}
void spin(){
ros::Rate r(10);
ros::Duration(1).sleep();
geometry_msgs::Twist cmd;
cmd.linear.z = 0.15;
cmd_pub_.publish(cmd);
ros::Duration(3).sleep();
cmd.linear.z = 0;
cmd_pub_.publish(cmd);
ros::Duration(3).sleep();
const double force = 0.025;
while(ros::ok()){
if(collision_map_.header.stamp != ros::Time(0)){
std::vector<dmath::Vector3D> obstacles_lc;
std::string map_frame = collision_map_.header.frame_id;
octomap::OcTree *tree = dynamic_cast<octomap::OcTree*>(octomap_msgs::msgToMap(collision_map_));
octomap::OcTree::leaf_iterator const end_it = tree->end_leafs();
for(octomap::OcTree::leaf_iterator it = tree->begin_leafs(0); it != end_it; it++){
geometry_msgs::PointStamped p_in, p_out;
p_in.header.frame_id = map_frame;
p_in.point.x = it.getX();
p_in.point.y = it.getY();
p_in.point.z = it.getZ();
try{
tf_listener_.transformPoint(base_link_, p_in, p_out);
dmath::Vector3D obs(p_out.point.x, p_out.point.y, p_out.point.z);
if(magnitude(obs) < 500){
obstacles_lc.push_back(obs);
}
}catch(tf::TransformException &ex){
ROS_ERROR_STREAM("Exception trying to transform octomap: " << ex.what());
}
}
ROS_INFO_STREAM("size = " << obstacles_lc.size());
dmath::Vector3D Fs;
for(int i=0; i < obstacles_lc.size(); i++){
Fs += get_potential_force(obstacles_lc[i], 0, 0.5, 1.0, 1.5);
}
//dmath::Vector3D g;
//Fs += get_potential_force(g, 2, 0, 1.5, 1);
dmath::Vector3D vel = Fs * force;
cmd.linear.x = vel.y;
cmd.linear.y = vel.x;
cmd.linear.z = vel.z;
ROS_INFO_STREAM("cmd = " << cmd);
cmd_pub_.publish(cmd);
}
r.sleep();
ros::spinOnce();
}
}
private:
dmath::Vector3D get_potential_force(const dmath::Vector3D &dest_lc, double A = 1, double B = 1, double n = 1, double m = 1){
dmath::Vector3D u = dest_lc;
u = normalize(u);
const double d = magnitude(dest_lc);
double U = 0;
if(fabs(d) > dmath::tol){
U = -A/pow(d, n) + B/pow(d, m);
}
return U * u;
}
void obstacleCallback(const octomap_msgs::OctomapPtr &obs_msg){
collision_map_ = *obs_msg;
}
octomap_msgs::Octomap collision_map_;
ros::Publisher cmd_pub_;
ros::Subscriber obs_sub_;
tf::TransformListener tf_listener_;
std::string base_link_;
};
int main(int argc, char *argv[]){
ros::init(argc, argv, "apf_planner");
ros::NodeHandle node;
ArtificialPotentialField apf(node);
apf.spin();
return 0;
}
<|endoftext|> |
<commit_before><commit_msg>Add some spacing so that status area lines up on cros<commit_after><|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/file_util.h"
#include "base/path_service.h"
#include "base/scoped_temp_dir.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/extensions/extension_constants.h"
#include "chrome/common/extensions/extension_unpacker.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/skia/include/core/SkBitmap.h"
namespace errors = extension_manifest_errors;
namespace keys = extension_manifest_keys;
class ExtensionUnpackerTest : public testing::Test {
public:
void SetupUnpacker(const std::string& crx_name) {
FilePath original_path;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &original_path));
original_path = original_path.AppendASCII("extensions")
.AppendASCII("unpacker")
.AppendASCII(crx_name);
ASSERT_TRUE(file_util::PathExists(original_path)) << original_path.value();
// Try bots won't let us write into DIR_TEST_DATA, so we have to create
// a temp folder to play in.
ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
FilePath crx_path = temp_dir_.path().AppendASCII(crx_name);
ASSERT_TRUE(file_util::CopyFile(original_path, crx_path)) <<
"Original path " << original_path.value() <<
", Crx path " << crx_path.value();
unpacker_.reset(
new ExtensionUnpacker(
crx_path, Extension::INTERNAL, Extension::NO_FLAGS));
}
protected:
ScopedTempDir temp_dir_;
scoped_ptr<ExtensionUnpacker> unpacker_;
};
TEST_F(ExtensionUnpackerTest, EmptyDefaultLocale) {
SetupUnpacker("empty_default_locale.crx");
EXPECT_FALSE(unpacker_->Run());
EXPECT_EQ(ASCIIToUTF16(errors::kInvalidDefaultLocale),
unpacker_->error_message());
}
TEST_F(ExtensionUnpackerTest, HasDefaultLocaleMissingLocalesFolder) {
SetupUnpacker("has_default_missing_locales.crx");
EXPECT_FALSE(unpacker_->Run());
EXPECT_EQ(ASCIIToUTF16(errors::kLocalesTreeMissing),
unpacker_->error_message());
}
TEST_F(ExtensionUnpackerTest, InvalidDefaultLocale) {
SetupUnpacker("invalid_default_locale.crx");
EXPECT_FALSE(unpacker_->Run());
EXPECT_EQ(ASCIIToUTF16(errors::kInvalidDefaultLocale),
unpacker_->error_message());
}
TEST_F(ExtensionUnpackerTest, InvalidMessagesFile) {
SetupUnpacker("invalid_messages_file.crx");
EXPECT_FALSE(unpacker_->Run());
EXPECT_TRUE(MatchPattern(unpacker_->error_message(),
ASCIIToUTF16("*_locales?en_US?messages.json: Line: 2, column: 3,"
" Dictionary keys must be quoted.")));
}
TEST_F(ExtensionUnpackerTest, MissingDefaultData) {
SetupUnpacker("missing_default_data.crx");
EXPECT_FALSE(unpacker_->Run());
EXPECT_EQ(ASCIIToUTF16(errors::kLocalesNoDefaultMessages),
unpacker_->error_message());
}
TEST_F(ExtensionUnpackerTest, MissingDefaultLocaleHasLocalesFolder) {
SetupUnpacker("missing_default_has_locales.crx");
EXPECT_FALSE(unpacker_->Run());
EXPECT_EQ(ASCIIToUTF16(errors::kLocalesNoDefaultLocaleSpecified),
unpacker_->error_message());
}
TEST_F(ExtensionUnpackerTest, MissingMessagesFile) {
SetupUnpacker("missing_messages_file.crx");
EXPECT_FALSE(unpacker_->Run());
EXPECT_TRUE(MatchPattern(unpacker_->error_message(),
ASCIIToUTF16(errors::kLocalesMessagesFileMissing) +
ASCIIToUTF16("*_locales?en_US?messages.json")));
}
TEST_F(ExtensionUnpackerTest, NoLocaleData) {
SetupUnpacker("no_locale_data.crx");
EXPECT_FALSE(unpacker_->Run());
EXPECT_EQ(ASCIIToUTF16(errors::kLocalesNoDefaultMessages),
unpacker_->error_message());
}
TEST_F(ExtensionUnpackerTest, GoodL10n) {
SetupUnpacker("good_l10n.crx");
EXPECT_TRUE(unpacker_->Run());
EXPECT_TRUE(unpacker_->error_message().empty());
ASSERT_EQ(2U, unpacker_->parsed_catalogs()->size());
}
TEST_F(ExtensionUnpackerTest, NoL10n) {
SetupUnpacker("no_l10n.crx");
EXPECT_TRUE(unpacker_->Run());
EXPECT_TRUE(unpacker_->error_message().empty());
EXPECT_EQ(0U, unpacker_->parsed_catalogs()->size());
}
<commit_msg>Marking ExtensionUnpackerTest.EmptyDefaultLocale as flake on Windows. See http://crbug.com/109238<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/file_util.h"
#include "base/path_service.h"
#include "base/scoped_temp_dir.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/extensions/extension_constants.h"
#include "chrome/common/extensions/extension_unpacker.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/skia/include/core/SkBitmap.h"
namespace errors = extension_manifest_errors;
namespace keys = extension_manifest_keys;
class ExtensionUnpackerTest : public testing::Test {
public:
void SetupUnpacker(const std::string& crx_name) {
FilePath original_path;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &original_path));
original_path = original_path.AppendASCII("extensions")
.AppendASCII("unpacker")
.AppendASCII(crx_name);
ASSERT_TRUE(file_util::PathExists(original_path)) << original_path.value();
// Try bots won't let us write into DIR_TEST_DATA, so we have to create
// a temp folder to play in.
ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
FilePath crx_path = temp_dir_.path().AppendASCII(crx_name);
ASSERT_TRUE(file_util::CopyFile(original_path, crx_path)) <<
"Original path " << original_path.value() <<
", Crx path " << crx_path.value();
unpacker_.reset(
new ExtensionUnpacker(
crx_path, Extension::INTERNAL, Extension::NO_FLAGS));
}
protected:
ScopedTempDir temp_dir_;
scoped_ptr<ExtensionUnpacker> unpacker_;
};
// Flaky on Windows, http://crbug.com/109238
#if defined(OS_WINDOWS)
#define MAYBE_EmptyDefaultLocale FLAKY_EmptyDefaultLocale
#else
#define MAYBE_EmptyDefaultLocale EmptyDefaultLocale
#endif
TEST_F(ExtensionUnpackerTest, MAYBE_EmptyDefaultLocale) {
SetupUnpacker("empty_default_locale.crx");
EXPECT_FALSE(unpacker_->Run());
EXPECT_EQ(ASCIIToUTF16(errors::kInvalidDefaultLocale),
unpacker_->error_message());
}
TEST_F(ExtensionUnpackerTest, HasDefaultLocaleMissingLocalesFolder) {
SetupUnpacker("has_default_missing_locales.crx");
EXPECT_FALSE(unpacker_->Run());
EXPECT_EQ(ASCIIToUTF16(errors::kLocalesTreeMissing),
unpacker_->error_message());
}
TEST_F(ExtensionUnpackerTest, InvalidDefaultLocale) {
SetupUnpacker("invalid_default_locale.crx");
EXPECT_FALSE(unpacker_->Run());
EXPECT_EQ(ASCIIToUTF16(errors::kInvalidDefaultLocale),
unpacker_->error_message());
}
TEST_F(ExtensionUnpackerTest, InvalidMessagesFile) {
SetupUnpacker("invalid_messages_file.crx");
EXPECT_FALSE(unpacker_->Run());
EXPECT_TRUE(MatchPattern(unpacker_->error_message(),
ASCIIToUTF16("*_locales?en_US?messages.json: Line: 2, column: 3,"
" Dictionary keys must be quoted.")));
}
TEST_F(ExtensionUnpackerTest, MissingDefaultData) {
SetupUnpacker("missing_default_data.crx");
EXPECT_FALSE(unpacker_->Run());
EXPECT_EQ(ASCIIToUTF16(errors::kLocalesNoDefaultMessages),
unpacker_->error_message());
}
TEST_F(ExtensionUnpackerTest, MissingDefaultLocaleHasLocalesFolder) {
SetupUnpacker("missing_default_has_locales.crx");
EXPECT_FALSE(unpacker_->Run());
EXPECT_EQ(ASCIIToUTF16(errors::kLocalesNoDefaultLocaleSpecified),
unpacker_->error_message());
}
TEST_F(ExtensionUnpackerTest, MissingMessagesFile) {
SetupUnpacker("missing_messages_file.crx");
EXPECT_FALSE(unpacker_->Run());
EXPECT_TRUE(MatchPattern(unpacker_->error_message(),
ASCIIToUTF16(errors::kLocalesMessagesFileMissing) +
ASCIIToUTF16("*_locales?en_US?messages.json")));
}
TEST_F(ExtensionUnpackerTest, NoLocaleData) {
SetupUnpacker("no_locale_data.crx");
EXPECT_FALSE(unpacker_->Run());
EXPECT_EQ(ASCIIToUTF16(errors::kLocalesNoDefaultMessages),
unpacker_->error_message());
}
TEST_F(ExtensionUnpackerTest, GoodL10n) {
SetupUnpacker("good_l10n.crx");
EXPECT_TRUE(unpacker_->Run());
EXPECT_TRUE(unpacker_->error_message().empty());
ASSERT_EQ(2U, unpacker_->parsed_catalogs()->size());
}
TEST_F(ExtensionUnpackerTest, NoL10n) {
SetupUnpacker("no_l10n.crx");
EXPECT_TRUE(unpacker_->Run());
EXPECT_TRUE(unpacker_->error_message().empty());
EXPECT_EQ(0U, unpacker_->parsed_catalogs()->size());
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2012 Adrien Guinet <adrien@guinet.me>
* 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 Adrien Guinet nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <usbtop/buses.h>
#include <usbtop/usb_bus.h>
#include <usbtop/usb_device.h>
#include <usbtop/usb_stats.h>
#include <usbtop/console_output.h>
#include <usbtop/should_stop.h>
#include <iostream>
#include <iomanip>
#include <unistd.h>
void usbtop::ConsoleOutput::main()
{
std::cout.precision(2);
std::cout.setf(std::ios::fixed);
while (true) {
usleep(250*1000);
if (usbtop::ShouldStop::value()) {
break;
}
clear_screen();
print_stats();
}
}
void usbtop::ConsoleOutput::clear_screen()
{
std::cout << "\033[2J\033[1;1H";
}
void usbtop::ConsoleOutput::print_stats()
{
UsbBuses::list_pop([](UsbBus const* bus)
{ print_stats_bus(*bus); });
}
void usbtop::ConsoleOutput::print_stats_bus(UsbBus const& bus)
{
std::cout << "Bus ID " << bus.id() << " (" << bus.desc() << ")";
std::cout << "\tTo device\tFrom device" << std::endl;
UsbBus::list_devices_t const& devs = bus.devices();
UsbBus::list_devices_t::const_iterator it;
for (it = devs.begin(); it != devs.end(); it++) {
UsbDevice const& dev(*it->second);
UsbStats const& stats(dev.stats());
std::cout << " Device ID " << it->first << " :\t";
double stats_to = stats.stats_to_device().bw_instant()/1024.0;
double stats_from = stats.stats_from_device().bw_instant()/1024.0;
std::cout << "\t\t" << stats_to << " KiB/s\t" << stats_from << " KiB/s" << std::endl;
}
}
<commit_msg>fix formatting for machines with larger number of devices (#32)<commit_after>/*
* Copyright (c) 2012 Adrien Guinet <adrien@guinet.me>
* 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 Adrien Guinet nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <usbtop/buses.h>
#include <usbtop/usb_bus.h>
#include <usbtop/usb_device.h>
#include <usbtop/usb_stats.h>
#include <usbtop/console_output.h>
#include <usbtop/should_stop.h>
#include <iostream>
#include <iomanip>
#include <unistd.h>
void usbtop::ConsoleOutput::main()
{
std::cout.precision(2);
std::cout.setf(std::ios::fixed);
while (true) {
usleep(250*1000);
if (usbtop::ShouldStop::value()) {
break;
}
clear_screen();
print_stats();
}
}
void usbtop::ConsoleOutput::clear_screen()
{
std::cout << "\033[2J\033[1;1H";
}
void usbtop::ConsoleOutput::print_stats()
{
UsbBuses::list_pop([](UsbBus const* bus)
{ print_stats_bus(*bus); });
}
void usbtop::ConsoleOutput::print_stats_bus(UsbBus const& bus)
{
std::cout << "Bus ID " << bus.id() << " (" << bus.desc() << ")";
std::cout << "\tTo device\tFrom device" << std::endl;
UsbBus::list_devices_t const& devs = bus.devices();
UsbBus::list_devices_t::const_iterator it;
for (it = devs.begin(); it != devs.end(); it++) {
UsbDevice const& dev(*it->second);
UsbStats const& stats(dev.stats());
std::cout << " Device ID " << std::setw(3) << it->first << " :\t";
double stats_to = stats.stats_to_device().bw_instant()/1024.0;
double stats_from = stats.stats_from_device().bw_instant()/1024.0;
std::cout << "\t\t\t" << stats_to << " KiB/s\t" << stats_from << " KiB/s" << std::endl;
}
}
<|endoftext|> |
<commit_before>/*
* Copyright 2017 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkThreadedBMPDevice.h"
#include "SkPath.h"
#include "SkSpecialImage.h"
#include "SkTaskGroup.h"
#include "SkVertices.h"
// Calling init(j, k) would initialize the j-th element on k-th thread. It returns false if it's
// already initiailized.
bool SkThreadedBMPDevice::DrawQueue::initColumn(int column, int thread) {
return fElements[column].tryInitOnce(&fThreadAllocs[thread]);
}
// Calling work(i, j, k) would draw j-th element the i-th tile on k-th thead. If the element still
// needs to be initialized, drawFn will return false without drawing.
bool SkThreadedBMPDevice::DrawQueue::work2D(int row, int column, int thread) {
return fElements[column].tryDraw(fDevice->fTileBounds[row], &fThreadAllocs[thread]);
}
void SkThreadedBMPDevice::DrawQueue::reset() {
if (fTasks) {
fTasks->finish();
}
fThreadAllocs.reset(fDevice->fThreadCnt);
fSize = 0;
// using TaskGroup2D = SkSpinningTaskGroup2D;
using TaskGroup2D = SkFlexibleTaskGroup2D;
fTasks.reset(new TaskGroup2D(this, fDevice->fTileCnt, fDevice->fExecutor,
fDevice->fThreadCnt));
fTasks->start();
}
SkThreadedBMPDevice::SkThreadedBMPDevice(const SkBitmap& bitmap,
int tiles,
int threads,
SkExecutor* executor)
: INHERITED(bitmap)
, fTileCnt(tiles)
, fThreadCnt(threads <= 0 ? tiles : threads)
, fQueue(this)
{
if (executor == nullptr) {
fInternalExecutor = SkExecutor::MakeFIFOThreadPool(fThreadCnt);
executor = fInternalExecutor.get();
}
fExecutor = executor;
// Tiling using stripes for now; we'll explore better tiling in the future.
int h = (bitmap.height() + fTileCnt - 1) / SkTMax(fTileCnt, 1);
int w = bitmap.width();
int top = 0;
for(int tid = 0; tid < fTileCnt; ++tid, top += h) {
fTileBounds.push_back(SkIRect::MakeLTRB(0, top, w, top + h));
}
fQueue.reset();
}
void SkThreadedBMPDevice::flush() {
fQueue.reset();
fAlloc.reset();
}
SkThreadedBMPDevice::DrawState::DrawState(SkThreadedBMPDevice* dev) {
// we need fDst to be set, and if we're actually drawing, to dirty the genID
if (!dev->accessPixels(&fDst)) {
// NoDrawDevice uses us (why?) so we have to catch this case w/ no pixels
fDst.reset(dev->imageInfo(), nullptr, 0);
}
fMatrix = dev->ctm();
fRC = dev->fRCStack.rc();
}
SkDraw SkThreadedBMPDevice::DrawState::getDraw() const {
SkDraw draw;
draw.fDst = fDst;
draw.fMatrix = &fMatrix;
draw.fRC = &fRC;
return draw;
}
SkThreadedBMPDevice::TileDraw::TileDraw(const DrawState& ds, const SkIRect& tileBounds)
: fTileRC(ds.fRC) {
fDst = ds.fDst;
fMatrix = &ds.fMatrix;
fTileRC.op(tileBounds, SkRegion::kIntersect_Op);
fRC = &fTileRC;
}
static inline SkRect get_fast_bounds(const SkRect& r, const SkPaint& p) {
SkRect result;
if (p.canComputeFastBounds()) {
result = p.computeFastBounds(r, &result);
} else {
result = SkRectPriv::MakeLargest();
}
return result;
}
void SkThreadedBMPDevice::drawPaint(const SkPaint& paint) {
SkRect drawBounds = SkRectPriv::MakeLargest();
fQueue.push(drawBounds, [=](SkArenaAlloc*, const DrawState& ds, const SkIRect& tileBounds){
TileDraw(ds, tileBounds).drawPaint(paint);
});
}
void SkThreadedBMPDevice::drawPoints(SkCanvas::PointMode mode, size_t count,
const SkPoint pts[], const SkPaint& paint) {
SkPoint* clonedPts = this->cloneArray(pts, count);
SkRect drawBounds = SkRectPriv::MakeLargest(); // TODO tighter drawBounds
fQueue.push(drawBounds, [=](SkArenaAlloc*, const DrawState& ds, const SkIRect& tileBounds){
TileDraw(ds, tileBounds).drawPoints(mode, count, clonedPts, paint, nullptr);
});
}
void SkThreadedBMPDevice::drawRect(const SkRect& r, const SkPaint& paint) {
SkRect drawBounds = get_fast_bounds(r, paint);
fQueue.push(drawBounds, [=](SkArenaAlloc*, const DrawState& ds, const SkIRect& tileBounds){
TileDraw(ds, tileBounds).drawRect(r, paint);
});
}
void SkThreadedBMPDevice::drawRRect(const SkRRect& rrect, const SkPaint& paint) {
#ifdef SK_IGNORE_BLURRED_RRECT_OPT
SkPath path;
path.addRRect(rrect);
// call the VIRTUAL version, so any subclasses who do handle drawPath aren't
// required to override drawRRect.
this->drawPath(path, paint, nullptr, false);
#else
SkRect drawBounds = get_fast_bounds(rrect.getBounds(), paint);
fQueue.push(drawBounds, [=](SkArenaAlloc*, const DrawState& ds, const SkIRect& tileBounds){
TileDraw(ds, tileBounds).drawRRect(rrect, paint);
});
#endif
}
void SkThreadedBMPDevice::drawPath(const SkPath& path, const SkPaint& paint,
const SkMatrix* prePathMatrix, bool pathIsMutable) {
SkRect drawBounds = path.isInverseFillType() ? SkRectPriv::MakeLargest()
: get_fast_bounds(path.getBounds(), paint);
if (path.countVerbs() < 4) { // when path is small, init-once has too much overhead
fQueue.push(drawBounds, [=](SkArenaAlloc*, const DrawState& ds, const SkIRect& tileBounds) {
TileDraw(ds, tileBounds).drawPath(path, paint, prePathMatrix, false);
});
} else {
fQueue.push(drawBounds, [=](SkArenaAlloc* alloc, DrawElement* elem) {
SkInitOnceData data = {alloc, elem};
elem->getDraw().drawPath(path, paint, prePathMatrix, false, false, nullptr, &data);
});
}
}
void SkThreadedBMPDevice::drawBitmap(const SkBitmap& bitmap, const SkMatrix& matrix,
const SkRect* dstOrNull, const SkPaint& paint) {
SkRect drawBounds;
SkRect* clonedDstOrNull = nullptr;
if (dstOrNull == nullptr) {
drawBounds = SkRect::MakeWH(bitmap.width(), bitmap.height());
matrix.mapRect(&drawBounds);
} else {
drawBounds = *dstOrNull;
clonedDstOrNull = fAlloc.make<SkRect>(*dstOrNull);
}
fQueue.push(drawBounds, [=](SkArenaAlloc*, const DrawState& ds, const SkIRect& tileBounds){
TileDraw(ds, tileBounds).drawBitmap(bitmap, matrix, clonedDstOrNull, paint);
});
}
void SkThreadedBMPDevice::drawSprite(const SkBitmap& bitmap, int x, int y, const SkPaint& paint) {
SkRect drawBounds = SkRect::MakeXYWH(x, y, bitmap.width(), bitmap.height());
fQueue.push<false>(drawBounds, [=](SkArenaAlloc*, const DrawState& ds,
const SkIRect& tileBounds){
TileDraw(ds, tileBounds).drawSprite(bitmap, x, y, paint);
});
}
void SkThreadedBMPDevice::drawText(const void* text, size_t len, SkScalar x, SkScalar y,
const SkPaint& paint) {
char* clonedText = this->cloneArray((const char*)text, len);
SkRect drawBounds = SkRectPriv::MakeLargest(); // TODO tighter drawBounds
fQueue.push(drawBounds, [=](SkArenaAlloc*, const DrawState& ds, const SkIRect& tileBounds){
TileDraw(ds, tileBounds).drawText(clonedText, len, x, y, paint,
&this->surfaceProps());
});
}
void SkThreadedBMPDevice::drawPosText(const void* text, size_t len, const SkScalar xpos[],
int scalarsPerPos, const SkPoint& offset, const SkPaint& paint) {
char* clonedText = this->cloneArray((const char*)text, len);
SkRect drawBounds = SkRectPriv::MakeLargest(); // TODO tighter drawBounds
fQueue.push(drawBounds, [=](SkArenaAlloc*, const DrawState& ds, const SkIRect& tileBounds){
TileDraw(ds, tileBounds).drawPosText(clonedText, len, xpos, scalarsPerPos, offset,
paint, &surfaceProps());
});
}
void SkThreadedBMPDevice::drawVertices(const SkVertices* vertices, SkBlendMode bmode,
const SkPaint& paint) {
const sk_sp<SkVertices> verts = sk_ref_sp(vertices); // retain vertices until flush
SkRect drawBounds = SkRectPriv::MakeLargest(); // TODO tighter drawBounds
fQueue.push(drawBounds, [=](SkArenaAlloc*, const DrawState& ds, const SkIRect& tileBounds){
TileDraw(ds, tileBounds).drawVertices(verts->mode(), verts->vertexCount(),
verts->positions(), verts->texCoords(),
verts->colors(), bmode, verts->indices(),
verts->indexCount(), paint);
});
}
sk_sp<SkSpecialImage> SkThreadedBMPDevice::snapSpecial() {
this->flush();
return this->makeSpecial(fBitmap);
}
<commit_msg>Clone the xpos array in drawPosText<commit_after>/*
* Copyright 2017 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkThreadedBMPDevice.h"
#include "SkPath.h"
#include "SkSpecialImage.h"
#include "SkTaskGroup.h"
#include "SkVertices.h"
// Calling init(j, k) would initialize the j-th element on k-th thread. It returns false if it's
// already initiailized.
bool SkThreadedBMPDevice::DrawQueue::initColumn(int column, int thread) {
return fElements[column].tryInitOnce(&fThreadAllocs[thread]);
}
// Calling work(i, j, k) would draw j-th element the i-th tile on k-th thead. If the element still
// needs to be initialized, drawFn will return false without drawing.
bool SkThreadedBMPDevice::DrawQueue::work2D(int row, int column, int thread) {
return fElements[column].tryDraw(fDevice->fTileBounds[row], &fThreadAllocs[thread]);
}
void SkThreadedBMPDevice::DrawQueue::reset() {
if (fTasks) {
fTasks->finish();
}
fThreadAllocs.reset(fDevice->fThreadCnt);
fSize = 0;
// using TaskGroup2D = SkSpinningTaskGroup2D;
using TaskGroup2D = SkFlexibleTaskGroup2D;
fTasks.reset(new TaskGroup2D(this, fDevice->fTileCnt, fDevice->fExecutor,
fDevice->fThreadCnt));
fTasks->start();
}
SkThreadedBMPDevice::SkThreadedBMPDevice(const SkBitmap& bitmap,
int tiles,
int threads,
SkExecutor* executor)
: INHERITED(bitmap)
, fTileCnt(tiles)
, fThreadCnt(threads <= 0 ? tiles : threads)
, fQueue(this)
{
if (executor == nullptr) {
fInternalExecutor = SkExecutor::MakeFIFOThreadPool(fThreadCnt);
executor = fInternalExecutor.get();
}
fExecutor = executor;
// Tiling using stripes for now; we'll explore better tiling in the future.
int h = (bitmap.height() + fTileCnt - 1) / SkTMax(fTileCnt, 1);
int w = bitmap.width();
int top = 0;
for(int tid = 0; tid < fTileCnt; ++tid, top += h) {
fTileBounds.push_back(SkIRect::MakeLTRB(0, top, w, top + h));
}
fQueue.reset();
}
void SkThreadedBMPDevice::flush() {
fQueue.reset();
fAlloc.reset();
}
SkThreadedBMPDevice::DrawState::DrawState(SkThreadedBMPDevice* dev) {
// we need fDst to be set, and if we're actually drawing, to dirty the genID
if (!dev->accessPixels(&fDst)) {
// NoDrawDevice uses us (why?) so we have to catch this case w/ no pixels
fDst.reset(dev->imageInfo(), nullptr, 0);
}
fMatrix = dev->ctm();
fRC = dev->fRCStack.rc();
}
SkDraw SkThreadedBMPDevice::DrawState::getDraw() const {
SkDraw draw;
draw.fDst = fDst;
draw.fMatrix = &fMatrix;
draw.fRC = &fRC;
return draw;
}
SkThreadedBMPDevice::TileDraw::TileDraw(const DrawState& ds, const SkIRect& tileBounds)
: fTileRC(ds.fRC) {
fDst = ds.fDst;
fMatrix = &ds.fMatrix;
fTileRC.op(tileBounds, SkRegion::kIntersect_Op);
fRC = &fTileRC;
}
static inline SkRect get_fast_bounds(const SkRect& r, const SkPaint& p) {
SkRect result;
if (p.canComputeFastBounds()) {
result = p.computeFastBounds(r, &result);
} else {
result = SkRectPriv::MakeLargest();
}
return result;
}
void SkThreadedBMPDevice::drawPaint(const SkPaint& paint) {
SkRect drawBounds = SkRectPriv::MakeLargest();
fQueue.push(drawBounds, [=](SkArenaAlloc*, const DrawState& ds, const SkIRect& tileBounds){
TileDraw(ds, tileBounds).drawPaint(paint);
});
}
void SkThreadedBMPDevice::drawPoints(SkCanvas::PointMode mode, size_t count,
const SkPoint pts[], const SkPaint& paint) {
SkPoint* clonedPts = this->cloneArray(pts, count);
SkRect drawBounds = SkRectPriv::MakeLargest(); // TODO tighter drawBounds
fQueue.push(drawBounds, [=](SkArenaAlloc*, const DrawState& ds, const SkIRect& tileBounds){
TileDraw(ds, tileBounds).drawPoints(mode, count, clonedPts, paint, nullptr);
});
}
void SkThreadedBMPDevice::drawRect(const SkRect& r, const SkPaint& paint) {
SkRect drawBounds = get_fast_bounds(r, paint);
fQueue.push(drawBounds, [=](SkArenaAlloc*, const DrawState& ds, const SkIRect& tileBounds){
TileDraw(ds, tileBounds).drawRect(r, paint);
});
}
void SkThreadedBMPDevice::drawRRect(const SkRRect& rrect, const SkPaint& paint) {
#ifdef SK_IGNORE_BLURRED_RRECT_OPT
SkPath path;
path.addRRect(rrect);
// call the VIRTUAL version, so any subclasses who do handle drawPath aren't
// required to override drawRRect.
this->drawPath(path, paint, nullptr, false);
#else
SkRect drawBounds = get_fast_bounds(rrect.getBounds(), paint);
fQueue.push(drawBounds, [=](SkArenaAlloc*, const DrawState& ds, const SkIRect& tileBounds){
TileDraw(ds, tileBounds).drawRRect(rrect, paint);
});
#endif
}
void SkThreadedBMPDevice::drawPath(const SkPath& path, const SkPaint& paint,
const SkMatrix* prePathMatrix, bool pathIsMutable) {
SkRect drawBounds = path.isInverseFillType() ? SkRectPriv::MakeLargest()
: get_fast_bounds(path.getBounds(), paint);
if (path.countVerbs() < 4) { // when path is small, init-once has too much overhead
fQueue.push(drawBounds, [=](SkArenaAlloc*, const DrawState& ds, const SkIRect& tileBounds) {
TileDraw(ds, tileBounds).drawPath(path, paint, prePathMatrix, false);
});
} else {
fQueue.push(drawBounds, [=](SkArenaAlloc* alloc, DrawElement* elem) {
SkInitOnceData data = {alloc, elem};
elem->getDraw().drawPath(path, paint, prePathMatrix, false, false, nullptr, &data);
});
}
}
void SkThreadedBMPDevice::drawBitmap(const SkBitmap& bitmap, const SkMatrix& matrix,
const SkRect* dstOrNull, const SkPaint& paint) {
SkRect drawBounds;
SkRect* clonedDstOrNull = nullptr;
if (dstOrNull == nullptr) {
drawBounds = SkRect::MakeWH(bitmap.width(), bitmap.height());
matrix.mapRect(&drawBounds);
} else {
drawBounds = *dstOrNull;
clonedDstOrNull = fAlloc.make<SkRect>(*dstOrNull);
}
fQueue.push(drawBounds, [=](SkArenaAlloc*, const DrawState& ds, const SkIRect& tileBounds){
TileDraw(ds, tileBounds).drawBitmap(bitmap, matrix, clonedDstOrNull, paint);
});
}
void SkThreadedBMPDevice::drawSprite(const SkBitmap& bitmap, int x, int y, const SkPaint& paint) {
SkRect drawBounds = SkRect::MakeXYWH(x, y, bitmap.width(), bitmap.height());
fQueue.push<false>(drawBounds, [=](SkArenaAlloc*, const DrawState& ds,
const SkIRect& tileBounds){
TileDraw(ds, tileBounds).drawSprite(bitmap, x, y, paint);
});
}
void SkThreadedBMPDevice::drawText(const void* text, size_t len, SkScalar x, SkScalar y,
const SkPaint& paint) {
char* clonedText = this->cloneArray((const char*)text, len);
SkRect drawBounds = SkRectPriv::MakeLargest(); // TODO tighter drawBounds
fQueue.push(drawBounds, [=](SkArenaAlloc*, const DrawState& ds, const SkIRect& tileBounds){
TileDraw(ds, tileBounds).drawText(clonedText, len, x, y, paint,
&this->surfaceProps());
});
}
void SkThreadedBMPDevice::drawPosText(const void* text, size_t len, const SkScalar xpos[],
int scalarsPerPos, const SkPoint& offset, const SkPaint& paint) {
char* clonedText = this->cloneArray((const char*)text, len);
SkScalar* clonedXpos = this->cloneArray(xpos, len * scalarsPerPos);
SkRect drawBounds = SkRectPriv::MakeLargest(); // TODO tighter drawBounds
fQueue.push(drawBounds, [=](SkArenaAlloc*, const DrawState& ds, const SkIRect& tileBounds){
TileDraw(ds, tileBounds).drawPosText(clonedText, len, clonedXpos, scalarsPerPos, offset,
paint, &surfaceProps());
});
}
void SkThreadedBMPDevice::drawVertices(const SkVertices* vertices, SkBlendMode bmode,
const SkPaint& paint) {
const sk_sp<SkVertices> verts = sk_ref_sp(vertices); // retain vertices until flush
SkRect drawBounds = SkRectPriv::MakeLargest(); // TODO tighter drawBounds
fQueue.push(drawBounds, [=](SkArenaAlloc*, const DrawState& ds, const SkIRect& tileBounds){
TileDraw(ds, tileBounds).drawVertices(verts->mode(), verts->vertexCount(),
verts->positions(), verts->texCoords(),
verts->colors(), bmode, verts->indices(),
verts->indexCount(), paint);
});
}
sk_sp<SkSpecialImage> SkThreadedBMPDevice::snapSpecial() {
this->flush();
return this->makeSpecial(fBitmap);
}
<|endoftext|> |
<commit_before>//=======================================================================
// Copyright (c) 2014 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include <iostream>
#include <memory>
#include <random>
#define DLL_SVM_SUPPORT
#include "dll/conv_rbm.hpp"
#include "dll/conv_dbn.hpp"
#include "dll/cpp_utils/algorithm.hpp"
#include "mnist/mnist_reader.hpp"
#include "mnist/mnist_utils.hpp"
template<typename DBN, typename Dataset, typename P>
void test_all(DBN& dbn, Dataset& dataset, P&& predictor){
std::cout << "Start testing" << std::endl;
std::cout << "Training Set" << std::endl;
auto error_rate = dll::test_set(dbn, dataset.training_images, dataset.training_labels, predictor);
std::cout << "\tError rate (normal): " << 100.0 * error_rate << std::endl;
std::cout << "Test Set" << std::endl;
error_rate = dll::test_set(dbn, dataset.test_images, dataset.test_labels, predictor);
std::cout << "\tError rate (normal): " << 100.0 * error_rate << std::endl;
}
int main(int argc, char* argv[]){
auto load = false;
auto svm = false;
auto grid = false;
for(int i = 1; i < argc; ++i){
std::string command(argv[i]);
if(command == "load"){
load = true;
}
if(command == "svm"){
svm = true;
}
if(command == "grid"){
grid = true;
}
}
auto dataset = mnist::read_dataset<std::vector, std::vector, double>();
if(dataset.training_images.empty() || dataset.training_labels.empty()){
return 1;
}
std::default_random_engine rng;
cpp::parallel_shuffle(
dataset.training_images.begin(), dataset.training_images.end(),
dataset.training_labels.begin(), dataset.training_labels.end(),
rng);
dataset.training_images.resize(5000);
dataset.training_labels.resize(5000);
mnist::binarize_dataset(dataset);
typedef dll::conv_dbn_desc<
dll::dbn_layers<
dll::conv_rbm_desc<28, 1, 17, 40, dll::momentum, dll::batch_size<50>, dll::weight_decay<dll::decay_type::L2>, dll::sparsity<dll::sparsity_method::LEE>>::rbm_t,
dll::conv_rbm_desc<17, 40, 12, 40, dll::momentum, dll::batch_size<50>, dll::weight_decay<dll::decay_type::L2>, dll::sparsity<dll::sparsity_method::LEE>>::rbm_t
>>::dbn_t dbn_t;
auto dbn = std::make_unique<dbn_t>();
dbn->layer<0>().pbias = 0.05;
dbn->layer<0>().pbias_lambda = 50;
dbn->layer<1>().pbias = 0.05;
dbn->layer<1>().pbias_lambda = 100;
dbn->display();
std::cout << "RBM1: Input: " << dbn->layer<0>().input_size() << std::endl;
std::cout << "RBM1: Output: " << dbn->layer<0>().output_size() << std::endl;
std::cout << "RBM2: Input: " << dbn->layer<1>().input_size() << std::endl;
std::cout << "RBM2: Output: " << dbn->layer<1>().output_size() << std::endl;
if(svm){
if(load){
std::cout << "Load from file" << std::endl;
std::ifstream is("dbn.dat", std::ifstream::binary);
dbn->load(is);
} else {
std::cout << "Start pretraining" << std::endl;
dbn->pretrain(dataset.training_images, 50);
}
if(grid){
svm::rbf_grid grid;
grid.type = svm::grid_search_type::LINEAR;
grid.c_first = 0.5;
grid.c_last = 18;
grid.c_steps = 12;
grid.gamma_first = 0.0;
grid.gamma_last = 1.0;
grid.gamma_steps = 12;
dbn->svm_grid_search(dataset.training_images, dataset.training_labels, 4, grid);
} else {
auto parameters = dll::default_svm_parameters();
//parameters.C = 2.09091;
//parameters.gamma = 0.272727;
if(!dbn->svm_train(dataset.training_images, dataset.training_labels, parameters)){
std::cout << "SVM training failed" << std::endl;
}
}
std::ofstream os("dbn.dat", std::ofstream::binary);
dbn->store(os);
if(!grid){
test_all(dbn, dataset, dll::svm_predictor());
}
} else {
if(load){
std::cout << "Load from file" << std::endl;
std::ifstream is("dbn.dat", std::ifstream::binary);
dbn->load(is);
} else {
std::cout << "Start pretraining" << std::endl;
dbn->pretrain(dataset.training_images, 5);
std::ofstream os("dbn.dat", std::ofstream::binary);
dbn->store(os);
}
}
return 0;
}
<commit_msg>First integration of MP<commit_after>//=======================================================================
// Copyright (c) 2014 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include <iostream>
#include <memory>
#include <random>
#define DLL_SVM_SUPPORT
#include "dll/conv_rbm.hpp"
#include "dll/conv_rbm_mp.hpp"
#include "dll/conv_dbn.hpp"
#include "dll/cpp_utils/algorithm.hpp"
#include "mnist/mnist_reader.hpp"
#include "mnist/mnist_utils.hpp"
template<typename DBN, typename Dataset, typename P>
void test_all(DBN& dbn, Dataset& dataset, P&& predictor){
std::cout << "Start testing" << std::endl;
std::cout << "Training Set" << std::endl;
auto error_rate = dll::test_set(dbn, dataset.training_images, dataset.training_labels, predictor);
std::cout << "\tError rate (normal): " << 100.0 * error_rate << std::endl;
std::cout << "Test Set" << std::endl;
error_rate = dll::test_set(dbn, dataset.test_images, dataset.test_labels, predictor);
std::cout << "\tError rate (normal): " << 100.0 * error_rate << std::endl;
}
int main(int argc, char* argv[]){
auto load = false;
auto svm = false;
auto grid = false;
auto mp = false;
for(int i = 1; i < argc; ++i){
std::string command(argv[i]);
if(command == "load"){
load = true;
} else if(command == "svm"){
svm = true;
} else if(command == "grid"){
grid = true;
} else if(command == "mp"){
mp = true;
}
}
auto dataset = mnist::read_dataset<std::vector, std::vector, double>();
if(dataset.training_images.empty() || dataset.training_labels.empty()){
return 1;
}
std::default_random_engine rng;
cpp::parallel_shuffle(
dataset.training_images.begin(), dataset.training_images.end(),
dataset.training_labels.begin(), dataset.training_labels.end(),
rng);
dataset.training_images.resize(5000);
dataset.training_labels.resize(5000);
mnist::binarize_dataset(dataset);
if(mp){
typedef dll::conv_dbn_desc<
dll::dbn_layers<
dll::conv_rbm_mp_desc<28, 1, 12, 40, 2, dll::momentum, dll::batch_size<50>, dll::weight_decay<dll::decay_type::L2>, dll::sparsity<dll::sparsity_method::LEE>>::rbm_t,
dll::conv_rbm_mp_desc<6, 40, 6, 40, 2, dll::momentum, dll::batch_size<50>, dll::weight_decay<dll::decay_type::L2>, dll::sparsity<dll::sparsity_method::LEE>>::rbm_t
>>::dbn_t dbn_t;
auto dbn = std::make_unique<dbn_t>();
dbn->layer<0>().pbias = 0.05;
dbn->layer<0>().pbias_lambda = 50;
dbn->layer<1>().pbias = 0.05;
dbn->layer<1>().pbias_lambda = 100;
dbn->display();
std::cout << "RBM1: Input: " << dbn->layer<0>().input_size() << std::endl;
std::cout << "RBM1: Output: " << dbn->layer<0>().output_size() << std::endl;
std::cout << "RBM2: Input: " << dbn->layer<1>().input_size() << std::endl;
std::cout << "RBM2: Output: " << dbn->layer<1>().output_size() << std::endl;
if(svm){
if(load){
std::cout << "Load from file" << std::endl;
std::ifstream is("dbn.dat", std::ifstream::binary);
dbn->load(is);
} else {
std::cout << "Start pretraining" << std::endl;
dbn->pretrain(dataset.training_images, 50);
}
if(grid){
svm::rbf_grid grid;
grid.type = svm::grid_search_type::LINEAR;
grid.c_first = 0.5;
grid.c_last = 18;
grid.c_steps = 12;
grid.gamma_first = 0.0;
grid.gamma_last = 1.0;
grid.gamma_steps = 12;
dbn->svm_grid_search(dataset.training_images, dataset.training_labels, 4, grid);
} else {
auto parameters = dll::default_svm_parameters();
//parameters.C = 2.09091;
//parameters.gamma = 0.272727;
if(!dbn->svm_train(dataset.training_images, dataset.training_labels, parameters)){
std::cout << "SVM training failed" << std::endl;
}
}
std::ofstream os("dbn.dat", std::ofstream::binary);
dbn->store(os);
if(!grid){
test_all(dbn, dataset, dll::svm_predictor());
}
} else {
if(load){
std::cout << "Load from file" << std::endl;
std::ifstream is("dbn.dat", std::ifstream::binary);
dbn->load(is);
} else {
std::cout << "Start pretraining" << std::endl;
dbn->pretrain(dataset.training_images, 5);
std::ofstream os("dbn.dat", std::ofstream::binary);
dbn->store(os);
}
}
} else {
typedef dll::conv_dbn_desc<
dll::dbn_layers<
dll::conv_rbm_desc<28, 1, 17, 40, dll::momentum, dll::batch_size<50>, dll::weight_decay<dll::decay_type::L2>, dll::sparsity<dll::sparsity_method::LEE>>::rbm_t,
dll::conv_rbm_desc<17, 40, 12, 40, dll::momentum, dll::batch_size<50>, dll::weight_decay<dll::decay_type::L2>, dll::sparsity<dll::sparsity_method::LEE>>::rbm_t
>>::dbn_t dbn_t;
auto dbn = std::make_unique<dbn_t>();
dbn->layer<0>().pbias = 0.05;
dbn->layer<0>().pbias_lambda = 50;
dbn->layer<1>().pbias = 0.05;
dbn->layer<1>().pbias_lambda = 100;
dbn->display();
std::cout << "RBM1: Input: " << dbn->layer<0>().input_size() << std::endl;
std::cout << "RBM1: Output: " << dbn->layer<0>().output_size() << std::endl;
std::cout << "RBM2: Input: " << dbn->layer<1>().input_size() << std::endl;
std::cout << "RBM2: Output: " << dbn->layer<1>().output_size() << std::endl;
if(svm){
if(load){
std::cout << "Load from file" << std::endl;
std::ifstream is("dbn.dat", std::ifstream::binary);
dbn->load(is);
} else {
std::cout << "Start pretraining" << std::endl;
dbn->pretrain(dataset.training_images, 50);
}
if(grid){
svm::rbf_grid grid;
grid.type = svm::grid_search_type::LINEAR;
grid.c_first = 0.5;
grid.c_last = 18;
grid.c_steps = 12;
grid.gamma_first = 0.0;
grid.gamma_last = 1.0;
grid.gamma_steps = 12;
dbn->svm_grid_search(dataset.training_images, dataset.training_labels, 4, grid);
} else {
auto parameters = dll::default_svm_parameters();
//parameters.C = 2.09091;
//parameters.gamma = 0.272727;
if(!dbn->svm_train(dataset.training_images, dataset.training_labels, parameters)){
std::cout << "SVM training failed" << std::endl;
}
}
std::ofstream os("dbn.dat", std::ofstream::binary);
dbn->store(os);
if(!grid){
test_all(dbn, dataset, dll::svm_predictor());
}
} else {
if(load){
std::cout << "Load from file" << std::endl;
std::ifstream is("dbn.dat", std::ifstream::binary);
dbn->load(is);
} else {
std::cout << "Start pretraining" << std::endl;
dbn->pretrain(dataset.training_images, 5);
std::ofstream os("dbn.dat", std::ofstream::binary);
dbn->store(os);
}
}
}
return 0;
}
<|endoftext|> |
<commit_before>/*
* SlidingWindowIteratorTest.cpp
*
* Created on: Aug 16, 2017
* Author: Péter Fankhauser
* Institute: ETH Zurich
*/
#include "grid_map_core/iterators/SlidingWindowIterator.hpp"
#include "grid_map_core/GridMap.hpp"
#include <cfloat>
#include <Eigen/Core>
#include <gtest/gtest.h>
#include <vector>
using namespace std;
using namespace grid_map;
TEST(SlidingWindowIterator, DISABLED_WindowSize3Cutoff)
{
GridMap map;
map.setGeometry(Length(8.1, 5.1), 1.0, Position(0.0, 0.0)); // bufferSize(8, 5)
map.add("layer");
map["layer"].setRandom();
SlidingWindowIterator iterator(map, "layer", SlidingWindowIterator::EdgeHandling::CROP, 3);
EXPECT_EQ(iterator.getData().rows(), 2);
EXPECT_EQ(iterator.getData().cols(), 2);
EXPECT_TRUE(iterator.getData().isApprox(map["layer"].block(0, 0, 2, 2)));
++iterator;
EXPECT_EQ(iterator.getData().rows(), 3);
EXPECT_EQ(iterator.getData().cols(), 2);
EXPECT_TRUE(iterator.getData().isApprox(map["layer"].block(0, 0, 3, 2)));
++iterator;
EXPECT_EQ(iterator.getData().rows(), 3);
EXPECT_EQ(iterator.getData().cols(), 2);
EXPECT_TRUE(iterator.getData().isApprox(map["layer"].block(1, 0, 3, 2)));
for (; !iterator.isPastEnd(); ++iterator) {
EXPECT_FALSE(iterator.isPastEnd());
if ((*iterator == Index(3, 2)).all()) break;
}
EXPECT_EQ(iterator.getData().rows(), 3);
EXPECT_EQ(iterator.getData().cols(), 3);
EXPECT_TRUE(iterator.getData().isApprox(map["layer"].block(2, 1, 3, 3)));
for (; !iterator.isPastEnd(); ++iterator) {
EXPECT_FALSE(iterator.isPastEnd());
if ((*iterator == Index(7, 4)).all()) break;
}
EXPECT_EQ(iterator.getData().rows(), 2);
EXPECT_EQ(iterator.getData().cols(), 2);
EXPECT_TRUE(iterator.getData().isApprox(map["layer"].block(6, 3, 2, 2)));
++iterator;
EXPECT_TRUE(iterator.isPastEnd());
}
TEST(SlidingWindowIterator, DISABLED_WindowSize5)
{
GridMap map;
map.setGeometry(Length(8.1, 5.1), 1.0, Position(0.0, 0.0)); // bufferSize(8, 5)
map.add("layer");
map["layer"].setRandom();
SlidingWindowIterator iterator(map, "layer", SlidingWindowIterator::EdgeHandling::CROP, 5);
EXPECT_EQ(iterator.getData().rows(), 3);
EXPECT_EQ(iterator.getData().cols(), 3);
EXPECT_TRUE(iterator.getData().isApprox(map["layer"].block(0, 0, 3, 3)));
++iterator;
EXPECT_EQ(iterator.getData().rows(), 4);
EXPECT_EQ(iterator.getData().cols(), 3);
EXPECT_TRUE(iterator.getData().isApprox(map["layer"].block(0, 0, 4, 3)));
++iterator;
EXPECT_EQ(iterator.getData().rows(), 5);
EXPECT_EQ(iterator.getData().cols(), 3);
EXPECT_TRUE(iterator.getData().isApprox(map["layer"].block(0, 0, 5, 3)));
for (; !iterator.isPastEnd(); ++iterator) {
EXPECT_FALSE(iterator.isPastEnd());
if ((*iterator == Index(3, 2)).all()) break;
}
EXPECT_EQ(iterator.getData().rows(), 5);
EXPECT_EQ(iterator.getData().cols(), 5);
EXPECT_TRUE(iterator.getData().isApprox(map["layer"].block(1, 0, 5, 5)));
for (; !iterator.isPastEnd(); ++iterator) {
EXPECT_FALSE(iterator.isPastEnd());
if ((*iterator == Index(7, 4)).all()) break;
}
EXPECT_EQ(iterator.getData().rows(), 3);
EXPECT_EQ(iterator.getData().cols(), 3);
EXPECT_TRUE(iterator.getData().isApprox(map["layer"].block(5, 2, 3, 3)));
++iterator;
EXPECT_TRUE(iterator.isPastEnd());
}
TEST(SlidingWindowIterator, DISABLED_WindowSize3Inside)
{
GridMap map;
map.setGeometry(Length(8.1, 5.1), 1.0, Position(0.0, 0.0)); // bufferSize(8, 5)
map.add("layer");
map["layer"].setRandom();
SlidingWindowIterator iterator(map, "layer", SlidingWindowIterator::EdgeHandling::INSIDE, 3);
EXPECT_EQ(iterator.getData().rows(), 3);
EXPECT_EQ(iterator.getData().cols(), 3);
EXPECT_TRUE(iterator.getData().isApprox(map["layer"].block(0, 0, 3, 3)));
for (; !iterator.isPastEnd(); ++iterator) {
EXPECT_FALSE(iterator.isPastEnd());
if ((*iterator == Index(3, 2)).all()) break;
}
EXPECT_EQ(iterator.getData().rows(), 3);
EXPECT_EQ(iterator.getData().cols(), 3);
EXPECT_TRUE(iterator.getData().isApprox(map["layer"].block(2, 1, 3, 3)));
for (; !iterator.isPastEnd(); ++iterator) {
EXPECT_FALSE(iterator.isPastEnd());
if ((*iterator == Index(6, 3)).all()) break;
}
EXPECT_EQ(iterator.getData().rows(), 3);
EXPECT_EQ(iterator.getData().cols(), 3);
EXPECT_TRUE(iterator.getData().isApprox(map["layer"].block(5, 2, 3, 3)));
++iterator;
EXPECT_TRUE(iterator.isPastEnd());
}
<commit_msg>Working on unit tests for sliding window iterator.<commit_after>/*
* SlidingWindowIteratorTest.cpp
*
* Created on: Aug 16, 2017
* Author: Péter Fankhauser
* Institute: ETH Zurich
*/
#include "grid_map_core/iterators/SlidingWindowIterator.hpp"
#include "grid_map_core/GridMap.hpp"
#include <cfloat>
#include <Eigen/Core>
#include <gtest/gtest.h>
#include <vector>
using namespace std;
using namespace grid_map;
TEST(SlidingWindowIterator, DISABLED_WindowSize3Cutoff)
{
GridMap map;
map.setGeometry(Length(8.1, 5.1), 1.0, Position(0.0, 0.0)); // bufferSize(8, 5)
map.add("layer");
map["layer"].setRandom();
SlidingWindowIterator iterator(map, "layer", SlidingWindowIterator::EdgeHandling::CROP, 3);
EXPECT_EQ(iterator.getData().rows(), 2);
EXPECT_EQ(iterator.getData().cols(), 2);
EXPECT_TRUE(iterator.getData().isApprox(map["layer"].block(0, 0, 2, 2)));
++iterator;
EXPECT_EQ(iterator.getData().rows(), 3);
EXPECT_EQ(iterator.getData().cols(), 2);
EXPECT_TRUE(iterator.getData().isApprox(map["layer"].block(0, 0, 3, 2)));
++iterator;
EXPECT_EQ(iterator.getData().rows(), 3);
EXPECT_EQ(iterator.getData().cols(), 2);
EXPECT_TRUE(iterator.getData().isApprox(map["layer"].block(1, 0, 3, 2)));
for (; !iterator.isPastEnd(); ++iterator) {
EXPECT_FALSE(iterator.isPastEnd());
if ((*iterator == Index(3, 2)).all()) break;
}
EXPECT_EQ(iterator.getData().rows(), 3);
EXPECT_EQ(iterator.getData().cols(), 3);
EXPECT_TRUE(iterator.getData().isApprox(map["layer"].block(2, 1, 3, 3)));
for (; !iterator.isPastEnd(); ++iterator) {
EXPECT_FALSE(iterator.isPastEnd());
if ((*iterator == Index(7, 4)).all()) break;
}
EXPECT_EQ(iterator.getData().rows(), 2);
EXPECT_EQ(iterator.getData().cols(), 2);
EXPECT_TRUE(iterator.getData().isApprox(map["layer"].block(6, 3, 2, 2)));
++iterator;
EXPECT_TRUE(iterator.isPastEnd());
}
TEST(SlidingWindowIterator, DISABLED_WindowSize5)
{
GridMap map;
map.setGeometry(Length(8.1, 5.1), 1.0, Position(0.0, 0.0)); // bufferSize(8, 5)
map.add("layer");
map["layer"].setRandom();
SlidingWindowIterator iterator(map, "layer", SlidingWindowIterator::EdgeHandling::CROP, 5);
EXPECT_EQ(iterator.getData().rows(), 3);
EXPECT_EQ(iterator.getData().cols(), 3);
EXPECT_TRUE(iterator.getData().isApprox(map["layer"].block(0, 0, 3, 3)));
++iterator;
EXPECT_EQ(iterator.getData().rows(), 4);
EXPECT_EQ(iterator.getData().cols(), 3);
EXPECT_TRUE(iterator.getData().isApprox(map["layer"].block(0, 0, 4, 3)));
++iterator;
EXPECT_EQ(iterator.getData().rows(), 5);
EXPECT_EQ(iterator.getData().cols(), 3);
EXPECT_TRUE(iterator.getData().isApprox(map["layer"].block(0, 0, 5, 3)));
for (; !iterator.isPastEnd(); ++iterator) {
EXPECT_FALSE(iterator.isPastEnd());
if ((*iterator == Index(3, 2)).all()) break;
}
EXPECT_EQ(iterator.getData().rows(), 5);
EXPECT_EQ(iterator.getData().cols(), 5);
EXPECT_TRUE(iterator.getData().isApprox(map["layer"].block(1, 0, 5, 5)));
for (; !iterator.isPastEnd(); ++iterator) {
EXPECT_FALSE(iterator.isPastEnd());
if ((*iterator == Index(7, 4)).all()) break;
}
EXPECT_EQ(iterator.getData().rows(), 3);
EXPECT_EQ(iterator.getData().cols(), 3);
EXPECT_TRUE(iterator.getData().isApprox(map["layer"].block(5, 2, 3, 3)));
++iterator;
EXPECT_TRUE(iterator.isPastEnd());
}
TEST(SlidingWindowIterator, WindowSize3Inside)
{
GridMap map;
map.setGeometry(Length(8.1, 5.1), 1.0, Position(0.0, 0.0)); // bufferSize(8, 5)
map.add("layer");
map["layer"].setRandom();
SlidingWindowIterator iterator(map, "layer", SlidingWindowIterator::EdgeHandling::INSIDE, 3);
EXPECT_EQ(iterator.getData().rows(), 3);
EXPECT_EQ(iterator.getData().cols(), 3);
EXPECT_TRUE(iterator.getData().isApprox(map["layer"].block(0, 0, 3, 3)));
for (; !iterator.isPastEnd(); ++iterator) {
EXPECT_FALSE(iterator.isPastEnd());
if ((*iterator == Index(3, 2)).all()) break;
}
EXPECT_EQ(iterator.getData().rows(), 3);
EXPECT_EQ(iterator.getData().cols(), 3);
EXPECT_TRUE(iterator.getData().isApprox(map["layer"].block(2, 1, 3, 3)));
for (; !iterator.isPastEnd(); ++iterator) {
EXPECT_FALSE(iterator.isPastEnd());
if ((*iterator == Index(6, 3)).all()) break;
}
EXPECT_EQ(iterator.getData().rows(), 3);
EXPECT_EQ(iterator.getData().cols(), 3);
EXPECT_TRUE(iterator.getData().isApprox(map["layer"].block(5, 2, 3, 3)));
++iterator;
EXPECT_TRUE(iterator.isPastEnd());
}
<|endoftext|> |
<commit_before>/// \file ROOT/RLogger.hxx
/// \ingroup Base ROOT7
/// \author Axel Naumann <axel@cern.ch>
/// \date 2015-03-29
/// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback
/// is welcome!
/*************************************************************************
* Copyright (C) 1995-2020, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#ifndef ROOT7_RLogger
#define ROOT7_RLogger
#include <atomic>
#include <list>
#include <memory>
#include <mutex>
#include <sstream>
#include <string>
#include <utility>
namespace ROOT {
namespace Experimental {
class RLogEntry;
class RLogManager;
/**
Kinds of diagnostics.
*/
enum class ELogLevel : unsigned char {
kUnset,
kFatal, ///< An error which causes further processing to be unreliable
kError, ///< An error
kWarning, ///< Warnings about likely unexpected behavior
kInfo, ///< Informational messages; used for instance for tracing
kDebug ///< Debug information; only useful for developers; can have added verbosity up to 255-kDebug.
};
inline ELogLevel operator+(ELogLevel severity, int offset)
{
return static_cast<ELogLevel>(static_cast<int>(severity) + offset);
}
/**
Keep track of emitted errors and warnings.
*/
class RLogDiagCount {
protected:
std::atomic<long long> fNumWarnings{0ll}; /// Number of warnings.
std::atomic<long long> fNumErrors{0ll}; /// Number of errors.
std::atomic<long long> fNumFatalErrors{0ll}; /// Number of fatal errors.
public:
/// Returns the current number of warnings.
long long GetNumWarnings() const { return fNumWarnings; }
/// Returns the current number of errors.
long long GetNumErrors() const { return fNumErrors; }
/// Returns the current number of fatal errors.
long long GetNumFatalErrors() const { return fNumFatalErrors; }
/// Increase warning or error count.
void Increment(ELogLevel severity)
{
switch (severity) {
case ELogLevel::kFatal: ++fNumFatalErrors; break;
case ELogLevel::kError: ++fNumErrors; break;
case ELogLevel::kWarning: ++fNumWarnings; break;
default:;
}
}
};
/**
Abstract RLogHandler base class. ROOT logs everything from info to error
to entities of this class.
*/
class RLogHandler {
public:
virtual ~RLogHandler();
/// Emit a log entry.
/// \param entry - the RLogEntry to be emitted.
/// \returns false if further emission of this Log should be suppressed.
///
/// \note This function is called concurrently; log emission must be locked
/// if needed. (The default log handler using ROOT's DefaultErrorHandler is locked.)
virtual bool Emit(const RLogEntry &entry) = 0;
};
/**
A log configuration for a channel, e.g. "RHist".
Each ROOT module has its own log, with potentially distinct verbosity.
*/
class RLogChannel : public RLogDiagCount {
/// Name as shown in diagnostics
std::string fName;
/// Verbosity of this channel. By default, use the global verbosity.
ELogLevel fVerbosity = ELogLevel::kUnset;
public:
/// Construct an anonymous channel.
RLogChannel() = default;
/// Construct an anonymous channel with a default vebosity.
explicit RLogChannel(ELogLevel verbosity) : fVerbosity(verbosity) {}
/// Construct a log channel given its name, which is part of the diagnostics.
RLogChannel(const std::string &name) : fName(name) {}
ELogLevel SetVerbosity(ELogLevel verbosity)
{
std::swap(fVerbosity, verbosity);
return verbosity;
}
ELogLevel GetVerbosity() const { return fVerbosity; }
ELogLevel GetEffectiveVerbosity(const RLogManager &mgr) const;
const std::string &GetName() const { return fName; }
};
/**
A RLogHandler that multiplexes diagnostics to different client `RLogHandler`s
and keeps track of the sum of `RLogDiagCount`s for all channels.
`RLogHandler::Get()` returns the process's (static) log manager.
*/
class RLogManager : public RLogChannel, public RLogHandler {
std::mutex fMutex;
std::list<std::unique_ptr<RLogHandler>> fHandlers;
public:
/// Initialize taking a RLogHandler.
RLogManager(std::unique_ptr<RLogHandler> lh) : RLogChannel(ELogLevel::kWarning)
{
fHandlers.emplace_back(std::move(lh));
}
static RLogManager &Get();
/// Add a RLogHandler in the front - to be called before all others.
void PushFront(std::unique_ptr<RLogHandler> handler) { fHandlers.emplace_front(std::move(handler)); }
/// Add a RLogHandler in the back - to be called after all others.
void PushBack(std::unique_ptr<RLogHandler> handler) { fHandlers.emplace_back(std::move(handler)); }
/// Remove and return the given log handler. Returns `nullptr` if not found.
std::unique_ptr<RLogHandler> Remove(RLogHandler *handler);
// Emit a `RLogEntry` to the RLogHandlers.
// Returns false if further emission of this Log should be suppressed.
bool Emit(const RLogEntry &entry) override;
};
/**
A diagnostic location, part of an RLogEntry.
*/
struct RLogLocation {
std::string fFile;
std::string fFuncName;
int fLine; // C++11 forbids "= 0" for braced-init-list initialization.
};
/**
A diagnostic that can be emitted by the RLogManager.
One can construct a RLogEntry through RLogBuilder, including streaming into
the diagnostic message and automatic emission.
*/
class RLogEntry {
public:
RLogLocation fLocation;
std::string fMessage;
RLogChannel *fChannel = nullptr;
ELogLevel fLevel = ELogLevel::kFatal;
RLogEntry(ELogLevel level, RLogChannel &channel) : fChannel(&channel), fLevel(level) {}
RLogEntry(ELogLevel level, RLogChannel &channel, const RLogLocation &loc)
: fLocation(loc), fChannel(&channel), fLevel(level)
{
}
bool IsDebug() const { return fLevel >= ELogLevel::kDebug; }
bool IsInfo() const { return fLevel == ELogLevel::kInfo; }
bool IsWarning() const { return fLevel == ELogLevel::kWarning; }
bool IsError() const { return fLevel == ELogLevel::kError; }
bool IsFatal() const { return fLevel == ELogLevel::kFatal; }
};
namespace Detail {
/**
Builds a diagnostic entry, emitted by the static RLogManager upon destruction of this builder,
where - by definition - the RLogEntry has been completely built.
This builder can be used through the utility preprocessor macros R__LOG_ERROR,
R__LOG_WARNING etc like this:
```c++
R__LOG_INFO(ROOT::Experimental::HistLog()) << "all we know is " << 42;
const int decreasedInfoLevel = 5;
R__LOG_XDEBUG(ROOT::Experimental::WebGUILog(), decreasedInfoLevel) << "nitty-gritty details";
```
This will automatically capture the current class and function name, the file and line number.
*/
class RLogBuilder : public std::ostringstream {
/// The log entry to be built.
RLogEntry fEntry;
public:
RLogBuilder(ELogLevel level, RLogChannel &channel) : fEntry(level, channel) {}
RLogBuilder(ELogLevel level, RLogChannel &channel, const std::string &filename, int line,
const std::string &funcname)
: fEntry(level, channel, {filename, funcname, line})
{
}
/// Emit the log entry through the static log manager.
~RLogBuilder()
{
fEntry.fMessage = str();
RLogManager::Get().Emit(fEntry);
}
};
} // namespace Detail
/**
Change the verbosity level (global or specific to the RLogChannel passed to the
constructor) for the lifetime of this object.
Example:
```c++
RLogScopedVerbosity debugThis(gFooLog, ELogLevel::kDebug);
Foo::SomethingToDebug();
```
*/
class RLogScopedVerbosity {
RLogChannel *fChannel;
ELogLevel fPrevLevel;
public:
RLogScopedVerbosity(RLogChannel &channel, ELogLevel verbosity)
: fChannel(&channel), fPrevLevel(channel.SetVerbosity(verbosity))
{
}
explicit RLogScopedVerbosity(ELogLevel verbosity) : RLogScopedVerbosity(RLogManager::Get(), verbosity) {}
~RLogScopedVerbosity() { fChannel->SetVerbosity(fPrevLevel); }
};
/**
Object to count the number of warnings and errors emitted by a section of code,
after construction of this type.
*/
class RLogScopedDiagCount {
RLogDiagCount *fCounter = nullptr;
/// The number of the RLogDiagCount's emitted warnings at construction time of *this.
long long fInitialWarnings = 0;
/// The number of the RLogDiagCount's emitted errors at construction time.
long long fInitialErrors = 0;
/// The number of the RLogDiagCount's emitted fatal errors at construction time.
long long fInitialFatalErrors = 0;
public:
/// Construct the scoped count given a counter (e.g. a channel or RLogManager).
/// The counter's lifetime must exceed the lifetime of this object!
explicit RLogScopedDiagCount(RLogDiagCount &cnt)
: fCounter(&cnt), fInitialWarnings(cnt.GetNumWarnings()), fInitialErrors(cnt.GetNumErrors()),
fInitialFatalErrors(cnt.GetNumFatalErrors())
{
}
/// Construct the scoped count for any diagnostic, whatever its channel.
RLogScopedDiagCount() : RLogScopedDiagCount(RLogManager::Get()) {}
/// Get the number of warnings that the RLogDiagCount has emitted since construction of *this.
long long GetAccumulatedWarnings() const { return fCounter->GetNumWarnings() - fInitialWarnings; }
/// Get the number of errors that the RLogDiagCount has emitted since construction of *this.
long long GetAccumulatedErrors() const { return fCounter->GetNumErrors() - fInitialErrors; }
/// Get the number of errors that the RLogDiagCount has emitted since construction of *this.
long long GetAccumulatedFatalErrors() const { return fCounter->GetNumFatalErrors() - fInitialFatalErrors; }
/// Whether the RLogDiagCount has emitted a warnings since construction time of *this.
bool HasWarningOccurred() const { return GetAccumulatedWarnings(); }
/// Whether the RLogDiagCount has emitted an error (fatal or not) since construction time of *this.
bool HasErrorOccurred() const { return GetAccumulatedErrors() + GetAccumulatedFatalErrors(); }
/// Whether the RLogDiagCount has emitted an error or a warning since construction time of *this.
bool HasErrorOrWarningOccurred() const { return HasWarningOccurred() || HasErrorOccurred(); }
};
namespace Internal {
inline RLogChannel &GetChannelOrManager()
{
return RLogManager::Get();
}
inline RLogChannel &GetChannelOrManager(RLogChannel &channel)
{
return channel;
}
} // namespace Internal
inline ELogLevel RLogChannel::GetEffectiveVerbosity(const RLogManager &mgr) const
{
if (fVerbosity == ELogLevel::kUnset)
return mgr.GetVerbosity();
return fVerbosity;
}
} // namespace Experimental
} // namespace ROOT
#if defined(_MSC_VER)
#define R__LOG_PRETTY_FUNCTION __FUNCSIG__
#else
#define R__LOG_PRETTY_FUNCTION __PRETTY_FUNCTION__
#endif
/*
Some implementation details:
- The conditional `RLogBuilder` use prevents stream operators from being called if
verbosity is too low, i.e.:
````
RLogScopedVerbosity silence(RLogLevel::kFatal);
R__LOG_DEBUG() << WillNotBeCalled();
```
- To update counts of warnings / errors / fatal errors, those RLogEntries must
always be created, even if in the end their emission will be silenced. This
should be fine, performance-wise, as they should not happen frequently.
- Use `(condition) && RLogBuilder(...)` instead of `if (condition) RLogBuilder(...)`
to prevent "ambiguous else" in invocations such as `if (something) R__LOG_DEBUG()...`.
*/
#define R__LOG_TO_CHANNEL(SEVERITY, CHANNEL) \
(SEVERITY < ROOT::Experimental::ELogLevel::kInfo || \
ROOT::Experimental::Internal::GetChannelOrManager(CHANNEL).GetEffectiveVerbosity( \
ROOT::Experimental::RLogManager::Get()) >= SEVERITY) && \
ROOT::Experimental::Detail::RLogBuilder(SEVERITY, ROOT::Experimental::Internal::GetChannelOrManager(CHANNEL), \
__FILE__, __LINE__, R__LOG_PRETTY_FUNCTION)
/// \name LogMacros
/// Macros to log diagnostics.
/// ```c++
/// R__LOG_INFO(ROOT::Experimental::HistLog()) << "all we know is " << 42;
///
/// RLogScopedVerbosity verbose(kDebug + 5);
/// const int decreasedInfoLevel = 5;
/// R__LOG_DEBUG(decreasedInfoLevel, ROOT::Experimental::WebGUILog()) << "nitty-gritty details";
/// ```
///\{
#define R__LOG_FATAL(...) R__LOG_TO_CHANNEL(ROOT::Experimental::ELogLevel::kFatal, __VA_ARGS__)
#define R__LOG_ERROR(...) R__LOG_TO_CHANNEL(ROOT::Experimental::ELogLevel::kError, __VA_ARGS__)
#define R__LOG_WARNING(...) R__LOG_TO_CHANNEL(ROOT::Experimental::ELogLevel::kWarning, __VA_ARGS__)
#define R__LOG_INFO(...) R__LOG_TO_CHANNEL(ROOT::Experimental::ELogLevel::kInfo, __VA_ARGS__)
#define R__LOG_DEBUG(DEBUGLEVEL, ...) R__LOG_TO_CHANNEL(ROOT::Experimental::ELogLevel::kDebug + DEBUGLEVEL, __VA_ARGS__)
///\}
#endif
<commit_msg>[foundation] Fix doc example (NFC).<commit_after>/// \file ROOT/RLogger.hxx
/// \ingroup Base ROOT7
/// \author Axel Naumann <axel@cern.ch>
/// \date 2015-03-29
/// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback
/// is welcome!
/*************************************************************************
* Copyright (C) 1995-2020, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#ifndef ROOT7_RLogger
#define ROOT7_RLogger
#include <atomic>
#include <list>
#include <memory>
#include <mutex>
#include <sstream>
#include <string>
#include <utility>
namespace ROOT {
namespace Experimental {
class RLogEntry;
class RLogManager;
/**
Kinds of diagnostics.
*/
enum class ELogLevel : unsigned char {
kUnset,
kFatal, ///< An error which causes further processing to be unreliable
kError, ///< An error
kWarning, ///< Warnings about likely unexpected behavior
kInfo, ///< Informational messages; used for instance for tracing
kDebug ///< Debug information; only useful for developers; can have added verbosity up to 255-kDebug.
};
inline ELogLevel operator+(ELogLevel severity, int offset)
{
return static_cast<ELogLevel>(static_cast<int>(severity) + offset);
}
/**
Keep track of emitted errors and warnings.
*/
class RLogDiagCount {
protected:
std::atomic<long long> fNumWarnings{0ll}; /// Number of warnings.
std::atomic<long long> fNumErrors{0ll}; /// Number of errors.
std::atomic<long long> fNumFatalErrors{0ll}; /// Number of fatal errors.
public:
/// Returns the current number of warnings.
long long GetNumWarnings() const { return fNumWarnings; }
/// Returns the current number of errors.
long long GetNumErrors() const { return fNumErrors; }
/// Returns the current number of fatal errors.
long long GetNumFatalErrors() const { return fNumFatalErrors; }
/// Increase warning or error count.
void Increment(ELogLevel severity)
{
switch (severity) {
case ELogLevel::kFatal: ++fNumFatalErrors; break;
case ELogLevel::kError: ++fNumErrors; break;
case ELogLevel::kWarning: ++fNumWarnings; break;
default:;
}
}
};
/**
Abstract RLogHandler base class. ROOT logs everything from info to error
to entities of this class.
*/
class RLogHandler {
public:
virtual ~RLogHandler();
/// Emit a log entry.
/// \param entry - the RLogEntry to be emitted.
/// \returns false if further emission of this Log should be suppressed.
///
/// \note This function is called concurrently; log emission must be locked
/// if needed. (The default log handler using ROOT's DefaultErrorHandler is locked.)
virtual bool Emit(const RLogEntry &entry) = 0;
};
/**
A log configuration for a channel, e.g. "RHist".
Each ROOT module has its own log, with potentially distinct verbosity.
*/
class RLogChannel : public RLogDiagCount {
/// Name as shown in diagnostics
std::string fName;
/// Verbosity of this channel. By default, use the global verbosity.
ELogLevel fVerbosity = ELogLevel::kUnset;
public:
/// Construct an anonymous channel.
RLogChannel() = default;
/// Construct an anonymous channel with a default vebosity.
explicit RLogChannel(ELogLevel verbosity) : fVerbosity(verbosity) {}
/// Construct a log channel given its name, which is part of the diagnostics.
RLogChannel(const std::string &name) : fName(name) {}
ELogLevel SetVerbosity(ELogLevel verbosity)
{
std::swap(fVerbosity, verbosity);
return verbosity;
}
ELogLevel GetVerbosity() const { return fVerbosity; }
ELogLevel GetEffectiveVerbosity(const RLogManager &mgr) const;
const std::string &GetName() const { return fName; }
};
/**
A RLogHandler that multiplexes diagnostics to different client `RLogHandler`s
and keeps track of the sum of `RLogDiagCount`s for all channels.
`RLogHandler::Get()` returns the process's (static) log manager.
*/
class RLogManager : public RLogChannel, public RLogHandler {
std::mutex fMutex;
std::list<std::unique_ptr<RLogHandler>> fHandlers;
public:
/// Initialize taking a RLogHandler.
RLogManager(std::unique_ptr<RLogHandler> lh) : RLogChannel(ELogLevel::kWarning)
{
fHandlers.emplace_back(std::move(lh));
}
static RLogManager &Get();
/// Add a RLogHandler in the front - to be called before all others.
void PushFront(std::unique_ptr<RLogHandler> handler) { fHandlers.emplace_front(std::move(handler)); }
/// Add a RLogHandler in the back - to be called after all others.
void PushBack(std::unique_ptr<RLogHandler> handler) { fHandlers.emplace_back(std::move(handler)); }
/// Remove and return the given log handler. Returns `nullptr` if not found.
std::unique_ptr<RLogHandler> Remove(RLogHandler *handler);
// Emit a `RLogEntry` to the RLogHandlers.
// Returns false if further emission of this Log should be suppressed.
bool Emit(const RLogEntry &entry) override;
};
/**
A diagnostic location, part of an RLogEntry.
*/
struct RLogLocation {
std::string fFile;
std::string fFuncName;
int fLine; // C++11 forbids "= 0" for braced-init-list initialization.
};
/**
A diagnostic that can be emitted by the RLogManager.
One can construct a RLogEntry through RLogBuilder, including streaming into
the diagnostic message and automatic emission.
*/
class RLogEntry {
public:
RLogLocation fLocation;
std::string fMessage;
RLogChannel *fChannel = nullptr;
ELogLevel fLevel = ELogLevel::kFatal;
RLogEntry(ELogLevel level, RLogChannel &channel) : fChannel(&channel), fLevel(level) {}
RLogEntry(ELogLevel level, RLogChannel &channel, const RLogLocation &loc)
: fLocation(loc), fChannel(&channel), fLevel(level)
{
}
bool IsDebug() const { return fLevel >= ELogLevel::kDebug; }
bool IsInfo() const { return fLevel == ELogLevel::kInfo; }
bool IsWarning() const { return fLevel == ELogLevel::kWarning; }
bool IsError() const { return fLevel == ELogLevel::kError; }
bool IsFatal() const { return fLevel == ELogLevel::kFatal; }
};
namespace Detail {
/**
Builds a diagnostic entry, emitted by the static RLogManager upon destruction of this builder,
where - by definition - the RLogEntry has been completely built.
This builder can be used through the utility preprocessor macros R__LOG_ERROR,
R__LOG_WARNING etc like this:
```c++
R__LOG_INFO(ROOT::Experimental::HistLog()) << "all we know is " << 42;
const int decreasedInfoLevel = 5;
R__LOG_XDEBUG(ROOT::Experimental::WebGUILog(), decreasedInfoLevel) << "nitty-gritty details";
```
This will automatically capture the current class and function name, the file and line number.
*/
class RLogBuilder : public std::ostringstream {
/// The log entry to be built.
RLogEntry fEntry;
public:
RLogBuilder(ELogLevel level, RLogChannel &channel) : fEntry(level, channel) {}
RLogBuilder(ELogLevel level, RLogChannel &channel, const std::string &filename, int line,
const std::string &funcname)
: fEntry(level, channel, {filename, funcname, line})
{
}
/// Emit the log entry through the static log manager.
~RLogBuilder()
{
fEntry.fMessage = str();
RLogManager::Get().Emit(fEntry);
}
};
} // namespace Detail
/**
Change the verbosity level (global or specific to the RLogChannel passed to the
constructor) for the lifetime of this object.
Example:
```c++
RLogScopedVerbosity debugThis(gFooLog, ELogLevel::kDebug);
Foo::SomethingToDebug();
```
*/
class RLogScopedVerbosity {
RLogChannel *fChannel;
ELogLevel fPrevLevel;
public:
RLogScopedVerbosity(RLogChannel &channel, ELogLevel verbosity)
: fChannel(&channel), fPrevLevel(channel.SetVerbosity(verbosity))
{
}
explicit RLogScopedVerbosity(ELogLevel verbosity) : RLogScopedVerbosity(RLogManager::Get(), verbosity) {}
~RLogScopedVerbosity() { fChannel->SetVerbosity(fPrevLevel); }
};
/**
Object to count the number of warnings and errors emitted by a section of code,
after construction of this type.
*/
class RLogScopedDiagCount {
RLogDiagCount *fCounter = nullptr;
/// The number of the RLogDiagCount's emitted warnings at construction time of *this.
long long fInitialWarnings = 0;
/// The number of the RLogDiagCount's emitted errors at construction time.
long long fInitialErrors = 0;
/// The number of the RLogDiagCount's emitted fatal errors at construction time.
long long fInitialFatalErrors = 0;
public:
/// Construct the scoped count given a counter (e.g. a channel or RLogManager).
/// The counter's lifetime must exceed the lifetime of this object!
explicit RLogScopedDiagCount(RLogDiagCount &cnt)
: fCounter(&cnt), fInitialWarnings(cnt.GetNumWarnings()), fInitialErrors(cnt.GetNumErrors()),
fInitialFatalErrors(cnt.GetNumFatalErrors())
{
}
/// Construct the scoped count for any diagnostic, whatever its channel.
RLogScopedDiagCount() : RLogScopedDiagCount(RLogManager::Get()) {}
/// Get the number of warnings that the RLogDiagCount has emitted since construction of *this.
long long GetAccumulatedWarnings() const { return fCounter->GetNumWarnings() - fInitialWarnings; }
/// Get the number of errors that the RLogDiagCount has emitted since construction of *this.
long long GetAccumulatedErrors() const { return fCounter->GetNumErrors() - fInitialErrors; }
/// Get the number of errors that the RLogDiagCount has emitted since construction of *this.
long long GetAccumulatedFatalErrors() const { return fCounter->GetNumFatalErrors() - fInitialFatalErrors; }
/// Whether the RLogDiagCount has emitted a warnings since construction time of *this.
bool HasWarningOccurred() const { return GetAccumulatedWarnings(); }
/// Whether the RLogDiagCount has emitted an error (fatal or not) since construction time of *this.
bool HasErrorOccurred() const { return GetAccumulatedErrors() + GetAccumulatedFatalErrors(); }
/// Whether the RLogDiagCount has emitted an error or a warning since construction time of *this.
bool HasErrorOrWarningOccurred() const { return HasWarningOccurred() || HasErrorOccurred(); }
};
namespace Internal {
inline RLogChannel &GetChannelOrManager()
{
return RLogManager::Get();
}
inline RLogChannel &GetChannelOrManager(RLogChannel &channel)
{
return channel;
}
} // namespace Internal
inline ELogLevel RLogChannel::GetEffectiveVerbosity(const RLogManager &mgr) const
{
if (fVerbosity == ELogLevel::kUnset)
return mgr.GetVerbosity();
return fVerbosity;
}
} // namespace Experimental
} // namespace ROOT
#if defined(_MSC_VER)
#define R__LOG_PRETTY_FUNCTION __FUNCSIG__
#else
#define R__LOG_PRETTY_FUNCTION __PRETTY_FUNCTION__
#endif
/*
Some implementation details:
- The conditional `RLogBuilder` use prevents stream operators from being called if
verbosity is too low, i.e.:
````
RLogScopedVerbosity silence(RLogLevel::kFatal);
R__LOG_DEBUG(7) << WillNotBeCalled();
```
- To update counts of warnings / errors / fatal errors, those RLogEntries must
always be created, even if in the end their emission will be silenced. This
should be fine, performance-wise, as they should not happen frequently.
- Use `(condition) && RLogBuilder(...)` instead of `if (condition) RLogBuilder(...)`
to prevent "ambiguous else" in invocations such as `if (something) R__LOG_DEBUG()...`.
*/
#define R__LOG_TO_CHANNEL(SEVERITY, CHANNEL) \
(SEVERITY < ROOT::Experimental::ELogLevel::kInfo || \
ROOT::Experimental::Internal::GetChannelOrManager(CHANNEL).GetEffectiveVerbosity( \
ROOT::Experimental::RLogManager::Get()) >= SEVERITY) && \
ROOT::Experimental::Detail::RLogBuilder(SEVERITY, ROOT::Experimental::Internal::GetChannelOrManager(CHANNEL), \
__FILE__, __LINE__, R__LOG_PRETTY_FUNCTION)
/// \name LogMacros
/// Macros to log diagnostics.
/// ```c++
/// R__LOG_INFO(ROOT::Experimental::HistLog()) << "all we know is " << 42;
///
/// RLogScopedVerbosity verbose(kDebug + 5);
/// const int decreasedInfoLevel = 5;
/// R__LOG_DEBUG(decreasedInfoLevel, ROOT::Experimental::WebGUILog()) << "nitty-gritty details";
/// ```
///\{
#define R__LOG_FATAL(...) R__LOG_TO_CHANNEL(ROOT::Experimental::ELogLevel::kFatal, __VA_ARGS__)
#define R__LOG_ERROR(...) R__LOG_TO_CHANNEL(ROOT::Experimental::ELogLevel::kError, __VA_ARGS__)
#define R__LOG_WARNING(...) R__LOG_TO_CHANNEL(ROOT::Experimental::ELogLevel::kWarning, __VA_ARGS__)
#define R__LOG_INFO(...) R__LOG_TO_CHANNEL(ROOT::Experimental::ELogLevel::kInfo, __VA_ARGS__)
#define R__LOG_DEBUG(DEBUGLEVEL, ...) R__LOG_TO_CHANNEL(ROOT::Experimental::ELogLevel::kDebug + DEBUGLEVEL, __VA_ARGS__)
///\}
#endif
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkSocketCommunicator.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-2000 Ken Martin, Will Schroeder, Bill Lorensen
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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
of any contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
* Modified source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
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 REGENTS OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
=========================================================================*/
#include "vtkSocketCommunicator.h"
#include "vtkObjectFactory.h"
#ifdef _WIN32
#define WSA_VERSION MAKEWORD(1,1)
#define vtkCloseSocketMacro(sock) (closesocket(sock))
#else
#define vtkCloseSocketMacro(sock) (close(sock))
#endif
//------------------------------------------------------------------------------
vtkSocketCommunicator* vtkSocketCommunicator::New()
{
// First try to create the object from the vtkObjectFactory
vtkObject* ret = vtkObjectFactory::CreateInstance("vtkSocketCommunicator");
if(ret)
{
return (vtkSocketCommunicator*)ret;
}
// If the factory was unable to create the object, then create it here.
return new vtkSocketCommunicator;
}
//----------------------------------------------------------------------------
vtkSocketCommunicator::vtkSocketCommunicator()
{
this->Initialized = 0;
this->Sockets = 0;
this->NumberOfProcesses = 1;
}
//----------------------------------------------------------------------------
vtkSocketCommunicator::~vtkSocketCommunicator()
{
for(int i=0; i<this->NumberOfProcesses; i++)
{
if (this->IsConnected[i])
{
vtkCloseSocketMacro(this->Sockets[i]);
}
}
delete[] this->Sockets;
delete[] this->IsConnected;
this->Sockets = 0;
this->IsConnected = 0;
}
void vtkSocketCommunicator::Initialize(int vtkNotUsed(argc), char *argv[])
{
argv = argv;
#ifdef _WIN32
WSAData wsaData;
if (WSAStartup(WSA_VERSION, &wsaData))
{
vtkErrorMacro("Could not initialize sockets !");
}
#endif
}
void vtkSocketCommunicator::SetNumberOfProcesses(int num)
{
if (this->Sockets)
{
vtkErrorMacro("Can not change the number of processes.");
return;
}
this->Sockets = new int[num];
this->IsConnected = new int[num];
for (int i=0; i<num; i++)
{
this->IsConnected[i] = 0;
}
this->NumberOfProcesses = num;
return;
}
//----------------------------------------------------------------------------
void vtkSocketCommunicator::PrintSelf(ostream& os, vtkIndent indent)
{
vtkMultiProcessController::PrintSelf(os,indent);
}
static inline int checkForError(int id, int maxId)
{
if ( id == 0 )
{
vtkGenericWarningMacro("Can not connect to myself!");
return 1;
}
else if ( id >= maxId )
{
vtkGenericWarningMacro("No port for process " << id << " exists.");
return 1;
}
return 0;
}
template <class T>
static int sendMessage(T* data, int length, int tag, int sock)
{
// Need to check the return value of these
send(sock, &tag, sizeof(int), 0);
send(sock, data, length*sizeof(T), 0);
return 1;
}
//----------------------------------------------------------------------------
int vtkSocketCommunicator::Send(int *data, int length, int remoteProcessId,
int tag)
{
if ( checkForError(remoteProcessId, this->NumberOfProcesses) )
{
return 0;
}
return sendMessage(data, length, tag, this->Sockets[remoteProcessId]);
}
//----------------------------------------------------------------------------
int vtkSocketCommunicator::Send(unsigned long *data, int length,
int remoteProcessId, int tag)
{
if ( checkForError(remoteProcessId, this->NumberOfProcesses) )
{
return 0;
}
return sendMessage(data, length, tag, this->Sockets[remoteProcessId]);
}
//----------------------------------------------------------------------------
int vtkSocketCommunicator::Send(char *data, int length,
int remoteProcessId, int tag)
{
if ( checkForError(remoteProcessId, this->NumberOfProcesses) )
{
return 0;
}
return sendMessage(data, length, tag, this->Sockets[remoteProcessId]);
}
//----------------------------------------------------------------------------
int vtkSocketCommunicator::Send(float *data, int length,
int remoteProcessId, int tag)
{
if ( checkForError(remoteProcessId, this->NumberOfProcesses) )
{
return 0;
}
return sendMessage(data, length, tag, this->Sockets[remoteProcessId]);
}
template <class T>
static int receiveMessage(T* data, int length, int tag, int sock)
{
int recvTag=-1;
// Need to check the return value of these
recv(sock, &recvTag, sizeof(int), MSG_PEEK);
if (recvTag != tag)
return 0;
recv(sock, &recvTag, sizeof(int), 0);
recv(sock, data, length*sizeof(T), 0);
return 1;
}
template <class T>
static int receiveFromAnySource(T* data, int length,
int tag, const int* sockets,
const int* isConnected,
int nOfProcesses)
{
int success;
for ( int i=1; i < nOfProcesses; i++)
{
if (isConnected[i])
{
success = receiveMessage(data, length, tag, sockets[i]);
if (success)
{
cout << "success" << endl;
return i;
}
}
}
return 0;
}
//----------------------------------------------------------------------------
int vtkSocketCommunicator::Receive(int *data, int length, int remoteProcessId,
int tag)
{
int status;
cout << remoteProcessId << endl;
if ( checkForError(remoteProcessId, this->NumberOfProcesses) )
{
return 0;
}
if (remoteProcessId == VTK_MP_CONTROLLER_ANY_SOURCE)
{
int id = receiveFromAnySource(data, length, tag, this->Sockets,
this->IsConnected, this->NumberOfProcesses);
if ( tag == VTK_MP_CONTROLLER_RMI_TAG )
{
data[2] = id;
}
return id;
}
return receiveMessage(data, length, tag, this->Sockets[remoteProcessId]);
}
//----------------------------------------------------------------------------
int vtkSocketCommunicator::Receive(unsigned long *data, int length,
int remoteProcessId, int tag)
{
if ( checkForError(remoteProcessId, this->NumberOfProcesses) )
{
return 0;
}
if (remoteProcessId == VTK_MP_CONTROLLER_ANY_SOURCE)
{
return receiveFromAnySource(data, length, tag, this->Sockets,
this->IsConnected, this->NumberOfProcesses);
}
return receiveMessage(data, length, tag, this->Sockets[remoteProcessId]);
}
//----------------------------------------------------------------------------
int vtkSocketCommunicator::Receive(char *data, int length,
int remoteProcessId, int tag)
{
if ( checkForError(remoteProcessId, this->NumberOfProcesses) )
{
return 0;
}
if (remoteProcessId == VTK_MP_CONTROLLER_ANY_SOURCE)
{
return receiveFromAnySource(data, length, tag, this->Sockets,
this->IsConnected, this->NumberOfProcesses);
}
return receiveMessage(data, length, tag, this->Sockets[remoteProcessId]);
}
int vtkSocketCommunicator::Receive(float *data, int length,
int remoteProcessId, int tag)
{
if ( checkForError(remoteProcessId, this->NumberOfProcesses) )
{
return 0;
}
if (remoteProcessId == VTK_MP_CONTROLLER_ANY_SOURCE)
{
return receiveFromAnySource(data, length, tag, this->Sockets,
this->IsConnected, this->NumberOfProcesses);
}
return receiveMessage(data, length, tag, this->Sockets[remoteProcessId]);
}
int vtkSocketCommunicator::WaitForConnection(int port, int timeout,
int processId)
{
if ( checkForError(processId, this->NumberOfProcesses) )
{
return 0;
}
if ( this->IsConnected[processId] )
{
vtkErrorMacro("Port " << processId << " is occupied.");
return 0;
}
int sock = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in server;
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons(port);
if ( bind(sock, (sockaddr *)&server, sizeof(server)) )
{
vtkErrorMacro("Can not bind socket to port " << port);
return 0;
}
listen(sock,1);
this->Sockets[processId] = accept(sock, 0, 0);
if ( this->Sockets[processId] == -1 )
{
vtkErrorMacro("Error in accept.");
return 0;
}
vtkCloseSocketMacro(sock);
this->IsConnected[processId] = 1;
return 1;
}
void vtkSocketCommunicator::CloseConnection ( int processId )
{
if ( this->IsConnected[processId] )
{
vtkCloseSocketMacro(this->Sockets[processId]);
this->IsConnected[processId] = 0;
}
}
int vtkSocketCommunicator::ConnectTo ( char* hostName, int port,
int processId )
{
if ( checkForError(processId, this->NumberOfProcesses) )
{
return 0;
}
if ( this->IsConnected[processId] )
{
vtkErrorMacro("Communicator port " << processId << " is occupied.");
return 0;
}
struct hostent* hp;
hp = gethostbyname(hostName);
if (!hp)
{
unsigned long addr = inet_addr(hostName);
hp = gethostbyaddr((char *)&addr, sizeof(addr), AF_INET);
}
if (!hp)
{
vtkErrorMacro("Unknown host: " << hostName);
return 0;
}
this->Sockets[processId] = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in name;
name.sin_family = AF_INET;
memcpy(&name.sin_addr, hp->h_addr, hp->h_length);
name.sin_port = htons(port);
if( connect(this->Sockets[processId], (sockaddr *)&name, sizeof(name)) < 0)
{
vtkErrorMacro("Can not connect to " << hostName << " on port " << port);
return 0;
}
vtkDebugMacro("Connected to " << hostName << " on port " << port);
this->IsConnected[processId] = 1;
return 1;
}
<commit_msg>ERR: Now compiles with VC++<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkSocketCommunicator.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-2000 Ken Martin, Will Schroeder, Bill Lorensen
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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
of any contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
* Modified source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
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 REGENTS OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
=========================================================================*/
#include "vtkSocketCommunicator.h"
#include "vtkObjectFactory.h"
#ifdef _WIN32
#define WSA_VERSION MAKEWORD(1,1)
#define vtkCloseSocketMacro(sock) (closesocket(sock))
#else
#define vtkCloseSocketMacro(sock) (close(sock))
#endif
//------------------------------------------------------------------------------
vtkSocketCommunicator* vtkSocketCommunicator::New()
{
// First try to create the object from the vtkObjectFactory
vtkObject* ret = vtkObjectFactory::CreateInstance("vtkSocketCommunicator");
if(ret)
{
return (vtkSocketCommunicator*)ret;
}
// If the factory was unable to create the object, then create it here.
return new vtkSocketCommunicator;
}
//----------------------------------------------------------------------------
vtkSocketCommunicator::vtkSocketCommunicator()
{
this->Initialized = 0;
this->Sockets = 0;
this->NumberOfProcesses = 1;
}
//----------------------------------------------------------------------------
vtkSocketCommunicator::~vtkSocketCommunicator()
{
for(int i=0; i<this->NumberOfProcesses; i++)
{
if (this->IsConnected[i])
{
vtkCloseSocketMacro(this->Sockets[i]);
}
}
delete[] this->Sockets;
delete[] this->IsConnected;
this->Sockets = 0;
this->IsConnected = 0;
}
void vtkSocketCommunicator::Initialize(int vtkNotUsed(argc), char *argv[])
{
argv = argv;
#ifdef _WIN32
WSAData wsaData;
if (WSAStartup(WSA_VERSION, &wsaData))
{
vtkErrorMacro("Could not initialize sockets !");
}
#endif
}
void vtkSocketCommunicator::SetNumberOfProcesses(int num)
{
if (this->Sockets)
{
vtkErrorMacro("Can not change the number of processes.");
return;
}
this->Sockets = new int[num];
this->IsConnected = new int[num];
for (int i=0; i<num; i++)
{
this->IsConnected[i] = 0;
}
this->NumberOfProcesses = num;
return;
}
//----------------------------------------------------------------------------
void vtkSocketCommunicator::PrintSelf(ostream& os, vtkIndent indent)
{
vtkMultiProcessController::PrintSelf(os,indent);
}
static inline int checkForError(int id, int maxId)
{
if ( id == 0 )
{
vtkGenericWarningMacro("Can not connect to myself!");
return 1;
}
else if ( id >= maxId )
{
vtkGenericWarningMacro("No port for process " << id << " exists.");
return 1;
}
return 0;
}
template <class T>
static int sendMessage(T* data, int length, int tag, int sock)
{
// Need to check the return value of these
send(sock, (char *)tag, sizeof(int), 0);
send(sock, (char *)data, length*sizeof(T), 0);
return 1;
}
//----------------------------------------------------------------------------
int vtkSocketCommunicator::Send(int *data, int length, int remoteProcessId,
int tag)
{
if ( checkForError(remoteProcessId, this->NumberOfProcesses) )
{
return 0;
}
return sendMessage(data, length, tag, this->Sockets[remoteProcessId]);
}
//----------------------------------------------------------------------------
int vtkSocketCommunicator::Send(unsigned long *data, int length,
int remoteProcessId, int tag)
{
if ( checkForError(remoteProcessId, this->NumberOfProcesses) )
{
return 0;
}
return sendMessage(data, length, tag, this->Sockets[remoteProcessId]);
}
//----------------------------------------------------------------------------
int vtkSocketCommunicator::Send(char *data, int length,
int remoteProcessId, int tag)
{
if ( checkForError(remoteProcessId, this->NumberOfProcesses) )
{
return 0;
}
return sendMessage(data, length, tag, this->Sockets[remoteProcessId]);
}
//----------------------------------------------------------------------------
int vtkSocketCommunicator::Send(float *data, int length,
int remoteProcessId, int tag)
{
if ( checkForError(remoteProcessId, this->NumberOfProcesses) )
{
return 0;
}
return sendMessage(data, length, tag, this->Sockets[remoteProcessId]);
}
template <class T>
static int receiveMessage(T* data, int length, int tag, int sock)
{
int recvTag=-1;
// Need to check the return value of these
recv(sock, (char *)&recvTag, sizeof(int), MSG_PEEK);
if (recvTag != tag)
return 0;
recv(sock, (char *)&recvTag, sizeof(int), 0);
recv(sock, (char *)data, length*sizeof(T), 0);
return 1;
}
template <class T>
static int receiveFromAnySource(T* data, int length,
int tag, const int* sockets,
const int* isConnected,
int nOfProcesses)
{
int success;
for ( int i=1; i < nOfProcesses; i++)
{
if (isConnected[i])
{
success = receiveMessage(data, length, tag, sockets[i]);
if (success)
{
cout << "success" << endl;
return i;
}
}
}
return 0;
}
//----------------------------------------------------------------------------
int vtkSocketCommunicator::Receive(int *data, int length, int remoteProcessId,
int tag)
{
int status;
cout << remoteProcessId << endl;
if ( checkForError(remoteProcessId, this->NumberOfProcesses) )
{
return 0;
}
if (remoteProcessId == VTK_MP_CONTROLLER_ANY_SOURCE)
{
int id = receiveFromAnySource(data, length, tag, this->Sockets,
this->IsConnected, this->NumberOfProcesses);
if ( tag == VTK_MP_CONTROLLER_RMI_TAG )
{
data[2] = id;
}
return id;
}
return receiveMessage(data, length, tag, this->Sockets[remoteProcessId]);
}
//----------------------------------------------------------------------------
int vtkSocketCommunicator::Receive(unsigned long *data, int length,
int remoteProcessId, int tag)
{
if ( checkForError(remoteProcessId, this->NumberOfProcesses) )
{
return 0;
}
if (remoteProcessId == VTK_MP_CONTROLLER_ANY_SOURCE)
{
return receiveFromAnySource(data, length, tag, this->Sockets,
this->IsConnected, this->NumberOfProcesses);
}
return receiveMessage(data, length, tag, this->Sockets[remoteProcessId]);
}
//----------------------------------------------------------------------------
int vtkSocketCommunicator::Receive(char *data, int length,
int remoteProcessId, int tag)
{
if ( checkForError(remoteProcessId, this->NumberOfProcesses) )
{
return 0;
}
if (remoteProcessId == VTK_MP_CONTROLLER_ANY_SOURCE)
{
return receiveFromAnySource(data, length, tag, this->Sockets,
this->IsConnected, this->NumberOfProcesses);
}
return receiveMessage(data, length, tag, this->Sockets[remoteProcessId]);
}
int vtkSocketCommunicator::Receive(float *data, int length,
int remoteProcessId, int tag)
{
if ( checkForError(remoteProcessId, this->NumberOfProcesses) )
{
return 0;
}
if (remoteProcessId == VTK_MP_CONTROLLER_ANY_SOURCE)
{
return receiveFromAnySource(data, length, tag, this->Sockets,
this->IsConnected, this->NumberOfProcesses);
}
return receiveMessage(data, length, tag, this->Sockets[remoteProcessId]);
}
int vtkSocketCommunicator::WaitForConnection(int port, int timeout,
int processId)
{
if ( checkForError(processId, this->NumberOfProcesses) )
{
return 0;
}
if ( this->IsConnected[processId] )
{
vtkErrorMacro("Port " << processId << " is occupied.");
return 0;
}
int sock = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in server;
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons(port);
if ( bind(sock, (sockaddr *)&server, sizeof(server)) )
{
vtkErrorMacro("Can not bind socket to port " << port);
return 0;
}
listen(sock,1);
this->Sockets[processId] = accept(sock, 0, 0);
if ( this->Sockets[processId] == -1 )
{
vtkErrorMacro("Error in accept.");
return 0;
}
vtkCloseSocketMacro(sock);
this->IsConnected[processId] = 1;
return 1;
}
void vtkSocketCommunicator::CloseConnection ( int processId )
{
if ( this->IsConnected[processId] )
{
vtkCloseSocketMacro(this->Sockets[processId]);
this->IsConnected[processId] = 0;
}
}
int vtkSocketCommunicator::ConnectTo ( char* hostName, int port,
int processId )
{
if ( checkForError(processId, this->NumberOfProcesses) )
{
return 0;
}
if ( this->IsConnected[processId] )
{
vtkErrorMacro("Communicator port " << processId << " is occupied.");
return 0;
}
struct hostent* hp;
hp = gethostbyname(hostName);
if (!hp)
{
unsigned long addr = inet_addr(hostName);
hp = gethostbyaddr((char *)&addr, sizeof(addr), AF_INET);
}
if (!hp)
{
vtkErrorMacro("Unknown host: " << hostName);
return 0;
}
this->Sockets[processId] = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in name;
name.sin_family = AF_INET;
memcpy(&name.sin_addr, hp->h_addr, hp->h_length);
name.sin_port = htons(port);
if( connect(this->Sockets[processId], (sockaddr *)&name, sizeof(name)) < 0)
{
vtkErrorMacro("Can not connect to " << hostName << " on port " << port);
return 0;
}
vtkDebugMacro("Connected to " << hostName << " on port " << port);
this->IsConnected[processId] = 1;
return 1;
}
<|endoftext|> |
<commit_before>#ifdef __TEST__
#include "ArrayTest.h"
ArrayTest::ArrayTest( ) :
allocator( Rumia::Allocator( ) ),
arr( Rumia::Array<int>( allocator ) ),
objArr( Rumia::Array<SomeClass>( allocator ) )
{
}
ArrayTest::~ArrayTest( )
{
}
void ArrayTest::SetUp( )
{
arr.PushBack( 1 );
arr.PushBack( 2 );
arr.PushBack( 3 );
arr.PushBack( 4 );
}
void ArrayTest::TearDown( )
{
arr.Clear( );
objArr.Clear( );
}
TEST_F( ArrayTest, Reserve )
{
EXPECT_EQ( arr.GetCapacity( ), 4 );
arr.Reserve( 8 );
EXPECT_EQ( arr.GetCapacity( ), 8 );
// arr.Reserve( 4 ); // it going to make assertion
}
TEST_F( ArrayTest, Resize )
{
EXPECT_EQ( arr.GetSize( ), 4 );
arr.Resize( 5 );
EXPECT_EQ( arr.GetSize( ), 5 );
arr.Resize( 4 );
EXPECT_EQ( arr.GetSize( ), 4 );
arr.Resize( 5, 999 );
EXPECT_EQ( arr.GetSize( ), 5 );
EXPECT_EQ( arr.At( 4 ), 999 );
}
TEST_F( ArrayTest, PushBack )
{
EXPECT_EQ( arr.At( 0 ), 1 );
EXPECT_EQ( arr.At( 1 ), 2 );
EXPECT_EQ( arr.At( 2 ), 3 );
EXPECT_EQ( arr.At( 3 ), 4 );
EXPECT_EQ( arr.GetCapacity( ), 4 );
EXPECT_EQ( arr.GetSize( ), 4 );
arr.PushBack( 5 );
EXPECT_EQ( arr.At( arr.GetSize( ) - 1 ), 5 );
EXPECT_EQ( arr.GetCapacity( ), 8 );
EXPECT_FALSE( arr.GetCapacity( ) == arr.GetSize( ) );
}
TEST_F( ArrayTest, PopBack )
{
EXPECT_EQ( arr.PopBack( ), 4 );
EXPECT_EQ( arr.GetSize( ), 3 );
EXPECT_EQ( arr.PopBack( ), 3);
EXPECT_EQ( arr.GetSize( ), 2 );
EXPECT_EQ( arr.PopBack( ), 2 );
EXPECT_EQ( arr.GetSize( ), 1 );
EXPECT_EQ( arr.PopBack( ), 1 );
EXPECT_EQ( arr.GetSize( ), 0 );
}
TEST_F( ArrayTest, Emplace )
{
arr.Emplace( 5 );
EXPECT_EQ( arr.GetSize( ), 5 );
EXPECT_EQ( arr.GetCapacity( ), 8 );
arr.Emplace( 6 );
EXPECT_EQ( arr.GetSize( ), 6 );
EXPECT_EQ( arr.At( arr.GetSize( ) - 1 ), 6 );
}
TEST_F( ArrayTest, Insert )
{
arr.Insert( 0, -1 );
EXPECT_EQ( arr.At( 0 ), -1 );
EXPECT_EQ( arr.GetSize( ), 5 );
EXPECT_EQ( arr.GetCapacity( ), 8 );
arr.Insert( arr.GetSize( ) - 1, 1001 );
EXPECT_EQ( arr.At( ( arr.GetSize( ) - 2 ) ), 1001 );
}
TEST_F( ArrayTest, IsEmpty )
{
EXPECT_TRUE( !arr.IsEmpty( ) );
arr.PopBack( );
arr.PopBack( );
arr.PopBack( );
arr.PopBack( );
EXPECT_TRUE( arr.IsEmpty( ) );
}
TEST_F( ArrayTest, IsFull )
{
EXPECT_TRUE( arr.IsFull( ) );
arr.PopBack( );
EXPECT_FALSE( arr.IsFull( ) );
arr.PushBack( 4 );
arr.PushBack( -1 );
EXPECT_FALSE( arr.IsFull( ) );
}
TEST_F( ArrayTest, Clear )
{
arr.Clear( false );
EXPECT_TRUE( arr.IsEmpty( ) );
arr.Clear( true );
EXPECT_EQ( arr.GetCapacity( ), 0 );
}
TEST_F( ArrayTest, Copy )
{
Rumia::Array<int> copyConstructorObj{ arr };
EXPECT_EQ( copyConstructorObj.PopBack( ), 4 );
EXPECT_EQ( copyConstructorObj.PopBack( ), 3 );
EXPECT_EQ( copyConstructorObj.PopBack( ), 2 );
EXPECT_EQ( copyConstructorObj.PopBack( ), 1 );
copyConstructorObj.PushBack( 999 );
// arr and copyConstructorObj is not a same object!
EXPECT_EQ( arr.PopBack( ), 4);
Rumia::Array<int> anotherCopy{ allocator };
anotherCopy = arr;
EXPECT_EQ( anotherCopy.PopBack( ), 3 );
EXPECT_EQ( anotherCopy.PopBack( ), 2 );
EXPECT_EQ( anotherCopy.PopBack( ), 1 );
EXPECT_TRUE( anotherCopy.IsEmpty( ) );
}
TEST_F( ArrayTest, Move )
{
Rumia::Array<int> movedObj( std::move( arr ) );
EXPECT_TRUE( arr.IsEmpty( ) );
EXPECT_EQ( movedObj.PopBack( ), 4 );
EXPECT_EQ( movedObj.PopBack( ), 3 );
Rumia::Array<int> anotherMovedObj{ allocator };
EXPECT_TRUE( anotherMovedObj.IsEmpty( ) );
anotherMovedObj = std::move( movedObj );
EXPECT_FALSE( anotherMovedObj.IsEmpty( ) );
EXPECT_TRUE( movedObj.IsEmpty( ) );
EXPECT_EQ( anotherMovedObj.PopBack( ), 2 );
EXPECT_EQ( anotherMovedObj.PopBack( ), 1 );
}
TEST_F( ArrayTest, ObjectMove )
{
SomeClass obj{ 30 };
objArr.PushBack( obj );
EXPECT_EQ( objArr.PopBack( ).m_data, 30 );
EXPECT_EQ( obj.m_data, 30 );
objArr.PushBack( std::move( obj ) );
EXPECT_EQ( objArr.PopBack( ).m_data, 30 );
EXPECT_EQ( obj.m_data, -1 );
}
TEST_F( ArrayTest, IndexOf )
{
EXPECT_EQ( arr.IndexOf( 1 ), 0 );
EXPECT_EQ( arr.IndexOf( 2 ), 1 );
EXPECT_EQ( arr.IndexOf( 3 ), 2 );
EXPECT_EQ( arr.IndexOf( 4 ), 3 );
EXPECT_EQ( arr.IndexOf( 9999 ), arr.GetSize( ) );
}
TEST_F( ArrayTest, EraseAt )
{
arr.EraseAt( 1 );
EXPECT_EQ( arr.GetSize( ), 3 );
EXPECT_EQ( arr.At( 1 ), 3 );
EXPECT_EQ( arr.At( 2 ), 4 );
}
TEST_F( ArrayTest, Erase )
{
arr.Erase( 2 );
EXPECT_EQ( arr.GetSize( ), 3 );
EXPECT_EQ( arr.At( 1 ), 3 );
EXPECT_EQ( arr.At( 2 ), 4 );
EXPECT_EQ( arr.IndexOf( 2 ), arr.GetSize( ) );
arr.Erase( 999 );
EXPECT_EQ( arr.GetSize( ), 3 );
arr.Clear( );
arr.PushBack( 1 );
arr.PushBack( 2 );
arr.Erase( arr.begin( ) );
EXPECT_EQ( 2, arr.At( 0 ) );
}
TEST_F( ArrayTest, FindIf )
{
arr.Clear( );
arr.PushBack( 1 );
arr.PushBack( 2 );
arr.PushBack( 3 );
int FoundData = ( *arr.FindIf( [ ]( int Data )->bool { return ( Data == 2 ); } ) );
EXPECT_EQ( FoundData, 2 );
}
TEST_F( ArrayTest, ConstItr )
{
arr.Clear( );
arr.PushBack( 1 );
arr.PushBack( 2 );
arr.PushBack( 3 );
int Counter = 1;
for ( auto itr = arr.cbegin( ); itr != arr.cend( ); ++itr )
{
EXPECT_EQ( ( *itr ), Counter );
++Counter;
}
}
#endif<commit_msg>Added Array shrink test case<commit_after>#ifdef __TEST__
#include "ArrayTest.h"
ArrayTest::ArrayTest( ) :
allocator( Rumia::Allocator( ) ),
arr( Rumia::Array<int>( allocator ) ),
objArr( Rumia::Array<SomeClass>( allocator ) )
{
}
ArrayTest::~ArrayTest( )
{
}
void ArrayTest::SetUp( )
{
arr.PushBack( 1 );
arr.PushBack( 2 );
arr.PushBack( 3 );
arr.PushBack( 4 );
}
void ArrayTest::TearDown( )
{
arr.Clear( );
objArr.Clear( );
}
TEST_F( ArrayTest, Reserve )
{
EXPECT_EQ( arr.GetCapacity( ), 4 );
arr.Reserve( 8 );
EXPECT_EQ( arr.GetCapacity( ), 8 );
// arr.Reserve( 4 ); // it going to make assertion
}
TEST_F( ArrayTest, Resize )
{
EXPECT_EQ( arr.GetSize( ), 4 );
arr.Resize( 5 );
EXPECT_EQ( arr.GetSize( ), 5 );
arr.Resize( 4 );
EXPECT_EQ( arr.GetSize( ), 4 );
arr.Resize( 5, 999 );
EXPECT_EQ( arr.GetSize( ), 5 );
EXPECT_EQ( arr.At( 4 ), 999 );
}
TEST_F( ArrayTest, PushBack )
{
EXPECT_EQ( arr.At( 0 ), 1 );
EXPECT_EQ( arr.At( 1 ), 2 );
EXPECT_EQ( arr.At( 2 ), 3 );
EXPECT_EQ( arr.At( 3 ), 4 );
EXPECT_EQ( arr.GetCapacity( ), 4 );
EXPECT_EQ( arr.GetSize( ), 4 );
arr.PushBack( 5 );
EXPECT_EQ( arr.At( arr.GetSize( ) - 1 ), 5 );
EXPECT_EQ( arr.GetCapacity( ), 8 );
EXPECT_FALSE( arr.GetCapacity( ) == arr.GetSize( ) );
}
TEST_F( ArrayTest, PopBack )
{
EXPECT_EQ( arr.PopBack( ), 4 );
EXPECT_EQ( arr.GetSize( ), 3 );
EXPECT_EQ( arr.PopBack( ), 3);
EXPECT_EQ( arr.GetSize( ), 2 );
EXPECT_EQ( arr.PopBack( ), 2 );
EXPECT_EQ( arr.GetSize( ), 1 );
EXPECT_EQ( arr.PopBack( ), 1 );
EXPECT_EQ( arr.GetSize( ), 0 );
}
TEST_F( ArrayTest, Emplace )
{
arr.Emplace( 5 );
EXPECT_EQ( arr.GetSize( ), 5 );
EXPECT_EQ( arr.GetCapacity( ), 8 );
arr.Emplace( 6 );
EXPECT_EQ( arr.GetSize( ), 6 );
EXPECT_EQ( arr.At( arr.GetSize( ) - 1 ), 6 );
}
TEST_F( ArrayTest, Insert )
{
arr.Insert( 0, -1 );
EXPECT_EQ( arr.At( 0 ), -1 );
EXPECT_EQ( arr.GetSize( ), 5 );
EXPECT_EQ( arr.GetCapacity( ), 8 );
arr.Insert( arr.GetSize( ) - 1, 1001 );
EXPECT_EQ( arr.At( ( arr.GetSize( ) - 2 ) ), 1001 );
}
TEST_F( ArrayTest, IsEmpty )
{
EXPECT_TRUE( !arr.IsEmpty( ) );
arr.PopBack( );
arr.PopBack( );
arr.PopBack( );
arr.PopBack( );
EXPECT_TRUE( arr.IsEmpty( ) );
}
TEST_F( ArrayTest, IsFull )
{
EXPECT_TRUE( arr.IsFull( ) );
arr.PopBack( );
EXPECT_FALSE( arr.IsFull( ) );
arr.PushBack( 4 );
arr.PushBack( -1 );
EXPECT_FALSE( arr.IsFull( ) );
}
TEST_F( ArrayTest, Clear )
{
arr.Clear( false );
EXPECT_TRUE( arr.IsEmpty( ) );
arr.Clear( true );
EXPECT_EQ( arr.GetCapacity( ), 0 );
}
TEST_F( ArrayTest, Copy )
{
Rumia::Array<int> copyConstructorObj{ arr };
EXPECT_EQ( copyConstructorObj.PopBack( ), 4 );
EXPECT_EQ( copyConstructorObj.PopBack( ), 3 );
EXPECT_EQ( copyConstructorObj.PopBack( ), 2 );
EXPECT_EQ( copyConstructorObj.PopBack( ), 1 );
copyConstructorObj.PushBack( 999 );
// arr and copyConstructorObj is not a same object!
EXPECT_EQ( arr.PopBack( ), 4);
Rumia::Array<int> anotherCopy{ allocator };
anotherCopy = arr;
EXPECT_EQ( anotherCopy.PopBack( ), 3 );
EXPECT_EQ( anotherCopy.PopBack( ), 2 );
EXPECT_EQ( anotherCopy.PopBack( ), 1 );
EXPECT_TRUE( anotherCopy.IsEmpty( ) );
}
TEST_F( ArrayTest, Move )
{
Rumia::Array<int> movedObj( std::move( arr ) );
EXPECT_TRUE( arr.IsEmpty( ) );
EXPECT_EQ( movedObj.PopBack( ), 4 );
EXPECT_EQ( movedObj.PopBack( ), 3 );
Rumia::Array<int> anotherMovedObj{ allocator };
EXPECT_TRUE( anotherMovedObj.IsEmpty( ) );
anotherMovedObj = std::move( movedObj );
EXPECT_FALSE( anotherMovedObj.IsEmpty( ) );
EXPECT_TRUE( movedObj.IsEmpty( ) );
EXPECT_EQ( anotherMovedObj.PopBack( ), 2 );
EXPECT_EQ( anotherMovedObj.PopBack( ), 1 );
}
TEST_F( ArrayTest, ObjectMove )
{
SomeClass obj{ 30 };
objArr.PushBack( obj );
EXPECT_EQ( objArr.PopBack( ).m_data, 30 );
EXPECT_EQ( obj.m_data, 30 );
objArr.PushBack( std::move( obj ) );
EXPECT_EQ( objArr.PopBack( ).m_data, 30 );
EXPECT_EQ( obj.m_data, -1 );
}
TEST_F( ArrayTest, IndexOf )
{
EXPECT_EQ( arr.IndexOf( 1 ), 0 );
EXPECT_EQ( arr.IndexOf( 2 ), 1 );
EXPECT_EQ( arr.IndexOf( 3 ), 2 );
EXPECT_EQ( arr.IndexOf( 4 ), 3 );
EXPECT_EQ( arr.IndexOf( 9999 ), arr.GetSize( ) );
}
TEST_F( ArrayTest, EraseAt )
{
arr.EraseAt( 1 );
EXPECT_EQ( arr.GetSize( ), 3 );
EXPECT_EQ( arr.At( 1 ), 3 );
EXPECT_EQ( arr.At( 2 ), 4 );
}
TEST_F( ArrayTest, Erase )
{
arr.Erase( 2 );
EXPECT_EQ( arr.GetSize( ), 3 );
EXPECT_EQ( arr.At( 1 ), 3 );
EXPECT_EQ( arr.At( 2 ), 4 );
EXPECT_EQ( arr.IndexOf( 2 ), arr.GetSize( ) );
arr.Erase( 999 );
EXPECT_EQ( arr.GetSize( ), 3 );
arr.Clear( );
arr.PushBack( 1 );
arr.PushBack( 2 );
arr.Erase( arr.begin( ) );
EXPECT_EQ( 2, arr.At( 0 ) );
}
TEST_F( ArrayTest, FindIf )
{
arr.Clear( );
arr.PushBack( 1 );
arr.PushBack( 2 );
arr.PushBack( 3 );
int FoundData = ( *arr.FindIf( [ ]( int Data )->bool { return ( Data == 2 ); } ) );
EXPECT_EQ( FoundData, 2 );
}
TEST_F( ArrayTest, ConstItr )
{
arr.Clear( );
arr.PushBack( 1 );
arr.PushBack( 2 );
arr.PushBack( 3 );
int Counter = 1;
for ( auto itr = arr.cbegin( ); itr != arr.cend( ); ++itr )
{
EXPECT_EQ( ( *itr ), Counter );
++Counter;
}
}
TEST_F( ArrayTest, Shrink )
{
arr.Clear( );
arr.PushBack( 1 ); // Capacity 2
arr.PushBack( 2 );
arr.PushBack( 3 ); // Capacity 4
arr.PushBack( 4 );
arr.PushBack( 5 ); // Capacity 8
EXPECT_EQ( arr.GetCapacity( ), 8 );
arr.Shrink( );
EXPECT_EQ( arr.GetCapacity( ), 5 );
EXPECT_EQ( arr[ 4 ], 5 );
}
#endif<|endoftext|> |
<commit_before>/*
*
* Copyright 2015 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <grpc/support/port_platform.h>
#if GPR_LINUX
#include <fcntl.h>
#include <unistd.h>
#endif
#include <algorithm>
#include <grpc/impl/codegen/gpr_types.h>
#include <grpc/support/log.h>
#include <grpc/support/time.h>
#include "src/core/lib/gpr/time_precise.h"
#if GPR_CYCLE_COUNTER_RDTSC_32 or GPR_CYCLE_COUNTER_RDTSC_64
#if GPR_LINUX
static bool read_freq_from_kernel(double* freq) {
// Google production kernel export the frequency for us in kHz.
int fd = open("/sys/devices/system/cpu/cpu0/tsc_freq_khz", O_RDONLY);
if (fd == -1) {
return false;
}
char line[1024] = {};
char* err;
bool ret = false;
int len = read(fd, line, sizeof(line) - 1);
if (len > 0) {
const long val = strtol(line, &err, 10);
if (line[0] != '\0' && (*err == '\n' || *err == '\0')) {
*freq = val * 1e3; // Value is kHz.
ret = true;
}
}
close(fd);
return ret;
}
#endif /* GPR_LINUX */
static double cycles_per_second = 0;
static gpr_cycle_counter start_cycle;
static bool is_fake_clock() {
gpr_timespec start = gpr_now(GPR_CLOCK_MONOTONIC);
int64_t sum = 0;
for (int i = 0; i < 8; ++i) {
gpr_timespec now = gpr_now(GPR_CLOCK_MONOTONIC);
gpr_timespec delta = gpr_time_sub(now, start);
sum += delta.tv_sec * GPR_NS_PER_SEC + delta.tv_nsec;
}
// If the clock doesn't move even a nano after 8 tries, it's a fake one.
return sum == 0;
}
void gpr_precise_clock_init(void) {
gpr_log(GPR_DEBUG, "Calibrating timers");
#if GPR_LINUX
if (read_freq_from_kernel(&cycles_per_second)) {
start_cycle = gpr_get_cycle_counter();
return;
}
#endif /* GPR_LINUX */
if (is_fake_clock()) {
cycles_per_second = 1;
start_cycle = 0;
return;
}
// Start from a loop of 1ms, and gradually increase the loop duration
// until we either converge or we have passed 255ms (1ms+2ms+...+128ms).
int64_t measurement_ns = GPR_NS_PER_MS;
double last_freq = -1;
bool converged = false;
for (int i = 0; i < 8 && !converged; ++i, measurement_ns *= 2) {
start_cycle = gpr_get_cycle_counter();
int64_t loop_ns;
gpr_timespec start = gpr_now(GPR_CLOCK_MONOTONIC);
do {
// TODO(soheil): Maybe sleep instead of busy polling.
gpr_timespec now = gpr_now(GPR_CLOCK_MONOTONIC);
gpr_timespec delta = gpr_time_sub(now, start);
loop_ns = delta.tv_sec * GPR_NS_PER_SEC + delta.tv_nsec;
} while (loop_ns < measurement_ns);
gpr_cycle_counter end_cycle = gpr_get_cycle_counter();
// Frequency should be in Hz.
const double freq =
static_cast<double>(end_cycle - start_cycle) / loop_ns * GPR_NS_PER_SEC;
converged =
last_freq != -1 && (freq * 0.99 < last_freq && last_freq < freq * 1.01);
last_freq = freq;
}
cycles_per_second = last_freq;
gpr_log(GPR_DEBUG, "... cycles_per_second = %f\n", cycles_per_second);
}
gpr_timespec gpr_cycle_counter_to_time(gpr_cycle_counter cycles) {
const double secs =
static_cast<double>(cycles - start_cycle) / cycles_per_second;
gpr_timespec ts;
ts.tv_sec = static_cast<int64_t>(secs);
ts.tv_nsec = static_cast<int32_t>(GPR_NS_PER_SEC *
(secs - static_cast<double>(ts.tv_sec)));
ts.clock_type = GPR_CLOCK_PRECISE;
return ts;
}
gpr_timespec gpr_cycle_counter_sub(gpr_cycle_counter a, gpr_cycle_counter b) {
const double secs = static_cast<double>(a - b) / cycles_per_second;
gpr_timespec ts;
ts.tv_sec = static_cast<int64_t>(secs);
ts.tv_nsec = static_cast<int32_t>(GPR_NS_PER_SEC *
(secs - static_cast<double>(ts.tv_sec)));
ts.clock_type = GPR_TIMESPAN;
return ts;
}
void gpr_precise_clock_now(gpr_timespec* clk) {
int64_t counter = gpr_get_cycle_counter();
*clk = gpr_cycle_counter_to_time(counter);
}
#elif GPR_CYCLE_COUNTER_FALLBACK
void gpr_precise_clock_init(void) {}
gpr_cycle_counter gpr_get_cycle_counter() {
gpr_timespec ts = gpr_now(GPR_CLOCK_REALTIME);
return gpr_timespec_to_micros(ts);
}
gpr_timespec gpr_cycle_counter_to_time(gpr_cycle_counter cycles) {
gpr_timespec ts;
ts.tv_sec = cycles / GPR_US_PER_SEC;
ts.tv_nsec = (cycles - ts.tv_sec * GPR_US_PER_SEC) * GPR_NS_PER_US;
ts.clock_type = GPR_CLOCK_PRECISE;
return ts;
}
void gpr_precise_clock_now(gpr_timespec* clk) {
*clk = gpr_now(GPR_CLOCK_REALTIME);
clk->clock_type = GPR_CLOCK_PRECISE;
}
gpr_timespec gpr_cycle_counter_sub(gpr_cycle_counter a, gpr_cycle_counter b) {
return gpr_time_sub(gpr_cycle_counter_to_time(a),
gpr_cycle_counter_to_time(b));
}
#endif /* GPR_CYCLE_COUNTER_FALLBACK */
<commit_msg>Replace or with ||<commit_after>/*
*
* Copyright 2015 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <grpc/support/port_platform.h>
#if GPR_LINUX
#include <fcntl.h>
#include <unistd.h>
#endif
#include <algorithm>
#include <grpc/impl/codegen/gpr_types.h>
#include <grpc/support/log.h>
#include <grpc/support/time.h>
#include "src/core/lib/gpr/time_precise.h"
#if GPR_CYCLE_COUNTER_RDTSC_32 || GPR_CYCLE_COUNTER_RDTSC_64
#if GPR_LINUX
static bool read_freq_from_kernel(double* freq) {
// Google production kernel export the frequency for us in kHz.
int fd = open("/sys/devices/system/cpu/cpu0/tsc_freq_khz", O_RDONLY);
if (fd == -1) {
return false;
}
char line[1024] = {};
char* err;
bool ret = false;
int len = read(fd, line, sizeof(line) - 1);
if (len > 0) {
const long val = strtol(line, &err, 10);
if (line[0] != '\0' && (*err == '\n' || *err == '\0')) {
*freq = val * 1e3; // Value is kHz.
ret = true;
}
}
close(fd);
return ret;
}
#endif /* GPR_LINUX */
static double cycles_per_second = 0;
static gpr_cycle_counter start_cycle;
static bool is_fake_clock() {
gpr_timespec start = gpr_now(GPR_CLOCK_MONOTONIC);
int64_t sum = 0;
for (int i = 0; i < 8; ++i) {
gpr_timespec now = gpr_now(GPR_CLOCK_MONOTONIC);
gpr_timespec delta = gpr_time_sub(now, start);
sum += delta.tv_sec * GPR_NS_PER_SEC + delta.tv_nsec;
}
// If the clock doesn't move even a nano after 8 tries, it's a fake one.
return sum == 0;
}
void gpr_precise_clock_init(void) {
gpr_log(GPR_DEBUG, "Calibrating timers");
#if GPR_LINUX
if (read_freq_from_kernel(&cycles_per_second)) {
start_cycle = gpr_get_cycle_counter();
return;
}
#endif /* GPR_LINUX */
if (is_fake_clock()) {
cycles_per_second = 1;
start_cycle = 0;
return;
}
// Start from a loop of 1ms, and gradually increase the loop duration
// until we either converge or we have passed 255ms (1ms+2ms+...+128ms).
int64_t measurement_ns = GPR_NS_PER_MS;
double last_freq = -1;
bool converged = false;
for (int i = 0; i < 8 && !converged; ++i, measurement_ns *= 2) {
start_cycle = gpr_get_cycle_counter();
int64_t loop_ns;
gpr_timespec start = gpr_now(GPR_CLOCK_MONOTONIC);
do {
// TODO(soheil): Maybe sleep instead of busy polling.
gpr_timespec now = gpr_now(GPR_CLOCK_MONOTONIC);
gpr_timespec delta = gpr_time_sub(now, start);
loop_ns = delta.tv_sec * GPR_NS_PER_SEC + delta.tv_nsec;
} while (loop_ns < measurement_ns);
gpr_cycle_counter end_cycle = gpr_get_cycle_counter();
// Frequency should be in Hz.
const double freq =
static_cast<double>(end_cycle - start_cycle) / loop_ns * GPR_NS_PER_SEC;
converged =
last_freq != -1 && (freq * 0.99 < last_freq && last_freq < freq * 1.01);
last_freq = freq;
}
cycles_per_second = last_freq;
gpr_log(GPR_DEBUG, "... cycles_per_second = %f\n", cycles_per_second);
}
gpr_timespec gpr_cycle_counter_to_time(gpr_cycle_counter cycles) {
const double secs =
static_cast<double>(cycles - start_cycle) / cycles_per_second;
gpr_timespec ts;
ts.tv_sec = static_cast<int64_t>(secs);
ts.tv_nsec = static_cast<int32_t>(GPR_NS_PER_SEC *
(secs - static_cast<double>(ts.tv_sec)));
ts.clock_type = GPR_CLOCK_PRECISE;
return ts;
}
gpr_timespec gpr_cycle_counter_sub(gpr_cycle_counter a, gpr_cycle_counter b) {
const double secs = static_cast<double>(a - b) / cycles_per_second;
gpr_timespec ts;
ts.tv_sec = static_cast<int64_t>(secs);
ts.tv_nsec = static_cast<int32_t>(GPR_NS_PER_SEC *
(secs - static_cast<double>(ts.tv_sec)));
ts.clock_type = GPR_TIMESPAN;
return ts;
}
void gpr_precise_clock_now(gpr_timespec* clk) {
int64_t counter = gpr_get_cycle_counter();
*clk = gpr_cycle_counter_to_time(counter);
}
#elif GPR_CYCLE_COUNTER_FALLBACK
void gpr_precise_clock_init(void) {}
gpr_cycle_counter gpr_get_cycle_counter() {
gpr_timespec ts = gpr_now(GPR_CLOCK_REALTIME);
return gpr_timespec_to_micros(ts);
}
gpr_timespec gpr_cycle_counter_to_time(gpr_cycle_counter cycles) {
gpr_timespec ts;
ts.tv_sec = cycles / GPR_US_PER_SEC;
ts.tv_nsec = (cycles - ts.tv_sec * GPR_US_PER_SEC) * GPR_NS_PER_US;
ts.clock_type = GPR_CLOCK_PRECISE;
return ts;
}
void gpr_precise_clock_now(gpr_timespec* clk) {
*clk = gpr_now(GPR_CLOCK_REALTIME);
clk->clock_type = GPR_CLOCK_PRECISE;
}
gpr_timespec gpr_cycle_counter_sub(gpr_cycle_counter a, gpr_cycle_counter b) {
return gpr_time_sub(gpr_cycle_counter_to_time(a),
gpr_cycle_counter_to_time(b));
}
#endif /* GPR_CYCLE_COUNTER_FALLBACK */
<|endoftext|> |
<commit_before>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2010-2012, Image Engine Design 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 Image Engine Design nor the names of any
// other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include "boost/format.hpp"
#include "OP/OP_Director.h"
#include "PRM/PRM_Default.h"
#include "PRM/PRM_Template.h"
#include "IECore/CompoundObject.h"
#include "IECore/TransformationMatrixData.h"
#include "IECore/VectorTypedData.h"
#include "Convert.h"
#include "ToHoudiniAttribConverter.h"
#include "SOP_InterpolatedCacheReader.h"
using namespace IECore;
using namespace IECoreHoudini;
static PRM_Name parameterNames[] = {
PRM_Name( "cacheSequence", "Cache Sequence" ),
PRM_Name( "objectFixes", "Object Prefix/Suffix" ),
PRM_Name( "attributeFixes", "Attribute Prefix/Suffix" ),
PRM_Name( "transformAttribute", "Transform Attribute" ),
PRM_Name( "frameMultiplier", "Frame Multiplier" ),
};
static PRM_Default frameMultiplierDefault( 1 );
PRM_Template SOP_InterpolatedCacheReader::parameters[] = {
PRM_Template( PRM_FILE, 1, ¶meterNames[0] ),
PRM_Template( PRM_STRING, 2, ¶meterNames[1] ),
PRM_Template( PRM_STRING, 2, ¶meterNames[2] ),
PRM_Template( PRM_STRING, 1, ¶meterNames[3] ),
PRM_Template( PRM_INT, 1, ¶meterNames[4], &frameMultiplierDefault ),
PRM_Template(),
};
SOP_InterpolatedCacheReader::SOP_InterpolatedCacheReader( OP_Network *net, const char *name, OP_Operator *op )
: SOP_Node( net, name, op ), m_cache( 0 ), m_cacheFileName(), m_frameMultiplier( -1 )
{
flags().setTimeDep( true );
}
SOP_InterpolatedCacheReader::~SOP_InterpolatedCacheReader()
{
}
OP_Node *SOP_InterpolatedCacheReader::create( OP_Network *net, const char *name, OP_Operator *op )
{
return new SOP_InterpolatedCacheReader( net, name, op );
}
OP_ERROR SOP_InterpolatedCacheReader::cookMySop( OP_Context &context )
{
flags().setTimeDep( true );
if ( lockInputs( context ) >= UT_ERROR_ABORT )
{
return error();
}
gdp->stashAll();
float time = context.getTime();
float frame = context.getFloatFrame();
UT_String paramVal;
evalString( paramVal, "cacheSequence", 0, time );
std::string cacheFileName = paramVal.toStdString();
evalString( paramVal, "objectFixes", 0, time );
std::string objectPrefix = paramVal.toStdString();
evalString( paramVal, "objectFixes", 1, time );
std::string objectSuffix = paramVal.toStdString();
evalString( paramVal, "attributeFixes", 0, time );
std::string attributePrefix = paramVal.toStdString();
evalString( paramVal, "attributeFixes", 1, time );
std::string attributeSuffix = paramVal.toStdString();
evalString( paramVal, "transformAttribute", 0, time );
std::string transformAttribute = paramVal.toStdString();
int frameMultiplier = evalInt( "frameMultiplier", 0, time );
// create the InterpolatedCache
if ( cacheFileName.compare( m_cacheFileName ) != 0 || frameMultiplier != m_frameMultiplier )
{
try
{
float fps = OPgetDirector()->getChannelManager()->getSamplesPerSec();
OversamplesCalculator calc( fps, 1, (int)fps * frameMultiplier );
m_cache = new InterpolatedCache( cacheFileName, InterpolatedCache::Linear, calc );
}
catch ( IECore::InvalidArgumentException e )
{
addWarning( SOP_ATTRIBUTE_INVALID, e.what() );
unlockInputs();
return error();
}
m_cacheFileName = cacheFileName;
m_frameMultiplier = frameMultiplier;
}
if ( !m_cache )
{
addWarning( SOP_MESSAGE, "SOP_InterpolatedCacheReader: Cache Sequence not found" );
unlockInputs();
return error();
}
std::vector<InterpolatedCache::ObjectHandle> objects;
std::vector<InterpolatedCache::AttributeHandle> attrs;
try
{
m_cache->objects( frame, objects );
}
catch ( IECore::Exception e )
{
addWarning( SOP_ATTRIBUTE_INVALID, e.what() );
unlockInputs();
return error();
}
duplicatePointSource( 0, context );
for ( GA_GroupTable::iterator<GA_ElementGroup> it=gdp->pointGroups().beginTraverse(); !it.atEnd(); ++it )
{
GA_PointGroup *group = (GA_PointGroup*)it.group();
if ( group->getInternal() || group->isEmpty() )
{
continue;
}
// match GA_PointGroup name to InterpolatedCache::ObjectHandle
std::string searchName = objectPrefix + group->getName().toStdString() + objectSuffix;
std::vector<InterpolatedCache::ObjectHandle>::iterator oIt = find( objects.begin(), objects.end(), searchName );
if ( oIt == objects.end() )
{
continue;
}
CompoundObjectPtr attributes = 0;
try
{
m_cache->attributes( frame, *oIt, attrs );
attributes = m_cache->read( frame, *oIt );
}
catch ( IECore::Exception e )
{
addError( SOP_ATTRIBUTE_INVALID, e.what() );
unlockInputs();
return error();
}
const CompoundObject::ObjectMap &attributeMap = attributes->members();
GA_Range pointRange = gdp->getPointRange( group );
// transfer the InterpolatedCache::Attributes onto the GA_PointGroup
/// \todo: this does not account for detail, prim, or vertex attribs...
for ( CompoundObject::ObjectMap::const_iterator aIt=attributeMap.begin(); aIt != attributeMap.end(); aIt++ )
{
const Data *data = IECore::runTimeCast<const Data>( aIt->second );
if ( !data )
{
continue;
}
ToHoudiniAttribConverterPtr converter = ToHoudiniAttribConverter::create( data );
if ( !converter )
{
continue;
}
// strip the prefix/suffix from the GA_Attribute name
std::string attrName = aIt->first.value();
size_t prefixLength = attributePrefix.length();
if ( prefixLength && ( search( attrName.begin(), attrName.begin()+prefixLength, attributePrefix.begin(), attributePrefix.end() ) == attrName.begin() ) )
{
attrName.erase( attrName.begin(), attrName.begin() + prefixLength );
}
size_t suffixLength = attributeSuffix.length();
if ( suffixLength && ( search( attrName.end() - suffixLength, attrName.end(), attributeSuffix.begin(), attributeSuffix.end() ) == ( attrName.end() - suffixLength ) ) )
{
attrName.erase( attrName.end() - suffixLength, attrName.end() );
}
if ( attrName == "P" )
{
const V3fVectorData *positions = IECore::runTimeCast<const V3fVectorData>( data );
if ( !positions )
{
continue;
}
size_t index = 0;
size_t entries = pointRange.getEntries();
const std::vector<Imath::V3f> &pos = positions->readable();
// Attempting to account for the vertex difference between an IECore::CurvesPrimitive and Houdini curves.
// As Houdini implicitly triples the endpoints of a curve, a cache generated from a single CurvesPrimitive
// will have exactly four extra vertices. In this case, we adjust the cache by ignoring the first two and
// last two V3fs. In all other cases, we report a warning and don't apply the cache to these points.
if ( pos.size() - 4 == entries )
{
index = 2;
}
else if ( pos.size() != entries )
{
addWarning( SOP_ATTRIBUTE_INVALID, ( boost::format( "Geometry/Cache mismatch: %s contains %d points, while cache expects %d." ) % group->getName().toStdString() % entries % pos.size() ).str().c_str() );
continue;
}
for ( GA_Iterator it=pointRange.begin(); !it.atEnd(); ++it, ++index )
{
gdp->setPos3( it.getOffset(), IECore::convert<UT_Vector3>( pos[index] ) );
}
}
else
{
converter->convert( attrName, gdp, pointRange );
}
}
// if transformAttribute is specified, use to to transform the points
if ( transformAttribute != "" )
{
const TransformationMatrixdData *transform = attributes->member<TransformationMatrixdData>( transformAttribute );
if ( transform )
{
transformPoints<double>( transform->readable(), pointRange );
}
else
{
const TransformationMatrixfData *transform = attributes->member<TransformationMatrixfData>( transformAttribute );
if ( transform )
{
transformPoints<float>( transform->readable(), pointRange );
}
}
}
}
unlockInputs();
return error();
}
template<typename T>
void SOP_InterpolatedCacheReader::transformPoints( const IECore::TransformationMatrix<T> &transform, const GA_Range &range )
{
UT_Matrix4T<T> matrix = IECore::convert<UT_Matrix4T<T> >( transform.transform() );
for ( GA_Iterator it=range.begin(); !it.atEnd(); ++it )
{
UT_Vector3 pos = gdp->getPos3( it.getOffset() );
pos *= matrix;
gdp->setPos3( it.getOffset(), pos );
}
}
<commit_msg>simplified logic and added threading todos<commit_after>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2010-2012, Image Engine Design 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 Image Engine Design nor the names of any
// other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include "boost/format.hpp"
#include "OP/OP_Director.h"
#include "PRM/PRM_Default.h"
#include "PRM/PRM_Template.h"
#include "IECore/CompoundObject.h"
#include "IECore/TransformationMatrixData.h"
#include "IECore/VectorTypedData.h"
#include "Convert.h"
#include "ToHoudiniAttribConverter.h"
#include "SOP_InterpolatedCacheReader.h"
using namespace IECore;
using namespace IECoreHoudini;
static PRM_Name parameterNames[] = {
PRM_Name( "cacheSequence", "Cache Sequence" ),
PRM_Name( "objectFixes", "Object Prefix/Suffix" ),
PRM_Name( "attributeFixes", "Attribute Prefix/Suffix" ),
PRM_Name( "transformAttribute", "Transform Attribute" ),
PRM_Name( "frameMultiplier", "Frame Multiplier" ),
};
static PRM_Default frameMultiplierDefault( 1 );
PRM_Template SOP_InterpolatedCacheReader::parameters[] = {
PRM_Template( PRM_FILE, 1, ¶meterNames[0] ),
PRM_Template( PRM_STRING, 2, ¶meterNames[1] ),
PRM_Template( PRM_STRING, 2, ¶meterNames[2] ),
PRM_Template( PRM_STRING, 1, ¶meterNames[3] ),
PRM_Template( PRM_INT, 1, ¶meterNames[4], &frameMultiplierDefault ),
PRM_Template(),
};
SOP_InterpolatedCacheReader::SOP_InterpolatedCacheReader( OP_Network *net, const char *name, OP_Operator *op )
: SOP_Node( net, name, op ), m_cache( 0 ), m_cacheFileName(), m_frameMultiplier( -1 )
{
flags().setTimeDep( true );
}
SOP_InterpolatedCacheReader::~SOP_InterpolatedCacheReader()
{
}
OP_Node *SOP_InterpolatedCacheReader::create( OP_Network *net, const char *name, OP_Operator *op )
{
return new SOP_InterpolatedCacheReader( net, name, op );
}
OP_ERROR SOP_InterpolatedCacheReader::cookMySop( OP_Context &context )
{
flags().setTimeDep( true );
if ( lockInputs( context ) >= UT_ERROR_ABORT )
{
return error();
}
gdp->stashAll();
float time = context.getTime();
float frame = context.getFloatFrame();
UT_String paramVal;
evalString( paramVal, "cacheSequence", 0, time );
std::string cacheFileName = paramVal.toStdString();
evalString( paramVal, "objectFixes", 0, time );
std::string objectPrefix = paramVal.toStdString();
evalString( paramVal, "objectFixes", 1, time );
std::string objectSuffix = paramVal.toStdString();
evalString( paramVal, "attributeFixes", 0, time );
std::string attributePrefix = paramVal.toStdString();
evalString( paramVal, "attributeFixes", 1, time );
std::string attributeSuffix = paramVal.toStdString();
evalString( paramVal, "transformAttribute", 0, time );
std::string transformAttribute = paramVal.toStdString();
int frameMultiplier = evalInt( "frameMultiplier", 0, time );
// create the InterpolatedCache
if ( cacheFileName.compare( m_cacheFileName ) != 0 || frameMultiplier != m_frameMultiplier )
{
try
{
float fps = OPgetDirector()->getChannelManager()->getSamplesPerSec();
OversamplesCalculator calc( fps, 1, (int)fps * frameMultiplier );
m_cache = new InterpolatedCache( cacheFileName, InterpolatedCache::Linear, calc );
}
catch ( IECore::InvalidArgumentException e )
{
addWarning( SOP_ATTRIBUTE_INVALID, e.what() );
unlockInputs();
return error();
}
m_cacheFileName = cacheFileName;
m_frameMultiplier = frameMultiplier;
}
if ( !m_cache )
{
addWarning( SOP_MESSAGE, "SOP_InterpolatedCacheReader: Cache Sequence not found" );
unlockInputs();
return error();
}
std::vector<InterpolatedCache::ObjectHandle> objects;
std::vector<InterpolatedCache::AttributeHandle> attrs;
try
{
m_cache->objects( frame, objects );
}
catch ( IECore::Exception e )
{
addWarning( SOP_ATTRIBUTE_INVALID, e.what() );
unlockInputs();
return error();
}
duplicatePointSource( 0, context );
for ( GA_GroupTable::iterator<GA_ElementGroup> it=gdp->pointGroups().beginTraverse(); !it.atEnd(); ++it )
{
GA_PointGroup *group = (GA_PointGroup*)it.group();
if ( group->getInternal() || group->isEmpty() )
{
continue;
}
// match GA_PointGroup name to InterpolatedCache::ObjectHandle
std::string searchName = objectPrefix + group->getName().toStdString() + objectSuffix;
std::vector<InterpolatedCache::ObjectHandle>::iterator oIt = find( objects.begin(), objects.end(), searchName );
if ( oIt == objects.end() )
{
continue;
}
CompoundObjectPtr attributes = 0;
try
{
m_cache->attributes( frame, *oIt, attrs );
attributes = m_cache->read( frame, *oIt );
}
catch ( IECore::Exception e )
{
addError( SOP_ATTRIBUTE_INVALID, e.what() );
unlockInputs();
return error();
}
const CompoundObject::ObjectMap &attributeMap = attributes->members();
GA_Range pointRange = gdp->getPointRange( group );
// transfer the InterpolatedCache::Attributes onto the GA_PointGroup
/// \todo: this does not account for detail, prim, or vertex attribs...
for ( CompoundObject::ObjectMap::const_iterator aIt=attributeMap.begin(); aIt != attributeMap.end(); aIt++ )
{
const Data *data = IECore::runTimeCast<const Data>( aIt->second );
if ( !data )
{
continue;
}
ToHoudiniAttribConverterPtr converter = ToHoudiniAttribConverter::create( data );
if ( !converter )
{
continue;
}
// strip the prefix/suffix from the GA_Attribute name
std::string attrName = aIt->first.value();
size_t prefixLength = attributePrefix.length();
if ( prefixLength && ( search( attrName.begin(), attrName.begin()+prefixLength, attributePrefix.begin(), attributePrefix.end() ) == attrName.begin() ) )
{
attrName.erase( attrName.begin(), attrName.begin() + prefixLength );
}
size_t suffixLength = attributeSuffix.length();
if ( suffixLength && ( search( attrName.end() - suffixLength, attrName.end(), attributeSuffix.begin(), attributeSuffix.end() ) == ( attrName.end() - suffixLength ) ) )
{
attrName.erase( attrName.end() - suffixLength, attrName.end() );
}
if ( attrName == "P" )
{
const V3fVectorData *positions = IECore::runTimeCast<const V3fVectorData>( data );
if ( !positions )
{
continue;
}
size_t index = 0;
size_t entries = pointRange.getEntries();
const std::vector<Imath::V3f> &pos = positions->readable();
// Attempting to account for the vertex difference between an IECore::CurvesPrimitive and Houdini curves.
// As Houdini implicitly triples the endpoints of a curve, a cache generated from a single CurvesPrimitive
// will have exactly four extra vertices. In this case, we adjust the cache by ignoring the first two and
// last two V3fs. In all other cases, we report a warning and don't apply the cache to these points.
if ( pos.size() - 4 == entries )
{
index = 2;
}
else if ( pos.size() != entries )
{
addWarning( SOP_ATTRIBUTE_INVALID, ( boost::format( "Geometry/Cache mismatch: %s contains %d points, while cache expects %d." ) % group->getName().toStdString() % entries % pos.size() ).str().c_str() );
continue;
}
/// \todo: try multi-threading this with a GA_SplittableRange
for ( GA_Iterator it=pointRange.begin(); !it.atEnd(); ++it, ++index )
{
gdp->setPos3( it.getOffset(), IECore::convert<UT_Vector3>( pos[index] ) );
}
}
else
{
converter->convert( attrName, gdp, pointRange );
}
}
// if transformAttribute is specified, use to to transform the points
if ( transformAttribute != "" )
{
const TransformationMatrixdData *transform = attributes->member<TransformationMatrixdData>( transformAttribute );
if ( transform )
{
transformPoints<double>( transform->readable(), pointRange );
}
else
{
const TransformationMatrixfData *transform = attributes->member<TransformationMatrixfData>( transformAttribute );
if ( transform )
{
transformPoints<float>( transform->readable(), pointRange );
}
}
}
}
unlockInputs();
return error();
}
template<typename T>
void SOP_InterpolatedCacheReader::transformPoints( const IECore::TransformationMatrix<T> &transform, const GA_Range &range )
{
UT_Matrix4T<T> matrix = IECore::convert<UT_Matrix4T<T> >( transform.transform() );
/// \todo: try multi-threading this with a GA_SplittableRange
for ( GA_Iterator it=range.begin(); !it.atEnd(); ++it )
{
gdp->setPos3( it.getOffset(), gdp->getPos3( it.getOffset() ) * matrix );
}
}
<|endoftext|> |
<commit_before>// Copyright eeGeo Ltd (2012-2014), All Rights Reserved
#include <jni.h>
#include <android/native_window.h>
#include <android/native_window_jni.h>
#include <android/asset_manager.h>
#include <android/asset_manager_jni.h>
#include <pthread.h>
#include "AppRunner.h"
#include "main.h"
#include "Logger.h"
#include "AndroidAppThreadAssertions.h"
using namespace Eegeo::Android;
using namespace Eegeo::Android::Input;
AndroidNativeState g_nativeState;
AppRunner* g_pAppRunner;
namespace
{
void FillEventFromJniData(
JNIEnv* jenv,
jint primaryActionIndex,
jint primaryActionIdentifier,
jint numPointers,
jfloatArray x,
jfloatArray y,
jintArray pointerIdentity,
jintArray pointerIndex,
TouchInputEvent& event);
}
JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* pvt)
{
ExampleApp::AndroidAppThreadAssertions::NominateCurrentlyRunningThreadAsUiThread();
g_nativeState.vm = vm;
return JNI_VERSION_1_6;
}
//lifecycle
JNIEXPORT long JNICALL Java_com_eegeo_mobileexampleapp_NativeJniCalls_createNativeCode(JNIEnv* jenv, jobject obj, jobject activity, jobject assetManager, jfloat dpi)
{
EXAMPLE_LOG("startNativeCode\n");
ExampleApp::AndroidAppThreadAssertions::NominateCurrentlyRunningThreadAsNativeThread();
g_nativeState.javaMainThread = pthread_self();
g_nativeState.mainThreadEnv = jenv;
g_nativeState.activity = jenv->NewGlobalRef(activity);
g_nativeState.activityClass = (jclass)jenv->NewGlobalRef(jenv->FindClass("com/eegeo/mobileexampleapp/MainActivity"));
g_nativeState.deviceDpi = dpi;
jmethodID getClassLoader = jenv->GetMethodID(g_nativeState.activityClass,"getClassLoader", "()Ljava/lang/ClassLoader;");
g_nativeState.classLoader = jenv->NewGlobalRef(jenv->CallObjectMethod(activity, getClassLoader));
g_nativeState.classLoaderClass = (jclass)jenv->NewGlobalRef(jenv->FindClass("java/lang/ClassLoader"));
g_nativeState.classLoaderLoadClassMethod = jenv->GetMethodID(g_nativeState.classLoaderClass, "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;");
g_nativeState.DetermineDeviceModel(jenv);
jthrowable exc;
exc = jenv->ExceptionOccurred();
if (exc)
{
jenv->ExceptionDescribe();
jenv->ExceptionClear();
return 0;
}
g_nativeState.assetManagerGlobalRef = jenv->NewGlobalRef(assetManager);
g_nativeState.assetManager = AAssetManager_fromJava(jenv, g_nativeState.assetManagerGlobalRef);
g_pAppRunner = Eegeo_NEW(AppRunner)(&g_nativeState);
return ((long)g_pAppRunner);
}
JNIEXPORT void JNICALL Java_com_eegeo_mobileexampleapp_NativeJniCalls_stopUpdatingNativeCode(JNIEnv* jenv, jobject obj)
{
g_pAppRunner->StopUpdatingNativeBeforeTeardown();
}
JNIEXPORT void JNICALL Java_com_eegeo_mobileexampleapp_NativeJniCalls_destroyNativeCode(JNIEnv* jenv, jobject obj)
{
EXAMPLE_LOG("stopNativeCode()\n");
Eegeo_DELETE g_pAppRunner;
g_pAppRunner = NULL;
jenv->DeleteGlobalRef(g_nativeState.assetManagerGlobalRef);
jenv->DeleteGlobalRef(g_nativeState.activity);
jenv->DeleteGlobalRef(g_nativeState.activityClass);
jenv->DeleteGlobalRef(g_nativeState.classLoaderClass);
jenv->DeleteGlobalRef(g_nativeState.classLoader);
ExampleApp::AndroidAppThreadAssertions::RemoveNominationForNativeThread();
}
JNIEXPORT void JNICALL Java_com_eegeo_mobileexampleapp_NativeJniCalls_pauseNativeCode(JNIEnv* jenv, jobject obj)
{
g_pAppRunner->Pause();
}
JNIEXPORT void JNICALL Java_com_eegeo_mobileexampleapp_NativeJniCalls_resumeNativeCode(JNIEnv* jenv, jobject obj)
{
g_pAppRunner->Resume();
}
JNIEXPORT void JNICALL Java_com_eegeo_mobileexampleapp_NativeJniCalls_updateNativeCode(JNIEnv* jenv, jobject obj, jfloat deltaSeconds)
{
g_pAppRunner->UpdateNative((float)deltaSeconds);
}
JNIEXPORT void JNICALL Java_com_eegeo_mobileexampleapp_NativeJniCalls_updateUiViewCode(JNIEnv* jenv, jobject obj, jfloat deltaSeconds)
{
g_pAppRunner->UpdateUiViews((float)deltaSeconds);
}
JNIEXPORT void JNICALL Java_com_eegeo_mobileexampleapp_NativeJniCalls_destroyApplicationUi(JNIEnv* jenv, jobject obj)
{
g_pAppRunner->DestroyApplicationUi();
}
JNIEXPORT void JNICALL Java_com_eegeo_mobileexampleapp_NativeJniCalls_setNativeSurface(JNIEnv* jenv, jobject obj, jobject surface)
{
ANativeWindow* newWindow = ANativeWindow_fromSurface(jenv, surface);
if (g_nativeState.window == newWindow)
{
// we can get same surface after resume from screen lock
return;
}
if(g_nativeState.window != NULL)
{
ANativeWindow_release(g_nativeState.window);
g_nativeState.window = NULL;
}
if (surface != NULL)
{
g_nativeState.window = newWindow;
if (g_nativeState.window != NULL)
{
g_pAppRunner->ActivateSurface();
}
}
}
JNIEXPORT void JNICALL Java_com_eegeo_mobileexampleapp_EegeoSurfaceView_processNativePointerDown(JNIEnv* jenv, jobject obj,
jint primaryActionIndex,
jint primaryActionIdentifier,
jint numPointers,
jfloatArray x,
jfloatArray y,
jintArray pointerIdentity,
jintArray pointerIndex)
{
TouchInputEvent event(false, true, primaryActionIndex, primaryActionIdentifier);
FillEventFromJniData(jenv, primaryActionIndex, primaryActionIdentifier, numPointers, x, y, pointerIdentity, pointerIndex, event);
g_pAppRunner->HandleTouchEvent(event);
}
JNIEXPORT void JNICALL Java_com_eegeo_mobileexampleapp_EegeoSurfaceView_processNativePointerUp(JNIEnv* jenv, jobject obj,
jint primaryActionIndex,
jint primaryActionIdentifier,
jint numPointers,
jfloatArray x,
jfloatArray y,
jintArray pointerIdentity,
jintArray pointerIndex)
{
TouchInputEvent event(true, false, primaryActionIndex, primaryActionIdentifier);
FillEventFromJniData(jenv, primaryActionIndex, primaryActionIdentifier, numPointers, x, y, pointerIdentity, pointerIndex, event);
g_pAppRunner->HandleTouchEvent(event);
}
JNIEXPORT void JNICALL Java_com_eegeo_mobileexampleapp_EegeoSurfaceView_processNativePointerMove(JNIEnv* jenv, jobject obj,
jint primaryActionIndex,
jint primaryActionIdentifier,
jint numPointers,
jfloatArray x,
jfloatArray y,
jintArray pointerIdentity,
jintArray pointerIndex)
{
TouchInputEvent event(false, false, primaryActionIndex, primaryActionIdentifier);
FillEventFromJniData(jenv, primaryActionIndex, primaryActionIdentifier, numPointers, x, y, pointerIdentity, pointerIndex, event);
g_pAppRunner->HandleTouchEvent(event);
}
namespace
{
void FillEventFromJniData(
JNIEnv* jenv,
jint primaryActionIndex,
jint primaryActionIdentifier,
jint numPointers,
jfloatArray x,
jfloatArray y,
jintArray pointerIdentity,
jintArray pointerIndex,
TouchInputEvent& event)
{
jfloat* xBuffer = jenv->GetFloatArrayElements(x, 0);
jfloat* yBuffer = jenv->GetFloatArrayElements(y, 0);
jint* identityBuffer = jenv->GetIntArrayElements(pointerIdentity, 0);
jint* indexBuffer = jenv->GetIntArrayElements(pointerIndex, 0);
for(int i = 0; i < numPointers; ++ i)
{
TouchInputPointerEvent p(xBuffer[i], yBuffer[i], identityBuffer[i], indexBuffer[i]);
event.pointerEvents.push_back(p);
}
jenv->ReleaseFloatArrayElements(x, xBuffer, 0);
jenv->ReleaseFloatArrayElements(y, yBuffer, 0);
jenv->ReleaseIntArrayElements(pointerIdentity, identityBuffer, 0);
jenv->ReleaseIntArrayElements(pointerIndex, indexBuffer, 0);
}
}
<commit_msg>MPLY-5268 'Changing orientation on Android orientation_v2 will show around half the screen appearing black'. Buddy: Ian<commit_after>// Copyright eeGeo Ltd (2012-2014), All Rights Reserved
#include <jni.h>
#include <android/native_window.h>
#include <android/native_window_jni.h>
#include <android/asset_manager.h>
#include <android/asset_manager_jni.h>
#include <pthread.h>
#include "AppRunner.h"
#include "main.h"
#include "Logger.h"
#include "AndroidAppThreadAssertions.h"
using namespace Eegeo::Android;
using namespace Eegeo::Android::Input;
AndroidNativeState g_nativeState;
AppRunner* g_pAppRunner;
namespace
{
void FillEventFromJniData(
JNIEnv* jenv,
jint primaryActionIndex,
jint primaryActionIdentifier,
jint numPointers,
jfloatArray x,
jfloatArray y,
jintArray pointerIdentity,
jintArray pointerIndex,
TouchInputEvent& event);
}
JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* pvt)
{
ExampleApp::AndroidAppThreadAssertions::NominateCurrentlyRunningThreadAsUiThread();
g_nativeState.vm = vm;
return JNI_VERSION_1_6;
}
//lifecycle
JNIEXPORT long JNICALL Java_com_eegeo_mobileexampleapp_NativeJniCalls_createNativeCode(JNIEnv* jenv, jobject obj, jobject activity, jobject assetManager, jfloat dpi)
{
EXAMPLE_LOG("startNativeCode\n");
ExampleApp::AndroidAppThreadAssertions::NominateCurrentlyRunningThreadAsNativeThread();
g_nativeState.javaMainThread = pthread_self();
g_nativeState.mainThreadEnv = jenv;
g_nativeState.activity = jenv->NewGlobalRef(activity);
g_nativeState.activityClass = (jclass)jenv->NewGlobalRef(jenv->FindClass("com/eegeo/mobileexampleapp/MainActivity"));
g_nativeState.deviceDpi = dpi;
jmethodID getClassLoader = jenv->GetMethodID(g_nativeState.activityClass,"getClassLoader", "()Ljava/lang/ClassLoader;");
g_nativeState.classLoader = jenv->NewGlobalRef(jenv->CallObjectMethod(activity, getClassLoader));
g_nativeState.classLoaderClass = (jclass)jenv->NewGlobalRef(jenv->FindClass("java/lang/ClassLoader"));
g_nativeState.classLoaderLoadClassMethod = jenv->GetMethodID(g_nativeState.classLoaderClass, "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;");
g_nativeState.DetermineDeviceModel(jenv);
jthrowable exc;
exc = jenv->ExceptionOccurred();
if (exc)
{
jenv->ExceptionDescribe();
jenv->ExceptionClear();
return 0;
}
g_nativeState.assetManagerGlobalRef = jenv->NewGlobalRef(assetManager);
g_nativeState.assetManager = AAssetManager_fromJava(jenv, g_nativeState.assetManagerGlobalRef);
g_pAppRunner = Eegeo_NEW(AppRunner)(&g_nativeState);
return ((long)g_pAppRunner);
}
JNIEXPORT void JNICALL Java_com_eegeo_mobileexampleapp_NativeJniCalls_stopUpdatingNativeCode(JNIEnv* jenv, jobject obj)
{
g_pAppRunner->StopUpdatingNativeBeforeTeardown();
}
JNIEXPORT void JNICALL Java_com_eegeo_mobileexampleapp_NativeJniCalls_destroyNativeCode(JNIEnv* jenv, jobject obj)
{
EXAMPLE_LOG("stopNativeCode()\n");
Eegeo_DELETE g_pAppRunner;
g_pAppRunner = NULL;
jenv->DeleteGlobalRef(g_nativeState.assetManagerGlobalRef);
jenv->DeleteGlobalRef(g_nativeState.activity);
jenv->DeleteGlobalRef(g_nativeState.activityClass);
jenv->DeleteGlobalRef(g_nativeState.classLoaderClass);
jenv->DeleteGlobalRef(g_nativeState.classLoader);
ExampleApp::AndroidAppThreadAssertions::RemoveNominationForNativeThread();
}
JNIEXPORT void JNICALL Java_com_eegeo_mobileexampleapp_NativeJniCalls_pauseNativeCode(JNIEnv* jenv, jobject obj)
{
g_pAppRunner->Pause();
}
JNIEXPORT void JNICALL Java_com_eegeo_mobileexampleapp_NativeJniCalls_resumeNativeCode(JNIEnv* jenv, jobject obj)
{
g_pAppRunner->Resume();
}
JNIEXPORT void JNICALL Java_com_eegeo_mobileexampleapp_NativeJniCalls_updateNativeCode(JNIEnv* jenv, jobject obj, jfloat deltaSeconds)
{
g_pAppRunner->UpdateNative((float)deltaSeconds);
}
JNIEXPORT void JNICALL Java_com_eegeo_mobileexampleapp_NativeJniCalls_updateUiViewCode(JNIEnv* jenv, jobject obj, jfloat deltaSeconds)
{
g_pAppRunner->UpdateUiViews((float)deltaSeconds);
}
JNIEXPORT void JNICALL Java_com_eegeo_mobileexampleapp_NativeJniCalls_destroyApplicationUi(JNIEnv* jenv, jobject obj)
{
g_pAppRunner->DestroyApplicationUi();
}
JNIEXPORT void JNICALL Java_com_eegeo_mobileexampleapp_NativeJniCalls_setNativeSurface(JNIEnv* jenv, jobject obj, jobject surface)
{
if(g_nativeState.window != NULL)
{
ANativeWindow_release(g_nativeState.window);
g_nativeState.window = NULL;
}
if (surface != NULL)
{
g_nativeState.window = ANativeWindow_fromSurface(jenv, surface);
if (g_nativeState.window != NULL)
{
g_pAppRunner->ActivateSurface();
}
}
}
JNIEXPORT void JNICALL Java_com_eegeo_mobileexampleapp_EegeoSurfaceView_processNativePointerDown(JNIEnv* jenv, jobject obj,
jint primaryActionIndex,
jint primaryActionIdentifier,
jint numPointers,
jfloatArray x,
jfloatArray y,
jintArray pointerIdentity,
jintArray pointerIndex)
{
TouchInputEvent event(false, true, primaryActionIndex, primaryActionIdentifier);
FillEventFromJniData(jenv, primaryActionIndex, primaryActionIdentifier, numPointers, x, y, pointerIdentity, pointerIndex, event);
g_pAppRunner->HandleTouchEvent(event);
}
JNIEXPORT void JNICALL Java_com_eegeo_mobileexampleapp_EegeoSurfaceView_processNativePointerUp(JNIEnv* jenv, jobject obj,
jint primaryActionIndex,
jint primaryActionIdentifier,
jint numPointers,
jfloatArray x,
jfloatArray y,
jintArray pointerIdentity,
jintArray pointerIndex)
{
TouchInputEvent event(true, false, primaryActionIndex, primaryActionIdentifier);
FillEventFromJniData(jenv, primaryActionIndex, primaryActionIdentifier, numPointers, x, y, pointerIdentity, pointerIndex, event);
g_pAppRunner->HandleTouchEvent(event);
}
JNIEXPORT void JNICALL Java_com_eegeo_mobileexampleapp_EegeoSurfaceView_processNativePointerMove(JNIEnv* jenv, jobject obj,
jint primaryActionIndex,
jint primaryActionIdentifier,
jint numPointers,
jfloatArray x,
jfloatArray y,
jintArray pointerIdentity,
jintArray pointerIndex)
{
TouchInputEvent event(false, false, primaryActionIndex, primaryActionIdentifier);
FillEventFromJniData(jenv, primaryActionIndex, primaryActionIdentifier, numPointers, x, y, pointerIdentity, pointerIndex, event);
g_pAppRunner->HandleTouchEvent(event);
}
namespace
{
void FillEventFromJniData(
JNIEnv* jenv,
jint primaryActionIndex,
jint primaryActionIdentifier,
jint numPointers,
jfloatArray x,
jfloatArray y,
jintArray pointerIdentity,
jintArray pointerIndex,
TouchInputEvent& event)
{
jfloat* xBuffer = jenv->GetFloatArrayElements(x, 0);
jfloat* yBuffer = jenv->GetFloatArrayElements(y, 0);
jint* identityBuffer = jenv->GetIntArrayElements(pointerIdentity, 0);
jint* indexBuffer = jenv->GetIntArrayElements(pointerIndex, 0);
for(int i = 0; i < numPointers; ++ i)
{
TouchInputPointerEvent p(xBuffer[i], yBuffer[i], identityBuffer[i], indexBuffer[i]);
event.pointerEvents.push_back(p);
}
jenv->ReleaseFloatArrayElements(x, xBuffer, 0);
jenv->ReleaseFloatArrayElements(y, yBuffer, 0);
jenv->ReleaseIntArrayElements(pointerIdentity, identityBuffer, 0);
jenv->ReleaseIntArrayElements(pointerIndex, indexBuffer, 0);
}
}
<|endoftext|> |
<commit_before>//
// TimedEventLoop.cpp
// Clock Signal
//
// Created by Thomas Harte on 29/07/2016.
// Copyright © 2016 Thomas Harte. All rights reserved.
//
#include "TimedEventLoop.hpp"
#include "../NumberTheory/Factors.hpp"
#include <algorithm>
#include <cassert>
using namespace Storage;
TimedEventLoop::TimedEventLoop(unsigned int input_clock_rate) :
input_clock_rate_(input_clock_rate) {}
void TimedEventLoop::run_for(const Cycles cycles) {
int remaining_cycles = cycles.as_int();
#ifndef NDEBUG
int cycles_advanced = 0;
#endif
while(cycles_until_event_ <= remaining_cycles) {
#ifndef NDEBUG
cycles_advanced += cycles_until_event_;
#endif
advance(cycles_until_event_);
remaining_cycles -= cycles_until_event_;
cycles_until_event_ = 0;
process_next_event();
}
if(remaining_cycles) {
cycles_until_event_ -= remaining_cycles;
#ifndef NDEBUG
cycles_advanced += remaining_cycles;
#endif
advance(remaining_cycles);
}
assert(cycles_advanced == cycles.as_int());
assert(cycles_until_event_ > 0);
}
unsigned int TimedEventLoop::get_cycles_until_next_event() {
return (unsigned int)std::max(cycles_until_event_, 0);
}
unsigned int TimedEventLoop::get_input_clock_rate() {
return input_clock_rate_;
}
void TimedEventLoop::reset_timer() {
subcycles_until_event_.set_zero();
cycles_until_event_ = 0;
}
void TimedEventLoop::jump_to_next_event() {
reset_timer();
process_next_event();
}
void TimedEventLoop::set_next_event_time_interval(Time interval) {
// Calculate [interval]*[input clock rate] + [subcycles until this event].
int64_t denominator = (int64_t)interval.clock_rate * (int64_t)subcycles_until_event_.clock_rate;
int64_t numerator =
(int64_t)subcycles_until_event_.clock_rate * (int64_t)input_clock_rate_ * (int64_t)interval.length +
(int64_t)interval.clock_rate * (int64_t)subcycles_until_event_.length;
// Simplify if necessary.
if(denominator > std::numeric_limits<unsigned int>::max()) {
int64_t common_divisor = NumberTheory::greatest_common_divisor(numerator % denominator, denominator);
denominator /= common_divisor;
numerator /= common_divisor;
}
// So this event will fire in the integral number of cycles from now, putting us at the remainder
// number of subcycles
assert(cycles_until_event_ == 0);
cycles_until_event_ += (int)(numerator / denominator);
assert(cycles_until_event_ >= 0);
subcycles_until_event_.length = (unsigned int)(numerator % denominator);
subcycles_until_event_.clock_rate = (unsigned int)denominator;
}
Time TimedEventLoop::get_time_into_next_event() {
// TODO: calculate, presumably as [length of interval] - ([cycles left] + [subcycles left])
Time zero;
return zero;
}
<commit_msg>Added an additional protection against overflow.<commit_after>//
// TimedEventLoop.cpp
// Clock Signal
//
// Created by Thomas Harte on 29/07/2016.
// Copyright © 2016 Thomas Harte. All rights reserved.
//
#include "TimedEventLoop.hpp"
#include "../NumberTheory/Factors.hpp"
#include <algorithm>
#include <cassert>
using namespace Storage;
TimedEventLoop::TimedEventLoop(unsigned int input_clock_rate) :
input_clock_rate_(input_clock_rate) {}
void TimedEventLoop::run_for(const Cycles cycles) {
int remaining_cycles = cycles.as_int();
#ifndef NDEBUG
int cycles_advanced = 0;
#endif
while(cycles_until_event_ <= remaining_cycles) {
#ifndef NDEBUG
cycles_advanced += cycles_until_event_;
#endif
advance(cycles_until_event_);
remaining_cycles -= cycles_until_event_;
cycles_until_event_ = 0;
process_next_event();
}
if(remaining_cycles) {
cycles_until_event_ -= remaining_cycles;
#ifndef NDEBUG
cycles_advanced += remaining_cycles;
#endif
advance(remaining_cycles);
}
assert(cycles_advanced == cycles.as_int());
assert(cycles_until_event_ > 0);
}
unsigned int TimedEventLoop::get_cycles_until_next_event() {
return (unsigned int)std::max(cycles_until_event_, 0);
}
unsigned int TimedEventLoop::get_input_clock_rate() {
return input_clock_rate_;
}
void TimedEventLoop::reset_timer() {
subcycles_until_event_.set_zero();
cycles_until_event_ = 0;
}
void TimedEventLoop::jump_to_next_event() {
reset_timer();
process_next_event();
}
void TimedEventLoop::set_next_event_time_interval(Time interval) {
// Calculate [interval]*[input clock rate] + [subcycles until this event].
int64_t denominator = (int64_t)interval.clock_rate * (int64_t)subcycles_until_event_.clock_rate;
int64_t numerator =
(int64_t)subcycles_until_event_.clock_rate * (int64_t)input_clock_rate_ * (int64_t)interval.length +
(int64_t)interval.clock_rate * (int64_t)subcycles_until_event_.length;
// Simplify if necessary.
if(denominator > std::numeric_limits<unsigned int>::max()) {
int64_t common_divisor = NumberTheory::greatest_common_divisor(numerator % denominator, denominator);
denominator /= common_divisor;
numerator /= common_divisor;
}
// So this event will fire in the integral number of cycles from now, putting us at the remainder
// number of subcycles
assert(cycles_until_event_ == 0);
cycles_until_event_ += (int)(numerator / denominator);
assert(cycles_until_event_ >= 0);
subcycles_until_event_.length = (unsigned int)(numerator % denominator);
subcycles_until_event_.clock_rate = (unsigned int)denominator;
subcycles_until_event_.simplify();
}
Time TimedEventLoop::get_time_into_next_event() {
// TODO: calculate, presumably as [length of interval] - ([cycles left] + [subcycles left])
Time zero;
return zero;
}
<|endoftext|> |
<commit_before>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
Copyright (c) 2008, 2009 Aristid Breitkreuz, Ash Berlin, Ruediger Sonderfeld
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 <iconv.h>
#include <errno.h>
#include <sstream>
#include <boost/algorithm/string.hpp>
#include "flusspferd/binary.hpp"
#include "flusspferd/encodings.hpp"
#include "flusspferd/create.hpp"
using namespace boost;
using namespace flusspferd;
void flusspferd::load_encodings_module(object container) {
object exports = container.get_property_object("exports");
// Load the binary module
global().call("require", "binary");
create_native_function(
exports,
"convertToString", &encodings::convert_to_string);
create_native_function(
exports,
"convertFromString", &encodings::convert_from_string);
create_native_function( exports, "convert", &encodings::convert);
}
// HELPER METHODS
// Actually do the conversion.
binary::vector_type do_convert(iconv_t conv, binary::vector_type const &in);
// call iconv_open, or throw an error if it cant
iconv_t open_convert(std::string const &from, std::string const &to);
// If no direct conversion is possible, do it via utf8. Helper method
object convert_via_utf8(std::string toEnc, std::string fromEnc,
binary const &source);
string
encodings::convert_to_string(std::string &enc, binary &source_binary) {
binary::vector_type const &source = source_binary.get_const_data();
to_lower(enc);
if (enc == "utf-8") {
binary::vector_type const &source = source_binary.get_const_data();
return string( (char*)&source[0], source.size());
}
else if (enc == "utf-16") {
// TODO: Assert on the possible alignment issue here
binary::vector_type const &source = source_binary.get_const_data();
return string( reinterpret_cast<char16_t const*>(&source[0]), source.size()/2);
}
else {
// Not UTF-8 or UTF-16, so convert to utf-8
// UTF-16 seems to suffer from a byte order issue. UTF-8 is less
// error prone it seems. FIXME
iconv_t conv = open_convert(enc, "utf-8");
binary::vector_type utf8 = do_convert(conv, source);
iconv_close(conv);
return string( reinterpret_cast<char const*>(&utf8[0]), utf8.size());
}
return string();
}
object
encodings::convert_from_string(std::string &enc, string const str) {
binary::vector_type source;
iconv_t conv = open_convert("utf-16", enc);
char16_t const *char_data = str.data();
// TODO: maybe make do_convert take (unsigned char*, size_t)
source.reserve(str.length() * 2);
source.insert(source.begin(),
(unsigned char*)char_data,
(unsigned char*)(char_data+str.length()) );
binary::vector_type const &out = do_convert(conv, source);
iconv_close(conv);
return create_native_object<byte_string>(object(), &out[0], out.size());
}
object encodings::convert(std::string &from, std::string &to,
binary &source_binary)
{
binary::vector_type const &source = source_binary.get_const_data();
to_lower(from);
to_lower(to);
if ( from == to ) {
// Encodings are the same, just return a copy of the binary
return create_native_object<byte_string>(
object(),
&source[0],
source.size()
);
}
iconv_t conv = open_convert(from, to);
binary::vector_type buf = do_convert(conv, source);
iconv_close(conv);
return create_native_object<byte_string>(object(), &buf[0], buf.size());
}
// End JS methods
binary::vector_type
do_convert(iconv_t conv, binary::vector_type const &source) {
binary::vector_type outbuf;
size_t out_left,
in_left = source.size();
out_left = in_left + in_left/16 + 32; // GPSEE's Wild-assed guess.
outbuf.resize(out_left);
const unsigned char *inbytes = &source[0],
*outbytes = &outbuf[0];
while (in_left) {
size_t n = iconv(conv,
(char**)&inbytes, &in_left,
(char**)&outbytes, &out_left
);
if (n == (size_t)(-1)) {
switch (errno) {
case E2BIG: {
// Not enough space in output
// Use GPSEE's WAG again. +32 assumes no encoding needs more than 32
// bytes(!) per character. Probably a safe bet.
size_t new_size = in_left + in_left/4 + 32,
old_size = outbytes - &outbuf[0];
outbuf.resize(old_size + new_size);
// The vector has probably realloced, so recalculate outbytes
outbytes = &outbuf[old_size];
out_left += new_size;
continue;
}
case EILSEQ:
// An invalid multibyte sequence has been encountered in the input.
case EINVAL:
// An incomplete multibyte sequence has been encountered in the input.
// Since we have provided the entire input, both these cases are the
// same.
throw flusspferd::exception("convert error", "TypeError");
break;
}
}
// Else all chars got converted
in_left -= n;
}
outbuf.resize(outbytes - &outbuf[0]);
return outbuf;
}
iconv_t open_convert(std::string const &from, std::string const &to) {
iconv_t conv = iconv_open(to.c_str(), from.c_str());
if (conv == (iconv_t)(-1)) {
std::stringstream ss;
ss << "Unable to convert from \"" << from
<< "\" to \"" << to << "\"";
throw flusspferd::exception(ss.str().c_str());
}
return conv;
}
object
convert_via_utf8(std::string const &to, std::string const &from,
binary const &) {
iconv_t to_utf = iconv_open("utf-8", from.c_str()),
from_utf = iconv_open(to.c_str(), "utf-8");
if (to_utf == (iconv_t)(-1) || from_utf == (iconv_t)(-1)) {
if (to_utf)
iconv_close(to_utf);
if (from_utf)
iconv_close(from_utf);
std::stringstream ss;
ss << "Unable to convert from \"" << from
<< "\" to \"" << to << "\"";
throw flusspferd::exception(ss.str().c_str());
}
return object();
}
<commit_msg>core/encodings: rework internal helper method to take pointer+len<commit_after>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
Copyright (c) 2008, 2009 Aristid Breitkreuz, Ash Berlin, Ruediger Sonderfeld
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 <iconv.h>
#include <errno.h>
#include <sstream>
#include <boost/algorithm/string.hpp>
#include "flusspferd/binary.hpp"
#include "flusspferd/encodings.hpp"
#include "flusspferd/create.hpp"
using namespace boost;
using namespace flusspferd;
void flusspferd::load_encodings_module(object container) {
object exports = container.get_property_object("exports");
// Load the binary module
global().call("require", "binary");
create_native_function(
exports,
"convertToString", &encodings::convert_to_string);
create_native_function(
exports,
"convertFromString", &encodings::convert_from_string);
create_native_function( exports, "convert", &encodings::convert);
}
// HELPER METHODS
// Actually do the conversion.
binary::vector_type do_convert(iconv_t conv, binary::element_type const* data,
size_t bytes);
// call iconv_open, or throw an error if it cant
iconv_t open_convert(std::string const &from, std::string const &to);
// If no direct conversion is possible, do it via utf8. Helper method
object convert_via_utf8(std::string toEnc, std::string fromEnc,
binary const &source);
string
encodings::convert_to_string(std::string &enc, binary &source_binary) {
binary::vector_type const &source = source_binary.get_const_data();
to_lower(enc);
if (enc == "utf-8") {
binary::vector_type const &source = source_binary.get_const_data();
return string( (char*)&source[0], source.size());
}
else if (enc == "utf-16") {
// TODO: Assert on the possible alignment issue here
binary::vector_type const &source = source_binary.get_const_data();
return string( reinterpret_cast<char16_t const*>(&source[0]), source.size()/2);
}
else {
// Not UTF-8 or UTF-16, so convert to utf-8
// UTF-16 seems to suffer from a byte order issue. UTF-8 is less
// error prone it seems. FIXME
iconv_t conv = open_convert(enc, "utf-8");
binary::vector_type utf8 = do_convert(conv, &source[0], source.size());
iconv_close(conv);
return string( reinterpret_cast<char const*>(&utf8[0]), utf8.size());
}
return string();
}
object
encodings::convert_from_string(std::string &enc, string const str) {
binary::vector_type source;
iconv_t conv = open_convert("utf-16", enc);
const unsigned char *char_data = (const unsigned char*)str.data();
binary::vector_type const &out = do_convert(conv, char_data, str.length()*2);
iconv_close(conv);
return create_native_object<byte_string>(object(), &out[0], out.size());
}
object encodings::convert(std::string &from, std::string &to,
binary &source_binary)
{
binary::vector_type const &source = source_binary.get_const_data();
to_lower(from);
to_lower(to);
if ( from == to ) {
// Encodings are the same, just return a copy of the binary
return create_native_object<byte_string>(
object(),
&source[0],
source.size()
);
}
iconv_t conv = open_convert(from, to);
binary::vector_type buf = do_convert(conv, &source[0], source.size());
iconv_close(conv);
return create_native_object<byte_string>(object(), &buf[0], buf.size());
}
// End JS methods
binary::vector_type
do_convert(iconv_t conv, binary::element_type const* data, size_t num_bytes) {
binary::vector_type outbuf;
size_t out_left,
in_left = num_bytes;
// Wikipedia says this:
// The chance of a random string of bytes being valid UTF-8 and not pure
// ASCII is 3.9% for a two-byte sequence, 0.41% for a three-byte sequence
// and 0.026% for a four-byte sequence.
out_left = in_left + in_left/16 + 32; // GPSEE's Wild-assed guess.
outbuf.resize(out_left);
const unsigned char *inbytes = data,
*outbytes = &outbuf[0];
while (in_left) {
size_t n = iconv(conv,
(char**)&inbytes, &in_left,
(char**)&outbytes, &out_left
);
if (n == (size_t)(-1)) {
switch (errno) {
case E2BIG: {
// Not enough space in output
// Use GPSEE's WAG again. +32 assumes no encoding needs more than 32
// bytes(!) per character. Probably a safe bet.
size_t new_size = in_left + in_left/4 + 32,
old_size = outbytes - &outbuf[0];
outbuf.resize(old_size + new_size);
// The vector has probably realloced, so recalculate outbytes
outbytes = &outbuf[old_size];
out_left += new_size;
continue;
}
case EILSEQ:
// An invalid multibyte sequence has been encountered in the input.
case EINVAL:
// An incomplete multibyte sequence has been encountered in the input.
// Since we have provided the entire input, both these cases are the
// same.
throw flusspferd::exception("convert error", "TypeError");
break;
}
}
// Else all chars got converted
in_left -= n;
}
outbuf.resize(outbytes - &outbuf[0]);
return outbuf;
}
iconv_t open_convert(std::string const &from, std::string const &to) {
iconv_t conv = iconv_open(to.c_str(), from.c_str());
if (conv == (iconv_t)(-1)) {
std::stringstream ss;
ss << "Unable to convert from \"" << from
<< "\" to \"" << to << "\"";
throw flusspferd::exception(ss.str().c_str());
}
return conv;
}
object
convert_via_utf8(std::string const &to, std::string const &from,
binary const &) {
iconv_t to_utf = iconv_open("utf-8", from.c_str()),
from_utf = iconv_open(to.c_str(), "utf-8");
if (to_utf == (iconv_t)(-1) || from_utf == (iconv_t)(-1)) {
if (to_utf)
iconv_close(to_utf);
if (from_utf)
iconv_close(from_utf);
std::stringstream ss;
ss << "Unable to convert from \"" << from
<< "\" to \"" << to << "\"";
throw flusspferd::exception(ss.str().c_str());
}
return object();
}
<|endoftext|> |
<commit_before>/******************************************************************************
* Copyright 2017 The Apollo 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 "modules/perception/obstacle/onboard/fusion_subnode.h"
#include <unordered_map>
#include "modules/common/adapters/adapter_manager.h"
#include "modules/common/configs/config_gflags.h"
#include "modules/common/log.h"
#include "modules/perception/common/perception_gflags.h"
#include "modules/perception/onboard/event_manager.h"
#include "modules/perception/onboard/shared_data_manager.h"
#include "modules/perception/onboard/subnode_helper.h"
namespace apollo {
namespace perception {
using apollo::canbus::Chassis;
using apollo::common::ErrorCode;
using apollo::common::Status;
using apollo::common::adapter::AdapterManager;
bool FusionSubnode::InitInternal() {
RegistAllAlgorithm();
AdapterManager::Init(FLAGS_perception_adapter_config_filename);
CHECK(AdapterManager::GetChassis()) << "Chassis is not initialized.";
AdapterManager::AddChassisCallback(&FusionSubnode::OnChassis, this);
CHECK(shared_data_manager_ != nullptr);
fusion_.reset(BaseFusionRegisterer::GetInstanceByName(FLAGS_onboard_fusion));
if (fusion_ == nullptr) {
AERROR << "Failed to get fusion instance: " << FLAGS_onboard_fusion;
return false;
}
if (!fusion_->Init()) {
AERROR << "Failed to init fusion:" << FLAGS_onboard_fusion;
return false;
}
radar_object_data_ = dynamic_cast<RadarObjectData *>(
shared_data_manager_->GetSharedData("RadarObjectData"));
if (radar_object_data_ == nullptr) {
AWARN << "Failed to get RadarObjectData.";
}
lidar_object_data_ = dynamic_cast<LidarObjectData *>(
shared_data_manager_->GetSharedData("LidarObjectData"));
if (lidar_object_data_ == nullptr) {
AWARN << "Failed to get LidarObjectData.";
}
camera_object_data_ = dynamic_cast<CameraObjectData *>(
shared_data_manager_->GetSharedData("CameraObjectData"));
if (camera_object_data_ == nullptr) {
AWARN << "Failed to get CameraObjectData.";
}
fusion_data_ = dynamic_cast<FusionSharedData *>(
shared_data_manager_->GetSharedData("FusionSharedData"));
if (fusion_data_ == nullptr) {
AWARN << "Failed to get FusionSharedData.";
}
lane_shared_data_ = dynamic_cast<LaneSharedData *>(
shared_data_manager_->GetSharedData("LaneSharedData"));
if (lane_shared_data_ == nullptr) {
AERROR << "failed to get shared data instance: LaneSharedData ";
return false;
}
lane_objects_.reset(new LaneObjects());
if (!InitOutputStream()) {
AERROR << "Failed to init output stream.";
return false;
}
AINFO << "Init FusionSubnode succ. Using fusion:" << fusion_->name();
return true;
}
bool FusionSubnode::InitOutputStream() {
// expect reserve_ format:
// pub_driven_event_id:n
// lidar_output_stream : event_id=n&sink_type=m&sink_name=x
// radar_output_stream : event_id=n&sink_type=m&sink_name=x
std::unordered_map<std::string, std::string> reserve_field_map;
if (!SubnodeHelper::ParseReserveField(reserve_, &reserve_field_map)) {
AERROR << "Failed to parse reserve string: " << reserve_;
return false;
}
auto iter = reserve_field_map.find("pub_driven_event_id");
if (iter == reserve_field_map.end()) {
AERROR << "Failed to find pub_driven_event_id:" << reserve_;
return false;
}
pub_driven_event_id_ = static_cast<EventID>(atoi((iter->second).c_str()));
auto lidar_iter = reserve_field_map.find("lidar_event_id");
if (lidar_iter == reserve_field_map.end()) {
AWARN << "Failed to find lidar_event_id:" << reserve_;
AINFO << "lidar_event_id will be set -1";
lidar_event_id_ = -1;
} else {
lidar_event_id_ = static_cast<EventID>(atoi((lidar_iter->second).c_str()));
}
auto radar_iter = reserve_field_map.find("radar_event_id");
if (radar_iter == reserve_field_map.end()) {
AWARN << "Failed to find radar_event_id:" << reserve_;
AINFO << "radar_event_id will be set -1";
radar_event_id_ = -1;
} else {
radar_event_id_ = static_cast<EventID>(atoi((radar_iter->second).c_str()));
}
auto camera_iter = reserve_field_map.find("camera_event_id");
if (camera_iter == reserve_field_map.end()) {
AWARN << "Failed to find camera_event_id:" << reserve_;
AINFO << "camera_event_id will be set -1";
camera_event_id_ = -1;
} else {
camera_event_id_ =
static_cast<EventID>(atoi((camera_iter->second).c_str()));
}
auto lane_iter = reserve_field_map.find("lane_event_id");
if (lane_iter == reserve_field_map.end()) {
AWARN << "Failed to find camera_event_id:" << reserve_;
AINFO << "camera_event_id will be set -1";
lane_event_id_ = -1;
} else {
lane_event_id_ = static_cast<EventID>(atoi((lane_iter->second).c_str()));
}
return true;
}
Status FusionSubnode::ProcEvents() {
for (auto event_meta : sub_meta_events_) {
// ignore lane event from polling
if (event_meta.event_id == lane_event_id_) continue;
std::vector<Event> events;
if (!SubscribeEvents(event_meta, &events)) {
AERROR << "event meta id:" << event_meta.event_id << " "
<< event_meta.from_node << " " << event_meta.to_node;
return Status(ErrorCode::PERCEPTION_ERROR, "Subscribe event fail.");
}
if (events.empty()) {
usleep(500);
continue;
}
Process(event_meta, events);
if (event_meta.event_id != pub_driven_event_id_) {
ADEBUG << "Not pub_driven_event_id, skip to publish."
<< " event_id:" << event_meta.event_id
<< " fused_obj_cnt:" << objects_.size();
continue;
}
// public obstacle message
PerceptionObstacles obstacles;
if (GeneratePbMsg(&obstacles)) {
common::adapter::AdapterManager::PublishPerceptionObstacles(obstacles);
}
AINFO << "Publish 3d perception fused msg. timestamp:"
<< GLOG_TIMESTAMP(timestamp_) << " obj_cnt:" << objects_.size();
}
return Status::OK();
}
Status FusionSubnode::Process(const EventMeta &event_meta,
const std::vector<Event> &events) {
std::vector<SensorObjects> sensor_objs;
if (!BuildSensorObjs(events, &sensor_objs)) {
AERROR << "Failed to build_sensor_objs";
error_code_ = common::PERCEPTION_ERROR_PROCESS;
return Status(ErrorCode::PERCEPTION_ERROR, "Failed to build_sensor_objs.");
}
PERF_BLOCK_START();
objects_.clear();
if (!fusion_->Fuse(sensor_objs, &objects_)) {
AWARN << "Failed to call fusion plugin."
<< " event_meta: [" << event_meta.to_string()
<< "] event_cnt:" << events.size() << " event_0: ["
<< events[0].to_string() << "]";
error_code_ = common::PERCEPTION_ERROR_PROCESS;
return Status(ErrorCode::PERCEPTION_ERROR, "Failed to call fusion plugin.");
}
if (event_meta.event_id == lidar_event_id_) {
PERF_BLOCK_END("fusion_lidar");
} else if (event_meta.event_id == radar_event_id_) {
PERF_BLOCK_END("fusion_radar");
} else if (event_meta.event_id == camera_event_id_) {
PERF_BLOCK_END("fusion_camera");
}
if (objects_.size() > 0 && FLAGS_publish_fusion_event) {
SharedDataPtr<FusionItem> fusion_item_ptr(new FusionItem);
fusion_item_ptr->timestamp = objects_[0]->latest_tracked_time;
const std::string &device_id = events[0].reserve;
for (auto obj : objects_) {
ObjectPtr objclone(new Object());
objclone->clone(*obj);
fusion_item_ptr->obstacles.push_back(objclone);
}
AINFO << "publishing event for timestamp deviceid and size of fusion object"
<< fusion_item_ptr->timestamp << " " << device_id << " "
<< fusion_item_ptr->obstacles.size();
PublishDataAndEvent(fusion_item_ptr->timestamp, device_id, fusion_item_ptr);
}
timestamp_ = sensor_objs[0].timestamp;
error_code_ = common::OK;
return Status::OK();
}
void FusionSubnode::PublishDataAndEvent(const double ×tamp,
const std::string &device_id,
const SharedDataPtr<FusionItem> &data) {
CommonSharedDataKey key(timestamp, device_id);
bool fusion_succ = fusion_data_->Add(key, data);
if (!fusion_succ) {
AERROR << "fusion shared data addkey failure";
}
AINFO << "adding key in fusion shared data " << key.ToString();
for (size_t idx = 0; idx < pub_meta_events_.size(); ++idx) {
const EventMeta &event_meta = pub_meta_events_[idx];
Event event;
event.event_id = event_meta.event_id;
event.timestamp = timestamp;
event.reserve = device_id;
event_manager_->Publish(event);
}
}
bool FusionSubnode::SubscribeEvents(const EventMeta &event_meta,
std::vector<Event> *events) const {
Event event;
// no blocking
while (event_manager_->Subscribe(event_meta.event_id, &event, true)) {
events->push_back(event);
}
return true;
}
bool FusionSubnode::BuildSensorObjs(
const std::vector<Event> &events,
std::vector<SensorObjects> *multi_sensor_objs) {
PERF_FUNCTION();
for (auto event : events) {
std::shared_ptr<SensorObjects> sensor_objects;
if (!GetSharedData(event, &sensor_objects)) {
return false;
}
// Make sure timestamp and type are filled.
sensor_objects->timestamp = event.timestamp;
if (event.event_id == lidar_event_id_) {
sensor_objects->sensor_type = SensorType::VELODYNE_64;
} else if (event.event_id == radar_event_id_) {
sensor_objects->sensor_type = SensorType::RADAR;
} else if (event.event_id == camera_event_id_) {
sensor_objects->sensor_type = SensorType::CAMERA;
} else {
AERROR << "Event id is not supported. event:" << event.to_string();
return false;
}
sensor_objects->sensor_id = GetSensorType(sensor_objects->sensor_type);
multi_sensor_objs->push_back(*sensor_objects);
ADEBUG << "get sensor objs:" << sensor_objects->ToString();
}
return true;
}
bool FusionSubnode::GetSharedData(const Event &event,
std::shared_ptr<SensorObjects> *objs) {
double timestamp = event.timestamp;
const std::string &device_id = event.reserve;
std::string data_key;
if (!SubnodeHelper::ProduceSharedDataKey(timestamp, device_id, &data_key)) {
AERROR << "Failed to produce shared data key. EventID:" << event.event_id
<< " timestamp:" << timestamp << " device_id:" << device_id;
return false;
}
bool get_data_succ = false;
if (event.event_id == lidar_event_id_ && lidar_object_data_ != nullptr) {
get_data_succ = lidar_object_data_->Get(data_key, objs);
} else if (event.event_id == radar_event_id_ &&
radar_object_data_ != nullptr) {
get_data_succ = radar_object_data_->Get(data_key, objs);
} else if (event.event_id == camera_event_id_ &&
camera_object_data_ != nullptr) {
get_data_succ = camera_object_data_->Get(data_key, objs);
// trying to get lane shared data as well
Event lane_event;
if (event_manager_->Subscribe(lane_event_id_, &lane_event, false)) {
get_data_succ = lane_shared_data_->Get(data_key, &lane_objects_);
ADEBUG << "getting lane data successfully for data key " << data_key;
}
} else {
AERROR << "Event id is not supported. event:" << event.to_string();
return false;
}
if (!get_data_succ) {
AERROR << "Failed to get shared data. event:" << event.to_string();
return false;
}
return true;
}
bool FusionSubnode::GeneratePbMsg(PerceptionObstacles *obstacles) {
common::adapter::AdapterManager::FillPerceptionObstaclesHeader(
FLAGS_obstacle_module_name, obstacles);
common::Header *header = obstacles->mutable_header();
if (pub_driven_event_id_ == lidar_event_id_) {
header->set_lidar_timestamp(timestamp_ * 1e9); // in ns
header->set_camera_timestamp(0);
header->set_radar_timestamp(0);
} else if (pub_driven_event_id_ == camera_event_id_) {
header->set_lidar_timestamp(0); // in ns
header->set_camera_timestamp(timestamp_ * 1e9);
header->set_radar_timestamp(0);
}
obstacles->set_error_code(error_code_);
for (const auto &obj : objects_) {
PerceptionObstacle *obstacle = obstacles->add_perception_obstacle();
obj->Serialize(obstacle);
}
if (FLAGS_use_navigation_mode) {
// generate lane marker protobuf messages
LaneMarkers *lane_markers = obstacles->mutable_lane_marker();
LaneObjectsToLaneMarkerProto(*(lane_objects_), lane_markers);
// Relative speed of objects + latest ego car speed in X
for (auto obstacle : obstacles->perception_obstacle()) {
obstacle.mutable_velocity()->set_x(obstacle.velocity().x() +
chassis_speed_mps_);
}
}
ADEBUG << "PerceptionObstacles: " << obstacles->ShortDebugString();
return true;
}
void FusionSubnode::RegistAllAlgorithm() {
RegisterFactoryProbabilisticFusion();
RegisterFactoryAsyncFusion();
}
void FusionSubnode::OnChassis(const Chassis &chassis) {
ADEBUG << "Received chassis data: run chassis callback.";
chassis_.CopyFrom(chassis);
chassis_speed_mps_ = chassis_.speed_mps();
}
} // namespace perception
} // namespace apollo
<commit_msg>fix fusion_subnode init failure (#3656)<commit_after>/******************************************************************************
* Copyright 2017 The Apollo 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 "modules/perception/obstacle/onboard/fusion_subnode.h"
#include <unordered_map>
#include "modules/common/adapters/adapter_manager.h"
#include "modules/common/configs/config_gflags.h"
#include "modules/common/log.h"
#include "modules/perception/common/perception_gflags.h"
#include "modules/perception/onboard/event_manager.h"
#include "modules/perception/onboard/shared_data_manager.h"
#include "modules/perception/onboard/subnode_helper.h"
namespace apollo {
namespace perception {
using apollo::canbus::Chassis;
using apollo::common::ErrorCode;
using apollo::common::Status;
using apollo::common::adapter::AdapterManager;
bool FusionSubnode::InitInternal() {
RegistAllAlgorithm();
AdapterManager::Init(FLAGS_perception_adapter_config_filename);
CHECK(AdapterManager::GetChassis()) << "Chassis is not initialized.";
AdapterManager::AddChassisCallback(&FusionSubnode::OnChassis, this);
CHECK(shared_data_manager_ != nullptr);
fusion_.reset(BaseFusionRegisterer::GetInstanceByName(FLAGS_onboard_fusion));
if (fusion_ == nullptr) {
AERROR << "Failed to get fusion instance: " << FLAGS_onboard_fusion;
return false;
}
if (!fusion_->Init()) {
AERROR << "Failed to init fusion:" << FLAGS_onboard_fusion;
return false;
}
radar_object_data_ = dynamic_cast<RadarObjectData *>(
shared_data_manager_->GetSharedData("RadarObjectData"));
if (radar_object_data_ == nullptr) {
AWARN << "Failed to get RadarObjectData.";
}
lidar_object_data_ = dynamic_cast<LidarObjectData *>(
shared_data_manager_->GetSharedData("LidarObjectData"));
if (lidar_object_data_ == nullptr) {
AWARN << "Failed to get LidarObjectData.";
}
camera_object_data_ = dynamic_cast<CameraObjectData *>(
shared_data_manager_->GetSharedData("CameraObjectData"));
if (camera_object_data_ == nullptr) {
AWARN << "Failed to get CameraObjectData.";
}
fusion_data_ = dynamic_cast<FusionSharedData *>(
shared_data_manager_->GetSharedData("FusionSharedData"));
if (fusion_data_ == nullptr) {
AWARN << "Failed to get FusionSharedData.";
}
lane_shared_data_ = dynamic_cast<LaneSharedData *>(
shared_data_manager_->GetSharedData("LaneSharedData"));
if (lane_shared_data_ == nullptr) {
AWARN << "failed to get shared data instance: LaneSharedData ";
}
lane_objects_.reset(new LaneObjects());
if (!InitOutputStream()) {
AERROR << "Failed to init output stream.";
return false;
}
AINFO << "Init FusionSubnode succ. Using fusion:" << fusion_->name();
return true;
}
bool FusionSubnode::InitOutputStream() {
// expect reserve_ format:
// pub_driven_event_id:n
// lidar_output_stream : event_id=n&sink_type=m&sink_name=x
// radar_output_stream : event_id=n&sink_type=m&sink_name=x
std::unordered_map<std::string, std::string> reserve_field_map;
if (!SubnodeHelper::ParseReserveField(reserve_, &reserve_field_map)) {
AERROR << "Failed to parse reserve string: " << reserve_;
return false;
}
auto iter = reserve_field_map.find("pub_driven_event_id");
if (iter == reserve_field_map.end()) {
AERROR << "Failed to find pub_driven_event_id:" << reserve_;
return false;
}
pub_driven_event_id_ = static_cast<EventID>(atoi((iter->second).c_str()));
auto lidar_iter = reserve_field_map.find("lidar_event_id");
if (lidar_iter == reserve_field_map.end()) {
AWARN << "Failed to find lidar_event_id:" << reserve_;
AINFO << "lidar_event_id will be set -1";
lidar_event_id_ = -1;
} else {
lidar_event_id_ = static_cast<EventID>(atoi((lidar_iter->second).c_str()));
}
auto radar_iter = reserve_field_map.find("radar_event_id");
if (radar_iter == reserve_field_map.end()) {
AWARN << "Failed to find radar_event_id:" << reserve_;
AINFO << "radar_event_id will be set -1";
radar_event_id_ = -1;
} else {
radar_event_id_ = static_cast<EventID>(atoi((radar_iter->second).c_str()));
}
auto camera_iter = reserve_field_map.find("camera_event_id");
if (camera_iter == reserve_field_map.end()) {
AWARN << "Failed to find camera_event_id:" << reserve_;
AINFO << "camera_event_id will be set -1";
camera_event_id_ = -1;
} else {
camera_event_id_ =
static_cast<EventID>(atoi((camera_iter->second).c_str()));
}
auto lane_iter = reserve_field_map.find("lane_event_id");
if (lane_iter == reserve_field_map.end()) {
AWARN << "Failed to find camera_event_id:" << reserve_;
AINFO << "camera_event_id will be set -1";
lane_event_id_ = -1;
} else {
lane_event_id_ = static_cast<EventID>(atoi((lane_iter->second).c_str()));
}
return true;
}
Status FusionSubnode::ProcEvents() {
for (auto event_meta : sub_meta_events_) {
// ignore lane event from polling
if (event_meta.event_id == lane_event_id_) continue;
std::vector<Event> events;
if (!SubscribeEvents(event_meta, &events)) {
AERROR << "event meta id:" << event_meta.event_id << " "
<< event_meta.from_node << " " << event_meta.to_node;
return Status(ErrorCode::PERCEPTION_ERROR, "Subscribe event fail.");
}
if (events.empty()) {
usleep(500);
continue;
}
Process(event_meta, events);
if (event_meta.event_id != pub_driven_event_id_) {
ADEBUG << "Not pub_driven_event_id, skip to publish."
<< " event_id:" << event_meta.event_id
<< " fused_obj_cnt:" << objects_.size();
continue;
}
// public obstacle message
PerceptionObstacles obstacles;
if (GeneratePbMsg(&obstacles)) {
common::adapter::AdapterManager::PublishPerceptionObstacles(obstacles);
}
AINFO << "Publish 3d perception fused msg. timestamp:"
<< GLOG_TIMESTAMP(timestamp_) << " obj_cnt:" << objects_.size();
}
return Status::OK();
}
Status FusionSubnode::Process(const EventMeta &event_meta,
const std::vector<Event> &events) {
std::vector<SensorObjects> sensor_objs;
if (!BuildSensorObjs(events, &sensor_objs)) {
AERROR << "Failed to build_sensor_objs";
error_code_ = common::PERCEPTION_ERROR_PROCESS;
return Status(ErrorCode::PERCEPTION_ERROR, "Failed to build_sensor_objs.");
}
PERF_BLOCK_START();
objects_.clear();
if (!fusion_->Fuse(sensor_objs, &objects_)) {
AWARN << "Failed to call fusion plugin."
<< " event_meta: [" << event_meta.to_string()
<< "] event_cnt:" << events.size() << " event_0: ["
<< events[0].to_string() << "]";
error_code_ = common::PERCEPTION_ERROR_PROCESS;
return Status(ErrorCode::PERCEPTION_ERROR, "Failed to call fusion plugin.");
}
if (event_meta.event_id == lidar_event_id_) {
PERF_BLOCK_END("fusion_lidar");
} else if (event_meta.event_id == radar_event_id_) {
PERF_BLOCK_END("fusion_radar");
} else if (event_meta.event_id == camera_event_id_) {
PERF_BLOCK_END("fusion_camera");
}
if (objects_.size() > 0 && FLAGS_publish_fusion_event) {
SharedDataPtr<FusionItem> fusion_item_ptr(new FusionItem);
fusion_item_ptr->timestamp = objects_[0]->latest_tracked_time;
const std::string &device_id = events[0].reserve;
for (auto obj : objects_) {
ObjectPtr objclone(new Object());
objclone->clone(*obj);
fusion_item_ptr->obstacles.push_back(objclone);
}
AINFO << "publishing event for timestamp deviceid and size of fusion object"
<< fusion_item_ptr->timestamp << " " << device_id << " "
<< fusion_item_ptr->obstacles.size();
PublishDataAndEvent(fusion_item_ptr->timestamp, device_id, fusion_item_ptr);
}
timestamp_ = sensor_objs[0].timestamp;
error_code_ = common::OK;
return Status::OK();
}
void FusionSubnode::PublishDataAndEvent(const double ×tamp,
const std::string &device_id,
const SharedDataPtr<FusionItem> &data) {
CommonSharedDataKey key(timestamp, device_id);
bool fusion_succ = fusion_data_->Add(key, data);
if (!fusion_succ) {
AERROR << "fusion shared data addkey failure";
}
AINFO << "adding key in fusion shared data " << key.ToString();
for (size_t idx = 0; idx < pub_meta_events_.size(); ++idx) {
const EventMeta &event_meta = pub_meta_events_[idx];
Event event;
event.event_id = event_meta.event_id;
event.timestamp = timestamp;
event.reserve = device_id;
event_manager_->Publish(event);
}
}
bool FusionSubnode::SubscribeEvents(const EventMeta &event_meta,
std::vector<Event> *events) const {
Event event;
// no blocking
while (event_manager_->Subscribe(event_meta.event_id, &event, true)) {
events->push_back(event);
}
return true;
}
bool FusionSubnode::BuildSensorObjs(
const std::vector<Event> &events,
std::vector<SensorObjects> *multi_sensor_objs) {
PERF_FUNCTION();
for (auto event : events) {
std::shared_ptr<SensorObjects> sensor_objects;
if (!GetSharedData(event, &sensor_objects)) {
return false;
}
// Make sure timestamp and type are filled.
sensor_objects->timestamp = event.timestamp;
if (event.event_id == lidar_event_id_) {
sensor_objects->sensor_type = SensorType::VELODYNE_64;
} else if (event.event_id == radar_event_id_) {
sensor_objects->sensor_type = SensorType::RADAR;
} else if (event.event_id == camera_event_id_) {
sensor_objects->sensor_type = SensorType::CAMERA;
} else {
AERROR << "Event id is not supported. event:" << event.to_string();
return false;
}
sensor_objects->sensor_id = GetSensorType(sensor_objects->sensor_type);
multi_sensor_objs->push_back(*sensor_objects);
ADEBUG << "get sensor objs:" << sensor_objects->ToString();
}
return true;
}
bool FusionSubnode::GetSharedData(const Event &event,
std::shared_ptr<SensorObjects> *objs) {
double timestamp = event.timestamp;
const std::string &device_id = event.reserve;
std::string data_key;
if (!SubnodeHelper::ProduceSharedDataKey(timestamp, device_id, &data_key)) {
AERROR << "Failed to produce shared data key. EventID:" << event.event_id
<< " timestamp:" << timestamp << " device_id:" << device_id;
return false;
}
bool get_data_succ = false;
if (event.event_id == lidar_event_id_ && lidar_object_data_ != nullptr) {
get_data_succ = lidar_object_data_->Get(data_key, objs);
} else if (event.event_id == radar_event_id_ &&
radar_object_data_ != nullptr) {
get_data_succ = radar_object_data_->Get(data_key, objs);
} else if (event.event_id == camera_event_id_ &&
camera_object_data_ != nullptr) {
get_data_succ = camera_object_data_->Get(data_key, objs);
// trying to get lane shared data as well
Event lane_event;
if (event_manager_->Subscribe(lane_event_id_, &lane_event, false)) {
get_data_succ = lane_shared_data_->Get(data_key, &lane_objects_);
ADEBUG << "getting lane data successfully for data key " << data_key;
}
} else {
AERROR << "Event id is not supported. event:" << event.to_string();
return false;
}
if (!get_data_succ) {
AERROR << "Failed to get shared data. event:" << event.to_string();
return false;
}
return true;
}
bool FusionSubnode::GeneratePbMsg(PerceptionObstacles *obstacles) {
common::adapter::AdapterManager::FillPerceptionObstaclesHeader(
FLAGS_obstacle_module_name, obstacles);
common::Header *header = obstacles->mutable_header();
if (pub_driven_event_id_ == lidar_event_id_) {
header->set_lidar_timestamp(timestamp_ * 1e9); // in ns
header->set_camera_timestamp(0);
header->set_radar_timestamp(0);
} else if (pub_driven_event_id_ == camera_event_id_) {
header->set_lidar_timestamp(0); // in ns
header->set_camera_timestamp(timestamp_ * 1e9);
header->set_radar_timestamp(0);
}
obstacles->set_error_code(error_code_);
for (const auto &obj : objects_) {
PerceptionObstacle *obstacle = obstacles->add_perception_obstacle();
obj->Serialize(obstacle);
}
if (FLAGS_use_navigation_mode) {
// generate lane marker protobuf messages
LaneMarkers *lane_markers = obstacles->mutable_lane_marker();
LaneObjectsToLaneMarkerProto(*(lane_objects_), lane_markers);
// Relative speed of objects + latest ego car speed in X
for (auto obstacle : obstacles->perception_obstacle()) {
obstacle.mutable_velocity()->set_x(obstacle.velocity().x() +
chassis_speed_mps_);
}
}
ADEBUG << "PerceptionObstacles: " << obstacles->ShortDebugString();
return true;
}
void FusionSubnode::RegistAllAlgorithm() {
RegisterFactoryProbabilisticFusion();
RegisterFactoryAsyncFusion();
}
void FusionSubnode::OnChassis(const Chassis &chassis) {
ADEBUG << "Received chassis data: run chassis callback.";
chassis_.CopyFrom(chassis);
chassis_speed_mps_ = chassis_.speed_mps();
}
} // namespace perception
} // namespace apollo
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "gfx/native_theme_linux.h"
#include "base/logging.h"
#include "gfx/size.h"
#include "gfx/rect.h"
namespace gfx {
unsigned int NativeThemeLinux::button_length_ = 14;
unsigned int NativeThemeLinux::scrollbar_width_ = 15;
unsigned int NativeThemeLinux::thumb_inactive_color_ = 0xf0ebe5;
unsigned int NativeThemeLinux::thumb_active_color_ = 0xfaf8f5;
unsigned int NativeThemeLinux::track_color_ = 0xe3ddd8;
#if !defined(OS_CHROMEOS)
// Chromeos has a different look.
// static
NativeThemeLinux* NativeThemeLinux::instance() {
// The global NativeThemeLinux instance.
static NativeThemeLinux s_native_theme;
return &s_native_theme;
}
#endif
NativeThemeLinux::NativeThemeLinux() {
}
NativeThemeLinux::~NativeThemeLinux() {
}
gfx::Size NativeThemeLinux::GetSize(Part part) const {
switch (part) {
case kScrollbarDownArrow:
case kScrollbarUpArrow:
return gfx::Size(scrollbar_width_, button_length_);
case kScrollbarLeftArrow:
case kScrollbarRightArrow:
return gfx::Size(button_length_, scrollbar_width_);
case kScrollbarHorizontalThumb:
// This matches Firefox on Linux.
return gfx::Size(2 * scrollbar_width_, scrollbar_width_);
case kScrollbarVerticalThumb:
// This matches Firefox on Linux.
return gfx::Size(scrollbar_width_, 2 * scrollbar_width_);
break;
case kScrollbarHorizontalTrack:
return gfx::Size(0, scrollbar_width_);
case kScrollbarVerticalTrack:
return gfx::Size(scrollbar_width_, 0);
}
return gfx::Size();
}
void NativeThemeLinux::PaintArrowButton(
skia::PlatformCanvas* canvas,
const gfx::Rect& rect, Part direction, State state) {
int widthMiddle, lengthMiddle;
SkPaint paint;
if (direction == kScrollbarUpArrow || direction == kScrollbarDownArrow) {
widthMiddle = rect.width() / 2 + 1;
lengthMiddle = rect.height() / 2 + 1;
} else {
lengthMiddle = rect.width() / 2 + 1;
widthMiddle = rect.height() / 2 + 1;
}
// Calculate button color.
SkScalar trackHSV[3];
SkColorToHSV(track_color_, trackHSV);
SkColor buttonColor = SaturateAndBrighten(trackHSV, 0, 0.2);
SkColor backgroundColor = buttonColor;
if (state == kPressed) {
SkScalar buttonHSV[3];
SkColorToHSV(buttonColor, buttonHSV);
buttonColor = SaturateAndBrighten(buttonHSV, 0, -0.1);
} else if (state == kHover) {
SkScalar buttonHSV[3];
SkColorToHSV(buttonColor, buttonHSV);
buttonColor = SaturateAndBrighten(buttonHSV, 0, 0.05);
}
SkIRect skrect;
skrect.set(rect.x(), rect.y(), rect.x() + rect.width(), rect.y()
+ rect.height());
// Paint the background (the area visible behind the rounded corners).
paint.setColor(backgroundColor);
canvas->drawIRect(skrect, paint);
// Paint the button's outline and fill the middle
SkPath outline;
switch (direction) {
case kScrollbarUpArrow:
outline.moveTo(rect.x() + 0.5, rect.y() + rect.height() + 0.5);
outline.rLineTo(0, -(rect.height() - 2));
outline.rLineTo(2, -2);
outline.rLineTo(rect.width() - 5, 0);
outline.rLineTo(2, 2);
outline.rLineTo(0, rect.height() - 2);
break;
case kScrollbarDownArrow:
outline.moveTo(rect.x() + 0.5, rect.y() - 0.5);
outline.rLineTo(0, rect.height() - 2);
outline.rLineTo(2, 2);
outline.rLineTo(rect.width() - 5, 0);
outline.rLineTo(2, -2);
outline.rLineTo(0, -(rect.height() - 2));
break;
case kScrollbarRightArrow:
outline.moveTo(rect.x() - 0.5, rect.y() + 0.5);
outline.rLineTo(rect.width() - 2, 0);
outline.rLineTo(2, 2);
outline.rLineTo(0, rect.height() - 5);
outline.rLineTo(-2, 2);
outline.rLineTo(-(rect.width() - 2), 0);
break;
case kScrollbarLeftArrow:
outline.moveTo(rect.x() + rect.width() + 0.5, rect.y() + 0.5);
outline.rLineTo(-(rect.width() - 2), 0);
outline.rLineTo(-2, 2);
outline.rLineTo(0, rect.height() - 5);
outline.rLineTo(2, 2);
outline.rLineTo(rect.width() - 2, 0);
break;
default:
break;
}
outline.close();
paint.setStyle(SkPaint::kFill_Style);
paint.setColor(buttonColor);
canvas->drawPath(outline, paint);
paint.setAntiAlias(true);
paint.setStyle(SkPaint::kStroke_Style);
SkScalar thumbHSV[3];
SkColorToHSV(thumb_inactive_color_, thumbHSV);
paint.setColor(OutlineColor(trackHSV, thumbHSV));
canvas->drawPath(outline, paint);
// If the button is disabled or read-only, the arrow is drawn with the
// outline color.
if (state != kDisabled)
paint.setColor(SK_ColorBLACK);
paint.setAntiAlias(false);
paint.setStyle(SkPaint::kFill_Style);
SkPath path;
// The constants in this block of code are hand-tailored to produce good
// looking arrows without anti-aliasing.
switch (direction) {
case kScrollbarUpArrow:
path.moveTo(rect.x() + widthMiddle - 4, rect.y() + lengthMiddle + 2);
path.rLineTo(7, 0);
path.rLineTo(-4, -4);
break;
case kScrollbarDownArrow:
path.moveTo(rect.x() + widthMiddle - 4, rect.y() + lengthMiddle - 3);
path.rLineTo(7, 0);
path.rLineTo(-4, 4);
break;
case kScrollbarRightArrow:
path.moveTo(rect.x() + lengthMiddle - 3, rect.y() + widthMiddle - 4);
path.rLineTo(0, 7);
path.rLineTo(4, -4);
break;
case kScrollbarLeftArrow:
path.moveTo(rect.x() + lengthMiddle + 1, rect.y() + widthMiddle - 5);
path.rLineTo(0, 9);
path.rLineTo(-4, -4);
break;
default:
break;
}
path.close();
canvas->drawPath(path, paint);
}
void NativeThemeLinux::Paint(skia::PlatformCanvas* canvas,
Part part,
State state,
const gfx::Rect& rect,
const ExtraParams& extra) {
switch (part) {
case kScrollbarDownArrow:
case kScrollbarUpArrow:
case kScrollbarLeftArrow:
case kScrollbarRightArrow:
PaintArrowButton(canvas, rect, part, state);
break;
case kScrollbarHorizontalThumb:
case kScrollbarVerticalThumb:
PaintThumb(canvas, part, state, rect);
break;
case kScrollbarHorizontalTrack:
case kScrollbarVerticalTrack:
PaintTrack(canvas, part, state, extra.scrollbar_track, rect);
break;
}
}
void NativeThemeLinux::PaintTrack(skia::PlatformCanvas* canvas,
Part part,
State state,
const ScrollbarTrackExtraParams& extra_params,
const gfx::Rect& rect) {
SkPaint paint;
SkIRect skrect;
skrect.set(rect.x(), rect.y(), rect.right(), rect.bottom());
SkScalar track_hsv[3];
SkColorToHSV(track_color_, track_hsv);
paint.setColor(SaturateAndBrighten(track_hsv, 0, 0));
canvas->drawIRect(skrect, paint);
SkScalar thumb_hsv[3];
SkColorToHSV(thumb_inactive_color_, thumb_hsv);
paint.setColor(OutlineColor(track_hsv, thumb_hsv));
DrawBox(canvas, rect, paint);
}
void NativeThemeLinux::PaintThumb(skia::PlatformCanvas* canvas,
Part part,
State state,
const gfx::Rect& rect) {
const bool hovered = state == kHover;
const int midx = rect.x() + rect.width() / 2;
const int midy = rect.y() + rect.height() / 2;
const bool vertical = part == kScrollbarVerticalThumb;
SkScalar thumb[3];
SkColorToHSV(hovered ? thumb_active_color_ : thumb_inactive_color_, thumb);
SkPaint paint;
paint.setColor(SaturateAndBrighten(thumb, 0, 0.02));
SkIRect skrect;
if (vertical)
skrect.set(rect.x(), rect.y(), midx + 1, rect.y() + rect.height());
else
skrect.set(rect.x(), rect.y(), rect.x() + rect.width(), midy + 1);
canvas->drawIRect(skrect, paint);
paint.setColor(SaturateAndBrighten(thumb, 0, -0.02));
if (vertical) {
skrect.set(
midx + 1, rect.y(), rect.x() + rect.width(), rect.y() + rect.height());
} else {
skrect.set(
rect.x(), midy + 1, rect.x() + rect.width(), rect.y() + rect.height());
}
canvas->drawIRect(skrect, paint);
SkScalar track[3];
SkColorToHSV(track_color_, track);
paint.setColor(OutlineColor(track, thumb));
DrawBox(canvas, rect, paint);
if (rect.height() > 10 && rect.width() > 10) {
const int grippy_half_width = 2;
const int inter_grippy_offset = 3;
if (vertical) {
DrawHorizLine(canvas,
midx - grippy_half_width,
midx + grippy_half_width,
midy - inter_grippy_offset,
paint);
DrawHorizLine(canvas,
midx - grippy_half_width,
midx + grippy_half_width,
midy,
paint);
DrawHorizLine(canvas,
midx - grippy_half_width,
midx + grippy_half_width,
midy + inter_grippy_offset,
paint);
} else {
DrawVertLine(canvas,
midx - inter_grippy_offset,
midy - grippy_half_width,
midy + grippy_half_width,
paint);
DrawVertLine(canvas,
midx,
midy - grippy_half_width,
midy + grippy_half_width,
paint);
DrawVertLine(canvas,
midx + inter_grippy_offset,
midy - grippy_half_width,
midy + grippy_half_width,
paint);
}
}
}
void NativeThemeLinux::DrawVertLine(SkCanvas* canvas,
int x,
int y1,
int y2,
const SkPaint& paint) const {
SkIRect skrect;
skrect.set(x, y1, x + 1, y2 + 1);
canvas->drawIRect(skrect, paint);
}
void NativeThemeLinux::DrawHorizLine(SkCanvas* canvas,
int x1,
int x2,
int y,
const SkPaint& paint) const {
SkIRect skrect;
skrect.set(x1, y, x2 + 1, y + 1);
canvas->drawIRect(skrect, paint);
}
void NativeThemeLinux::DrawBox(SkCanvas* canvas,
const gfx::Rect& rect,
const SkPaint& paint) const {
const int right = rect.x() + rect.width() - 1;
const int bottom = rect.y() + rect.height() - 1;
DrawHorizLine(canvas, rect.x(), right, rect.y(), paint);
DrawVertLine(canvas, right, rect.y(), bottom, paint);
DrawHorizLine(canvas, rect.x(), right, bottom, paint);
DrawVertLine(canvas, rect.x(), rect.y(), bottom, paint);
}
SkScalar NativeThemeLinux::Clamp(SkScalar value,
SkScalar min,
SkScalar max) const {
return std::min(std::max(value, min), max);
}
SkColor NativeThemeLinux::SaturateAndBrighten(SkScalar* hsv,
SkScalar saturate_amount,
SkScalar brighten_amount) const {
SkScalar color[3];
color[0] = hsv[0];
color[1] = Clamp(hsv[1] + saturate_amount, 0.0, 1.0);
color[2] = Clamp(hsv[2] + brighten_amount, 0.0, 1.0);
return SkHSVToColor(color);
}
SkColor NativeThemeLinux::OutlineColor(SkScalar* hsv1, SkScalar* hsv2) const {
// GTK Theme engines have way too much control over the layout of
// the scrollbar. We might be able to more closely approximate its
// look-and-feel, if we sent whole images instead of just colors
// from the browser to the renderer. But even then, some themes
// would just break.
//
// So, instead, we don't even try to 100% replicate the look of
// the native scrollbar. We render our own version, but we make
// sure to pick colors that blend in nicely with the system GTK
// theme. In most cases, we can just sample a couple of pixels
// from the system scrollbar and use those colors to draw our
// scrollbar.
//
// This works fine for the track color and the overall thumb
// color. But it fails spectacularly for the outline color used
// around the thumb piece. Not all themes have a clearly defined
// outline. For some of them it is partially transparent, and for
// others the thickness is very unpredictable.
//
// So, instead of trying to approximate the system theme, we
// instead try to compute a reasonable looking choice based on the
// known color of the track and the thumb piece. This is difficult
// when trying to deal both with high- and low-contrast themes,
// and both with positive and inverted themes.
//
// The following code has been tested to look OK with all of the
// default GTK themes.
SkScalar min_diff = Clamp((hsv1[1] + hsv2[1]) * 1.2, 0.2, 0.5);
SkScalar diff = Clamp(fabs(hsv1[2] - hsv2[2]) / 2, min_diff, 0.5);
if (hsv1[2] + hsv2[2] > 1.0)
diff = -diff;
return SaturateAndBrighten(hsv2, -0.2, diff);
}
void NativeThemeLinux::SetScrollbarColors(unsigned inactive_color,
unsigned active_color,
unsigned track_color) const {
thumb_inactive_color_ = inactive_color;
thumb_active_color_ = active_color;
track_color_ = track_color;
}
} // namespace gfx
<commit_msg>Make drawing consistent with webkit wrt default colors and effects We weren't drawing the new chromium scrollbars exactly the same as webkit had, causing layout test failures.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "gfx/native_theme_linux.h"
#include "base/logging.h"
#include "gfx/size.h"
#include "gfx/rect.h"
namespace gfx {
unsigned int NativeThemeLinux::button_length_ = 14;
unsigned int NativeThemeLinux::scrollbar_width_ = 15;
unsigned int NativeThemeLinux::thumb_inactive_color_ = 0xeaeaea;
unsigned int NativeThemeLinux::thumb_active_color_ = 0xf4f4f4;
unsigned int NativeThemeLinux::track_color_ = 0xd3d3d3;
#if !defined(OS_CHROMEOS)
// Chromeos has a different look.
// static
NativeThemeLinux* NativeThemeLinux::instance() {
// The global NativeThemeLinux instance.
static NativeThemeLinux s_native_theme;
return &s_native_theme;
}
#endif
NativeThemeLinux::NativeThemeLinux() {
}
NativeThemeLinux::~NativeThemeLinux() {
}
gfx::Size NativeThemeLinux::GetSize(Part part) const {
switch (part) {
case kScrollbarDownArrow:
case kScrollbarUpArrow:
return gfx::Size(scrollbar_width_, button_length_);
case kScrollbarLeftArrow:
case kScrollbarRightArrow:
return gfx::Size(button_length_, scrollbar_width_);
case kScrollbarHorizontalThumb:
// This matches Firefox on Linux.
return gfx::Size(2 * scrollbar_width_, scrollbar_width_);
case kScrollbarVerticalThumb:
// This matches Firefox on Linux.
return gfx::Size(scrollbar_width_, 2 * scrollbar_width_);
break;
case kScrollbarHorizontalTrack:
return gfx::Size(0, scrollbar_width_);
case kScrollbarVerticalTrack:
return gfx::Size(scrollbar_width_, 0);
}
return gfx::Size();
}
void NativeThemeLinux::PaintArrowButton(
skia::PlatformCanvas* canvas,
const gfx::Rect& rect, Part direction, State state) {
int widthMiddle, lengthMiddle;
SkPaint paint;
if (direction == kScrollbarUpArrow || direction == kScrollbarDownArrow) {
widthMiddle = rect.width() / 2 + 1;
lengthMiddle = rect.height() / 2 + 1;
} else {
lengthMiddle = rect.width() / 2 + 1;
widthMiddle = rect.height() / 2 + 1;
}
// Calculate button color.
SkScalar trackHSV[3];
SkColorToHSV(track_color_, trackHSV);
SkColor buttonColor = SaturateAndBrighten(trackHSV, 0, 0.2);
SkColor backgroundColor = buttonColor;
if (state == kPressed) {
SkScalar buttonHSV[3];
SkColorToHSV(buttonColor, buttonHSV);
buttonColor = SaturateAndBrighten(buttonHSV, 0, -0.1);
} else if (state == kHover) {
SkScalar buttonHSV[3];
SkColorToHSV(buttonColor, buttonHSV);
buttonColor = SaturateAndBrighten(buttonHSV, 0, 0.05);
}
SkIRect skrect;
skrect.set(rect.x(), rect.y(), rect.x() + rect.width(), rect.y()
+ rect.height());
// Paint the background (the area visible behind the rounded corners).
paint.setColor(backgroundColor);
canvas->drawIRect(skrect, paint);
// Paint the button's outline and fill the middle
SkPath outline;
switch (direction) {
case kScrollbarUpArrow:
outline.moveTo(rect.x() + 0.5, rect.y() + rect.height() + 0.5);
outline.rLineTo(0, -(rect.height() - 2));
outline.rLineTo(2, -2);
outline.rLineTo(rect.width() - 5, 0);
outline.rLineTo(2, 2);
outline.rLineTo(0, rect.height() - 2);
break;
case kScrollbarDownArrow:
outline.moveTo(rect.x() + 0.5, rect.y() - 0.5);
outline.rLineTo(0, rect.height() - 2);
outline.rLineTo(2, 2);
outline.rLineTo(rect.width() - 5, 0);
outline.rLineTo(2, -2);
outline.rLineTo(0, -(rect.height() - 2));
break;
case kScrollbarRightArrow:
outline.moveTo(rect.x() - 0.5, rect.y() + 0.5);
outline.rLineTo(rect.width() - 2, 0);
outline.rLineTo(2, 2);
outline.rLineTo(0, rect.height() - 5);
outline.rLineTo(-2, 2);
outline.rLineTo(-(rect.width() - 2), 0);
break;
case kScrollbarLeftArrow:
outline.moveTo(rect.x() + rect.width() + 0.5, rect.y() + 0.5);
outline.rLineTo(-(rect.width() - 2), 0);
outline.rLineTo(-2, 2);
outline.rLineTo(0, rect.height() - 5);
outline.rLineTo(2, 2);
outline.rLineTo(rect.width() - 2, 0);
break;
default:
break;
}
outline.close();
paint.setStyle(SkPaint::kFill_Style);
paint.setColor(buttonColor);
canvas->drawPath(outline, paint);
paint.setAntiAlias(true);
paint.setStyle(SkPaint::kStroke_Style);
SkScalar thumbHSV[3];
SkColorToHSV(thumb_inactive_color_, thumbHSV);
paint.setColor(OutlineColor(trackHSV, thumbHSV));
canvas->drawPath(outline, paint);
// If the button is disabled or read-only, the arrow is drawn with the
// outline color.
if (state != kDisabled)
paint.setColor(SK_ColorBLACK);
paint.setAntiAlias(false);
paint.setStyle(SkPaint::kFill_Style);
SkPath path;
// The constants in this block of code are hand-tailored to produce good
// looking arrows without anti-aliasing.
switch (direction) {
case kScrollbarUpArrow:
path.moveTo(rect.x() + widthMiddle - 4, rect.y() + lengthMiddle + 2);
path.rLineTo(7, 0);
path.rLineTo(-4, -4);
break;
case kScrollbarDownArrow:
path.moveTo(rect.x() + widthMiddle - 4, rect.y() + lengthMiddle - 3);
path.rLineTo(7, 0);
path.rLineTo(-4, 4);
break;
case kScrollbarRightArrow:
path.moveTo(rect.x() + lengthMiddle - 3, rect.y() + widthMiddle - 4);
path.rLineTo(0, 7);
path.rLineTo(4, -4);
break;
case kScrollbarLeftArrow:
path.moveTo(rect.x() + lengthMiddle + 1, rect.y() + widthMiddle - 5);
path.rLineTo(0, 9);
path.rLineTo(-4, -4);
break;
default:
break;
}
path.close();
canvas->drawPath(path, paint);
}
void NativeThemeLinux::Paint(skia::PlatformCanvas* canvas,
Part part,
State state,
const gfx::Rect& rect,
const ExtraParams& extra) {
switch (part) {
case kScrollbarDownArrow:
case kScrollbarUpArrow:
case kScrollbarLeftArrow:
case kScrollbarRightArrow:
PaintArrowButton(canvas, rect, part, state);
break;
case kScrollbarHorizontalThumb:
case kScrollbarVerticalThumb:
PaintThumb(canvas, part, state, rect);
break;
case kScrollbarHorizontalTrack:
case kScrollbarVerticalTrack:
PaintTrack(canvas, part, state, extra.scrollbar_track, rect);
break;
}
}
void NativeThemeLinux::PaintTrack(skia::PlatformCanvas* canvas,
Part part,
State state,
const ScrollbarTrackExtraParams& extra_params,
const gfx::Rect& rect) {
SkPaint paint;
SkIRect skrect;
skrect.set(rect.x(), rect.y(), rect.right(), rect.bottom());
SkScalar track_hsv[3];
SkColorToHSV(track_color_, track_hsv);
paint.setColor(SaturateAndBrighten(track_hsv, 0, 0));
canvas->drawIRect(skrect, paint);
SkScalar thumb_hsv[3];
SkColorToHSV(thumb_inactive_color_, thumb_hsv);
paint.setColor(OutlineColor(track_hsv, thumb_hsv));
DrawBox(canvas, rect, paint);
}
void NativeThemeLinux::PaintThumb(skia::PlatformCanvas* canvas,
Part part,
State state,
const gfx::Rect& rect) {
const bool hovered = state == kHover;
const int midx = rect.x() + rect.width() / 2;
const int midy = rect.y() + rect.height() / 2;
const bool vertical = part == kScrollbarVerticalThumb;
SkScalar thumb[3];
SkColorToHSV(hovered ? thumb_active_color_ : thumb_inactive_color_, thumb);
SkPaint paint;
paint.setColor(SaturateAndBrighten(thumb, 0, 0.02));
SkIRect skrect;
if (vertical)
skrect.set(rect.x(), rect.y(), midx + 1, rect.y() + rect.height());
else
skrect.set(rect.x(), rect.y(), rect.x() + rect.width(), midy + 1);
canvas->drawIRect(skrect, paint);
paint.setColor(SaturateAndBrighten(thumb, 0, -0.02));
if (vertical) {
skrect.set(
midx + 1, rect.y(), rect.x() + rect.width(), rect.y() + rect.height());
} else {
skrect.set(
rect.x(), midy + 1, rect.x() + rect.width(), rect.y() + rect.height());
}
canvas->drawIRect(skrect, paint);
SkScalar track[3];
SkColorToHSV(track_color_, track);
paint.setColor(OutlineColor(track, thumb));
DrawBox(canvas, rect, paint);
if (rect.height() > 10 && rect.width() > 10) {
const int grippy_half_width = 2;
const int inter_grippy_offset = 3;
if (vertical) {
DrawHorizLine(canvas,
midx - grippy_half_width,
midx + grippy_half_width,
midy - inter_grippy_offset,
paint);
DrawHorizLine(canvas,
midx - grippy_half_width,
midx + grippy_half_width,
midy,
paint);
DrawHorizLine(canvas,
midx - grippy_half_width,
midx + grippy_half_width,
midy + inter_grippy_offset,
paint);
} else {
DrawVertLine(canvas,
midx - inter_grippy_offset,
midy - grippy_half_width,
midy + grippy_half_width,
paint);
DrawVertLine(canvas,
midx,
midy - grippy_half_width,
midy + grippy_half_width,
paint);
DrawVertLine(canvas,
midx + inter_grippy_offset,
midy - grippy_half_width,
midy + grippy_half_width,
paint);
}
}
}
void NativeThemeLinux::DrawVertLine(SkCanvas* canvas,
int x,
int y1,
int y2,
const SkPaint& paint) const {
SkIRect skrect;
skrect.set(x, y1, x + 1, y2 + 1);
canvas->drawIRect(skrect, paint);
}
void NativeThemeLinux::DrawHorizLine(SkCanvas* canvas,
int x1,
int x2,
int y,
const SkPaint& paint) const {
SkIRect skrect;
skrect.set(x1, y, x2 + 1, y + 1);
canvas->drawIRect(skrect, paint);
}
void NativeThemeLinux::DrawBox(SkCanvas* canvas,
const gfx::Rect& rect,
const SkPaint& paint) const {
const int right = rect.x() + rect.width() - 1;
const int bottom = rect.y() + rect.height() - 1;
DrawHorizLine(canvas, rect.x(), right, rect.y(), paint);
DrawVertLine(canvas, right, rect.y(), bottom, paint);
DrawHorizLine(canvas, rect.x(), right, bottom, paint);
DrawVertLine(canvas, rect.x(), rect.y(), bottom, paint);
}
SkScalar NativeThemeLinux::Clamp(SkScalar value,
SkScalar min,
SkScalar max) const {
return std::min(std::max(value, min), max);
}
SkColor NativeThemeLinux::SaturateAndBrighten(SkScalar* hsv,
SkScalar saturate_amount,
SkScalar brighten_amount) const {
SkScalar color[3];
color[0] = hsv[0];
color[1] = Clamp(hsv[1] + saturate_amount, 0.0, 1.0);
color[2] = Clamp(hsv[2] + brighten_amount, 0.0, 1.0);
return SkHSVToColor(color);
}
SkColor NativeThemeLinux::OutlineColor(SkScalar* hsv1, SkScalar* hsv2) const {
// GTK Theme engines have way too much control over the layout of
// the scrollbar. We might be able to more closely approximate its
// look-and-feel, if we sent whole images instead of just colors
// from the browser to the renderer. But even then, some themes
// would just break.
//
// So, instead, we don't even try to 100% replicate the look of
// the native scrollbar. We render our own version, but we make
// sure to pick colors that blend in nicely with the system GTK
// theme. In most cases, we can just sample a couple of pixels
// from the system scrollbar and use those colors to draw our
// scrollbar.
//
// This works fine for the track color and the overall thumb
// color. But it fails spectacularly for the outline color used
// around the thumb piece. Not all themes have a clearly defined
// outline. For some of them it is partially transparent, and for
// others the thickness is very unpredictable.
//
// So, instead of trying to approximate the system theme, we
// instead try to compute a reasonable looking choice based on the
// known color of the track and the thumb piece. This is difficult
// when trying to deal both with high- and low-contrast themes,
// and both with positive and inverted themes.
//
// The following code has been tested to look OK with all of the
// default GTK themes.
SkScalar min_diff = Clamp((hsv1[1] + hsv2[1]) * 1.2, 0.28, 0.5);
SkScalar diff = Clamp(fabs(hsv1[2] - hsv2[2]) / 2, min_diff, 0.5);
if (hsv1[2] + hsv2[2] > 1.0)
diff = -diff;
return SaturateAndBrighten(hsv2, -0.2, diff);
}
void NativeThemeLinux::SetScrollbarColors(unsigned inactive_color,
unsigned active_color,
unsigned track_color) const {
thumb_inactive_color_ = inactive_color;
thumb_active_color_ = active_color;
track_color_ = track_color;
}
} // namespace gfx
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2009, Willow Garage, Inc.
*
* 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 names of Stanford University or Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <cstdio>
#include "ros/this_node.h"
#include "ros/names.h"
#include "ros/topic_manager.h"
#include "ros/init.h"
namespace ros
{
namespace names
{
void init(const M_string& remappings);
}
namespace this_node
{
std::string g_name = "empty";
std::string g_namespace;
const std::string& getName()
{
return g_name;
}
const std::string& getNamespace()
{
return g_namespace;
}
void getAdvertisedTopics(V_string& topics)
{
TopicManager::instance()->getAdvertisedTopics(topics);
}
void getSubscribedTopics(V_string& topics)
{
TopicManager::instance()->getSubscribedTopics(topics);
}
void init(const std::string& name, const M_string& remappings, uint32_t options)
{
char *ns_env = getenv("ROS_NAMESPACE");
if (ns_env)
{
g_namespace = ns_env;
}
g_name = name;
bool disable_anon = false;
M_string::const_iterator it = remappings.find("__name");
if (it != remappings.end())
{
g_name = it->second;
disable_anon = true;
}
it = remappings.find("__ns");
if (it != remappings.end())
{
g_namespace = it->second;
}
if (g_namespace.empty())
{
g_namespace = "/";
}
std::string error;
if (!names::validate(g_namespace, error))
{
ROS_WARN("Namespace is invalid: %s This will be an error in future versions of ROS.", error.c_str());
}
// names must be initialized here, because it requires the namespace to already be known so that it can properly resolve names.
// It must be done before we resolve g_name, because otherwise the name will not get remapped.
names::init(remappings);
if (g_name.find("/") != std::string::npos)
{
throw InvalidNodeNameException(g_name, "node names cannot contain /");
}
g_name = names::resolve(g_namespace, g_name);
if (options & init_options::AnonymousName && !disable_anon)
{
char buf[200];
snprintf(buf, sizeof(buf), "_%llu", (unsigned long long)WallTime::now().toNSec());
g_name += buf;
}
}
} // namespace this_node
} // namespace ros
<commit_msg>throw if a node name contains a ~<commit_after>/*
* Copyright (C) 2009, Willow Garage, Inc.
*
* 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 names of Stanford University or Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <cstdio>
#include "ros/this_node.h"
#include "ros/names.h"
#include "ros/topic_manager.h"
#include "ros/init.h"
namespace ros
{
namespace names
{
void init(const M_string& remappings);
}
namespace this_node
{
std::string g_name = "empty";
std::string g_namespace;
const std::string& getName()
{
return g_name;
}
const std::string& getNamespace()
{
return g_namespace;
}
void getAdvertisedTopics(V_string& topics)
{
TopicManager::instance()->getAdvertisedTopics(topics);
}
void getSubscribedTopics(V_string& topics)
{
TopicManager::instance()->getSubscribedTopics(topics);
}
void init(const std::string& name, const M_string& remappings, uint32_t options)
{
char *ns_env = getenv("ROS_NAMESPACE");
if (ns_env)
{
g_namespace = ns_env;
}
g_name = name;
bool disable_anon = false;
M_string::const_iterator it = remappings.find("__name");
if (it != remappings.end())
{
g_name = it->second;
disable_anon = true;
}
it = remappings.find("__ns");
if (it != remappings.end())
{
g_namespace = it->second;
}
if (g_namespace.empty())
{
g_namespace = "/";
}
std::string error;
if (!names::validate(g_namespace, error))
{
ROS_WARN("Namespace is invalid: %s This will be an error in future versions of ROS.", error.c_str());
}
// names must be initialized here, because it requires the namespace to already be known so that it can properly resolve names.
// It must be done before we resolve g_name, because otherwise the name will not get remapped.
names::init(remappings);
if (g_name.find("/") != std::string::npos)
{
throw InvalidNodeNameException(g_name, "node names cannot contain /");
}
if (g_name.find("~") != std::string::npos)
{
throw InvalidNodeNameException(g_name, "node names cannot contain ~");
}
g_name = names::resolve(g_namespace, g_name);
if (options & init_options::AnonymousName && !disable_anon)
{
char buf[200];
snprintf(buf, sizeof(buf), "_%llu", (unsigned long long)WallTime::now().toNSec());
g_name += buf;
}
}
} // namespace this_node
} // namespace ros
<|endoftext|> |
<commit_before>#include "hanse_depthengine/depth_engine.h"
DepthEngine::DepthEngine() :
depth_target_(0),
pressure_bias_(0),
pressure_current_(0),
pressure_init_(false),
emergency_stop_(false),
pids_enabled_(true),
depth_pid_enabled_(true),
motors_enabled_(true),
depth_output_(0)
{
// Initialisierung der Standard-Service Nachrichten.
enable_msg_.request.enable = true;
disable_msg_.request.enable = false;
// Registrierung der Publisher und Subscriber.
pub_depth_current_ = nh_.advertise<std_msgs::Float64>("/hanse/pid/depth/input", 1);
pub_depth_target_ = nh_.advertise<std_msgs::Float64>("/hanse/pid/depth/target",1);
pub_motor_up_ = nh_.advertise<hanse_msgs::sollSpeed>("/hanse/motors/up", 1);
sub_pressure_ = nh_.subscribe<hanse_msgs::pressure>("/hanse/pressure/depth", 10,
&DepthEngine::pressureCallback, this);
sub_depth_output_ = nh_.subscribe<std_msgs::Float64>(
"/hanse/pid/depth/output", 10, &DepthEngine::depthOutputCallback, this);
publish_timer_ = nh_.createTimer(ros::Duration(1),
&DepthEngine::publishTimerCallback, this);
gamepad_timer_ = nh_.createTimer(ros::Duration(300),
&DepthEngine::gamepadTimerCallback, this);
sub_mux_selected_ = nh_.subscribe<std_msgs::String>("/hanse/commands/cmd_vel_mux/selected",
1, &DepthEngine::muxSelectedCallback, this);
// Registrierung der Services.
srv_handle_engine_command_ = nh_.advertiseService("engine/depth/handleEngineCommand",
&DepthEngine::handleEngineCommand, this);
srv_enable_depth_pid_ = nh_.advertiseService("engine/depth/enableDepthPid",
&DepthEngine::enableDepthPid, this);
srv_enable_motors_ = nh_.advertiseService("engine/depth/enableMotors",
&DepthEngine::enableMotors, this);
srv_reset_zero_pressure_ = nh_.advertiseService("engine/depth/resetZeroPressure",
&DepthEngine::resetZeroPressure, this);
srv_set_emergency_stop_ = nh_.advertiseService("engine/depth/setEmergencyStop",
&DepthEngine::setEmergencyStop, this);
srv_set_depth_ = nh_.advertiseService("engine/depth/setDepth", &DepthEngine::setDepth, this);
srv_increment_depth_ = nh_.advertiseService("engine/depth/incDepth", &DepthEngine::incrementDepth, this);
dyn_reconfigure_cb_ = boost::bind(&DepthEngine::dynReconfigureCallback, this, _1, _2);
dyn_reconfigure_srv_.setCallback(dyn_reconfigure_cb_);
// Registrierung der Service Clients.
srv_client_depth_pid_ = nh_.serviceClient<hanse_srvs::Bool>("/hanse/pid/depth/enable");
// Aktivierung des Tiefen-PID-Regler.
if (config_.depth_pid_enabled_at_start)
{
if (callDepthPidEnableService(true))
{
ROS_INFO("Depth PID enabled.");
depth_pid_enabled_ = true;
}
else
{
ROS_ERROR("Depth PID couldn't be enabled. Shutdown.");
ros::shutdown();
}
}
ROS_INFO("Depth engine started.");
}
void DepthEngine::dynReconfigureCallback(hanse_depthengine::DepthengineConfig &config, uint32_t level)
{
ROS_INFO("got new parameters, level=%d", level);
config_ = config;
publish_timer_.setPeriod(ros::Duration(1.0/config.publish_frequency));
gamepad_timer_.setPeriod(ros::Duration(config.gamepad_timeout));
}
void DepthEngine::velocityCallback(const geometry_msgs::Twist::ConstPtr &twist)
{
gamepad_timeout_ = false;
if (gamepad_running_)
{
gamepad_timer_.stop();
}
if (twist->linear.z != 0)
{
depth_target_ = twist->linear.z;
if (depth_target_ < 0)
{
depth_target_ = 0;
}
}
if (gamepad_running_)
{
gamepad_timer_.start();
}
}
// Auswertung und Zwischenspeicherung der Eingabedaten des Drucksensors.
void DepthEngine::pressureCallback(
const hanse_msgs::pressure::ConstPtr& pressure)
{
if (!pressure_init_)
{
pressure_bias_ = pressure->data;
pressure_init_ = true;
}
pressure_current_ = pressure->data;
}
// Speicherung der Zieltiefe
bool DepthEngine::setDepth(
hanse_srvs::SetTarget::Request &req,
hanse_srvs::SetTarget::Response &res)
{
depth_target_ = req.target;
return true;
}
bool DepthEngine::incrementDepth(hanse_srvs::SetTarget::Request &req,
hanse_srvs::SetTarget::Response &res)
{
depth_target_ += req.target;
if (depth_target_ < 0)
{
depth_target_ = 0;
}
return true;
}
// Auswertung und Zwischenspeicherung der Ausgabedaten des Druck-PID-Reglers.
void DepthEngine::depthOutputCallback(
const std_msgs::Float64::ConstPtr& depth_output)
{
depth_output_ = depth_output->data;
}
void DepthEngine::muxSelectedCallback(const std_msgs::String::ConstPtr &topic)
{
if (topic->data.find("cmd_vel_joystick") != std::string::npos)
{
gamepad_running_ = true;
gamepad_timer_.start();
}
else
{
gamepad_timeout_ = false;
gamepad_running_ = false;
gamepad_timer_.stop();
}
}
void DepthEngine::gamepadTimerCallback(const ros::TimerEvent &e)
{
gamepad_timer_.stop();
gamepad_timeout_ = true;
depth_target_ = 0;
ROS_INFO("Gamepad connection lost. Come up.");
}
// Ausführung jeweils nach Ablauf des Timers. Wird verwendet, um sämtliche
// Ausgaben auf die vorgesehenen Topics zu schreiben.
void DepthEngine::publishTimerCallback(const ros::TimerEvent &e)
{
hanse_msgs::sollSpeed motor_height_msg;
motor_height_msg.header.stamp = ros::Time::now();
if(emergency_stop_ || gamepad_timeout_)
{
motor_height_msg.data = 64;
}
else
{
if (motors_enabled_)
{
// Tiefensteuerung.
std_msgs::Float64 depth_target_msg;
depth_target_msg.data = depth_target_ + pressure_bias_;
if (depth_target_msg.data < config_.min_depth_pressure)
{
depth_target_msg.data = config_.min_depth_pressure;
}
else if(depth_target_msg.data > config_.max_depth_pressure)
{
depth_target_msg.data = config_.max_depth_pressure;
}
pub_depth_target_.publish(depth_target_msg);
std_msgs::Float64 depth_current_msg;
depth_current_msg.data = pressure_current_;
pub_depth_current_.publish(depth_current_msg);
motor_height_msg.data = -depth_output_;
}
else
{
motor_height_msg.data = 0;
}
}
pub_motor_up_.publish(motor_height_msg);
}
bool DepthEngine::handleEngineCommand(hanse_srvs::EngineCommand::Request &req,
hanse_srvs::EngineCommand::Response &res)
{
if (req.setEmergencyStop && !emergency_stop_)
{
emergency_stop_ = true;
pids_enabled_ = false;
// Deaktivierung des Tiefen-PID-Reglers.
if(depth_pid_enabled_)
{
if (callDepthPidEnableService(false))
{
ROS_INFO("Depth PID disabled.");
}
else
{
ROS_ERROR("Depth PID couldn't be disabled.");
}
}
// Tiefe auf 0 setzen
depth_target_ = 0;
}
else if (!req.setEmergencyStop)
{
if (emergency_stop_)
{
emergency_stop_ = false;
pids_enabled_ = true;
if (req.enableDepthPid)
{
if (callDepthPidEnableService(true))
{
ROS_INFO("Depth PID enabled.");
}
else
{
ROS_ERROR("Depth PID couldn't be enabled.");
}
}
depth_pid_enabled_ = req.enableDepthPid;
}
else
{
if (!depth_pid_enabled_ && req.enableDepthPid)
{
if (callDepthPidEnableService(true))
{
ROS_INFO("Depth PID enabled.");
depth_pid_enabled_ = true;
}
else
{
ROS_ERROR("Depth PID couldn't be enabled.");
}
}
else if (depth_pid_enabled_ && !req.enableDepthPid)
{
if (callDepthPidEnableService(false))
{
ROS_INFO("Depth PID disabled.");
depth_pid_enabled_ = false;
}
else
{
ROS_ERROR("Depth PID couldn't be disabled.");
}
}
}
if (motors_enabled_ != req.enableMotors)
{
if (req.enableMotors)
{
ROS_INFO("Motors enabled.");
}
else
{
ROS_INFO("Motors disabled.");
}
motors_enabled_ = req.enableMotors;
}
if (req.resetZeroPressure)
{
ROS_INFO("Resetting zero pressure.");
pressure_init_ = false;
}
}
return true;
}
bool DepthEngine::enableDepthPid(hanse_srvs::Bool::Request &req,
hanse_srvs::Bool::Response &res)
{
if (pids_enabled_) {
if (!depth_pid_enabled_ && req.enable)
{
if (callDepthPidEnableService(true))
{
ROS_INFO("Depth PID enabled.");
depth_pid_enabled_ = true;
}
else
{
ROS_ERROR("Depth PID couldn't be enabled.");
}
}
else if (depth_pid_enabled_ && !req.enable)
{
if (callDepthPidEnableService(false))
{
ROS_INFO("Depth PID disabled.");
depth_pid_enabled_ = false;
}
else
{
ROS_ERROR("Depth PID couldn't be disabled.");
}
}
}
else
{
depth_pid_enabled_ = req.enable;
}
return true;
}
bool DepthEngine::enableMotors(hanse_srvs::Bool::Request &req,
hanse_srvs::Bool::Response &res)
{
motors_enabled_ = req.enable;
return true;
}
bool DepthEngine::resetZeroPressure(hanse_srvs::Empty::Request &req,
hanse_srvs::Empty::Response &res)
{
pressure_init_ = false;
return true;
}
bool DepthEngine::setEmergencyStop(hanse_srvs::Bool::Request &req,
hanse_srvs::Bool::Response &res)
{
if (req.enable && !emergency_stop_)
{
emergency_stop_ = true;
pids_enabled_ = false;
// Deaktivierung des Tiefen-PID-Reglers.
if(depth_pid_enabled_) {
if (callDepthPidEnableService(false))
{
ROS_INFO("Depth PID disabled.");
}
else
{
ROS_ERROR("Depth PID couldn't be disabled.");
}
}
// Tiefe auf 0 setzen
depth_target_ = 0;
}
else if (!req.enable && emergency_stop_)
{
emergency_stop_ = false;
pids_enabled_ = true;
// Aktivierung der zuvor aktivierten PID Regler
if (depth_pid_enabled_)
{
if (callDepthPidEnableService(true))
{
ROS_INFO("Depth PID enabled.");
}
else
{
ROS_ERROR("Depth PID couldn't be enabled.");
}
}
}
return true;
}
bool DepthEngine::callDepthPidEnableService(const bool msg)
{
int8_t counter = 0;
ros::Rate loop_rate(4);
bool success = false;
while(ros::ok() && counter < NUM_SERVICE_LOOPS)
{
if ((msg && srv_client_depth_pid_.call(enable_msg_)) ||
(!msg && srv_client_depth_pid_.call(disable_msg_)))
{
success = true;
break;
}
counter++;
loop_rate.sleep();
}
return success;
}
int main(int argc, char** argv)
{
ros::init(argc, argv, "depthengine_node");
ros::start();
DepthEngine engine_control;
ros::spin();
}
<commit_msg>fixed gamepad_timeout_ flag in depth engine<commit_after>#include "hanse_depthengine/depth_engine.h"
DepthEngine::DepthEngine() :
depth_target_(0),
pressure_bias_(0),
pressure_current_(0),
pressure_init_(false),
emergency_stop_(false),
pids_enabled_(true),
depth_pid_enabled_(true),
motors_enabled_(true),
depth_output_(0)
{
// Initialisierung der Standard-Service Nachrichten.
enable_msg_.request.enable = true;
disable_msg_.request.enable = false;
// Registrierung der Publisher und Subscriber.
pub_depth_current_ = nh_.advertise<std_msgs::Float64>("/hanse/pid/depth/input", 1);
pub_depth_target_ = nh_.advertise<std_msgs::Float64>("/hanse/pid/depth/target",1);
pub_motor_up_ = nh_.advertise<hanse_msgs::sollSpeed>("/hanse/motors/up", 1);
sub_pressure_ = nh_.subscribe<hanse_msgs::pressure>("/hanse/pressure/depth", 10,
&DepthEngine::pressureCallback, this);
sub_depth_output_ = nh_.subscribe<std_msgs::Float64>(
"/hanse/pid/depth/output", 10, &DepthEngine::depthOutputCallback, this);
publish_timer_ = nh_.createTimer(ros::Duration(1),
&DepthEngine::publishTimerCallback, this);
gamepad_timer_ = nh_.createTimer(ros::Duration(300),
&DepthEngine::gamepadTimerCallback, this);
sub_mux_selected_ = nh_.subscribe<std_msgs::String>("/hanse/commands/cmd_vel_mux/selected",
1, &DepthEngine::muxSelectedCallback, this);
// Registrierung der Services.
srv_handle_engine_command_ = nh_.advertiseService("engine/depth/handleEngineCommand",
&DepthEngine::handleEngineCommand, this);
srv_enable_depth_pid_ = nh_.advertiseService("engine/depth/enableDepthPid",
&DepthEngine::enableDepthPid, this);
srv_enable_motors_ = nh_.advertiseService("engine/depth/enableMotors",
&DepthEngine::enableMotors, this);
srv_reset_zero_pressure_ = nh_.advertiseService("engine/depth/resetZeroPressure",
&DepthEngine::resetZeroPressure, this);
srv_set_emergency_stop_ = nh_.advertiseService("engine/depth/setEmergencyStop",
&DepthEngine::setEmergencyStop, this);
srv_set_depth_ = nh_.advertiseService("engine/depth/setDepth", &DepthEngine::setDepth, this);
srv_increment_depth_ = nh_.advertiseService("engine/depth/incDepth", &DepthEngine::incrementDepth, this);
dyn_reconfigure_cb_ = boost::bind(&DepthEngine::dynReconfigureCallback, this, _1, _2);
dyn_reconfigure_srv_.setCallback(dyn_reconfigure_cb_);
// Registrierung der Service Clients.
srv_client_depth_pid_ = nh_.serviceClient<hanse_srvs::Bool>("/hanse/pid/depth/enable");
// Aktivierung des Tiefen-PID-Regler.
if (config_.depth_pid_enabled_at_start)
{
if (callDepthPidEnableService(true))
{
ROS_INFO("Depth PID enabled.");
depth_pid_enabled_ = true;
}
else
{
ROS_ERROR("Depth PID couldn't be enabled. Shutdown.");
ros::shutdown();
}
}
ROS_INFO("Depth engine started.");
}
void DepthEngine::dynReconfigureCallback(hanse_depthengine::DepthengineConfig &config, uint32_t level)
{
ROS_INFO("got new parameters, level=%d", level);
config_ = config;
publish_timer_.setPeriod(ros::Duration(1.0/config.publish_frequency));
gamepad_timer_.setPeriod(ros::Duration(config.gamepad_timeout));
}
void DepthEngine::velocityCallback(const geometry_msgs::Twist::ConstPtr &twist)
{
gamepad_timeout_ = false;
if (gamepad_running_)
{
gamepad_timer_.stop();
}
if (twist->linear.z != 0)
{
depth_target_ = twist->linear.z;
if (depth_target_ < 0)
{
depth_target_ = 0;
}
}
if (gamepad_running_)
{
gamepad_timer_.start();
}
}
// Auswertung und Zwischenspeicherung der Eingabedaten des Drucksensors.
void DepthEngine::pressureCallback(
const hanse_msgs::pressure::ConstPtr& pressure)
{
if (!pressure_init_)
{
pressure_bias_ = pressure->data;
pressure_init_ = true;
}
pressure_current_ = pressure->data;
}
// Speicherung der Zieltiefe
bool DepthEngine::setDepth(
hanse_srvs::SetTarget::Request &req,
hanse_srvs::SetTarget::Response &res)
{
depth_target_ = req.target;
return true;
}
bool DepthEngine::incrementDepth(hanse_srvs::SetTarget::Request &req,
hanse_srvs::SetTarget::Response &res)
{
depth_target_ += req.target;
if (depth_target_ < 0)
{
depth_target_ = 0;
}
return true;
}
// Auswertung und Zwischenspeicherung der Ausgabedaten des Druck-PID-Reglers.
void DepthEngine::depthOutputCallback(
const std_msgs::Float64::ConstPtr& depth_output)
{
depth_output_ = depth_output->data;
}
void DepthEngine::muxSelectedCallback(const std_msgs::String::ConstPtr &topic)
{
if (topic->data.find("cmd_vel_joystick") != std::string::npos)
{
gamepad_running_ = true;
gamepad_timeout_ = false;
gamepad_timer_.start();
}
else
{
gamepad_timeout_ = false;
gamepad_running_ = false;
gamepad_timer_.stop();
}
}
void DepthEngine::gamepadTimerCallback(const ros::TimerEvent &e)
{
gamepad_timer_.stop();
gamepad_timeout_ = true;
depth_target_ = 0;
ROS_INFO("Gamepad connection lost. Come up.");
}
// Ausführung jeweils nach Ablauf des Timers. Wird verwendet, um sämtliche
// Ausgaben auf die vorgesehenen Topics zu schreiben.
void DepthEngine::publishTimerCallback(const ros::TimerEvent &e)
{
hanse_msgs::sollSpeed motor_height_msg;
motor_height_msg.header.stamp = ros::Time::now();
if(emergency_stop_ || gamepad_timeout_)
{
motor_height_msg.data = 64;
}
else
{
if (motors_enabled_)
{
// Tiefensteuerung.
std_msgs::Float64 depth_target_msg;
depth_target_msg.data = depth_target_ + pressure_bias_;
if (depth_target_msg.data < config_.min_depth_pressure)
{
depth_target_msg.data = config_.min_depth_pressure;
}
else if(depth_target_msg.data > config_.max_depth_pressure)
{
depth_target_msg.data = config_.max_depth_pressure;
}
pub_depth_target_.publish(depth_target_msg);
std_msgs::Float64 depth_current_msg;
depth_current_msg.data = pressure_current_;
pub_depth_current_.publish(depth_current_msg);
motor_height_msg.data = -depth_output_;
}
else
{
motor_height_msg.data = 0;
}
}
pub_motor_up_.publish(motor_height_msg);
}
bool DepthEngine::handleEngineCommand(hanse_srvs::EngineCommand::Request &req,
hanse_srvs::EngineCommand::Response &res)
{
if (req.setEmergencyStop && !emergency_stop_)
{
emergency_stop_ = true;
pids_enabled_ = false;
// Deaktivierung des Tiefen-PID-Reglers.
if(depth_pid_enabled_)
{
if (callDepthPidEnableService(false))
{
ROS_INFO("Depth PID disabled.");
}
else
{
ROS_ERROR("Depth PID couldn't be disabled.");
}
}
// Tiefe auf 0 setzen
depth_target_ = 0;
}
else if (!req.setEmergencyStop)
{
if (emergency_stop_)
{
emergency_stop_ = false;
pids_enabled_ = true;
if (req.enableDepthPid)
{
if (callDepthPidEnableService(true))
{
ROS_INFO("Depth PID enabled.");
}
else
{
ROS_ERROR("Depth PID couldn't be enabled.");
}
}
depth_pid_enabled_ = req.enableDepthPid;
}
else
{
if (!depth_pid_enabled_ && req.enableDepthPid)
{
if (callDepthPidEnableService(true))
{
ROS_INFO("Depth PID enabled.");
depth_pid_enabled_ = true;
}
else
{
ROS_ERROR("Depth PID couldn't be enabled.");
}
}
else if (depth_pid_enabled_ && !req.enableDepthPid)
{
if (callDepthPidEnableService(false))
{
ROS_INFO("Depth PID disabled.");
depth_pid_enabled_ = false;
}
else
{
ROS_ERROR("Depth PID couldn't be disabled.");
}
}
}
if (motors_enabled_ != req.enableMotors)
{
if (req.enableMotors)
{
ROS_INFO("Motors enabled.");
}
else
{
ROS_INFO("Motors disabled.");
}
motors_enabled_ = req.enableMotors;
}
if (req.resetZeroPressure)
{
ROS_INFO("Resetting zero pressure.");
pressure_init_ = false;
}
}
return true;
}
bool DepthEngine::enableDepthPid(hanse_srvs::Bool::Request &req,
hanse_srvs::Bool::Response &res)
{
if (pids_enabled_) {
if (!depth_pid_enabled_ && req.enable)
{
if (callDepthPidEnableService(true))
{
ROS_INFO("Depth PID enabled.");
depth_pid_enabled_ = true;
}
else
{
ROS_ERROR("Depth PID couldn't be enabled.");
}
}
else if (depth_pid_enabled_ && !req.enable)
{
if (callDepthPidEnableService(false))
{
ROS_INFO("Depth PID disabled.");
depth_pid_enabled_ = false;
}
else
{
ROS_ERROR("Depth PID couldn't be disabled.");
}
}
}
else
{
depth_pid_enabled_ = req.enable;
}
return true;
}
bool DepthEngine::enableMotors(hanse_srvs::Bool::Request &req,
hanse_srvs::Bool::Response &res)
{
motors_enabled_ = req.enable;
return true;
}
bool DepthEngine::resetZeroPressure(hanse_srvs::Empty::Request &req,
hanse_srvs::Empty::Response &res)
{
pressure_init_ = false;
return true;
}
bool DepthEngine::setEmergencyStop(hanse_srvs::Bool::Request &req,
hanse_srvs::Bool::Response &res)
{
if (req.enable && !emergency_stop_)
{
emergency_stop_ = true;
pids_enabled_ = false;
// Deaktivierung des Tiefen-PID-Reglers.
if(depth_pid_enabled_) {
if (callDepthPidEnableService(false))
{
ROS_INFO("Depth PID disabled.");
}
else
{
ROS_ERROR("Depth PID couldn't be disabled.");
}
}
// Tiefe auf 0 setzen
depth_target_ = 0;
}
else if (!req.enable && emergency_stop_)
{
emergency_stop_ = false;
pids_enabled_ = true;
// Aktivierung der zuvor aktivierten PID Regler
if (depth_pid_enabled_)
{
if (callDepthPidEnableService(true))
{
ROS_INFO("Depth PID enabled.");
}
else
{
ROS_ERROR("Depth PID couldn't be enabled.");
}
}
}
return true;
}
bool DepthEngine::callDepthPidEnableService(const bool msg)
{
int8_t counter = 0;
ros::Rate loop_rate(4);
bool success = false;
while(ros::ok() && counter < NUM_SERVICE_LOOPS)
{
if ((msg && srv_client_depth_pid_.call(enable_msg_)) ||
(!msg && srv_client_depth_pid_.call(disable_msg_)))
{
success = true;
break;
}
counter++;
loop_rate.sleep();
}
return success;
}
int main(int argc, char** argv)
{
ros::init(argc, argv, "depthengine_node");
ros::start();
DepthEngine engine_control;
ros::spin();
}
<|endoftext|> |
<commit_before>/*
* AlgorandOperation
*
* Created by Rémi Barjon on 12/05/2020.
*
* The MIT License (MIT)
*
* Copyright (c) 2020 Ledger
*
* 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 "AlgorandOperation.hpp"
#include "../AlgorandAccount.hpp"
#include "../transactions/api_impl/AlgorandTransactionImpl.hpp"
#include <wallet/common/database/OperationDatabaseHelper.h>
#include <fmt/format.h>
#include <sys/stat.h>
namespace ledger {
namespace core {
namespace algorand {
Operation::Operation(const std::shared_ptr<AbstractAccount>& account)
: ::ledger::core::OperationApi(account)
, transaction(nullptr)
, algorandType{}
, rewards(0)
{}
Operation::Operation(const std::shared_ptr<AbstractAccount>& account,
const model::Transaction& txn)
: Operation(account)
{
setTransaction(txn);
inflate();
}
std::shared_ptr<api::AlgorandTransaction> Operation::getTransaction() const
{
return transaction;
}
api::AlgorandOperationType Operation::getAlgorandOperationType() const
{
return algorandType;
}
std::string Operation::getRewards() const
{
return std::to_string(rewards);
}
bool Operation::isComplete()
{
return static_cast<bool>(transaction);
}
void Operation::refreshUid(const std::string&)
{
const auto& txn = getTransactionData();
const auto id =
fmt::format("{}+{}", *txn.header.id, api::to_string(algorandType));
getBackend().uid = OperationDatabaseHelper::createUid(getBackend().accountUid, id, getOperationType());
}
const model::Transaction& Operation::getTransactionData() const
{
return transaction->getTransactionData();
}
void Operation::setTransaction(const model::Transaction& txn)
{
transaction = std::make_shared<AlgorandTransactionImpl>(txn);
}
void Operation::setAlgorandOperationType(api::AlgorandOperationType t)
{
algorandType = t;
}
void Operation::inflate()
{
if (!getAccount() || !transaction) { return; }
inflateFromAccount();
inflateFromTransaction();
}
void Operation::inflateFromAccount()
{
const auto& account = getAlgorandAccount();
getBackend().accountUid = account.getAccountUid();
getBackend().walletUid = account.getWallet()->getWalletUid();
getBackend().currencyName = account.getWallet()->getCurrency().name;
getBackend().trust = std::make_shared<TrustIndicator>();
}
void Operation::inflateFromTransaction()
{
inflateDate();
inflateBlock();
inflateAmountAndFees();
inflateSenders();
inflateRecipients();
inflateType(); // inflateAmountAndFees must be called first
inflateAlgorandOperationType();
refreshUid();
}
void Operation::inflateDate()
{
const auto& txn = getTransactionData();
getBackend().date = std::chrono::system_clock::time_point(
std::chrono::seconds(txn.header.timestamp.getValueOr(0)));
}
void Operation::inflateBlock()
{
const auto& txn = getTransactionData();
getBackend().block = [&]() {
api::Block block;
block.currencyName = getBackend().currencyName;
if (txn.header.round) {
if (*txn.header.round > std::numeric_limits<int64_t>::max()) {
throw make_exception(api::ErrorCode::OUT_OF_RANGE, "Block height exceeds maximum value");
}
block.height = static_cast<int64_t>(*txn.header.round);
block.blockHash = std::to_string(*txn.header.round);
}
if (txn.header.timestamp) {
block.time = std::chrono::system_clock::time_point(std::chrono::seconds(*txn.header.timestamp));
}
block.uid = BlockDatabaseHelper::createBlockUid(block);
return block;
}();
}
void Operation::inflateAmountAndFees()
{
const auto& account = getAlgorandAccount().getAddress();
const auto& txn = getTransactionData();
auto amount = BigInt::ZERO;
auto u64ToBigInt = [](uint64_t n) {
return BigInt(static_cast<unsigned long long>(n));
};
if (account == txn.header.sender.toString()) {
const auto senderRewards = txn.header.senderRewards.getValueOr(0);
amount = amount - u64ToBigInt(senderRewards);
getBackend().fees = u64ToBigInt(txn.header.fee);
rewards += senderRewards;
}
if (txn.header.type == model::constants::pay) {
const auto& details = boost::get<model::PaymentTxnFields>(txn.details);
if (txn.header.sender == details.receiverAddr) {
getBackend().amount = amount;
return;
}
if (account == txn.header.sender.toString()) {
amount = amount + u64ToBigInt(details.amount);
}
if (account == details.receiverAddr.toString()) {
const auto receiverRewards = txn.header.receiverRewards.getValueOr(0);
amount = amount + u64ToBigInt(details.amount);
amount = amount + u64ToBigInt(receiverRewards);
rewards += receiverRewards;
}
if (details.closeAddr && account == details.closeAddr->toString()) {
const auto closeRewards = txn.header.closeRewards.getValueOr(0);
amount = amount + u64ToBigInt(details.closeAmount.getValueOr(0));
amount = amount + u64ToBigInt(closeRewards);
rewards += closeRewards;
}
}
getBackend().amount = amount;
}
void Operation::inflateSenders()
{
const auto& txn = getTransactionData();
getBackend().senders = { txn.header.sender.toString() };
}
void Operation::inflateRecipients()
{
const auto& txn = getTransactionData();
getBackend().recipients = {};
if (txn.header.type == model::constants::pay) {
const auto& details = boost::get<model::PaymentTxnFields>(txn.details);
getBackend().recipients.push_back(details.receiverAddr.toString());
if (details.closeAddr) {
getBackend().recipients.push_back(details.closeAddr->toString());
}
} else if (txn.header.type == model::constants::axfer) {
const auto& details = boost::get<model::AssetTransferTxnFields>(txn.details);
getBackend().recipients.push_back(details.assetReceiver.toString());
if (details.assetCloseTo) {
getBackend().recipients.push_back(details.assetCloseTo->toString());
}
}
}
void Operation::inflateType()
{
const auto& account = getAlgorandAccount().getAddress();
const auto& txn = getTransactionData();
getBackend().type = api::OperationType::NONE;
if (txn.header.sender.toString() == account) {
getBackend().type = api::OperationType::SEND;
} else if (txn.header.type == model::constants::pay) {
const auto& details = boost::get<model::PaymentTxnFields>(txn.details);
if (details.receiverAddr.toString() == account ||
details.closeAddr && details.closeAddr->toString() == account) {
getBackend().type = api::OperationType::RECEIVE;
}
} else if (txn.header.type == model::constants::axfer) {
const auto& details = boost::get<model::AssetTransferTxnFields>(txn.details);
if (details.assetReceiver.toString() == account ||
details.assetCloseTo && details.assetCloseTo->toString() == account) {
getBackend().type = api::OperationType::RECEIVE;
}
}
}
const Account& Operation::getAlgorandAccount() const
{
return static_cast<Account&>(*getAccount());
}
void Operation::inflateAlgorandOperationType()
{
const auto& txn = transaction->getTransactionData();
if (txn.header.type == model::constants::pay) {
const auto& details = boost::get<model::PaymentTxnFields>(txn.details);
if (details.closeAddr) {
algorandType = api::AlgorandOperationType::ACCOUNT_CLOSE;
} else {
algorandType = api::AlgorandOperationType::PAYMENT;
}
} else if (txn.header.type == model::constants::keyreg) {
const auto& details = boost::get<model::KeyRegTxnFields>(txn.details);
if (details.nonParticipation && !(*details.nonParticipation)) {
algorandType = api::AlgorandOperationType::ACCOUNT_REGISTER_ONLINE;
} else {
algorandType = api::AlgorandOperationType::ACCOUNT_REGISTER_OFFLINE;
}
} else if (txn.header.type == model::constants::acfg) {
const auto& details = boost::get<model::AssetConfigTxnFields>(txn.details);
if (!details.assetId) {
algorandType = api::AlgorandOperationType::ASSET_CREATE;
} else if (!details.assetParams) {
algorandType = api::AlgorandOperationType::ASSET_DESTROY;
} else {
algorandType = api::AlgorandOperationType::ASSET_RECONFIGURE;
}
} else if (txn.header.type == model::constants::axfer) {
const auto& details = boost::get<model::AssetTransferTxnFields>(txn.details);
if (details.assetSender) {
algorandType = api::AlgorandOperationType::ASSET_REVOKE;
} else if (details.assetCloseTo) {
algorandType = api::AlgorandOperationType::ASSET_OPT_OUT;
} else if (!details.assetAmount
|| (*details.assetAmount == 0 && txn.header.sender == details.assetReceiver)) {
algorandType = api::AlgorandOperationType::ASSET_OPT_IN;
} else {
algorandType = api::AlgorandOperationType::ASSET_TRANSFER;
}
} else if (txn.header.type == model::constants::afreeze) {
algorandType = api::AlgorandOperationType::ASSET_FREEZE;
} else {
algorandType = api::AlgorandOperationType::UNSUPPORTED;
}
}
} // namespace algorand
} // namespace core
} // namespace ledger
<commit_msg>Tag an operation as close or opt-out only for the sender, not receivers (#62)<commit_after>/*
* AlgorandOperation
*
* Created by Rémi Barjon on 12/05/2020.
*
* The MIT License (MIT)
*
* Copyright (c) 2020 Ledger
*
* 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 "AlgorandOperation.hpp"
#include "../AlgorandAccount.hpp"
#include "../transactions/api_impl/AlgorandTransactionImpl.hpp"
#include <wallet/common/database/OperationDatabaseHelper.h>
#include <fmt/format.h>
#include <sys/stat.h>
namespace ledger {
namespace core {
namespace algorand {
Operation::Operation(const std::shared_ptr<AbstractAccount>& account)
: ::ledger::core::OperationApi(account)
, transaction(nullptr)
, algorandType{}
, rewards(0)
{}
Operation::Operation(const std::shared_ptr<AbstractAccount>& account,
const model::Transaction& txn)
: Operation(account)
{
setTransaction(txn);
inflate();
}
std::shared_ptr<api::AlgorandTransaction> Operation::getTransaction() const
{
return transaction;
}
api::AlgorandOperationType Operation::getAlgorandOperationType() const
{
return algorandType;
}
std::string Operation::getRewards() const
{
return std::to_string(rewards);
}
bool Operation::isComplete()
{
return static_cast<bool>(transaction);
}
void Operation::refreshUid(const std::string&)
{
const auto& txn = getTransactionData();
const auto id =
fmt::format("{}+{}", *txn.header.id, api::to_string(algorandType));
getBackend().uid = OperationDatabaseHelper::createUid(getBackend().accountUid, id, getOperationType());
}
const model::Transaction& Operation::getTransactionData() const
{
return transaction->getTransactionData();
}
void Operation::setTransaction(const model::Transaction& txn)
{
transaction = std::make_shared<AlgorandTransactionImpl>(txn);
}
void Operation::setAlgorandOperationType(api::AlgorandOperationType t)
{
algorandType = t;
}
void Operation::inflate()
{
if (!getAccount() || !transaction) { return; }
inflateFromAccount();
inflateFromTransaction();
}
void Operation::inflateFromAccount()
{
const auto& account = getAlgorandAccount();
getBackend().accountUid = account.getAccountUid();
getBackend().walletUid = account.getWallet()->getWalletUid();
getBackend().currencyName = account.getWallet()->getCurrency().name;
getBackend().trust = std::make_shared<TrustIndicator>();
}
void Operation::inflateFromTransaction()
{
inflateDate();
inflateBlock();
inflateAmountAndFees();
inflateSenders();
inflateRecipients();
inflateType(); // inflateAmountAndFees must be called first
inflateAlgorandOperationType();
refreshUid();
}
void Operation::inflateDate()
{
const auto& txn = getTransactionData();
getBackend().date = std::chrono::system_clock::time_point(
std::chrono::seconds(txn.header.timestamp.getValueOr(0)));
}
void Operation::inflateBlock()
{
const auto& txn = getTransactionData();
getBackend().block = [&]() {
api::Block block;
block.currencyName = getBackend().currencyName;
if (txn.header.round) {
if (*txn.header.round > std::numeric_limits<int64_t>::max()) {
throw make_exception(api::ErrorCode::OUT_OF_RANGE, "Block height exceeds maximum value");
}
block.height = static_cast<int64_t>(*txn.header.round);
block.blockHash = std::to_string(*txn.header.round);
}
if (txn.header.timestamp) {
block.time = std::chrono::system_clock::time_point(std::chrono::seconds(*txn.header.timestamp));
}
block.uid = BlockDatabaseHelper::createBlockUid(block);
return block;
}();
}
void Operation::inflateAmountAndFees()
{
const auto& account = getAlgorandAccount().getAddress();
const auto& txn = getTransactionData();
auto amount = BigInt::ZERO;
auto u64ToBigInt = [](uint64_t n) {
return BigInt(static_cast<unsigned long long>(n));
};
if (account == txn.header.sender.toString()) {
const auto senderRewards = txn.header.senderRewards.getValueOr(0);
amount = amount - u64ToBigInt(senderRewards);
getBackend().fees = u64ToBigInt(txn.header.fee);
rewards += senderRewards;
}
if (txn.header.type == model::constants::pay) {
const auto& details = boost::get<model::PaymentTxnFields>(txn.details);
if (txn.header.sender == details.receiverAddr) {
getBackend().amount = amount;
return;
}
if (account == txn.header.sender.toString()) {
amount = amount + u64ToBigInt(details.amount);
}
if (account == details.receiverAddr.toString()) {
const auto receiverRewards = txn.header.receiverRewards.getValueOr(0);
amount = amount + u64ToBigInt(details.amount);
amount = amount + u64ToBigInt(receiverRewards);
rewards += receiverRewards;
}
if (details.closeAddr && account == details.closeAddr->toString()) {
const auto closeRewards = txn.header.closeRewards.getValueOr(0);
amount = amount + u64ToBigInt(details.closeAmount.getValueOr(0));
amount = amount + u64ToBigInt(closeRewards);
rewards += closeRewards;
}
}
getBackend().amount = amount;
}
void Operation::inflateSenders()
{
const auto& txn = getTransactionData();
getBackend().senders = { txn.header.sender.toString() };
}
void Operation::inflateRecipients()
{
const auto& txn = getTransactionData();
getBackend().recipients = {};
if (txn.header.type == model::constants::pay) {
const auto& details = boost::get<model::PaymentTxnFields>(txn.details);
getBackend().recipients.push_back(details.receiverAddr.toString());
if (details.closeAddr) {
getBackend().recipients.push_back(details.closeAddr->toString());
}
} else if (txn.header.type == model::constants::axfer) {
const auto& details = boost::get<model::AssetTransferTxnFields>(txn.details);
getBackend().recipients.push_back(details.assetReceiver.toString());
if (details.assetCloseTo) {
getBackend().recipients.push_back(details.assetCloseTo->toString());
}
}
}
void Operation::inflateType()
{
const auto& account = getAlgorandAccount().getAddress();
const auto& txn = getTransactionData();
getBackend().type = api::OperationType::NONE;
if (txn.header.sender.toString() == account) {
getBackend().type = api::OperationType::SEND;
} else if (txn.header.type == model::constants::pay) {
const auto& details = boost::get<model::PaymentTxnFields>(txn.details);
if (details.receiverAddr.toString() == account ||
details.closeAddr && details.closeAddr->toString() == account) {
getBackend().type = api::OperationType::RECEIVE;
}
} else if (txn.header.type == model::constants::axfer) {
const auto& details = boost::get<model::AssetTransferTxnFields>(txn.details);
if (details.assetReceiver.toString() == account ||
details.assetCloseTo && details.assetCloseTo->toString() == account) {
getBackend().type = api::OperationType::RECEIVE;
}
}
}
const Account& Operation::getAlgorandAccount() const
{
return static_cast<Account&>(*getAccount());
}
void Operation::inflateAlgorandOperationType()
{
const auto& account = getAlgorandAccount().getAddress();
const auto& txn = transaction->getTransactionData();
if (txn.header.type == model::constants::pay) {
const auto& details = boost::get<model::PaymentTxnFields>(txn.details);
if (details.closeAddr && txn.header.sender.toString() == account) {
algorandType = api::AlgorandOperationType::ACCOUNT_CLOSE;
} else {
algorandType = api::AlgorandOperationType::PAYMENT;
}
} else if (txn.header.type == model::constants::keyreg) {
const auto& details = boost::get<model::KeyRegTxnFields>(txn.details);
if (details.nonParticipation && !(*details.nonParticipation)) {
algorandType = api::AlgorandOperationType::ACCOUNT_REGISTER_ONLINE;
} else {
algorandType = api::AlgorandOperationType::ACCOUNT_REGISTER_OFFLINE;
}
} else if (txn.header.type == model::constants::acfg) {
const auto& details = boost::get<model::AssetConfigTxnFields>(txn.details);
if (!details.assetId) {
algorandType = api::AlgorandOperationType::ASSET_CREATE;
} else if (!details.assetParams) {
algorandType = api::AlgorandOperationType::ASSET_DESTROY;
} else {
algorandType = api::AlgorandOperationType::ASSET_RECONFIGURE;
}
} else if (txn.header.type == model::constants::axfer) {
const auto& details = boost::get<model::AssetTransferTxnFields>(txn.details);
if (details.assetSender && details.assetSender->toString() == account) {
algorandType = api::AlgorandOperationType::ASSET_REVOKE;
} else if (details.assetCloseTo && txn.header.sender.toString() == account) {
algorandType = api::AlgorandOperationType::ASSET_OPT_OUT;
} else if (details.assetAmount.getValueOr(0) == 0 && txn.header.sender == details.assetReceiver) {
algorandType = api::AlgorandOperationType::ASSET_OPT_IN;
} else {
algorandType = api::AlgorandOperationType::ASSET_TRANSFER;
}
} else if (txn.header.type == model::constants::afreeze) {
algorandType = api::AlgorandOperationType::ASSET_FREEZE;
} else {
algorandType = api::AlgorandOperationType::UNSUPPORTED;
}
}
} // namespace algorand
} // namespace core
} // namespace ledger
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QPointF>
#include <QNetworkProxy>
#ifdef Q_OS_SYMBIAN
#include <QMessageBox>
#include <qnetworksession.h>
#include <qnetworkconfigmanager.h>
#endif
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "qmaptile.h"
#include "qrouterequest.h"
#include "qmapmarker.h"
#include "qmapellipse.h"
#include "qmaproute.h"
#include "qmaprect.h"
#include "qmapline.h"
#include "qmappolygon.h"
#include "qmapmarker.h"
QTM_USE_NAMESPACE
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow),
geoNetworkManager("", "")
{
ui->setupUi(this);
QNetworkProxy proxy(QNetworkProxy::HttpProxy, "172.16.42.41", 8080);
geoNetworkManager.setMapProxy(proxy);
geoNetworkManager.setMapServer("maptile.mapplayer.maps.svc.ovi.com");
qgv = new QGraphicsView(this);
qgv->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
qgv->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
qgv->setVisible(true);
qgv->setGeometry(QRect(0, 0, width(), height()));
QGraphicsScene* scene = new QGraphicsScene(0, 0, width(), height());
qgv->setScene(scene);
mapView = new QMapView();
qgv->scene()->addItem(mapView);
mapView->setGeometry(0, 0, width(), height());
QObject::connect(&geoNetworkManager, SIGNAL(finished(QRouteReply*)),
this, SLOT(routeReplyFinished(QRouteReply*)));
QObject::connect(mapView, SIGNAL(mapClicked(QGeoCoordinate, QGraphicsSceneMouseEvent*)),
this, SLOT(mapClicked(QGeoCoordinate, QGraphicsSceneMouseEvent*)));
QObject::connect(mapView, SIGNAL(zoomLevelChanged(quint16, quint16)),
this, SLOT(zoomLevelChanged(quint16, quint16)));
QObject::connect(mapView, SIGNAL(mapObjectSelected(QMapObject*)),
this, SLOT(mapObjectSelected(QMapObject*)));
slider = new QSlider(Qt::Vertical, this);
slider->setMinimum(0);
slider->setMaximum(18);
slider->setSliderPosition(4);
#ifdef Q_OS_SYMBIAN
slider->setGeometry(10, 10, 80, 170);
#else
slider->setGeometry(10, 10, 30, 100);
#endif
slider->setVisible(true);
QObject::connect(slider, SIGNAL(sliderMoved(int)),
mapView, SLOT(setZoomLevel(int)));
//QGraphicsProxyWidget* proxy = qgv->scene()->addWidget(slider);
popupMenu = new QMenu(this);
QAction* menuItem;
menuItem = new QAction(tr("Add marker here"), this);
popupMenu->addAction(menuItem);
QObject::connect(menuItem, SIGNAL(triggered(bool)),
this, SLOT(addMarker(bool)));
menuItem = new QAction(tr(""), this);
menuItem->setSeparator(true);
popupMenu->addAction(menuItem);
menuItem = new QAction(tr("Add route"), this);
popupMenu->addAction(menuItem);
QObject::connect(menuItem, SIGNAL(triggered(bool)),
this, SLOT(setRtFromTo(bool)));
menuItem = new QAction(tr("Draw line"), this);
popupMenu->addAction(menuItem);
QObject::connect(menuItem, SIGNAL(triggered(bool)),
this, SLOT(drawLine(bool)));
menuItem = new QAction(tr("Draw rectangle"), this);
popupMenu->addAction(menuItem);
QObject::connect(menuItem, SIGNAL(triggered(bool)),
this, SLOT(drawRect(bool)));
menuItem = new QAction(tr("Draw ellipse"), this);
popupMenu->addAction(menuItem);
QObject::connect(menuItem, SIGNAL(triggered(bool)),
this, SLOT(drawEllipse(bool)));
menuItem = new QAction(tr("Draw polygon"), this);
popupMenu->addAction(menuItem);
QObject::connect(menuItem, SIGNAL(triggered(bool)),
this, SLOT(drawPolygon(bool)));
menuItem = new QAction(tr(""), this);
menuItem->setSeparator(true);
popupMenu->addAction(menuItem);
mnDay = new QAction(tr("Normal daylight"), this);
popupMenu->addAction(mnDay);
QObject::connect(mnDay, SIGNAL(triggered(bool)),
this, SLOT(setScheme(bool)));
mnSat = new QAction(tr("Satellite"), this);
popupMenu->addAction(mnSat);
QObject::connect(mnSat, SIGNAL(triggered(bool)),
this, SLOT(setScheme(bool)));
mnTer = new QAction(tr("Terrain"), this);
popupMenu->addAction(mnTer);
QObject::connect(mnTer, SIGNAL(triggered(bool)),
this, SLOT(setScheme(bool)));
menuItem = new QAction(tr(""), this);
menuItem->setSeparator(true);
popupMenu->addAction(menuItem);
menuItem = new QAction(tr("Exit"), this);
popupMenu->addAction(menuItem);
QObject::connect(menuItem, SIGNAL(triggered(bool)),
this, SLOT(close()));
setContextMenuPolicy(Qt::CustomContextMenu);
QObject::connect(this, SIGNAL(customContextMenuRequested(const QPoint&)),
this, SLOT(customContextMenuRequest(const QPoint&)));
QTimer::singleShot(0, this, SLOT(delayedInit()));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::delayedInit()
{
#ifdef Q_OS_SYMBIAN
// Set Internet Access Point
QNetworkConfigurationManager manager;
const bool canStartIAP = (manager.capabilities()
& QNetworkConfigurationManager::CanStartAndStopInterfaces);
// Is there default access point, use it
QNetworkConfiguration cfg = manager.defaultConfiguration();
if (!cfg.isValid() || (!canStartIAP && cfg.state() != QNetworkConfiguration::Active)) {
QMessageBox::information(this, tr("MapViewer Example"), tr(
"Available Access Points not found."));
return;
}
session = new QNetworkSession(cfg, this);
session->open();
session->waitForOpened(-1);
#endif
mapView->init(&geoNetworkManager, QGeoCoordinate(52.35, 13));
}
void MainWindow::resizeEvent(QResizeEvent* event)
{
qgv->resize(event->size());
qgv->setSceneRect(0, 0, event->size().width(), event->size().height());
mapView->resize(event->size());
}
void MainWindow::changeEvent(QEvent *e)
{
QMainWindow::changeEvent(e);
switch (e->type()) {
case QEvent::LanguageChange:
ui->retranslateUi(this);
break;
default:
break;
}
}
void MainWindow::routeReplyFinished(QRouteReply* reply)
{
QList<QRoute> routes = reply->routes();
if (routes.size() > 0) {
QColor routeColor(Qt::blue);
routeColor.setAlpha(127); //semi-transparent
QPen pen(routeColor);
pen.setWidth(7);
pen.setCapStyle(Qt::RoundCap);
mapView->addMapObject(new QMapRoute(routes[0], pen));
}
}
void MainWindow::mapClicked(QGeoCoordinate geoCoord, QGraphicsSceneMouseEvent* /*mouseEvent*/)
{
lastClicked = geoCoord;
}
void MainWindow::customContextMenuRequest(const QPoint& point)
{
if(focusWidget()==qgv)
popupMenu->popup(mapToGlobal(point));
}
void MainWindow::mapObjectSelected(QMapObject* /*mapObject*/)
{
int x = 0;
x++; //just a stub
}
void MainWindow::setRtFromTo(bool /*checked*/)
{
if (selectedMarkers.count() < 2)
return;
QGeoCoordinate from = selectedMarkers.first()->point();
QGeoCoordinate to = selectedMarkers.last()->point();
QRouteRequest request;
request.setSource(from);
request.setDestination(to);
for (int i = 1; i < selectedMarkers.count() - 1; i++) {
request.addStopOver(selectedMarkers[i]->point());
}
geoNetworkManager.get(request);
selectedMarkers.clear();
}
void MainWindow::zoomLevelChanged(quint16 /*oldZoomLevel*/, quint16 newZoomLevel)
{
slider->setSliderPosition(newZoomLevel);
}
void MainWindow::setScheme(bool /*checked*/)
{
if (sender() == mnDay)
mapView->setScheme(MapScheme(MapScheme::Normal_Day));
else if (sender() == mnSat)
mapView->setScheme(MapScheme(MapScheme::Satellite_Day));
else if (sender() == mnTer)
mapView->setScheme(MapScheme(MapScheme::Terrain_Day));
}
void MainWindow::addMarker(bool /*checked*/)
{
QMapMarker* marker = new QMapMarker(lastClicked, QString::number(selectedMarkers.count() + 1));
mapView->addMapObject(marker);
selectedMarkers.append(marker);
}
void MainWindow::drawLine(bool /*checked*/)
{
for (int i = 0; i < selectedMarkers.count() - 1; i++) {
const QMapMarker* m1 = selectedMarkers[i];
const QMapMarker* m2 = selectedMarkers[i + 1];
QPen pen(Qt::red);
pen.setWidth(2);
QMapLine* line = new QMapLine(m1->point(), m2->point(), pen, 1);
mapView->addMapObject(line);
}
selectedMarkers.clear();
}
void MainWindow::drawRect(bool /*checked*/)
{
for (int i = 0; i < selectedMarkers.count() - 1; i++) {
const QMapMarker* m1 = selectedMarkers[i];
const QMapMarker* m2 = selectedMarkers[i + 1];
QPen pen(Qt::white);
pen.setWidth(2);
QColor fill(Qt::black);
fill.setAlpha(65);
mapView->addMapObject(new QMapRect(m1->point(), m2->point(), pen, QBrush(fill), 1));
}
selectedMarkers.clear();
}
void MainWindow::drawEllipse(bool /*checked*/)
{
for (int i = 0; i < selectedMarkers.count() - 1; i++) {
const QMapMarker* m1 = selectedMarkers[i];
const QMapMarker* m2 = selectedMarkers[i + 1];
QPen pen(Qt::white);
pen.setWidth(2);
QColor fill(Qt::black);
fill.setAlpha(65);
mapView->addMapObject(new QMapEllipse(m1->point(), m2->point(), pen, QBrush(fill), 1));
}
selectedMarkers.clear();
}
void MainWindow::drawPolygon(bool /*checked*/)
{
QList<QGeoCoordinate> coords;
for (int i = 0; i < selectedMarkers.count(); i++) {
coords.append(selectedMarkers[i]->point());
}
QPen pen(Qt::white);
pen.setWidth(2);
QColor fill(Qt::black);
fill.setAlpha(65);
mapView->addMapObject(new QMapPolygon(coords, pen, QBrush(fill), 1));
selectedMarkers.clear();
}
<commit_msg>mapviewer example popup menu draw items into submenu<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QPointF>
#include <QNetworkProxy>
#ifdef Q_OS_SYMBIAN
#include <QMessageBox>
#include <qnetworksession.h>
#include <qnetworkconfigmanager.h>
#endif
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "qmaptile.h"
#include "qrouterequest.h"
#include "qmapmarker.h"
#include "qmapellipse.h"
#include "qmaproute.h"
#include "qmaprect.h"
#include "qmapline.h"
#include "qmappolygon.h"
#include "qmapmarker.h"
QTM_USE_NAMESPACE
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow),
geoNetworkManager("", "")
{
ui->setupUi(this);
QNetworkProxy proxy(QNetworkProxy::HttpProxy, "172.16.42.41", 8080);
geoNetworkManager.setMapProxy(proxy);
geoNetworkManager.setMapServer("maptile.mapplayer.maps.svc.ovi.com");
qgv = new QGraphicsView(this);
qgv->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
qgv->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
qgv->setVisible(true);
qgv->setGeometry(QRect(0, 0, width(), height()));
QGraphicsScene* scene = new QGraphicsScene(0, 0, width(), height());
qgv->setScene(scene);
mapView = new QMapView();
qgv->scene()->addItem(mapView);
mapView->setGeometry(0, 0, width(), height());
QObject::connect(&geoNetworkManager, SIGNAL(finished(QRouteReply*)),
this, SLOT(routeReplyFinished(QRouteReply*)));
QObject::connect(mapView, SIGNAL(mapClicked(QGeoCoordinate, QGraphicsSceneMouseEvent*)),
this, SLOT(mapClicked(QGeoCoordinate, QGraphicsSceneMouseEvent*)));
QObject::connect(mapView, SIGNAL(zoomLevelChanged(quint16, quint16)),
this, SLOT(zoomLevelChanged(quint16, quint16)));
QObject::connect(mapView, SIGNAL(mapObjectSelected(QMapObject*)),
this, SLOT(mapObjectSelected(QMapObject*)));
slider = new QSlider(Qt::Vertical, this);
slider->setMinimum(0);
slider->setMaximum(18);
slider->setSliderPosition(4);
#ifdef Q_OS_SYMBIAN
slider->setGeometry(10, 10, 80, 170);
#else
slider->setGeometry(10, 10, 30, 100);
#endif
slider->setVisible(true);
QObject::connect(slider, SIGNAL(sliderMoved(int)),
mapView, SLOT(setZoomLevel(int)));
//QGraphicsProxyWidget* proxy = qgv->scene()->addWidget(slider);
popupMenu = new QMenu(this);
QAction* menuItem;
menuItem = new QAction(tr("Add marker here"), this);
popupMenu->addAction(menuItem);
QObject::connect(menuItem, SIGNAL(triggered(bool)),
this, SLOT(addMarker(bool)));
menuItem = new QAction(tr(""), this);
menuItem->setSeparator(true);
popupMenu->addAction(menuItem);
menuItem = new QAction(tr("Add route"), this);
popupMenu->addAction(menuItem);
QObject::connect(menuItem, SIGNAL(triggered(bool)),
this, SLOT(setRtFromTo(bool)));
QMenu* subMenuItem = new QMenu(tr("Draw"), this);
popupMenu->addMenu(subMenuItem);
menuItem = new QAction(tr("Line"), this);
subMenuItem->addAction(menuItem);
QObject::connect(menuItem, SIGNAL(triggered(bool)),
this, SLOT(drawLine(bool)));
menuItem = new QAction(tr("Rectangle"), this);
subMenuItem->addAction(menuItem);
QObject::connect(menuItem, SIGNAL(triggered(bool)),
this, SLOT(drawRect(bool)));
menuItem = new QAction(tr("Ellipse"), this);
subMenuItem->addAction(menuItem);
QObject::connect(menuItem, SIGNAL(triggered(bool)),
this, SLOT(drawEllipse(bool)));
menuItem = new QAction(tr("Polygon"), this);
subMenuItem->addAction(menuItem);
QObject::connect(menuItem, SIGNAL(triggered(bool)),
this, SLOT(drawPolygon(bool)));
menuItem = new QAction(tr(""), this);
menuItem->setSeparator(true);
popupMenu->addAction(menuItem);
mnDay = new QAction(tr("Normal daylight"), this);
popupMenu->addAction(mnDay);
QObject::connect(mnDay, SIGNAL(triggered(bool)),
this, SLOT(setScheme(bool)));
mnSat = new QAction(tr("Satellite"), this);
popupMenu->addAction(mnSat);
QObject::connect(mnSat, SIGNAL(triggered(bool)),
this, SLOT(setScheme(bool)));
mnTer = new QAction(tr("Terrain"), this);
popupMenu->addAction(mnTer);
QObject::connect(mnTer, SIGNAL(triggered(bool)),
this, SLOT(setScheme(bool)));
menuItem = new QAction(tr(""), this);
menuItem->setSeparator(true);
popupMenu->addAction(menuItem);
menuItem = new QAction(tr("Exit"), this);
popupMenu->addAction(menuItem);
QObject::connect(menuItem, SIGNAL(triggered(bool)),
this, SLOT(close()));
setContextMenuPolicy(Qt::CustomContextMenu);
QObject::connect(this, SIGNAL(customContextMenuRequested(const QPoint&)),
this, SLOT(customContextMenuRequest(const QPoint&)));
QTimer::singleShot(0, this, SLOT(delayedInit()));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::delayedInit()
{
#ifdef Q_OS_SYMBIAN
// Set Internet Access Point
QNetworkConfigurationManager manager;
const bool canStartIAP = (manager.capabilities()
& QNetworkConfigurationManager::CanStartAndStopInterfaces);
// Is there default access point, use it
QNetworkConfiguration cfg = manager.defaultConfiguration();
if (!cfg.isValid() || (!canStartIAP && cfg.state() != QNetworkConfiguration::Active)) {
QMessageBox::information(this, tr("MapViewer Example"), tr(
"Available Access Points not found."));
return;
}
session = new QNetworkSession(cfg, this);
session->open();
session->waitForOpened(-1);
#endif
mapView->init(&geoNetworkManager, QGeoCoordinate(52.35, 13));
}
void MainWindow::resizeEvent(QResizeEvent* event)
{
qgv->resize(event->size());
qgv->setSceneRect(0, 0, event->size().width(), event->size().height());
mapView->resize(event->size());
}
void MainWindow::changeEvent(QEvent *e)
{
QMainWindow::changeEvent(e);
switch (e->type()) {
case QEvent::LanguageChange:
ui->retranslateUi(this);
break;
default:
break;
}
}
void MainWindow::routeReplyFinished(QRouteReply* reply)
{
QList<QRoute> routes = reply->routes();
if (routes.size() > 0) {
QColor routeColor(Qt::blue);
routeColor.setAlpha(127); //semi-transparent
QPen pen(routeColor);
pen.setWidth(7);
pen.setCapStyle(Qt::RoundCap);
mapView->addMapObject(new QMapRoute(routes[0], pen));
}
}
void MainWindow::mapClicked(QGeoCoordinate geoCoord, QGraphicsSceneMouseEvent* /*mouseEvent*/)
{
lastClicked = geoCoord;
}
void MainWindow::customContextMenuRequest(const QPoint& point)
{
if(focusWidget()==qgv)
popupMenu->popup(mapToGlobal(point));
}
void MainWindow::mapObjectSelected(QMapObject* /*mapObject*/)
{
int x = 0;
x++; //just a stub
}
void MainWindow::setRtFromTo(bool /*checked*/)
{
if (selectedMarkers.count() < 2)
return;
QGeoCoordinate from = selectedMarkers.first()->point();
QGeoCoordinate to = selectedMarkers.last()->point();
QRouteRequest request;
request.setSource(from);
request.setDestination(to);
for (int i = 1; i < selectedMarkers.count() - 1; i++) {
request.addStopOver(selectedMarkers[i]->point());
}
geoNetworkManager.get(request);
selectedMarkers.clear();
}
void MainWindow::zoomLevelChanged(quint16 /*oldZoomLevel*/, quint16 newZoomLevel)
{
slider->setSliderPosition(newZoomLevel);
}
void MainWindow::setScheme(bool /*checked*/)
{
if (sender() == mnDay)
mapView->setScheme(MapScheme(MapScheme::Normal_Day));
else if (sender() == mnSat)
mapView->setScheme(MapScheme(MapScheme::Satellite_Day));
else if (sender() == mnTer)
mapView->setScheme(MapScheme(MapScheme::Terrain_Day));
}
void MainWindow::addMarker(bool /*checked*/)
{
QMapMarker* marker = new QMapMarker(lastClicked, QString::number(selectedMarkers.count() + 1));
mapView->addMapObject(marker);
selectedMarkers.append(marker);
}
void MainWindow::drawLine(bool /*checked*/)
{
for (int i = 0; i < selectedMarkers.count() - 1; i++) {
const QMapMarker* m1 = selectedMarkers[i];
const QMapMarker* m2 = selectedMarkers[i + 1];
QPen pen(Qt::red);
pen.setWidth(2);
QMapLine* line = new QMapLine(m1->point(), m2->point(), pen, 1);
mapView->addMapObject(line);
}
selectedMarkers.clear();
}
void MainWindow::drawRect(bool /*checked*/)
{
for (int i = 0; i < selectedMarkers.count() - 1; i++) {
const QMapMarker* m1 = selectedMarkers[i];
const QMapMarker* m2 = selectedMarkers[i + 1];
QPen pen(Qt::white);
pen.setWidth(2);
QColor fill(Qt::black);
fill.setAlpha(65);
mapView->addMapObject(new QMapRect(m1->point(), m2->point(), pen, QBrush(fill), 1));
}
selectedMarkers.clear();
}
void MainWindow::drawEllipse(bool /*checked*/)
{
for (int i = 0; i < selectedMarkers.count() - 1; i++) {
const QMapMarker* m1 = selectedMarkers[i];
const QMapMarker* m2 = selectedMarkers[i + 1];
QPen pen(Qt::white);
pen.setWidth(2);
QColor fill(Qt::black);
fill.setAlpha(65);
mapView->addMapObject(new QMapEllipse(m1->point(), m2->point(), pen, QBrush(fill), 1));
}
selectedMarkers.clear();
}
void MainWindow::drawPolygon(bool /*checked*/)
{
QList<QGeoCoordinate> coords;
for (int i = 0; i < selectedMarkers.count(); i++) {
coords.append(selectedMarkers[i]->point());
}
QPen pen(Qt::white);
pen.setWidth(2);
QColor fill(Qt::black);
fill.setAlpha(65);
mapView->addMapObject(new QMapPolygon(coords, pen, QBrush(fill), 1));
selectedMarkers.clear();
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: accessiblecomponenthelper.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: vg $ $Date: 2005-02-16 15:50:52 $
*
* 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 EXPRESS 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 COMPHELPER_ACCESSIBLE_COMPONENT_HELPER_HXX
#define COMPHELPER_ACCESSIBLE_COMPONENT_HELPER_HXX
#ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLECOMPONENT_HPP_
#include <com/sun/star/accessibility/XAccessibleComponent.hpp>
#endif
#ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLEEXTENDEDCOMPONENT_HPP_
#include <com/sun/star/accessibility/XAccessibleExtendedComponent.hpp>
#endif
#ifndef COMPHELPER_ACCESSIBLE_CONTEXT_HELPER_HXX
#include <comphelper/accessiblecontexthelper.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef _COMPHELPER_UNO3_HXX_
#include <comphelper/uno3.hxx>
#endif
#ifndef INCLUDED_COMPHELPERDLLAPI_H
#include "comphelper/comphelperdllapi.h"
#endif
//.........................................................................
namespace comphelper
{
//.........................................................................
//=====================================================================
//= OCommonAccessibleComponent
//=====================================================================
/** base class encapsulating common functionality for the helper classes implementing
the XAccessibleComponent respectively XAccessibleExtendendComponent
*/
class COMPHELPER_DLLPUBLIC OCommonAccessibleComponent : public OAccessibleContextHelper
{
protected:
OCommonAccessibleComponent();
/// see the respective base class ctor for an extensive comment on this, please
OCommonAccessibleComponent( IMutex* _pExternalLock );
~OCommonAccessibleComponent();
protected:
/// implements the calculation of the bounding rectangle - still waiting to be overwritten
virtual ::com::sun::star::awt::Rectangle SAL_CALL implGetBounds( ) throw (::com::sun::star::uno::RuntimeException) = 0;
protected:
/** non-virtual versions of the methods which can be implemented using <method>implGetBounds</method>
note: getLocationOnScreen relies on a valid parent (XAccessibleContext::getParent()->getAccessibleContext()),
which itself implements XAccessibleComponent
*/
sal_Bool SAL_CALL containsPoint( const ::com::sun::star::awt::Point& aPoint ) throw (::com::sun::star::uno::RuntimeException);
::com::sun::star::awt::Point SAL_CALL getLocation( ) throw (::com::sun::star::uno::RuntimeException);
::com::sun::star::awt::Point SAL_CALL getLocationOnScreen( ) throw (::com::sun::star::uno::RuntimeException);
::com::sun::star::awt::Size SAL_CALL getSize( ) throw (::com::sun::star::uno::RuntimeException);
::com::sun::star::awt::Rectangle SAL_CALL getBounds( ) throw (::com::sun::star::uno::RuntimeException);
};
//=====================================================================
//= OAccessibleComponentHelper
//=====================================================================
struct OAccessibleComponentHelper_Base :
public ::cppu::ImplHelper1< ::com::sun::star::accessibility::XAccessibleComponent >
{};
/** a helper class for implementing an AccessibleContext which at the same time
supports an XAccessibleComponent interface.
*/
class COMPHELPER_DLLPUBLIC OAccessibleComponentHelper
:public OCommonAccessibleComponent
,public OAccessibleComponentHelper_Base
{
protected:
OAccessibleComponentHelper( );
/// see the respective base class ctor for an extensive comment on this, please
OAccessibleComponentHelper( IMutex* _pExternalLock );
public:
// XInterface
DECLARE_XINTERFACE( )
DECLARE_XTYPEPROVIDER( )
// XAccessibleComponent - default implementations
virtual sal_Bool SAL_CALL containsPoint( const ::com::sun::star::awt::Point& aPoint ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::awt::Point SAL_CALL getLocation( ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::awt::Point SAL_CALL getLocationOnScreen( ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::awt::Size SAL_CALL getSize( ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::awt::Rectangle SAL_CALL getBounds( ) throw (::com::sun::star::uno::RuntimeException);
};
//=====================================================================
//= OAccessibleExtendedComponentHelper
//=====================================================================
typedef ::cppu::ImplHelper1 < ::com::sun::star::accessibility::XAccessibleExtendedComponent
> OAccessibleExtendedComponentHelper_Base;
/** a helper class for implementing an AccessibleContext which at the same time
supports an XAccessibleExtendedComponent interface.
*/
class COMPHELPER_DLLPUBLIC OAccessibleExtendedComponentHelper
:public OCommonAccessibleComponent
,public OAccessibleExtendedComponentHelper_Base
{
protected:
OAccessibleExtendedComponentHelper( );
/// see the respective base class ctor for an extensive comment on this, please
OAccessibleExtendedComponentHelper( IMutex* _pExternalLock );
public:
// XInterface
DECLARE_XINTERFACE( )
DECLARE_XTYPEPROVIDER( )
// XAccessibleComponent - default implementations
virtual sal_Bool SAL_CALL containsPoint( const ::com::sun::star::awt::Point& aPoint ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::awt::Point SAL_CALL getLocation( ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::awt::Point SAL_CALL getLocationOnScreen( ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::awt::Size SAL_CALL getSize( ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::awt::Rectangle SAL_CALL getBounds( ) throw (::com::sun::star::uno::RuntimeException);
};
//.........................................................................
} // namespace comphelper
//.........................................................................
#endif // COMPHELPER_ACCESSIBLE_COMPONENT_HELPER_HXX
<commit_msg>INTEGRATION: CWS ooo19126 (1.5.56); FILE MERGED 2005/09/05 15:23:36 rt 1.5.56.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: accessiblecomponenthelper.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: rt $ $Date: 2005-09-08 02:24:35 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef COMPHELPER_ACCESSIBLE_COMPONENT_HELPER_HXX
#define COMPHELPER_ACCESSIBLE_COMPONENT_HELPER_HXX
#ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLECOMPONENT_HPP_
#include <com/sun/star/accessibility/XAccessibleComponent.hpp>
#endif
#ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLEEXTENDEDCOMPONENT_HPP_
#include <com/sun/star/accessibility/XAccessibleExtendedComponent.hpp>
#endif
#ifndef COMPHELPER_ACCESSIBLE_CONTEXT_HELPER_HXX
#include <comphelper/accessiblecontexthelper.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef _COMPHELPER_UNO3_HXX_
#include <comphelper/uno3.hxx>
#endif
#ifndef INCLUDED_COMPHELPERDLLAPI_H
#include "comphelper/comphelperdllapi.h"
#endif
//.........................................................................
namespace comphelper
{
//.........................................................................
//=====================================================================
//= OCommonAccessibleComponent
//=====================================================================
/** base class encapsulating common functionality for the helper classes implementing
the XAccessibleComponent respectively XAccessibleExtendendComponent
*/
class COMPHELPER_DLLPUBLIC OCommonAccessibleComponent : public OAccessibleContextHelper
{
protected:
OCommonAccessibleComponent();
/// see the respective base class ctor for an extensive comment on this, please
OCommonAccessibleComponent( IMutex* _pExternalLock );
~OCommonAccessibleComponent();
protected:
/// implements the calculation of the bounding rectangle - still waiting to be overwritten
virtual ::com::sun::star::awt::Rectangle SAL_CALL implGetBounds( ) throw (::com::sun::star::uno::RuntimeException) = 0;
protected:
/** non-virtual versions of the methods which can be implemented using <method>implGetBounds</method>
note: getLocationOnScreen relies on a valid parent (XAccessibleContext::getParent()->getAccessibleContext()),
which itself implements XAccessibleComponent
*/
sal_Bool SAL_CALL containsPoint( const ::com::sun::star::awt::Point& aPoint ) throw (::com::sun::star::uno::RuntimeException);
::com::sun::star::awt::Point SAL_CALL getLocation( ) throw (::com::sun::star::uno::RuntimeException);
::com::sun::star::awt::Point SAL_CALL getLocationOnScreen( ) throw (::com::sun::star::uno::RuntimeException);
::com::sun::star::awt::Size SAL_CALL getSize( ) throw (::com::sun::star::uno::RuntimeException);
::com::sun::star::awt::Rectangle SAL_CALL getBounds( ) throw (::com::sun::star::uno::RuntimeException);
};
//=====================================================================
//= OAccessibleComponentHelper
//=====================================================================
struct OAccessibleComponentHelper_Base :
public ::cppu::ImplHelper1< ::com::sun::star::accessibility::XAccessibleComponent >
{};
/** a helper class for implementing an AccessibleContext which at the same time
supports an XAccessibleComponent interface.
*/
class COMPHELPER_DLLPUBLIC OAccessibleComponentHelper
:public OCommonAccessibleComponent
,public OAccessibleComponentHelper_Base
{
protected:
OAccessibleComponentHelper( );
/// see the respective base class ctor for an extensive comment on this, please
OAccessibleComponentHelper( IMutex* _pExternalLock );
public:
// XInterface
DECLARE_XINTERFACE( )
DECLARE_XTYPEPROVIDER( )
// XAccessibleComponent - default implementations
virtual sal_Bool SAL_CALL containsPoint( const ::com::sun::star::awt::Point& aPoint ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::awt::Point SAL_CALL getLocation( ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::awt::Point SAL_CALL getLocationOnScreen( ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::awt::Size SAL_CALL getSize( ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::awt::Rectangle SAL_CALL getBounds( ) throw (::com::sun::star::uno::RuntimeException);
};
//=====================================================================
//= OAccessibleExtendedComponentHelper
//=====================================================================
typedef ::cppu::ImplHelper1 < ::com::sun::star::accessibility::XAccessibleExtendedComponent
> OAccessibleExtendedComponentHelper_Base;
/** a helper class for implementing an AccessibleContext which at the same time
supports an XAccessibleExtendedComponent interface.
*/
class COMPHELPER_DLLPUBLIC OAccessibleExtendedComponentHelper
:public OCommonAccessibleComponent
,public OAccessibleExtendedComponentHelper_Base
{
protected:
OAccessibleExtendedComponentHelper( );
/// see the respective base class ctor for an extensive comment on this, please
OAccessibleExtendedComponentHelper( IMutex* _pExternalLock );
public:
// XInterface
DECLARE_XINTERFACE( )
DECLARE_XTYPEPROVIDER( )
// XAccessibleComponent - default implementations
virtual sal_Bool SAL_CALL containsPoint( const ::com::sun::star::awt::Point& aPoint ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::awt::Point SAL_CALL getLocation( ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::awt::Point SAL_CALL getLocationOnScreen( ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::awt::Size SAL_CALL getSize( ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::awt::Rectangle SAL_CALL getBounds( ) throw (::com::sun::star::uno::RuntimeException);
};
//.........................................................................
} // namespace comphelper
//.........................................................................
#endif // COMPHELPER_ACCESSIBLE_COMPONENT_HELPER_HXX
<|endoftext|> |
<commit_before><commit_msg>Fix Linux build break.<commit_after><|endoftext|> |
<commit_before>#include "robobo.h"
int main(int argc, char** argv) {
std::string confDir = ".";
std::string confName = "robobo.conf";
if (argc > 1) { // analyze arguments
bool exitAfter = false;
for (int i = 1; i < argc; i++) { // iterate through all arguments
if (strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "-?") == 0) {
std::cout << "RoBoBo-IRC-BoBo IRC Bot Help" << std::endl;
std::cout << std::endl;
std::cout << "RoBoBo can connect to IRC servers. All of its functionality outside of" << std::endl << "connecting to servers is provided by loaded modules." << std::endl;
std::cout << "See the README file for more information." << std::endl;
std::cout << std::endl;
std::cout << "Some command line arguments are provided to perform certain actions. With no" << std::endl << "parameters, the bot will run as a bot. With some command line arguments, the" << std::endl << "functionality of the bot can be changed." << std::endl;
std::cout << "Command Line Arguments:" << std::endl;
std::cout << "\t--help: display this help and exit" << std::endl;
std::cout << "\t--version: display RoBoBo's version and exit" << std::endl;
std::cout << "\t--confdir <directory>: make RoBoBo look in the specified directory for the configuration" << std::endl;
std::cout << "\t--confname <filename>: make RoBoBo look for the specified file in the conf directory for configuration information" << std::endl;
exitAfter = true;
} else if (strcmp(argv[i], "--version") == 0 || strcmp(argv[i], "-v") == 0) {
std::cout << "RoBoBo-IRC-BoBo Pre-alpha Development Version" << std::endl;
exitAfter = true;
} else if (strcmp(argv[i], "--confdir") == 0) {
if (++i >= argc) {
std::cout << "An argument was not specified for the --confdir argument." << std::endl;
return 0;
}
confDir = argv[i];
std::cout << "Looking for the configuration file in " << confDir << std::endl;
} else if (strcmp(argv[i], "--confname") == 0) {
if (++i >= argc) {
std::cout << "An argument was not specified for the --confname argument." << std::endl;
return 0;
}
confName = argv[i];
std::cout << "Looking for a configuration file named " << confName << std::endl;
}
std::cout << std::endl; // add a newline after a parameter's output
}
if (exitAfter)
return 0;
}
new ModuleInterface (ConfigReader (confName, confDir)); //run actual bot
pthread_exit(NULL);
}<commit_msg>Add short-version arguments to help.<commit_after>#include "robobo.h"
int main(int argc, char** argv) {
std::string confDir = ".";
std::string confName = "robobo.conf";
if (argc > 1) { // analyze arguments
bool exitAfter = false;
for (int i = 1; i < argc; i++) { // iterate through all arguments
if (strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "-?") == 0) {
std::cout << "RoBoBo-IRC-BoBo IRC Bot Help" << std::endl;
std::cout << std::endl;
std::cout << "RoBoBo can connect to IRC servers. All of its functionality outside of" << std::endl << "connecting to servers is provided by loaded modules." << std::endl;
std::cout << "See the README file for more information." << std::endl;
std::cout << std::endl;
std::cout << "Some command line arguments are provided to perform certain actions. With no" << std::endl << "parameters, the bot will run as a bot. With some command line arguments, the" << std::endl << "functionality of the bot can be changed." << std::endl;
std::cout << "Command Line Arguments:" << std::endl;
std::cout << "\t--help: display this help and exit" << std::endl;
std::cout << "\t\t-h: same as --help" << std::endl;
std::cout << "\t\t-?: same as --help" << std::endl;
std::cout << "\t--version: display RoBoBo's version and exit" << std::endl;
std::cout << "\t\t-v: same as --version" << std::endl;
std::cout << "\t--confdir <directory>: make RoBoBo look in the specified directory for the configuration" << std::endl;
std::cout << "\t--confname <filename>: make RoBoBo look for the specified file in the conf directory for configuration information" << std::endl;
exitAfter = true;
} else if (strcmp(argv[i], "--version") == 0 || strcmp(argv[i], "-v") == 0) {
std::cout << "RoBoBo-IRC-BoBo Pre-alpha Development Version" << std::endl;
exitAfter = true;
} else if (strcmp(argv[i], "--confdir") == 0) {
if (++i >= argc) {
std::cout << "An argument was not specified for the --confdir argument." << std::endl;
return 0;
}
confDir = argv[i];
std::cout << "Looking for the configuration file in " << confDir << std::endl;
} else if (strcmp(argv[i], "--confname") == 0) {
if (++i >= argc) {
std::cout << "An argument was not specified for the --confname argument." << std::endl;
return 0;
}
confName = argv[i];
std::cout << "Looking for a configuration file named " << confName << std::endl;
}
std::cout << std::endl; // add a newline after a parameter's output
}
if (exitAfter)
return 0;
}
new ModuleInterface (ConfigReader (confName, confDir)); //run actual bot
pthread_exit(NULL);
}<|endoftext|> |
<commit_before>/**
* @file Cosa/Board/StandardUSB.hh
* @version 1.0
*
* @section License
* Copyright (C) 2013, Mikael Patel
*
* 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
*
* This file is part of the Arduino Che Cosa project.
*/
#ifndef __COSA_BOARD_STANDARD_USB_HH__
#define __COSA_BOARD_STANDARD_USB_HH__
/**
* Cosa STANDARD USB Board pin symbol definitions for the ATmega32u4
* based boards such as Arduino Leonardo, Micro and LilyPad USB. Cosa
* does not use pin numbers as Arduino/Wiring, instead strong data
* type is used (enum types) for the specific pin classes; DigitalPin,
* AnalogPin, PWMPin, etc.
*
* The pin numbers for ATmega32u4 are mapped as in Arduino. The static
* inline functions, SFR, BIT and UART, rely on compiler optimizations
* to be reduced.
*/
class Board {
friend class Pin;
friend class UART;
private:
/**
* Do not allow instances. This is a static singleton; name space.
*/
Board() {}
/**
* Return Special Function Register for given Arduino pin number.
* @param[in] pin number.
* @return special register pointer.
*/
static volatile uint8_t* SFR(uint8_t pin)
{
return (pin < 8 ? &PINB :
pin < 16 ? &PINC :
pin < 24 ? &PIND :
pin < 32 ? &PINE :
&PINF);
}
/**
* Return Pin Change Mask Register for given Arduino pin number.
* @param[in] pin number.
* @return pin change mask register pointer.
*/
static volatile uint8_t* PCIMR(uint8_t pin)
{
return (&PCMSK0);
}
/**
* Return bit position for given Arduino pin number in Special
* Function Register.
* @param[in] pin number.
* @return pin bit position.
*/
static const uint8_t BIT(uint8_t pin)
{
return (pin & 0x07);
}
/**
* Return UART Register for given Arduino serial port.
* @param[in] port number.
* @return UART register pointer.
*/
static volatile uint8_t* UART(uint8_t port)
{
return (&UCSR1A);
}
public:
/**
* Digital pin symbols
*/
enum DigitalPin {
D0 = 18,
D1 = 19,
D2 = 17,
D3 = 16,
D4 = 20,
D5 = 14,
D6 = 23,
D7 = 30,
D8 = 4,
D9 = 5,
D10 = 6,
D11 = 7,
D12 = 22,
D13 = 15,
D14 = 39,
D15 = 38,
D16 = 37,
D17 = 34,
D18 = 33,
D19 = 32,
LED = D13
} __attribute__((packed));
/**
* Analog pin symbols
*/
enum AnalogPin {
A0 = 39,
A1 = 38,
A2 = 37,
A3 = 34,
A4 = 33,
A5 = 32
} __attribute__((packed));
/**
* Reference voltage; ARef pin, Vcc or internal 2V56
*/
enum Reference {
APIN_REFERENCE = 0,
AVCC_REFERENCE = _BV(REFS0),
A2V56_REFERENCE = (_BV(REFS1) | _BV(REFS0))
} __attribute__((packed));
/**
* PWM pin symbols; sub-set of digital pins to allow compile
* time checking
*/
enum PWMPin {
PWM0 = D11,
PWM1 = D3,
PWM2 = D9,
PWM3 = D10,
PWM4 = D5,
PWM5 = D13,
PWM6 = D6
} __attribute__((packed));
/**
* External interrupt pin symbols; sub-set of digital pins
* to allow compile time checking.
*/
enum ExternalInterruptPin {
EXT0 = D3,
EXT1 = D2,
EXT2 = D0,
EXT3 = D1
} __attribute__((packed));
/**
* Pin change interrupt (PCI) pins. Number of port registers.
*/
enum InterruptPin {
PCI0 = 0,
PCI1 = 1,
PCI2 = 2,
PCI3 = 3,
PCI4 = 4,
PCI5 = 5,
PCI6 = 6,
PCI7 = 7
} __attribute__((packed));
/**
* Pins used for TWI interface (in port D, digital pin 2-3)
*/
enum TWIPin {
SDA = 1,
SCL = 0
} __attribute__((packed));
/**
* Pins used for SPI interface (in port B, bit 1-3)
*/
enum SPIPin {
SS = 0,
MOSI = 2,
MISO = 3,
SCK = 1
} __attribute__((packed));
/**
* Auxiliary
*/
enum {
VBG = (_BV(MUX4) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1)),
UART_MAX = 1,
EXT_MAX = 7,
PCINT_MAX = 1,
PIN_MAX = 38
} __attribute__((packed));
};
/**
* Redefined symbols to allow generic code.
*/
#define USART_UDRE_vect USART1_UDRE_vect
#define USART_RX_vect USART1_RX_vect
#define USART_TX_vect USART1_TX_vect
#define UCSZ00 UCSZ10
#define UCSZ01 UCSZ11
#define UCSZ02 UCSZ12
#define UPM00 UPM10
#define UPM01 UPM11
#define USBS0 USBS1
#define U2X0 U2X1
#define RXCIE0 RXCIE1
#define RXEN0 RXEN1
#define TXEN0 TXEN1
#define UDRIE0 UDRIE1
#define TXCIE0 TXCIE1
/**
* Forward declare interrupt service routines to allow them as friends.
*/
extern "C" {
void ADC_vect(void) __attribute__ ((signal));
void ANALOG_COMP_vect(void) __attribute__ ((signal));
void INT0_vect(void) __attribute__ ((signal));
void INT1_vect(void) __attribute__ ((signal));
void INT2_vect(void) __attribute__ ((signal));
void INT3_vect(void) __attribute__ ((signal));
void INT6_vect(void) __attribute__ ((signal));
void PCINT0_vect(void) __attribute__ ((signal));
void SPI_STC_vect(void) __attribute__ ((signal));
void TIMER0_COMPA_vect(void) __attribute__ ((signal));
void TIMER0_COMPB_vect(void) __attribute__ ((signal));
void TIMER0_OVF_vect(void) __attribute__ ((signal));
void TIMER1_CAPT_vect(void) __attribute__ ((signal));
void TIMER1_COMPA_vect(void) __attribute__ ((signal));
void TIMER1_COMPB_vect(void) __attribute__ ((signal));
void TIMER1_COMPC_vect(void) __attribute__ ((signal));
void TIMER1_OVF_vect(void) __attribute__ ((signal));
void TIMER3_CAPT_vect(void) __attribute__ ((signal));
void TIMER3_COMPA_vect(void) __attribute__ ((signal));
void TIMER3_COMPB_vect(void) __attribute__ ((signal));
void TIMER3_COMPC_vect(void) __attribute__ ((signal));
void TIMER3_OVF_vect(void) __attribute__ ((signal));
void TIMER4_COMPA_vect(void) __attribute__ ((signal));
void TIMER4_COMPB_vect(void) __attribute__ ((signal));
void TIMER4_COMPD_vect(void) __attribute__ ((signal));
void TIMER4_FPF_vect(void) __attribute__ ((signal));
void TIMER4_OVF_vect(void) __attribute__ ((signal));
void TWI_vect(void) __attribute__ ((signal));
void WDT_vect(void) __attribute__ ((signal));
void USART_RX_vect(void) __attribute__ ((signal));
void USART_TX_vect(void) __attribute__ ((signal));
void USART_UDRE_vect(void) __attribute__ ((signal));
void USB_COM_vect(void) __attribute__ ((signal));
void USB_GEN_vect(void) __attribute__ ((signal));
}
#endif
<commit_msg>Restore missing ADCW symbol for Atmega32u4 variant.<commit_after>/**
* @file Cosa/Board/StandardUSB.hh
* @version 1.0
*
* @section License
* Copyright (C) 2013, Mikael Patel
*
* 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
*
* This file is part of the Arduino Che Cosa project.
*/
#ifndef __COSA_BOARD_STANDARD_USB_HH__
#define __COSA_BOARD_STANDARD_USB_HH__
/**
* Cosa STANDARD USB Board pin symbol definitions for the ATmega32u4
* based boards such as Arduino Leonardo, Micro and LilyPad USB. Cosa
* does not use pin numbers as Arduino/Wiring, instead strong data
* type is used (enum types) for the specific pin classes; DigitalPin,
* AnalogPin, PWMPin, etc.
*
* The pin numbers for ATmega32u4 are mapped as in Arduino. The static
* inline functions, SFR, BIT and UART, rely on compiler optimizations
* to be reduced.
*/
class Board {
friend class Pin;
friend class UART;
private:
/**
* Do not allow instances. This is a static singleton; name space.
*/
Board() {}
/**
* Return Special Function Register for given Arduino pin number.
* @param[in] pin number.
* @return special register pointer.
*/
static volatile uint8_t* SFR(uint8_t pin)
{
return (pin < 8 ? &PINB :
pin < 16 ? &PINC :
pin < 24 ? &PIND :
pin < 32 ? &PINE :
&PINF);
}
/**
* Return Pin Change Mask Register for given Arduino pin number.
* @param[in] pin number.
* @return pin change mask register pointer.
*/
static volatile uint8_t* PCIMR(uint8_t pin)
{
return (&PCMSK0);
}
/**
* Return bit position for given Arduino pin number in Special
* Function Register.
* @param[in] pin number.
* @return pin bit position.
*/
static const uint8_t BIT(uint8_t pin)
{
return (pin & 0x07);
}
/**
* Return UART Register for given Arduino serial port.
* @param[in] port number.
* @return UART register pointer.
*/
static volatile uint8_t* UART(uint8_t port)
{
return (&UCSR1A);
}
public:
/**
* Digital pin symbols
*/
enum DigitalPin {
D0 = 18,
D1 = 19,
D2 = 17,
D3 = 16,
D4 = 20,
D5 = 14,
D6 = 23,
D7 = 30,
D8 = 4,
D9 = 5,
D10 = 6,
D11 = 7,
D12 = 22,
D13 = 15,
D14 = 39,
D15 = 38,
D16 = 37,
D17 = 34,
D18 = 33,
D19 = 32,
LED = D13
} __attribute__((packed));
/**
* Analog pin symbols
*/
enum AnalogPin {
A0 = 39,
A1 = 38,
A2 = 37,
A3 = 34,
A4 = 33,
A5 = 32
} __attribute__((packed));
/**
* Reference voltage; ARef pin, Vcc or internal 2V56
*/
enum Reference {
APIN_REFERENCE = 0,
AVCC_REFERENCE = _BV(REFS0),
A2V56_REFERENCE = (_BV(REFS1) | _BV(REFS0))
} __attribute__((packed));
/**
* PWM pin symbols; sub-set of digital pins to allow compile
* time checking
*/
enum PWMPin {
PWM0 = D11,
PWM1 = D3,
PWM2 = D9,
PWM3 = D10,
PWM4 = D5,
PWM5 = D13,
PWM6 = D6
} __attribute__((packed));
/**
* External interrupt pin symbols; sub-set of digital pins
* to allow compile time checking.
*/
enum ExternalInterruptPin {
EXT0 = D3,
EXT1 = D2,
EXT2 = D0,
EXT3 = D1
} __attribute__((packed));
/**
* Pin change interrupt (PCI) pins. Number of port registers.
*/
enum InterruptPin {
PCI0 = 0,
PCI1 = 1,
PCI2 = 2,
PCI3 = 3,
PCI4 = 4,
PCI5 = 5,
PCI6 = 6,
PCI7 = 7
} __attribute__((packed));
/**
* Pins used for TWI interface (in port D, digital pin 2-3)
*/
enum TWIPin {
SDA = 1,
SCL = 0
} __attribute__((packed));
/**
* Pins used for SPI interface (in port B, bit 1-3)
*/
enum SPIPin {
SS = 0,
MOSI = 2,
MISO = 3,
SCK = 1
} __attribute__((packed));
/**
* Auxiliary
*/
enum {
VBG = (_BV(MUX4) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1)),
UART_MAX = 1,
EXT_MAX = 7,
PCINT_MAX = 1,
PIN_MAX = 38
} __attribute__((packed));
};
/**
* Redefined symbols to allow generic code.
*/
#define USART_UDRE_vect USART1_UDRE_vect
#define USART_RX_vect USART1_RX_vect
#define USART_TX_vect USART1_TX_vect
#define UCSZ00 UCSZ10
#define UCSZ01 UCSZ11
#define UCSZ02 UCSZ12
#define UPM00 UPM10
#define UPM01 UPM11
#define USBS0 USBS1
#define U2X0 U2X1
#define RXCIE0 RXCIE1
#define RXEN0 RXEN1
#define TXEN0 TXEN1
#define UDRIE0 UDRIE1
#define TXCIE0 TXCIE1
#if !defined(ADCW)
#define ADCW ADC
#endif
/**
* Forward declare interrupt service routines to allow them as friends.
*/
extern "C" {
void ADC_vect(void) __attribute__ ((signal));
void ANALOG_COMP_vect(void) __attribute__ ((signal));
void INT0_vect(void) __attribute__ ((signal));
void INT1_vect(void) __attribute__ ((signal));
void INT2_vect(void) __attribute__ ((signal));
void INT3_vect(void) __attribute__ ((signal));
void INT6_vect(void) __attribute__ ((signal));
void PCINT0_vect(void) __attribute__ ((signal));
void SPI_STC_vect(void) __attribute__ ((signal));
void TIMER0_COMPA_vect(void) __attribute__ ((signal));
void TIMER0_COMPB_vect(void) __attribute__ ((signal));
void TIMER0_OVF_vect(void) __attribute__ ((signal));
void TIMER1_CAPT_vect(void) __attribute__ ((signal));
void TIMER1_COMPA_vect(void) __attribute__ ((signal));
void TIMER1_COMPB_vect(void) __attribute__ ((signal));
void TIMER1_COMPC_vect(void) __attribute__ ((signal));
void TIMER1_OVF_vect(void) __attribute__ ((signal));
void TIMER3_CAPT_vect(void) __attribute__ ((signal));
void TIMER3_COMPA_vect(void) __attribute__ ((signal));
void TIMER3_COMPB_vect(void) __attribute__ ((signal));
void TIMER3_COMPC_vect(void) __attribute__ ((signal));
void TIMER3_OVF_vect(void) __attribute__ ((signal));
void TIMER4_COMPA_vect(void) __attribute__ ((signal));
void TIMER4_COMPB_vect(void) __attribute__ ((signal));
void TIMER4_COMPD_vect(void) __attribute__ ((signal));
void TIMER4_FPF_vect(void) __attribute__ ((signal));
void TIMER4_OVF_vect(void) __attribute__ ((signal));
void TWI_vect(void) __attribute__ ((signal));
void WDT_vect(void) __attribute__ ((signal));
void USART_RX_vect(void) __attribute__ ((signal));
void USART_TX_vect(void) __attribute__ ((signal));
void USART_UDRE_vect(void) __attribute__ ((signal));
void USB_COM_vect(void) __attribute__ ((signal));
void USB_GEN_vect(void) __attribute__ ((signal));
}
#endif
<|endoftext|> |
<commit_before>#include "base.hpp"
#include "ButtonStatus.hpp"
#include "Client.hpp"
#include "CommonData.hpp"
#include "Config.hpp"
#include "Core.hpp"
#include "RemapClass.hpp"
#include "remap.hpp"
#include "util/CallBackWrapper.hpp"
#include "util/EventInputQueue.hpp"
#include "util/EventOutputQueue.hpp"
#include "util/EventWatcher.hpp"
#include "util/KeyboardRepeat.hpp"
#include "util/ListHookedConsumer.hpp"
#include "util/ListHookedKeyboard.hpp"
#include "util/ListHookedPointing.hpp"
#include "util/NumHeldDownKeys.hpp"
#include "util/PressDownKeys.hpp"
#include "util/TimerWrapper.hpp"
#include "RemapFunc/HoldingKeyToKey.hpp"
#include "RemapFunc/KeyOverlaidModifier.hpp"
#include "RemapFunc/PointingRelativeToScroll.hpp"
#include "VirtualKey.hpp"
#include <sys/errno.h>
#include <IOKit/IOWorkLoop.h>
#include <IOKit/IOTimerEventSource.h>
namespace org_pqrs_KeyRemap4MacBook {
namespace Core {
namespace {
IOWorkLoop* workLoop = NULL;
TimerWrapper timer_refresh;
// ------------------------------------------------------------
enum {
REFRESH_DEVICE_INTERVAL = 3000,
};
void
refreshHookedDevice(OSObject* owner, IOTimerEventSource* sender)
{
IOLockWrapper::ScopedLock lk(timer_refresh.getlock());
ListHookedKeyboard::instance().refresh_callback();
ListHookedConsumer::instance().refresh_callback();
ListHookedPointing::instance().refresh_callback();
timer_refresh.setTimeoutMS(REFRESH_DEVICE_INTERVAL);
}
}
void
start(void)
{
CommonData::initialize();
EventWatcher::initialize();
PressDownKeys::initialize();
FlagStatus::initialize();
ButtonStatus::initialize();
KeyRemap4MacBook_client::initialize();
ListHookedKeyboard::instance().initialize();
ListHookedConsumer::instance().initialize();
ListHookedPointing::instance().initialize();
workLoop = IOWorkLoop::workLoop();
if (! workLoop) {
IOLOG_ERROR("IOWorkLoop::workLoop failed\n");
} else {
timer_refresh.initialize(workLoop, NULL, refreshHookedDevice);
timer_refresh.setTimeoutMS(REFRESH_DEVICE_INTERVAL);
KeyboardRepeat::initialize(*workLoop);
EventInputQueue::initialize(*workLoop);
VirtualKey::initialize(*workLoop);
EventOutputQueue::initialize(*workLoop);
RemapFunc::HoldingKeyToKey::static_initialize(*workLoop);
RemapFunc::KeyOverlaidModifier::static_initialize(*workLoop);
RemapFunc::PointingRelativeToScroll::static_initialize(*workLoop);
ListHookedKeyboard::static_initialize(*workLoop);
RemapClassManager::initialize(*workLoop);
}
sysctl_register();
}
void
stop(void)
{
{
IOLockWrapper::ScopedLock lk_eventlock(CommonData::getEventLock());
sysctl_unregister();
timer_refresh.terminate();
RemapClassManager::terminate();
ListHookedKeyboard::instance().terminate();
ListHookedConsumer::instance().terminate();
ListHookedPointing::instance().terminate();
KeyboardRepeat::terminate();
EventInputQueue::terminate();
VirtualKey::terminate();
EventOutputQueue::terminate();
RemapFunc::HoldingKeyToKey::static_terminate();
RemapFunc::KeyOverlaidModifier::static_terminate();
RemapFunc::PointingRelativeToScroll::static_terminate();
ListHookedKeyboard::static_terminate();
if (workLoop) {
workLoop->release();
workLoop = NULL;
}
KeyRemap4MacBook_client::terminate();
EventWatcher::terminate();
PressDownKeys::terminate();
}
CommonData::terminate();
}
// ======================================================================
bool
notifierfunc_hookKeyboard(void* target, void* refCon, IOService* newService, IONotifier* notifier)
{
IOLOG_DEBUG("notifierfunc_hookKeyboard newService:%p\n", newService);
IOHIDevice* device = OSDynamicCast(IOHIKeyboard, newService);
if (! device) return false;
ListHookedKeyboard::instance().push_back(new ListHookedKeyboard::Item(device));
ListHookedConsumer::instance().push_back(new ListHookedConsumer::Item(device));
return true;
}
bool
notifierfunc_unhookKeyboard(void* target, void* refCon, IOService* newService, IONotifier* notifier)
{
IOLOG_DEBUG("notifierfunc_unhookKeyboard newService:%p\n", newService);
IOHIDevice* device = OSDynamicCast(IOHIKeyboard, newService);
if (! device) return false;
ListHookedKeyboard::instance().erase(device);
ListHookedConsumer::instance().erase(device);
return true;
}
bool
notifierfunc_hookPointing(void* target, void* refCon, IOService* newService, IONotifier* notifier)
{
IOLOG_DEBUG("notifierfunc_hookPointing newService:%p\n", newService);
IOHIDevice* device = OSDynamicCast(IOHIPointing, newService);
if (! device) return false;
ListHookedPointing::instance().push_back(new ListHookedPointing::Item(device));
return true;
}
bool
notifierfunc_unhookPointing(void* target, void* refCon, IOService* newService, IONotifier* notifier)
{
IOLOG_DEBUG("notifierfunc_unhookPointing newService:%p\n", newService);
IOHIDevice* device = OSDynamicCast(IOHIPointing, newService);
if (! device) return false;
ListHookedPointing::instance().erase(device);
return true;
}
// ======================================================================
void
remap_KeyboardEventCallback(Params_KeyboardEventCallBack& params)
{
params.log();
// ------------------------------------------------------------
RemapParams remapParams(params);
// ------------------------------------------------------------
FlagStatus::set(params.key, params.flags);
RemapClassManager::remap_key(remapParams);
// ------------------------------------------------------------
if (! remapParams.isremapped) {
Params_KeyboardEventCallBack::auto_ptr ptr(Params_KeyboardEventCallBack::alloc(params.eventType, FlagStatus::makeFlags(), params.key,
params.charCode, params.charSet, params.origCharCode, params.origCharSet,
params.keyboardType, false));
if (ptr) {
KeyboardRepeat::set(*ptr);
EventOutputQueue::FireKey::fire(*ptr);
}
}
if (NumHeldDownKeys::iszero()) {
NumHeldDownKeys::reset();
KeyboardRepeat::cancel();
EventWatcher::reset();
FlagStatus::reset();
ButtonStatus::reset();
VirtualKey::reset();
EventOutputQueue::FireModifiers::fire(FlagStatus::makeFlags());
EventOutputQueue::FireRelativePointer::fire();
PressDownKeys::clear();
}
RemapFunc::PointingRelativeToScroll::cancelScroll();
}
void
remap_KeyboardSpecialEventCallback(Params_KeyboardSpecialEventCallback& params)
{
params.log();
RemapConsumerParams remapParams(params);
// ------------------------------------------------------------
RemapClassManager::remap_consumer(remapParams);
// ----------------------------------------
if (! remapParams.isremapped) {
Params_KeyboardSpecialEventCallback::auto_ptr ptr(Params_KeyboardSpecialEventCallback::alloc(params.eventType, FlagStatus::makeFlags(), params.key,
params.flavor, params.guid, false));
if (ptr) {
KeyboardRepeat::set(*ptr);
EventOutputQueue::FireConsumer::fire(*ptr);
}
}
RemapFunc::PointingRelativeToScroll::cancelScroll();
}
void
remap_RelativePointerEventCallback(Params_RelativePointerEventCallback& params)
{
params.log();
RemapPointingParams_relative remapParams(params);
ButtonStatus::set(params.ex_button, params.ex_isbuttondown);
RemapClassManager::remap_pointing(remapParams);
// ------------------------------------------------------------
if (! remapParams.isremapped) {
EventOutputQueue::FireRelativePointer::fire(ButtonStatus::makeButtons(), params.dx, params.dy);
}
}
void
remap_ScrollWheelEventCallback(Params_ScrollWheelEventCallback& params)
{
params.log();
EventOutputQueue::FireScrollWheel::fire(params);
RemapFunc::PointingRelativeToScroll::cancelScroll();
}
}
}
<commit_msg>use CommonData::getEventLock @ notifierfunc_*<commit_after>#include "base.hpp"
#include "ButtonStatus.hpp"
#include "Client.hpp"
#include "CommonData.hpp"
#include "Config.hpp"
#include "Core.hpp"
#include "RemapClass.hpp"
#include "remap.hpp"
#include "util/CallBackWrapper.hpp"
#include "util/EventInputQueue.hpp"
#include "util/EventOutputQueue.hpp"
#include "util/EventWatcher.hpp"
#include "util/KeyboardRepeat.hpp"
#include "util/ListHookedConsumer.hpp"
#include "util/ListHookedKeyboard.hpp"
#include "util/ListHookedPointing.hpp"
#include "util/NumHeldDownKeys.hpp"
#include "util/PressDownKeys.hpp"
#include "util/TimerWrapper.hpp"
#include "RemapFunc/HoldingKeyToKey.hpp"
#include "RemapFunc/KeyOverlaidModifier.hpp"
#include "RemapFunc/PointingRelativeToScroll.hpp"
#include "VirtualKey.hpp"
#include <sys/errno.h>
#include <IOKit/IOWorkLoop.h>
#include <IOKit/IOTimerEventSource.h>
namespace org_pqrs_KeyRemap4MacBook {
namespace Core {
namespace {
IOWorkLoop* workLoop = NULL;
TimerWrapper timer_refresh;
// ------------------------------------------------------------
enum {
REFRESH_DEVICE_INTERVAL = 3000,
};
void
refreshHookedDevice(OSObject* owner, IOTimerEventSource* sender)
{
IOLockWrapper::ScopedLock lk(timer_refresh.getlock());
ListHookedKeyboard::instance().refresh_callback();
ListHookedConsumer::instance().refresh_callback();
ListHookedPointing::instance().refresh_callback();
timer_refresh.setTimeoutMS(REFRESH_DEVICE_INTERVAL);
}
}
void
start(void)
{
CommonData::initialize();
EventWatcher::initialize();
PressDownKeys::initialize();
FlagStatus::initialize();
ButtonStatus::initialize();
KeyRemap4MacBook_client::initialize();
ListHookedKeyboard::instance().initialize();
ListHookedConsumer::instance().initialize();
ListHookedPointing::instance().initialize();
workLoop = IOWorkLoop::workLoop();
if (! workLoop) {
IOLOG_ERROR("IOWorkLoop::workLoop failed\n");
} else {
timer_refresh.initialize(workLoop, NULL, refreshHookedDevice);
timer_refresh.setTimeoutMS(REFRESH_DEVICE_INTERVAL);
KeyboardRepeat::initialize(*workLoop);
EventInputQueue::initialize(*workLoop);
VirtualKey::initialize(*workLoop);
EventOutputQueue::initialize(*workLoop);
RemapFunc::HoldingKeyToKey::static_initialize(*workLoop);
RemapFunc::KeyOverlaidModifier::static_initialize(*workLoop);
RemapFunc::PointingRelativeToScroll::static_initialize(*workLoop);
ListHookedKeyboard::static_initialize(*workLoop);
RemapClassManager::initialize(*workLoop);
}
sysctl_register();
}
void
stop(void)
{
{
IOLockWrapper::ScopedLock lk_eventlock(CommonData::getEventLock());
sysctl_unregister();
timer_refresh.terminate();
RemapClassManager::terminate();
ListHookedKeyboard::instance().terminate();
ListHookedConsumer::instance().terminate();
ListHookedPointing::instance().terminate();
KeyboardRepeat::terminate();
EventInputQueue::terminate();
VirtualKey::terminate();
EventOutputQueue::terminate();
RemapFunc::HoldingKeyToKey::static_terminate();
RemapFunc::KeyOverlaidModifier::static_terminate();
RemapFunc::PointingRelativeToScroll::static_terminate();
ListHookedKeyboard::static_terminate();
if (workLoop) {
workLoop->release();
workLoop = NULL;
}
KeyRemap4MacBook_client::terminate();
EventWatcher::terminate();
PressDownKeys::terminate();
}
CommonData::terminate();
}
// ======================================================================
bool
notifierfunc_hookKeyboard(void* target, void* refCon, IOService* newService, IONotifier* notifier)
{
IOLockWrapper::ScopedLock lk_eventlock(CommonData::getEventLock());
IOLOG_DEBUG("notifierfunc_hookKeyboard newService:%p\n", newService);
IOHIDevice* device = OSDynamicCast(IOHIKeyboard, newService);
if (! device) return false;
ListHookedKeyboard::instance().push_back(new ListHookedKeyboard::Item(device));
ListHookedConsumer::instance().push_back(new ListHookedConsumer::Item(device));
return true;
}
bool
notifierfunc_unhookKeyboard(void* target, void* refCon, IOService* newService, IONotifier* notifier)
{
IOLockWrapper::ScopedLock lk_eventlock(CommonData::getEventLock());
IOLOG_DEBUG("notifierfunc_unhookKeyboard newService:%p\n", newService);
IOHIDevice* device = OSDynamicCast(IOHIKeyboard, newService);
if (! device) return false;
ListHookedKeyboard::instance().erase(device);
ListHookedConsumer::instance().erase(device);
return true;
}
bool
notifierfunc_hookPointing(void* target, void* refCon, IOService* newService, IONotifier* notifier)
{
IOLockWrapper::ScopedLock lk_eventlock(CommonData::getEventLock());
IOLOG_DEBUG("notifierfunc_hookPointing newService:%p\n", newService);
IOHIDevice* device = OSDynamicCast(IOHIPointing, newService);
if (! device) return false;
ListHookedPointing::instance().push_back(new ListHookedPointing::Item(device));
return true;
}
bool
notifierfunc_unhookPointing(void* target, void* refCon, IOService* newService, IONotifier* notifier)
{
IOLockWrapper::ScopedLock lk_eventlock(CommonData::getEventLock());
IOLOG_DEBUG("notifierfunc_unhookPointing newService:%p\n", newService);
IOHIDevice* device = OSDynamicCast(IOHIPointing, newService);
if (! device) return false;
ListHookedPointing::instance().erase(device);
return true;
}
// ======================================================================
void
remap_KeyboardEventCallback(Params_KeyboardEventCallBack& params)
{
params.log();
// ------------------------------------------------------------
RemapParams remapParams(params);
// ------------------------------------------------------------
FlagStatus::set(params.key, params.flags);
RemapClassManager::remap_key(remapParams);
// ------------------------------------------------------------
if (! remapParams.isremapped) {
Params_KeyboardEventCallBack::auto_ptr ptr(Params_KeyboardEventCallBack::alloc(params.eventType, FlagStatus::makeFlags(), params.key,
params.charCode, params.charSet, params.origCharCode, params.origCharSet,
params.keyboardType, false));
if (ptr) {
KeyboardRepeat::set(*ptr);
EventOutputQueue::FireKey::fire(*ptr);
}
}
if (NumHeldDownKeys::iszero()) {
NumHeldDownKeys::reset();
KeyboardRepeat::cancel();
EventWatcher::reset();
FlagStatus::reset();
ButtonStatus::reset();
VirtualKey::reset();
EventOutputQueue::FireModifiers::fire(FlagStatus::makeFlags());
EventOutputQueue::FireRelativePointer::fire();
PressDownKeys::clear();
}
RemapFunc::PointingRelativeToScroll::cancelScroll();
}
void
remap_KeyboardSpecialEventCallback(Params_KeyboardSpecialEventCallback& params)
{
params.log();
RemapConsumerParams remapParams(params);
// ------------------------------------------------------------
RemapClassManager::remap_consumer(remapParams);
// ----------------------------------------
if (! remapParams.isremapped) {
Params_KeyboardSpecialEventCallback::auto_ptr ptr(Params_KeyboardSpecialEventCallback::alloc(params.eventType, FlagStatus::makeFlags(), params.key,
params.flavor, params.guid, false));
if (ptr) {
KeyboardRepeat::set(*ptr);
EventOutputQueue::FireConsumer::fire(*ptr);
}
}
RemapFunc::PointingRelativeToScroll::cancelScroll();
}
void
remap_RelativePointerEventCallback(Params_RelativePointerEventCallback& params)
{
params.log();
RemapPointingParams_relative remapParams(params);
ButtonStatus::set(params.ex_button, params.ex_isbuttondown);
RemapClassManager::remap_pointing(remapParams);
// ------------------------------------------------------------
if (! remapParams.isremapped) {
EventOutputQueue::FireRelativePointer::fire(ButtonStatus::makeButtons(), params.dx, params.dy);
}
}
void
remap_ScrollWheelEventCallback(Params_ScrollWheelEventCallback& params)
{
params.log();
EventOutputQueue::FireScrollWheel::fire(params);
RemapFunc::PointingRelativeToScroll::cancelScroll();
}
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2012, 2013 Aldebaran Robotics. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the COPYING file.
*/
#include <boost/filesystem.hpp>
#include <locale>
#include <cstdio>
#include <cstdlib>
#include <cstdarg>
#include <unistd.h> //gethostname
#include <algorithm>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <string>
#include <limits.h>
# include <pwd.h>
# include <sys/time.h>
# include <sys/socket.h>
# include <sys/types.h>
# include <arpa/inet.h>
#ifndef ANDROID
# include <ifaddrs.h>
#endif
#if defined (__linux__)
# include <sys/prctl.h>
#endif
#include <pthread.h>
#include <qi/os.hpp>
#include <qi/log.hpp>
#include <qi/error.hpp>
#include <qi/qi.hpp>
#include "filesystem.hpp"
#include "utils.hpp"
namespace qi {
namespace os {
FILE* fopen(const char *filename, const char *mode) {
return ::fopen(boost::filesystem::path(filename, qi::unicodeFacet()).string(qi::unicodeFacet()).c_str(),
boost::filesystem::path(mode, qi::unicodeFacet()).string(qi::unicodeFacet()).c_str());
}
int stat(const char *filename, struct ::stat* status) {
return ::stat(boost::filesystem::path(filename, qi::unicodeFacet()).string(qi::unicodeFacet()).c_str(), status);
}
std::string getenv(const char *var) {
char *res = ::getenv(boost::filesystem::path(var, qi::unicodeFacet()).string(qi::unicodeFacet()).c_str());
if (res == NULL)
return "";
return std::string(res);
}
int setenv(const char *var, const char *value) {
return ::setenv(boost::filesystem::path(var, qi::unicodeFacet()).string(qi::unicodeFacet()).c_str(),
boost::filesystem::path(value, qi::unicodeFacet()).string(qi::unicodeFacet()).c_str(), 1);
}
void sleep(unsigned int seconds) {
// In case sleep was interrupted by a signal,
// keep sleeping until we have slept the correct amount
// of time.
while (seconds != 0) {
seconds = ::sleep(seconds);
}
}
void msleep(unsigned int milliseconds) {
// Not the same for usleep: it returns a non-zero
// error code if it was interupted...
usleep(milliseconds * 1000);
}
std::string home()
{
std::string envHome = qi::os::getenv("HOME");
if (envHome != "")
{
return boost::filesystem::path(envHome, qi::unicodeFacet()).make_preferred().string(qi::unicodeFacet());
}
// $HOME environment variable not defined:
char *lgn;
struct passwd *pw;
if ((lgn = getlogin()) != NULL && (pw = getpwnam(lgn)) != NULL)
{
return boost::filesystem::path(pw->pw_dir, qi::unicodeFacet()).make_preferred().string(qi::unicodeFacet());
}
// Give up:
return "";
}
std::string mktmpdir(const char *prefix)
{
std::string sprefix;
std::string tmpdir;
std::string path;
int i = 0;
if (prefix)
sprefix = prefix;
bool isCreated = false;
do
{
tmpdir = sprefix;
tmpdir += randomstr(7);
boost::filesystem::path pp(qi::os::tmp(), qi::unicodeFacet());
pp.append(tmpdir, qi::unicodeFacet());
path = pp.make_preferred().string(qi::unicodeFacet());
++i;
try
{
isCreated = boost::filesystem::create_directory(pp.make_preferred());
}
catch (const boost::filesystem::filesystem_error &e)
{
qiLogDebug("qi::os") << "Attempt " << i << " fail to create tmpdir! " << e.what();
}
}
while (i < TMP_MAX && !isCreated);
return path;
}
std::string tmp()
{
std::string temp = ::qi::os::getenv("TMPDIR");
if (temp.empty())
temp = "/tmp/";
boost::filesystem::path p = boost::filesystem::path(temp, qi::unicodeFacet());
return p.string(qi::unicodeFacet());
}
int gettimeofday(qi::os::timeval *tp) {
struct ::timeval tv;
int ret = ::gettimeofday(&tv, 0);
tp->tv_sec = tv.tv_sec;
tp->tv_usec = tv.tv_usec;
return ret;
}
std::string tmpdir(const char *prefix)
{
return mktmpdir(prefix);
}
#ifdef ANDROID
std::string gethostname()
{
assert(0 && "qi::os::gethostname is not implemented for android, "
"use the JAVA API instead");
return "";
}
#else
std::string gethostname()
{
long hostNameMax;
#ifdef HAVE_SC_HOST_NAME_MAX
hostNameMax = sysconf(_SC_HOST_NAME_MAX) + 1;
#else
hostNameMax = HOST_NAME_MAX + 1;
#endif
char *szHostName = (char*) malloc(hostNameMax * sizeof(char));
memset(szHostName, 0, hostNameMax);
if (::gethostname(szHostName, hostNameMax) == 0) {
std::string hostname(szHostName);
free(szHostName);
return hostname;
}
free(szHostName);
return std::string();
}
#endif
int isatty(int fd)
{
return ::isatty(fd);
}
char* strdup(const char *src)
{
return ::strdup(src);
}
int snprintf(char *str, size_t size, const char *format, ...)
{
va_list list;
va_start(list, format);
int ret = vsnprintf(str, size, format, list);
va_end(list);
return ret;
}
unsigned short findAvailablePort(unsigned short port)
{
struct sockaddr_in name;
name.sin_family = AF_INET;
name.sin_addr.s_addr = htonl(INADDR_ANY);
int sock = ::socket(AF_INET, SOCK_STREAM, 0);
// cast ushort into int to check all ports between
// [49152, 65535] (e.g. USHRT_MAX)
unsigned short iPort = port != 0 ? port : static_cast<unsigned short>(49152);
int unavailable = -1;
do
{
name.sin_port = htons(iPort);
unavailable = ::bind(sock, (struct sockaddr *)&name, sizeof(name));
if (!unavailable)
{
unavailable = ::close(sock);
if (!unavailable)
break;
}
++iPort;
}
while (iPort + 1 > USHRT_MAX);
if (unavailable)
{
iPort = 0;
qiLogError("core.common.network") << "findAvailablePort Socket Cannot find available port, Last Error: "
<< unavailable << std::endl;
}
qiLogDebug("core.common.network") << "findAvailablePort: Returning port: "
<< iPort << std::endl;
return iPort;
}
#ifdef ANDROID
std::map<std::string, std::vector<std::string> > hostIPAddrs(bool ipv6Addr)
{
qiLogWarning("libqi.hostIPAddrs") << "qi::os::hostIPAddrs is partially implemented on Android: Only return the loopback address.";
std::map<std::string, std::vector<std::string> > res;
std::vector<std::string> addrs;
addrs.push_back("127.0.0.1");
res["lo"] = addrs;
return res;
}
#else
std::map<std::string, std::vector<std::string> > hostIPAddrs(bool ipv6Addr)
{
std::map<std::string, std::vector<std::string> > ifsMap;
struct ifaddrs *ifAddrStruct = 0;
struct ifaddrs *ifa = 0;
void *tmpAddrPtr = 0;
int ret = 0;
ret = getifaddrs(&ifAddrStruct);
if (ret == -1) {
qiLogError("getifaddrs") << "getifaddrs failed: " << strerror(errno);
return std::map<std::string, std::vector<std::string> >();
}
for (ifa = ifAddrStruct; ifa != 0; ifa = ifa->ifa_next)
{
if (!ifa->ifa_addr)
continue;
if (ifa->ifa_addr->sa_family == AF_INET && !ipv6Addr)
{
tmpAddrPtr = &((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;
char addressBuffer[INET_ADDRSTRLEN];
inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN);
ifsMap[ifa->ifa_name].push_back(addressBuffer);
}
else if (ifa->ifa_addr->sa_family == AF_INET6 && ipv6Addr)
{
tmpAddrPtr = &((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_addr;
char addressBuffer[INET6_ADDRSTRLEN];
inet_ntop(AF_INET6, tmpAddrPtr, addressBuffer, INET6_ADDRSTRLEN);
ifsMap[ifa->ifa_name].push_back(addressBuffer);
}
}
freeifaddrs(ifAddrStruct);
return ifsMap;
}
#endif
void setCurrentThreadName(const std::string &name) {
#if defined (__linux__) && !defined(ANDROID)
prctl(PR_SET_NAME, name.c_str(), 0, 0, 0);
#elif defined (__APPLE__)
pthread_setname_np(name.c_str());
#elif defined (ANDROID)
//no implementation under Android
#else
//BSD, whatever...
pthread_set_name_np(pthread_self(), name.c_str());
#endif
}
long numberOfCPUs()
{
return sysconf(_SC_NPROCESSORS_CONF);
}
//true on success
bool setCurrentThreadCPUAffinity(const std::vector<int> &cpus) {
#if defined (__linux__) && !defined(ANDROID)
cpu_set_t cpu;
pthread_t self = pthread_self();
CPU_ZERO(&cpu);
for (unsigned int i = 0; i < cpus.size(); ++i)
CPU_SET(cpus[i], &cpu);
int ret = 0;
ret = pthread_setaffinity_np(self, sizeof(cpu_set_t), &cpu);
return !ret;
#endif
return false;
}
static std::string readLink(const std::string &link)
{
boost::filesystem::path p(link, qi::unicodeFacet());
while (boost::filesystem::exists(p))
{
if (boost::filesystem::is_symlink(p))
{
p = boost::filesystem::read_symlink(p);
}
else
{
std::string basename = p.parent_path().filename().string(qi::unicodeFacet());
std::string filename = p.filename().string(qi::unicodeFacet());
boost::filesystem::path res(basename, qi::unicodeFacet());
res.append(filename, qi::unicodeFacet());
return res.make_preferred().string(qi::unicodeFacet());
}
}
return std::string();
}
std::string timezone()
{
std::string link = readLink("/etc/timezone");
if (link.empty())
link = readLink("/etc/localtime");
if (link.empty())
qiLogError("core.common") << "Could not find timezone!";
return link;
}
}
}
<commit_msg>android: Implement hostIPAddrs<commit_after>/*
* Copyright (c) 2012, 2013 Aldebaran Robotics. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the COPYING file.
*/
#include <boost/filesystem.hpp>
#include <locale>
#include <cstdio>
#include <cstdlib>
#include <cstdarg>
#include <unistd.h> //gethostname
#include <algorithm>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <string>
#include <limits.h>
# include <pwd.h>
# include <sys/time.h>
# include <sys/socket.h>
# include <sys/types.h>
# include <arpa/inet.h>
#ifndef ANDROID
# include <ifaddrs.h>
#else
# include <dirent.h>
# include <linux/if_arp.h>
#endif
#if defined (__linux__)
# include <sys/prctl.h>
#endif
#include <pthread.h>
#include <qi/os.hpp>
#include <qi/log.hpp>
#include <qi/error.hpp>
#include <qi/qi.hpp>
#include "filesystem.hpp"
#include "utils.hpp"
namespace qi {
namespace os {
FILE* fopen(const char *filename, const char *mode) {
return ::fopen(boost::filesystem::path(filename, qi::unicodeFacet()).string(qi::unicodeFacet()).c_str(),
boost::filesystem::path(mode, qi::unicodeFacet()).string(qi::unicodeFacet()).c_str());
}
int stat(const char *filename, struct ::stat* status) {
return ::stat(boost::filesystem::path(filename, qi::unicodeFacet()).string(qi::unicodeFacet()).c_str(), status);
}
std::string getenv(const char *var) {
char *res = ::getenv(boost::filesystem::path(var, qi::unicodeFacet()).string(qi::unicodeFacet()).c_str());
if (res == NULL)
return "";
return std::string(res);
}
int setenv(const char *var, const char *value) {
return ::setenv(boost::filesystem::path(var, qi::unicodeFacet()).string(qi::unicodeFacet()).c_str(),
boost::filesystem::path(value, qi::unicodeFacet()).string(qi::unicodeFacet()).c_str(), 1);
}
void sleep(unsigned int seconds) {
// In case sleep was interrupted by a signal,
// keep sleeping until we have slept the correct amount
// of time.
while (seconds != 0) {
seconds = ::sleep(seconds);
}
}
void msleep(unsigned int milliseconds) {
// Not the same for usleep: it returns a non-zero
// error code if it was interupted...
usleep(milliseconds * 1000);
}
std::string home()
{
std::string envHome = qi::os::getenv("HOME");
if (envHome != "")
{
return boost::filesystem::path(envHome, qi::unicodeFacet()).make_preferred().string(qi::unicodeFacet());
}
// $HOME environment variable not defined:
char *lgn;
struct passwd *pw;
if ((lgn = getlogin()) != NULL && (pw = getpwnam(lgn)) != NULL)
{
return boost::filesystem::path(pw->pw_dir, qi::unicodeFacet()).make_preferred().string(qi::unicodeFacet());
}
// Give up:
return "";
}
std::string mktmpdir(const char *prefix)
{
std::string sprefix;
std::string tmpdir;
std::string path;
int i = 0;
if (prefix)
sprefix = prefix;
bool isCreated = false;
do
{
tmpdir = sprefix;
tmpdir += randomstr(7);
boost::filesystem::path pp(qi::os::tmp(), qi::unicodeFacet());
pp.append(tmpdir, qi::unicodeFacet());
path = pp.make_preferred().string(qi::unicodeFacet());
++i;
try
{
isCreated = boost::filesystem::create_directory(pp.make_preferred());
}
catch (const boost::filesystem::filesystem_error &e)
{
qiLogDebug("qi::os") << "Attempt " << i << " fail to create tmpdir! " << e.what();
}
}
while (i < TMP_MAX && !isCreated);
return path;
}
std::string tmp()
{
std::string temp = ::qi::os::getenv("TMPDIR");
if (temp.empty())
temp = "/tmp/";
boost::filesystem::path p = boost::filesystem::path(temp, qi::unicodeFacet());
return p.string(qi::unicodeFacet());
}
int gettimeofday(qi::os::timeval *tp) {
struct ::timeval tv;
int ret = ::gettimeofday(&tv, 0);
tp->tv_sec = tv.tv_sec;
tp->tv_usec = tv.tv_usec;
return ret;
}
std::string tmpdir(const char *prefix)
{
return mktmpdir(prefix);
}
#ifdef ANDROID
std::string gethostname()
{
assert(0 && "qi::os::gethostname is not implemented for android, "
"use the JAVA API instead");
return "";
}
#else
std::string gethostname()
{
long hostNameMax;
#ifdef HAVE_SC_HOST_NAME_MAX
hostNameMax = sysconf(_SC_HOST_NAME_MAX) + 1;
#else
hostNameMax = HOST_NAME_MAX + 1;
#endif
char *szHostName = (char*) malloc(hostNameMax * sizeof(char));
memset(szHostName, 0, hostNameMax);
if (::gethostname(szHostName, hostNameMax) == 0) {
std::string hostname(szHostName);
free(szHostName);
return hostname;
}
free(szHostName);
return std::string();
}
#endif
int isatty(int fd)
{
return ::isatty(fd);
}
char* strdup(const char *src)
{
return ::strdup(src);
}
int snprintf(char *str, size_t size, const char *format, ...)
{
va_list list;
va_start(list, format);
int ret = vsnprintf(str, size, format, list);
va_end(list);
return ret;
}
unsigned short findAvailablePort(unsigned short port)
{
struct sockaddr_in name;
name.sin_family = AF_INET;
name.sin_addr.s_addr = htonl(INADDR_ANY);
int sock = ::socket(AF_INET, SOCK_STREAM, 0);
// cast ushort into int to check all ports between
// [49152, 65535] (e.g. USHRT_MAX)
unsigned short iPort = port != 0 ? port : static_cast<unsigned short>(49152);
int unavailable = -1;
do
{
name.sin_port = htons(iPort);
unavailable = ::bind(sock, (struct sockaddr *)&name, sizeof(name));
if (!unavailable)
{
unavailable = ::close(sock);
if (!unavailable)
break;
}
++iPort;
}
while (static_cast<unsigned int>(iPort + 1) > USHRT_MAX);
if (unavailable)
{
iPort = 0;
qiLogError("core.common.network") << "findAvailablePort Socket Cannot find available port, Last Error: "
<< unavailable << std::endl;
}
qiLogDebug("core.common.network") << "findAvailablePort: Returning port: "
<< iPort << std::endl;
return iPort;
}
#ifdef ANDROID
std::map<std::string, std::vector<std::string> > hostIPAddrs(bool ipv6Addr)
{
std::map<std::string, std::vector<std::string> > res;
std::vector<std::string> addrs;
std::string interfacesDirectory = "/sys/class/net/";
DIR *d;
struct dirent *de;
std::string interfaceName;
uint32_t addr, flags;
struct ifreq ifr;
int ioctl_sock;
static char buf[32];
// Initialize test socket and open interfaces directory
ioctl_sock = socket(AF_INET, SOCK_DGRAM, 0);
if (ioctl_sock < 0 ||
(d = opendir(interfacesDirectory.c_str())) == 0)
{
qiLogError("qi.hostIPAddrs") << "socket() failed: " << strerror(errno);
return res;
}
// Foreach interface
while ((de = readdir(d)))
{
// Get interface name and set it in ifreq struct
interfaceName = de->d_name;
if (interfaceName == "." || interfaceName == "..")
continue;
// set name in ifreq struct
memset(&ifr, 0, sizeof(struct ifreq));
strncpy(ifr.ifr_name, de->d_name, strlen(de->d_name) + 1);
// Get interface IP address
if (ioctl(ioctl_sock, SIOCGIFADDR, &ifr) < 0)
continue;
addr = ((struct sockaddr_in*) &ifr.ifr_addr)->sin_addr.s_addr;
// Get interface flags
if (ioctl(ioctl_sock, SIOCGIFFLAGS, &ifr) < 0)
continue;
flags = ifr.ifr_flags;
// Check if interface is down
if (!(flags & 1) || addr == 0)
continue;
// Set address in map
addrs.clear();
sprintf(buf,"%d.%d.%d.%d", addr & 255, ((addr >> 8) & 255), ((addr >> 16) & 255), (addr >> 24));
addrs.push_back(buf);
qiLogVerbose("qi.hostIPAddrs") << "New endpoints for " << interfaceName << ": " << buf;
// set addrs in map
res[interfaceName] = addrs;
}
closedir(d);
close(ioctl_sock);
return res;
}
#else
std::map<std::string, std::vector<std::string> > hostIPAddrs(bool ipv6Addr)
{
std::map<std::string, std::vector<std::string> > ifsMap;
struct ifaddrs *ifAddrStruct = 0;
struct ifaddrs *ifa = 0;
void *tmpAddrPtr = 0;
int ret = 0;
ret = getifaddrs(&ifAddrStruct);
if (ret == -1) {
qiLogError("getifaddrs") << "getifaddrs failed: " << strerror(errno);
return std::map<std::string, std::vector<std::string> >();
}
for (ifa = ifAddrStruct; ifa != 0; ifa = ifa->ifa_next)
{
if (!ifa->ifa_addr)
continue;
if (ifa->ifa_addr->sa_family == AF_INET && !ipv6Addr)
{
tmpAddrPtr = &((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;
char addressBuffer[INET_ADDRSTRLEN];
inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN);
ifsMap[ifa->ifa_name].push_back(addressBuffer);
}
else if (ifa->ifa_addr->sa_family == AF_INET6 && ipv6Addr)
{
tmpAddrPtr = &((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_addr;
char addressBuffer[INET6_ADDRSTRLEN];
inet_ntop(AF_INET6, tmpAddrPtr, addressBuffer, INET6_ADDRSTRLEN);
ifsMap[ifa->ifa_name].push_back(addressBuffer);
}
}
freeifaddrs(ifAddrStruct);
return ifsMap;
}
#endif
void setCurrentThreadName(const std::string &name) {
#if defined (__linux__) && !defined(ANDROID)
prctl(PR_SET_NAME, name.c_str(), 0, 0, 0);
#elif defined (__APPLE__)
pthread_setname_np(name.c_str());
#elif defined (ANDROID)
//no implementation under Android
#else
//BSD, whatever...
pthread_set_name_np(pthread_self(), name.c_str());
#endif
}
long numberOfCPUs()
{
return sysconf(_SC_NPROCESSORS_CONF);
}
//true on success
bool setCurrentThreadCPUAffinity(const std::vector<int> &cpus) {
#if defined (__linux__) && !defined(ANDROID)
cpu_set_t cpu;
pthread_t self = pthread_self();
CPU_ZERO(&cpu);
for (unsigned int i = 0; i < cpus.size(); ++i)
CPU_SET(cpus[i], &cpu);
int ret = 0;
ret = pthread_setaffinity_np(self, sizeof(cpu_set_t), &cpu);
return !ret;
#endif
return false;
}
static std::string readLink(const std::string &link)
{
boost::filesystem::path p(link, qi::unicodeFacet());
while (boost::filesystem::exists(p))
{
if (boost::filesystem::is_symlink(p))
{
p = boost::filesystem::read_symlink(p);
}
else
{
std::string basename = p.parent_path().filename().string(qi::unicodeFacet());
std::string filename = p.filename().string(qi::unicodeFacet());
boost::filesystem::path res(basename, qi::unicodeFacet());
res.append(filename, qi::unicodeFacet());
return res.make_preferred().string(qi::unicodeFacet());
}
}
return std::string();
}
std::string timezone()
{
std::string link = readLink("/etc/timezone");
if (link.empty())
link = readLink("/etc/localtime");
if (link.empty())
qiLogError("core.common") << "Could not find timezone!";
return link;
}
}
}
<|endoftext|> |
<commit_before>/* -*- Mode: C++; indent-tabs-mode: nil -*- */
#include <cassert>
#include <iomanip>
#include <iostream>
#include <vector>
#include <schwa/macros.h>
#include <schwa/config.h>
#include <schwa/pool.h>
#include <schwa/port.h>
#include <schwa/dr.h>
#include <schwa/io/array_reader.h>
#include <schwa/msgpack.h>
namespace cf = schwa::config;
namespace dr = schwa::dr;
namespace io = schwa::io;
namespace mp = schwa::msgpack;
namespace port = schwa::port;
namespace {
class Config : public cf::OpMain {
public:
cf::IStreamOp input;
Config(void) :
cf::OpMain("drui", "Schwa-Lab Docrep UI"),
input(*this, "input", "input filename")
{ }
virtual ~Config(void) { }
};
class FauxDoc : public dr::Doc {
public:
class Schema;
};
class FauxDoc::Schema : public dr::Doc::Schema<FauxDoc> {
public:
Schema(void) : dr::Doc::Schema<FauxDoc>("FauxDoc", "The document class.") { }
};
class DocProcessor {
private:
static const char *SEP;
static const char *REPR_NIL;
static const char *REPR_UNKNOWN;
const FauxDoc &_doc;
std::ostream &_out;
const unsigned int _doc_num;
unsigned int _indent;
void process_fields(const std::vector<dr::RTFieldDef *> &fields);
void process_store(const dr::RTStoreDef &store);
std::ostream &write_indent(void);
std::ostream &write_field(const dr::RTStoreDef &store, const dr::RTFieldDef &field, const mp::Value &value);
void write_pointer(const dr::RTStoreDef &store, const dr::RTFieldDef &field, const mp::Value &value);
void write_primitive(const mp::Value &value);
void write_slice(const dr::RTFieldDef &field, const mp::Value &value);
public:
DocProcessor(const FauxDoc &doc, std::ostream &out, unsigned int doc_num) :
_doc(doc),
_out(out),
_doc_num(doc_num),
_indent(0)
{ }
void process_doc(void);
inline void operator ()(void) { process_doc(); }
private:
DISALLOW_COPY_AND_ASSIGN(DocProcessor);
friend class DocProcessorTest;
};
const char *DocProcessor::SEP = "\t\033[1;30m # ";
const char *DocProcessor::REPR_NIL = "<nil>";
const char *DocProcessor::REPR_UNKNOWN = "<UNKNOWN VALUE>";
void
DocProcessor::process_doc(void) {
const dr::RTManager &rt = *_doc.rt();
write_indent() << _doc_num << ": {" << SEP << "Document" << port::OFF << "\n";
++_indent;
const dr::RTSchema *schema = rt.doc;
assert(schema != nullptr);
// TODO document fields? where are they?
//process_fields(schema->fields);
for (const auto *store : schema->stores)
process_store(*store);
--_indent;
write_indent() << "},\n";
}
void
DocProcessor::process_fields(const std::vector<dr::RTFieldDef *> &fields) {
for (const dr::RTFieldDef *field : fields) {
(void)field;
}
}
void
DocProcessor::process_store(const dr::RTStoreDef &store) {
assert(store.is_lazy());
const dr::RTSchema &klass = *store.klass;
// decode the lazy store values into dynamic msgpack objects
schwa::Pool pool(4096);
io::ArrayReader reader(store.lazy_data, store.lazy_nbytes);
mp::Value *value = mp::read_dynamic(reader, pool);
// <instances> ::= [ <instance> ]
assert(is_array(value->type));
const mp::Array &array = *value->via._array;
// write header
write_indent() << store.serial << ": {";
_out << SEP << klass.serial;
_out << " (" << array.size() << ")"<< port::OFF << "\n";
++_indent;
for (uint32_t i = 0; i != array.size(); ++i) {
assert(is_map(array[i].type));
const mp::Map &map = *array[i].via._map;
write_indent() << "0x" << std::hex << i << std::dec << ": {\n";
++_indent;
// <instance> ::= { <field_id> : <obj_val> }
for (uint32_t j = 0; j != map.size(); ++j) {
assert(is_uint(map.get(j).key.type));
const mp::Map::Pair &pair = map.get(j);
const dr::RTFieldDef &field = *klass.fields[pair.key.via._uint64];
write_indent() << field.serial << ": ";
write_field(store, field, pair.value) << "\n";
}
--_indent;
write_indent() << "},\n";
}
--_indent;
write_indent() << "},\n";
}
std::ostream &
DocProcessor::write_indent(void) {
for (unsigned int i = 0; i != _indent; ++i)
_out << " ";
return _out;
}
std::ostream &
DocProcessor::write_field(const dr::RTStoreDef &store, const dr::RTFieldDef &field, const mp::Value &value) {
const auto flags = _out.flags();
if (field.is_slice)
write_slice(field, value);
else if (field.points_into != nullptr || field.is_self_pointer)
write_pointer(store, field, value);
else
write_primitive(value);
_out.flags(flags);
return _out;
}
void
DocProcessor::write_slice(const dr::RTFieldDef &field, const mp::Value &value) {
assert(is_array(value.type));
const auto &array = *value.via._array;
assert(array.size() == 2);
assert(is_uint(array[0].type));
assert(is_uint(array[1].type));
const uint64_t a = array[0].via._uint64;
const uint64_t b = array[1].via._uint64;
_out << "[0x" << std::hex << a << ", 0x" << std::hex << (a + b) << "],";
_out << SEP;
if (field.points_into == nullptr)
_out << "byte slice";
else
_out << "slice into " << field.points_into->serial;
_out << " (" << std::dec << a << ", " << std::dec << (a + b) << ")" << port::OFF;
}
void
DocProcessor::write_pointer(const dr::RTStoreDef &store, const dr::RTFieldDef &field, const mp::Value &value) {
if (field.is_collection) {
assert(is_array(value.type));
const mp::Array &array = *value.via._array;
_out << "[";
for (uint32_t i = 0; i != array.size(); ++i) {
const mp::Value &v = array[i];
if (i != 0)
_out << ", ";
if (is_nil(v.type) || is_uint(v.type)) {
if (is_nil(v.type))
_out << REPR_NIL;
else
_out << "0x" << std::hex << v.via._uint64;
}
else
_out << port::RED << v.type << port::OFF;
}
_out << "]";
}
else {
if (is_nil(value.type) || is_uint(value.type)) {
if (is_nil(value.type))
_out << REPR_NIL;
else
_out << "0x" << std::hex << value.via._uint64;
}
else
_out << port::RED << value.type << port::OFF;
}
_out << SEP;
if (field.is_self_pointer)
_out << "self-pointer" << (field.is_collection ? "s" : "") << " into " << store.serial;
else
_out << "pointer" << (field.is_collection ? "s" : "") << " into " << field.points_into->serial;
_out << port::OFF;
}
void
DocProcessor::write_primitive(const mp::Value &value) {
if (is_bool(value.type)) {
_out << std::boolalpha << value.via._bool << ",";
}
else if (is_double(value.type)) {
_out << value.via._double << ",";
_out << SEP << "double" << port::OFF;
}
else if (is_float(value.type)) {
_out << value.via._float << ",";
_out << SEP << "float" << port::OFF;
}
else if (is_int(value.type)) {
_out << "0x" << std::hex << value.via._int64 << std::dec << ",";
_out << SEP << "int (" << value.via._int64 << ")" << port::OFF;
}
else if (is_nil(value.type)) {
_out << REPR_NIL;
}
else if (is_uint(value.type)) {
_out << "0x" << std::hex << value.via._uint64 << std::dec << ",";
_out << SEP << "uint (" << value.via._uint64 << ")" << port::OFF;
}
else if (is_array(value.type)) {
_out << port::RED << "TODO array" << port::OFF;
}
else if (is_map(value.type)) {
_out << port::RED << "TODO map" << port::OFF;
}
else if (is_raw(value.type)) {
const mp::Raw &raw = *value.via._raw;
(_out << "\"").write(raw.value(), raw.size()) << "\",";
_out << SEP << "raw (" << std::dec << raw.size() << "B)" << port::OFF;
}
else
_out << port::RED << REPR_UNKNOWN << port::OFF;
}
} // namespace
int
main(int argc, char *argv[]) {
// process args
Config c;
c.main(argc, argv);
// construct a docrep reader over the provided input stream
std::istream &in = c.input.file();
FauxDoc::Schema schema;
dr::Reader reader(in, schema);
// read the documents off the input stream
FauxDoc doc;
for (unsigned int i = 0; reader >> doc; ++i)
DocProcessor(doc, std::cout, i)();
return 0;
}
<commit_msg>* more work to drui<commit_after>/* -*- Mode: C++; indent-tabs-mode: nil -*- */
#include <cassert>
#include <iomanip>
#include <iostream>
#include <vector>
#include <schwa/macros.h>
#include <schwa/config.h>
#include <schwa/pool.h>
#include <schwa/port.h>
#include <schwa/dr.h>
#include <schwa/io/array_reader.h>
#include <schwa/msgpack.h>
namespace cf = schwa::config;
namespace dr = schwa::dr;
namespace io = schwa::io;
namespace mp = schwa::msgpack;
namespace port = schwa::port;
namespace {
class Config : public cf::OpMain {
public:
cf::IStreamOp input;
cf::Op<int> limit;
Config(void) :
cf::OpMain("drui", "Schwa-Lab Docrep UI"),
input(*this, "input", "input filename"),
limit(*this, "limit", "upper bound on the number of documents to process from the input stream", -1)
{ }
virtual ~Config(void) { }
};
class FauxDoc : public dr::Doc {
public:
class Schema;
};
class FauxDoc::Schema : public dr::Doc::Schema<FauxDoc> {
public:
Schema(void) : dr::Doc::Schema<FauxDoc>("FauxDoc", "The document class.") { }
};
class DocProcessor {
private:
static const char *SEP;
static const char *REPR_NIL;
static const char *REPR_UNKNOWN;
const FauxDoc &_doc;
std::ostream &_out;
const unsigned int _doc_num;
unsigned int _indent;
void process_fields(const std::vector<dr::RTFieldDef *> &fields);
void process_store(const dr::RTStoreDef &store);
std::ostream &write_indent(void);
std::ostream &write_field(const dr::RTStoreDef &store, const dr::RTFieldDef &field, const mp::Value &value);
void write_pointer(const dr::RTStoreDef &store, const dr::RTFieldDef &field, const mp::Value &value);
void write_primitive(const mp::Value &value);
void write_slice(const dr::RTFieldDef &field, const mp::Value &value);
public:
DocProcessor(const FauxDoc &doc, std::ostream &out, unsigned int doc_num) :
_doc(doc),
_out(out),
_doc_num(doc_num),
_indent(0)
{ }
void process_doc(void);
inline void operator ()(void) { process_doc(); }
private:
DISALLOW_COPY_AND_ASSIGN(DocProcessor);
friend class DocProcessorTest;
};
const char *DocProcessor::SEP = "\t\033[1;30m # ";
const char *DocProcessor::REPR_NIL = "<nil>";
const char *DocProcessor::REPR_UNKNOWN = "<UNKNOWN VALUE>";
void
DocProcessor::process_doc(void) {
const dr::RTManager &rt = *_doc.rt();
write_indent() << port::BOLD << _doc_num << ":" << port::OFF << " {" << SEP << "Document" << port::OFF << "\n";
++_indent;
const dr::RTSchema *schema = rt.doc;
assert(schema != nullptr);
// TODO document fields? where are they?
//process_fields(schema->fields);
for (const auto *store : schema->stores)
process_store(*store);
--_indent;
write_indent() << "},\n";
}
void
DocProcessor::process_fields(const std::vector<dr::RTFieldDef *> &fields) {
for (const dr::RTFieldDef *field : fields) {
(void)field;
}
}
void
DocProcessor::process_store(const dr::RTStoreDef &store) {
assert(store.is_lazy());
const dr::RTSchema &klass = *store.klass;
// iterate through each field name to find the largest name so we can align
// all of the values when printing out.
unsigned int max_length = 0;
for (const auto& field : klass.fields)
if (field->serial.size() > max_length)
max_length = field->serial.size();
// decode the lazy store values into dynamic msgpack objects
schwa::Pool pool(4096);
io::ArrayReader reader(store.lazy_data, store.lazy_nbytes);
mp::Value *value = mp::read_dynamic(reader, pool);
// <instances> ::= [ <instance> ]
assert(is_array(value->type));
const mp::Array &array = *value->via._array;
// write header
write_indent() << port::BOLD << store.serial << ":" << port::OFF << " {";
_out << SEP << klass.serial;
_out << " (" << array.size() << ")"<< port::OFF << "\n";
++_indent;
for (uint32_t i = 0; i != array.size(); ++i) {
assert(is_map(array[i].type));
const mp::Map &map = *array[i].via._map;
write_indent() << port::BOLD << "0x" << std::hex << i << std::dec << ":" << port::OFF << " {\n";
++_indent;
// <instance> ::= { <field_id> : <obj_val> }
for (uint32_t j = 0; j != map.size(); ++j) {
assert(is_uint(map.get(j).key.type));
const mp::Map::Pair &pair = map.get(j);
const dr::RTFieldDef &field = *klass.fields[pair.key.via._uint64];
write_indent() << port::BOLD << std::setw(max_length) << std::left << field.serial << ": " << port::OFF;
write_field(store, field, pair.value) << "\n";
}
--_indent;
write_indent() << "},\n";
}
--_indent;
write_indent() << "},\n";
}
std::ostream &
DocProcessor::write_indent(void) {
for (unsigned int i = 0; i != _indent; ++i)
_out << " ";
return _out;
}
std::ostream &
DocProcessor::write_field(const dr::RTStoreDef &store, const dr::RTFieldDef &field, const mp::Value &value) {
const auto flags = _out.flags();
if (field.is_slice)
write_slice(field, value);
else if (field.points_into != nullptr || field.is_self_pointer)
write_pointer(store, field, value);
else
write_primitive(value);
_out.flags(flags);
return _out;
}
void
DocProcessor::write_slice(const dr::RTFieldDef &field, const mp::Value &value) {
assert(is_array(value.type));
const auto &array = *value.via._array;
assert(array.size() == 2);
assert(is_uint(array[0].type));
assert(is_uint(array[1].type));
const uint64_t a = array[0].via._uint64;
const uint64_t b = array[1].via._uint64;
_out << "[0x" << std::hex << a << ", 0x" << std::hex << (a + b) << "],";
_out << SEP;
if (field.points_into == nullptr)
_out << "byte slice";
else
_out << "slice into " << field.points_into->serial;
_out << " (" << std::dec << a << ", " << std::dec << (a + b) << ")" << port::OFF;
}
void
DocProcessor::write_pointer(const dr::RTStoreDef &store, const dr::RTFieldDef &field, const mp::Value &value) {
if (field.is_collection) {
assert(is_array(value.type));
const mp::Array &array = *value.via._array;
_out << "[";
for (uint32_t i = 0; i != array.size(); ++i) {
const mp::Value &v = array[i];
if (i != 0)
_out << ", ";
if (is_nil(v.type) || is_uint(v.type)) {
if (is_nil(v.type))
_out << REPR_NIL;
else
_out << "0x" << std::hex << v.via._uint64;
}
else
_out << port::RED << v.type << port::OFF;
}
_out << "]";
}
else {
if (is_nil(value.type) || is_uint(value.type)) {
if (is_nil(value.type))
_out << REPR_NIL;
else
_out << "0x" << std::hex << value.via._uint64;
}
else
_out << port::RED << value.type << port::OFF;
}
_out << SEP;
if (field.is_self_pointer)
_out << "self-pointer" << (field.is_collection ? "s" : "") << " into " << store.serial;
else
_out << "pointer" << (field.is_collection ? "s" : "") << " into " << field.points_into->serial;
_out << port::OFF;
}
void
DocProcessor::write_primitive(const mp::Value &value) {
if (is_bool(value.type)) {
_out << std::boolalpha << value.via._bool << ",";
}
else if (is_double(value.type)) {
_out << value.via._double << ",";
_out << SEP << "double" << port::OFF;
}
else if (is_float(value.type)) {
_out << value.via._float << ",";
_out << SEP << "float" << port::OFF;
}
else if (is_int(value.type)) {
_out << "0x" << std::hex << value.via._int64 << std::dec << ",";
_out << SEP << "int (" << value.via._int64 << ")" << port::OFF;
}
else if (is_nil(value.type)) {
_out << REPR_NIL;
}
else if (is_uint(value.type)) {
_out << "0x" << std::hex << value.via._uint64 << std::dec << ",";
_out << SEP << "uint (" << value.via._uint64 << ")" << port::OFF;
}
else if (is_array(value.type)) {
_out << port::RED << "TODO array" << port::OFF;
}
else if (is_map(value.type)) {
_out << port::RED << "TODO map" << port::OFF;
}
else if (is_raw(value.type)) {
const mp::Raw &raw = *value.via._raw;
(_out << "\"").write(raw.value(), raw.size()) << "\",";
_out << SEP << "raw (" << std::dec << raw.size() << "B)" << port::OFF;
}
else
_out << port::RED << REPR_UNKNOWN << port::OFF;
}
} // namespace
int
main(int argc, char *argv[]) {
// process args
Config c;
c.main(argc, argv);
// construct a docrep reader over the provided input stream
std::istream &in = c.input.file();
FauxDoc::Schema schema;
dr::Reader reader(in, schema);
// read the documents off the input stream
FauxDoc doc;
for (unsigned int i = 0; reader >> doc; ++i)
DocProcessor(doc, std::cout, i)();
return 0;
}
<|endoftext|> |
<commit_before>#include <stingray/toolkit/toolkit.h>
#include <stdio.h>
#include <stdarg.h>
#include <stingray/log/Logger.h>
#include <stingray/toolkit/Backtrace.h>
#include <stingray/toolkit/StringUtils.h>
#include <stingray/toolkit/array.h>
namespace stingray
{
NullPtrType null;
void _append_extended_diagnostics(std::stringstream& result, const Detail::IToolkitException& tkit_ex)
{
std::string backtrace = tkit_ex.GetBacktrace();
result << "\n in function '" << tkit_ex.GetFunctionName() << "'" <<
"\n in file '" << tkit_ex.GetFilename() << "' at line " << ToString(tkit_ex.GetLine());
if (!backtrace.empty())
result << "\n" << backtrace;
}
void DebuggingHelper::BreakpointHere()
{
TRACER;
}
void DebuggingHelper::TerminateWithMessage(const std::string& str)
{
Logger::Error() << "Terminate was requested: " << str;
std::terminate();
}
}
#ifdef _STLP_DEBUG_MESSAGE
void __stl_debug_message(const char * format_str, ...)
{
va_list args;
va_start(args, format_str);
stingray::array<char, 4096> buffer;
int count = vsnprintf(buffer.data(), buffer.size(), format_str, args);
if (count > 0)
{
std::string str(buffer.data(), count);
stingray::Logger::Error() << str << stingray::Backtrace().Get();
}
else
stingray::Logger::Error() << "Can't form stlport error message!\n" << stingray::Backtrace().Get();
va_end(args);
}
#endif
<commit_msg>Added backtrace to DebuggingHelper::TerminateWithMessage<commit_after>#include <stingray/toolkit/toolkit.h>
#include <stdio.h>
#include <stdarg.h>
#include <stingray/log/Logger.h>
#include <stingray/toolkit/Backtrace.h>
#include <stingray/toolkit/StringUtils.h>
#include <stingray/toolkit/array.h>
namespace stingray
{
NullPtrType null;
void _append_extended_diagnostics(std::stringstream& result, const Detail::IToolkitException& tkit_ex)
{
std::string backtrace = tkit_ex.GetBacktrace();
result << "\n in function '" << tkit_ex.GetFunctionName() << "'" <<
"\n in file '" << tkit_ex.GetFilename() << "' at line " << ToString(tkit_ex.GetLine());
if (!backtrace.empty())
result << "\n" << backtrace;
}
void DebuggingHelper::BreakpointHere()
{
TRACER;
}
void DebuggingHelper::TerminateWithMessage(const std::string& str)
{
std::string backtrace = Backtrace().Get();
Logger::Error() << "Terminate was requested: " << str << (backtrace.empty() ? "" : ("\nbacktrace: " + backtrace));
std::terminate();
}
}
#ifdef _STLP_DEBUG_MESSAGE
void __stl_debug_message(const char * format_str, ...)
{
va_list args;
va_start(args, format_str);
stingray::array<char, 4096> buffer;
int count = vsnprintf(buffer.data(), buffer.size(), format_str, args);
if (count > 0)
{
std::string str(buffer.data(), count);
stingray::Logger::Error() << str << stingray::Backtrace().Get();
}
else
stingray::Logger::Error() << "Can't form stlport error message!\n" << stingray::Backtrace().Get();
va_end(args);
}
#endif
<|endoftext|> |
<commit_before>#include "WPILib.h"
#include "Subsystems/Intake.h"
#include "Subsystems/Shooter.h"
#include "Commands/IntakeBall.h"
#include "Commands/PushBall.h"
#include "Commands/SpinUp.h"
#include "Commands/SpinDown.h"
#include "Commands/Shoot.h"
#include "Subsystems/Drive.h"
#include "Subsystems/CameraMount.h"
#include <math.h>
#include <vector>
#include <memory>
using namespace subsystems;
class Asimov: public IterativeRobot
{
private: // subsystems
Joystick left_stick_, right_stick_, xbox_;
Drive drive_;
Intake intake_;
CameraMount mount_;
Shooter shooter_;
private: // test modes and other things which will become outsourced to other classes
bool tank_drive_;
enum Modes {AUTO = 0, MANUAL, PUSH};
Modes mode;
enum Button {A = 1, B, X, Y, L_TRIGGER, R_TRIGGER, BACK, START, L_STICK, R_STICK};
enum Axes {L_XAXIS = 0, L_YAXIS, L_TRIG, R_TRIG, R_XAXIS, R_YAXIS};
double speed;
bool lock;
private: // commands and triggers
std::vector<Command*> commands;
std::vector<JoystickButton*> triggers;
public:
Asimov(): left_stick_(0), right_stick_(1), xbox_(2),
tank_drive_(false), mode(AUTO), speed(0.0), lock(false)
{
}
private:
// Init
void RobotInit() override
{
drive_.Initialize();
mount_.doConfigure();
shooter_.Initialize();
intake_.Initialize();
shooter_.SetMode(Shooter::Mode_t::VELOCITY);
intake_.SetMode(Intake::Mode_t::VBUS);
intake_.SetShootVelocity(0.6);
intake_.SetIntakeSpeed(0.6);
shooter_.SetAllowedError(1000);
mode = AUTO;
lock = false;
BindControls();
}
void BindControls()
{
commands.push_back(intake_.MakeIntakeBall());
triggers.push_back(new JoystickButton(&xbox_, A));
triggers.back()->WhenPressed(commands.back());
triggers.push_back(new JoystickButton(&xbox_, START));
triggers.back()->CancelWhenPressed(commands.back());
auto push_ball_command = intake_.MakePushBall();
triggers.push_back(new JoystickButton(&xbox_, B));
commands.push_back(push_ball_command);
triggers.back()->WhenPressed(commands.back());
triggers.push_back(new JoystickButton(&xbox_, Y));
commands.push_back(shooter_.MakeSpinUp(0.9));
triggers.back()->WhenPressed(commands.back());
triggers.push_back(new JoystickButton(&xbox_, X));
triggers.back()->CancelWhenPressed(commands.back());
commands.push_back(shooter_.MakeSpinDown());
triggers.back()->WhenPressed(commands.back());
triggers.push_back(new JoystickButton(&xbox_, R_TRIGGER));
commands.push_back(new commands::Shoot(&intake_, &shooter_, 2.0));
triggers.back()->WhenPressed(commands.back());
}
// Disabled
void DisabledInit() override
{
}
void DisabledPeriodic() override
{
Scheduler::GetInstance()->Run();
}
// Teleop
void TeleopInit() override
{
TestDriveInit();
}
void TeleopPeriodic() override
{
Scheduler::GetInstance()->Run();
TestDrivePeriodic();
UpdateDash();
}
// Autonomous
void AutonomousInit() override
{
}
void AutonomousPeriodic() override
{
Scheduler::GetInstance()->Run();
}
void TestInit()
{
TestBoulderInit();
TestDriveInit();
}
void TestPeriodic()
{
TestBoulderPeriodic();
TestDrivePeriodic();
}
// Test
void TestBoulderInit()
{
}
void TestDriveInit()
{
drive_.Configure();
drive_.SetMode(Drive::Mode_t::Velocity);
}
void TestDrivePeriodic()
{
if(left_stick_.GetButton(Joystick::ButtonType::kTriggerButton) ||
right_stick_.GetButton(Joystick::ButtonType::kTriggerButton))
{
drive_.SetMode(subsystems::Drive::Mode_t::VBus);
}
else
drive_.SetMode(subsystems::Drive::Mode_t::Velocity);
if(left_stick_.GetRawButton(7))
tank_drive_ = true;
else if(right_stick_.GetRawButton(7))
tank_drive_ = false;
if(tank_drive_)
drive_.TankDrive(left_stick_.GetY() * fabs(left_stick_.GetY()),
right_stick_.GetY() * fabs(right_stick_.GetY()));
else
drive_.ArcadeDrive(right_stick_.GetY() * fabs(right_stick_.GetY()),
left_stick_.GetX() * fabs(left_stick_.GetX()));
UpdateDriveDash();
}
void UpdateDriveDash()
{
SmartDashboard::PutNumber("Left Setpoint", drive_.GetLeftSetPointRPM());
SmartDashboard::PutNumber("Left Speed", drive_.GetLeftRPM());
SmartDashboard::PutNumber("Right Setpoint", drive_.GetRightSetPointRPM());
SmartDashboard::PutNumber("Right Speed", drive_.GetRightRPM());
}
void TestBoulderPeriodic()
{
if (xbox_.GetRawButton(A))
{
mode = AUTO;
}
else if (xbox_.GetRawButton(B))
{
mode = MANUAL;
}
else if (xbox_.GetRawButton(X))
{
mode = PUSH;
}
if (xbox_.GetRawButton(L_TRIGGER))
{
lock = true;
}
else if(xbox_.GetRawButton(BACK))
{
lock = false;
}
if(xbox_.GetRawButton(START))
{
shooter_.SetMode(Shooter::Mode_t::VBUS);
}
else
{
shooter_.SetMode(Shooter::Mode_t::VELOCITY);
}
if(!lock)
{
speed = xbox_.GetRawAxis(L_TRIG);
}
shooter_.SpinUp(speed);
switch (mode)
{
case AUTO:
intake_.TakeBall(true);
break;
case MANUAL:
if (fabs(xbox_.GetRawAxis(R_YAXIS)) < 0.05)
intake_.Stop();
else
intake_.SetSpeed(xbox_.GetRawAxis(R_YAXIS)); //needs to be right stick
break;
case PUSH:
intake_.OutakeBall();
break;
}
UpdateDash();
}
void UpdateDash()
{
SmartDashboard::PutNumber("Shooter Error", shooter_.GetErr());
}
};
START_ROBOT_CLASS(Asimov)
<commit_msg>Makes drive straight the autonomous routine<commit_after>#include "WPILib.h"
#include "Subsystems/Intake.h"
#include "Subsystems/Shooter.h"
#include "Commands/IntakeBall.h"
#include "Commands/PushBall.h"
#include "Commands/SpinUp.h"
#include "Commands/SpinDown.h"
#include "Commands/Shoot.h"
#include "Subsystems/Drive.h"
#include "Subsystems/CameraMount.h"
#include <math.h>
#include <vector>
#include <memory>
using namespace subsystems;
class Asimov: public IterativeRobot
{
private: // subsystems
Joystick left_stick_, right_stick_, xbox_;
Drive drive_;
Intake intake_;
CameraMount mount_;
Shooter shooter_;
private: // test modes and other things which will become outsourced to other classes
bool tank_drive_;
enum Modes {AUTO = 0, MANUAL, PUSH};
Modes mode;
enum Button {A = 1, B, X, Y, L_TRIGGER, R_TRIGGER, BACK, START, L_STICK, R_STICK};
enum Axes {L_XAXIS = 0, L_YAXIS, L_TRIG, R_TRIG, R_XAXIS, R_YAXIS};
double speed;
bool lock;
private: // commands and triggers
Command * auton_command_;
std::vector<Command*> commands;
std::vector<JoystickButton*> triggers;
public:
Asimov(): left_stick_(0), right_stick_(1), xbox_(2),
tank_drive_(false), mode(AUTO), speed(0.0), lock(false)
{
}
private:
// Init
void RobotInit() override
{
drive_.Initialize();
mount_.doConfigure();
shooter_.Initialize();
intake_.Initialize();
shooter_.SetMode(Shooter::Mode_t::VELOCITY);
intake_.SetMode(Intake::Mode_t::VBUS);
intake_.SetShootVelocity(0.6);
intake_.SetIntakeSpeed(0.6);
shooter_.SetAllowedError(1000);
mode = AUTO;
lock = false;
BindControls();
auton_command_ = drive_.MakeDriveStraight(0.5, Drive::Meters_t(6)); // Drive at 50% speed for 6 seconds
}
void BindControls()
{
commands.push_back(intake_.MakeIntakeBall());
triggers.push_back(new JoystickButton(&xbox_, A));
triggers.back()->WhenPressed(commands.back());
triggers.push_back(new JoystickButton(&xbox_, START));
triggers.back()->CancelWhenPressed(commands.back());
auto push_ball_command = intake_.MakePushBall();
triggers.push_back(new JoystickButton(&xbox_, B));
commands.push_back(push_ball_command);
triggers.back()->WhenPressed(commands.back());
triggers.push_back(new JoystickButton(&xbox_, Y));
commands.push_back(shooter_.MakeSpinUp(0.9));
triggers.back()->WhenPressed(commands.back());
triggers.push_back(new JoystickButton(&xbox_, X));
triggers.back()->CancelWhenPressed(commands.back());
commands.push_back(shooter_.MakeSpinDown());
triggers.back()->WhenPressed(commands.back());
triggers.push_back(new JoystickButton(&xbox_, R_TRIGGER));
commands.push_back(new commands::Shoot(&intake_, &shooter_, 2.0));
triggers.back()->WhenPressed(commands.back());
}
// Disabled
void DisabledInit() override
{
}
void DisabledPeriodic() override
{
Scheduler::GetInstance()->Run();
}
// Teleop
void TeleopInit() override
{
TestDriveInit();
}
void TeleopPeriodic() override
{
Scheduler::GetInstance()->Run();
TestDrivePeriodic();
UpdateDash();
}
// Autonomous
void AutonomousInit() override
{
auton_command_->Start();
}
void AutonomousPeriodic() override
{
Scheduler::GetInstance()->Run();
}
void TestInit()
{
TestBoulderInit();
TestDriveInit();
}
void TestPeriodic()
{
TestBoulderPeriodic();
TestDrivePeriodic();
}
// Test
void TestBoulderInit()
{
}
void TestDriveInit()
{
drive_.Configure();
drive_.SetMode(Drive::Mode_t::Velocity);
}
void TestDrivePeriodic()
{
if(left_stick_.GetButton(Joystick::ButtonType::kTriggerButton) ||
right_stick_.GetButton(Joystick::ButtonType::kTriggerButton))
{
drive_.SetMode(subsystems::Drive::Mode_t::VBus);
}
else
drive_.SetMode(subsystems::Drive::Mode_t::Velocity);
if(left_stick_.GetRawButton(7))
tank_drive_ = true;
else if(right_stick_.GetRawButton(7))
tank_drive_ = false;
if(tank_drive_)
drive_.TankDrive(left_stick_.GetY() * fabs(left_stick_.GetY()),
right_stick_.GetY() * fabs(right_stick_.GetY()));
else
drive_.ArcadeDrive(right_stick_.GetY() * fabs(right_stick_.GetY()),
left_stick_.GetX() * fabs(left_stick_.GetX()));
UpdateDriveDash();
}
void UpdateDriveDash()
{
SmartDashboard::PutNumber("Left Setpoint", drive_.GetLeftSetPointRPM());
SmartDashboard::PutNumber("Left Speed", drive_.GetLeftRPM());
SmartDashboard::PutNumber("Right Setpoint", drive_.GetRightSetPointRPM());
SmartDashboard::PutNumber("Right Speed", drive_.GetRightRPM());
}
void TestBoulderPeriodic()
{
if (xbox_.GetRawButton(A))
{
mode = AUTO;
}
else if (xbox_.GetRawButton(B))
{
mode = MANUAL;
}
else if (xbox_.GetRawButton(X))
{
mode = PUSH;
}
if (xbox_.GetRawButton(L_TRIGGER))
{
lock = true;
}
else if(xbox_.GetRawButton(BACK))
{
lock = false;
}
if(xbox_.GetRawButton(START))
{
shooter_.SetMode(Shooter::Mode_t::VBUS);
}
else
{
shooter_.SetMode(Shooter::Mode_t::VELOCITY);
}
if(!lock)
{
speed = xbox_.GetRawAxis(L_TRIG);
}
shooter_.SpinUp(speed);
switch (mode)
{
case AUTO:
intake_.TakeBall(true);
break;
case MANUAL:
if (fabs(xbox_.GetRawAxis(R_YAXIS)) < 0.05)
intake_.Stop();
else
intake_.SetSpeed(xbox_.GetRawAxis(R_YAXIS)); //needs to be right stick
break;
case PUSH:
intake_.OutakeBall();
break;
}
UpdateDash();
}
void UpdateDash()
{
SmartDashboard::PutNumber("Shooter Error", shooter_.GetErr());
}
};
START_ROBOT_CLASS(Asimov)
<|endoftext|> |
<commit_before><commit_msg>:construction: chore(vm): add binary operations vm executor<commit_after><|endoftext|> |
<commit_before>/******************************************************************************\
* ___ __ *
* /\_ \ __/\ \ *
* \//\ \ /\_\ \ \____ ___ _____ _____ __ *
* \ \ \ \/\ \ \ '__`\ /'___\/\ '__`\/\ '__`\ /'__`\ *
* \_\ \_\ \ \ \ \L\ \/\ \__/\ \ \L\ \ \ \L\ \/\ \L\.\_ *
* /\____\\ \_\ \_,__/\ \____\\ \ ,__/\ \ ,__/\ \__/.\_\ *
* \/____/ \/_/\/___/ \/____/ \ \ \/ \ \ \/ \/__/\/_/ *
* \ \_\ \ \_\ *
* \/_/ \/_/ *
* *
* Copyright (C) 2011-2013 *
* Dominik Charousset <dominik.charousset@haw-hamburg.de> *
* *
* This file is part of libcppa. *
* libcppa 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. *
* *
* libcppa 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 libcppa. If not, see <http://www.gnu.org/licenses/>. *
\******************************************************************************/
#ifndef CPPA_PRODUCER_CONSUMER_LIST_HPP
#define CPPA_PRODUCER_CONSUMER_LIST_HPP
#define CPPA_CACHE_LINE_SIZE 64
#include <chrono>
#include <thread>
#include <atomic>
#include <cassert>
// GCC hack
#if !defined(_GLIBCXX_USE_SCHED_YIELD) && !defined(__clang__)
#include <time.h>
namespace std { namespace this_thread { namespace {
inline void yield() noexcept {
timespec req;
req.tv_sec = 0;
req.tv_nsec = 1;
nanosleep(&req, nullptr);
}
} } } // namespace std::this_thread::<anonymous>
#endif
// another GCC hack
#if !defined(_GLIBCXX_USE_NANOSLEEP) && !defined(__clang__)
#include <time.h>
namespace std { namespace this_thread { namespace {
template<typename Rep, typename Period>
inline void sleep_for(const chrono::duration<Rep, Period>& rt) {
auto sec = chrono::duration_cast<chrono::seconds>(rt);
auto nsec = chrono::duration_cast<chrono::nanoseconds>(rt - sec);
timespec req;
req.tv_sec = sec.count();
req.tv_nsec = nsec.count();
nanosleep(&req, nullptr);
}
} } } // namespace std::this_thread::<anonymous>
#endif
namespace cppa { namespace util {
/**
* @brief A producer-consumer list.
*
* For implementation details see http://drdobbs.com/cpp/211601363.
*/
template<typename T>
class producer_consumer_list {
public:
typedef T value_type;
typedef size_t size_type;
typedef ptrdiff_t difference_type;
typedef value_type& reference;
typedef const value_type& const_reference;
typedef value_type* pointer;
typedef const value_type* const_pointer;
struct node {
pointer value;
std::atomic<node*> next;
node(pointer val) : value(val), next(nullptr) { }
static constexpr size_type payload_size =
sizeof(pointer) + sizeof(std::atomic<node*>);
static constexpr size_type pad_size = (CPPA_CACHE_LINE_SIZE * ((payload_size / CPPA_CACHE_LINE_SIZE) + 1)) - payload_size;
// avoid false sharing
char pad[pad_size];
};
private:
static_assert(sizeof(node*) < CPPA_CACHE_LINE_SIZE,
"sizeof(node*) >= CPPA_CACHE_LINE_SIZE");
// for one consumer at a time
node* m_first;
char m_pad1[CPPA_CACHE_LINE_SIZE - sizeof(node*)];
// for one producers at a time
node* m_last;
char m_pad2[CPPA_CACHE_LINE_SIZE - sizeof(node*)];
// shared among producers
std::atomic<bool> m_consumer_lock;
std::atomic<bool> m_producer_lock;
public:
producer_consumer_list() {
m_first = m_last = new node(nullptr);
m_consumer_lock = false;
m_producer_lock = false;
}
~producer_consumer_list() {
while (m_first) {
node* tmp = m_first;
m_first = tmp->next;
delete tmp;
}
}
inline void push_back(pointer value) {
assert(value != nullptr);
node* tmp = new node(value);
// acquire exclusivity
while (m_producer_lock.exchange(true)) {
std::this_thread::yield();
}
// publish & swing last forward
m_last->next = tmp;
m_last = tmp;
// release exclusivity
m_producer_lock = false;
}
// returns nullptr on failure
pointer try_pop() {
pointer result = nullptr;
while (m_consumer_lock.exchange(true)) {
std::this_thread::yield();
}
// only one consumer allowed
node* first = m_first;
node* next = m_first->next;
if (next) {
// queue is not empty
result = next->value; // take it out of the node
next->value = nullptr;
// swing first forward
m_first = next;
// release exclusivity
m_consumer_lock = false;
// delete old dummy
//first->value = nullptr;
delete first;
return result;
}
else {
// release exclusivity
m_consumer_lock = false;
return nullptr;
}
}
bool empty() const {
// this seems to be a non-thread-safe implementation,
// however, any 'race condition' that might occur
// only means we cannot assume an empty list
return m_first == m_last;
}
};
} } // namespace cppa::util
#endif // CPPA_PRODUCER_CONSUMER_LIST_HPP
<commit_msg>use atomic head/tail pointer in prod/consumer list<commit_after>/******************************************************************************\
* ___ __ *
* /\_ \ __/\ \ *
* \//\ \ /\_\ \ \____ ___ _____ _____ __ *
* \ \ \ \/\ \ \ '__`\ /'___\/\ '__`\/\ '__`\ /'__`\ *
* \_\ \_\ \ \ \ \L\ \/\ \__/\ \ \L\ \ \ \L\ \/\ \L\.\_ *
* /\____\\ \_\ \_,__/\ \____\\ \ ,__/\ \ ,__/\ \__/.\_\ *
* \/____/ \/_/\/___/ \/____/ \ \ \/ \ \ \/ \/__/\/_/ *
* \ \_\ \ \_\ *
* \/_/ \/_/ *
* *
* Copyright (C) 2011-2013 *
* Dominik Charousset <dominik.charousset@haw-hamburg.de> *
* *
* This file is part of libcppa. *
* libcppa 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. *
* *
* libcppa 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 libcppa. If not, see <http://www.gnu.org/licenses/>. *
\******************************************************************************/
#ifndef CPPA_PRODUCER_CONSUMER_LIST_HPP
#define CPPA_PRODUCER_CONSUMER_LIST_HPP
#define CPPA_CACHE_LINE_SIZE 64
#include <chrono>
#include <thread>
#include <atomic>
#include <cassert>
// GCC hack
#if !defined(_GLIBCXX_USE_SCHED_YIELD) && !defined(__clang__)
#include <time.h>
namespace std { namespace this_thread { namespace {
inline void yield() throw {
timespec req;
req.tv_sec = 0;
req.tv_nsec = 1;
nanosleep(&req, nullptr);
}
} } } // namespace std::this_thread::<anonymous>
#endif
// another GCC hack
#if !defined(_GLIBCXX_USE_NANOSLEEP) && !defined(__clang__)
#include <time.h>
namespace std { namespace this_thread { namespace {
template<typename Rep, typename Period>
inline void sleep_for(const chrono::duration<Rep, Period>& rt) {
auto sec = chrono::duration_cast<chrono::seconds>(rt);
auto nsec = chrono::duration_cast<chrono::nanoseconds>(rt - sec);
timespec req;
req.tv_sec = sec.count();
req.tv_nsec = nsec.count();
nanosleep(&req, nullptr);
}
} } } // namespace std::this_thread::<anonymous>
#endif
namespace cppa { namespace util {
/**
* @brief A producer-consumer list.
*
* For implementation details see http://drdobbs.com/cpp/211601363.
*/
template<typename T>
class producer_consumer_list {
public:
typedef T value_type;
typedef size_t size_type;
typedef ptrdiff_t difference_type;
typedef value_type& reference;
typedef const value_type& const_reference;
typedef value_type* pointer;
typedef const value_type* const_pointer;
class node {
public:
pointer value;
std::atomic<node*> next;
node(pointer val) : value(val), next(nullptr) { }
private:
static constexpr size_type payload_size =
sizeof(pointer) + sizeof(std::atomic<node*>);
static constexpr size_type cline_size = CPPA_CACHE_LINE_SIZE;
static constexpr size_type pad_size =
(cline_size * ((payload_size / cline_size) + 1)) - payload_size;
// avoid false sharing
char pad[pad_size];
};
private:
static_assert(sizeof(node*) < CPPA_CACHE_LINE_SIZE,
"sizeof(node*) >= CPPA_CACHE_LINE_SIZE");
// for one consumer at a time
std::atomic<node*> m_first;
char m_pad1[CPPA_CACHE_LINE_SIZE - sizeof(node*)];
// for one producers at a time
std::atomic<node*> m_last;
char m_pad2[CPPA_CACHE_LINE_SIZE - sizeof(node*)];
// shared among producers
std::atomic<bool> m_consumer_lock;
std::atomic<bool> m_producer_lock;
public:
producer_consumer_list() {
auto ptr = new node(nullptr);
m_first = ptr;
m_last = ptr;
m_consumer_lock = false;
m_producer_lock = false;
}
~producer_consumer_list() {
while (m_first) {
node* tmp = m_first;
m_first = tmp->next.load();
delete tmp;
}
}
inline void push_back(pointer value) {
assert(value != nullptr);
node* tmp = new node(value);
// acquire exclusivity
while (m_producer_lock.exchange(true)) {
std::this_thread::yield();
}
// publish & swing last forward
m_last.load()->next = tmp;
m_last = tmp;
// release exclusivity
m_producer_lock = false;
}
// returns nullptr on failure
pointer try_pop() {
pointer result = nullptr;
while (m_consumer_lock.exchange(true)) {
std::this_thread::yield();
}
// only one consumer allowed
node* first = m_first;
node* next = m_first.load()->next;
if (next) {
// queue is not empty
result = next->value; // take it out of the node
next->value = nullptr;
// swing first forward
m_first = next;
// release exclusivity
m_consumer_lock = false;
// delete old dummy
//first->value = nullptr;
delete first;
return result;
}
else {
// release exclusivity
m_consumer_lock = false;
return nullptr;
}
}
bool empty() const {
// atomically compares first and last pointer without locks
return m_first == m_last;
}
};
} } // namespace cppa::util
#endif // CPPA_PRODUCER_CONSUMER_LIST_HPP
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: macro_expander.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: vg $ $Date: 2007-10-15 11:53:16 $
*
* 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 2007 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 CPPUHELPER_SOURCE_MACRO_EXPANDER_HXX
#define CPPUHELPER_SOURCE_MACRO_EXPANDER_HXX
#ifndef _SAL_CONFIG_H_
#include "sal/config.h"
#endif
namespace rtl { class OUString; }
namespace cppuhelper {
namespace detail {
/**
* Helper function to expand macros based on the unorc/uno.ini.
*
* @internal
*
* @param text
* Some text.
*
* @return
* The expanded text.
*
* @exception com::sun::star::lang::IllegalArgumentException
* If uriReference is a vnd.sun.star.expand URL reference that contains unknown
* macros.
*/
::rtl::OUString expandMacros(rtl::OUString const & text);
}
}
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.2.22); FILE MERGED 2008/04/01 15:10:54 thb 1.2.22.2: #i85898# Stripping all external header guards 2008/03/28 15:25:26 rt 1.2.22.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: macro_expander.hxx,v $
* $Revision: 1.3 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef CPPUHELPER_SOURCE_MACRO_EXPANDER_HXX
#define CPPUHELPER_SOURCE_MACRO_EXPANDER_HXX
#include "sal/config.h"
namespace rtl { class OUString; }
namespace cppuhelper {
namespace detail {
/**
* Helper function to expand macros based on the unorc/uno.ini.
*
* @internal
*
* @param text
* Some text.
*
* @return
* The expanded text.
*
* @exception com::sun::star::lang::IllegalArgumentException
* If uriReference is a vnd.sun.star.expand URL reference that contains unknown
* macros.
*/
::rtl::OUString expandMacros(rtl::OUString const & text);
}
}
#endif
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include <windows.h>
#include "..\includes\CPatch.h"
#include "..\includes\IniReader.h"
HMODULE h_e2mfc_dll = NULL;
HMODULE comics = NULL;
float iniFOV, FOV;
float fAspectRatio, stdViewPortSize, fWidthFactor, fDiffFactor;
float fVisibilityFactor1, fVisibilityFactor2;
unsigned int ScreenWidth, ScreenHeight;
DWORD jmpAddress, jmpFOV;
DWORD _EAX, _EBX, _nEDX; float _EDX;
bool bComicsMode;
int __fastcall PDriverGetWidth(int a1)
{
int result; // eax@2
if (*(DWORD *)(a1 + 48))
result = *(DWORD *)(a1 + 52);
else
result = *(DWORD *)(a1 + 4);
ScreenWidth = result;
return result;
}
int __fastcall PDriverGetHeight(int a1)
{
int result; // eax@2
if (*(DWORD *)(a1 + 48))
result = *(DWORD *)(a1 + 56);
else
result = *(DWORD *)(a1 + 8);
ScreenHeight = result;
return result;
}
void __declspec(naked)PatchFOV()
{
__asm mov ebx, FOV
__asm push ebx //FOV value
__asm mov ecx, esi
__asm call ebp
__asm jmp jmpFOV
}
void __fastcall P_CameraSetFOV(DWORD P_Camera, float FOVvalue)
{
FOVvalue *= iniFOV;
if (*(float *)&FOVvalue != *(float *)(P_Camera + 284))
{
if (*(float *)&FOVvalue >= 0.0)
{
if (FOVvalue <= 3.1241393f)
{
*(BYTE *)(P_Camera + 236) |= 0x40u;
*(float *)(P_Camera + 284) = FOVvalue;
}
}
else
{
*(BYTE *)(P_Camera + 236) |= 0x40u;
*(DWORD *)(P_Camera + 284) = 0;
}
}
}
void __declspec(naked)ForceEntireViewport()
{
__asm mov ax, 1
__asm ret
}
void __declspec(naked)DisableSubViewport()
{
__asm ret 10h
}
void __declspec(naked)PCameraValidateHook()
{
__asm mov _EAX, eax
__asm mov _EBX, ebx
__asm mov edx, [esp + 4]
__asm mov _EDX, edx
__asm mov _nEDX, edx
if (_EDX >= 0.7f && _EDX <= 0.8f)
{
if ((_EBX == 1 && _EAX == 8) || (_EBX == 0 && _EAX != 8))
{
if (!fDiffFactor)
{
fDiffFactor = fWidthFactor / _EDX;
}
if (fDiffFactor)
_EDX *= fDiffFactor;
__asm mov edx, _EDX
}
}
else
{
if (_EAX == 8 && _EDX < 0.7f)
{
if (fDiffFactor)
_EDX *= fDiffFactor;
if (_EBX == 1 && _EAX == 8 && _nEDX != 0x3ED413CD) //0.414213568, it's to avoid comics stretching
__asm mov edx, _EDX
}
else
{
if ((_EDX > 0.8f && _EDX <= 1.5f) && _nEDX != 0x3F800000)
{
if (fDiffFactor)
_EDX *= fDiffFactor;
if ((_EBX == 1 && _EAX == 8) || (_EBX == 0 && _EAX != 8))
__asm mov edx, _EDX
}
}
}
__asm mov[esi + 20Ch], edx
__asm jmp jmpAddress
}
DWORD WINAPI Thread(LPVOID)
{
CIniReader iniReader("");
iniFOV = iniReader.ReadFloat("MAIN", "FOV", 0.0f);
do
{
Sleep(100);
h_e2mfc_dll = GetModuleHandle("e2mfc.dll");
} while (h_e2mfc_dll == NULL);
CPatch::RedirectCall((DWORD)h_e2mfc_dll + 0x176AF, PDriverGetWidth);
CPatch::RedirectCall((DWORD)h_e2mfc_dll + 0x176F4, PDriverGetHeight);
CPatch::RedirectJump((DWORD)h_e2mfc_dll + 0x156A0, DisableSubViewport);
CPatch::RedirectJump((DWORD)h_e2mfc_dll + 0x14C80, ForceEntireViewport);
do
{
Sleep(0);
} while (ScreenWidth == 0 || ScreenHeight == 0);
/*if (iniFOV)
{
//FOV = iniFOV;
//jmpFOV = 0x428F86;
//CPatch::RedirectJump(0x428F81, PatchFOV); //fov hack
//CPatch::RedirectJump((DWORD)h_e2mfc_dll + 0x14E70, P_CameraSetFOV);
//CPatch::SetPointer(0x428F7B, P_CameraSetFOV);
}*/
fAspectRatio = static_cast<float>(ScreenWidth) / static_cast<float>(ScreenHeight);
fWidthFactor = fAspectRatio / (16.0f / 9.0f);
if (fAspectRatio >= 1.4f)
{
jmpAddress = (DWORD)h_e2mfc_dll + 0x15041;
CPatch::RedirectJump((DWORD)h_e2mfc_dll + 0x15037, PCameraValidateHook);
//object disappearance fix
CPatch::SetFloat((DWORD)h_e2mfc_dll + 0x15B87 + 0x6, 0.0f);
stdViewPortSize = 640.0f;
CPatch::SetPointer((DWORD)h_e2mfc_dll + 0x176D4 + 0x2, &stdViewPortSize);
DWORD nComicsCheck = (DWORD)h_e2mfc_dll + 0x61183;
//doors graphics fix
fVisibilityFactor1 = 0.5f;
fVisibilityFactor2 = 1.5f;
//CPatch::SetPointer((DWORD)GetModuleHandle("X_GameObjectsMFC.dll") + 0xA8D0 + 0x4F5 + 0x2, &fVisibilityFactor4);
CPatch::SetPointer((DWORD)GetModuleHandle("X_GameObjectsMFC.dll") + 0xA8D0 + 0x4CE + 0x2, &fVisibilityFactor1);
//CPatch::SetPointer((DWORD)GetModuleHandle("X_GameObjectsMFC.dll") + 0xA8D0 + 0x4AC + 0x2, &fVisibilityFactor3);
CPatch::SetPointer((DWORD)GetModuleHandle("X_GameObjectsMFC.dll") + 0xA8D0 + 0x485 + 0x2, &fVisibilityFactor2);
//CPatch::SetPointer((DWORD)GetModuleHandle("X_GameObjectsMFC.dll") + 0x101F39 + 0x2, &fVisibilityFactor1);
//CPatch::SetPointer((DWORD)GetModuleHandle("X_GameObjectsMFC.dll") + 0x101F67 + 0x2, &fVisibilityFactor2);
if (iniReader.ReadInteger("MAIN", "COMICS_MODE", 0))
bComicsMode = !bComicsMode;
while (true)
{
Sleep(0);
if ((GetAsyncKeyState(VK_F2) & 1) && ((unsigned char)*(DWORD*)nComicsCheck == 0xAE))
{
bComicsMode = !bComicsMode;
iniReader.WriteInteger("MAIN", "COMICS_MODE", bComicsMode);
while ((GetAsyncKeyState(VK_F2) & 0x8000) > 0) { Sleep(0); }
}
if (bComicsMode)
{
Sleep(1);
if ((unsigned char)*(DWORD*)nComicsCheck == 0xAE)
{
stdViewPortSize = 480.0f * (fAspectRatio);
CPatch::SetFloat((DWORD)h_e2mfc_dll + 0x434F4, 480.0f); //480.0f
}
else
{
stdViewPortSize = 640.0f;
CPatch::SetFloat((DWORD)h_e2mfc_dll + 0x434F4, 480.0f); //480.0f
}
}
else
{
Sleep(1);
if ((unsigned char)*(DWORD*)nComicsCheck == 0xAE)
{
stdViewPortSize = (480.0f * (fAspectRatio) / 1.17936117936f);
CPatch::SetFloat((DWORD)h_e2mfc_dll + 0x434F4, 480.0f / 1.17936117936f); //480.0f
}
else
{
stdViewPortSize = 640.0f;
CPatch::SetFloat((DWORD)h_e2mfc_dll + 0x434F4, 480.0f); //480.0f
}
}
}
}
return 0;
}
BOOL APIENTRY DllMain(HMODULE /*hModule*/, DWORD reason, LPVOID /*lpReserved*/)
{
if (reason == DLL_PROCESS_ATTACH)
{
CreateThread(0, 0, (LPTHREAD_START_ROUTINE)&Thread, NULL, 0, NULL);
}
return TRUE;
}<commit_msg>Widescreen Fixes Pack v2.5.3<commit_after>#include "stdafx.h"
#include <windows.h>
#include "..\includes\CPatch.h"
#include "..\includes\IniReader.h"
HMODULE h_e2mfc_dll = NULL;
HMODULE comics = NULL;
float iniFOV, FOV;
float fAspectRatio, stdViewPortSize, fWidthFactor, fDiffFactor;
float fVisibilityFactor1, fVisibilityFactor2;
unsigned int ScreenWidth, ScreenHeight;
DWORD jmpAddress, jmpFOV;
DWORD _EAX, _EBX, _nEDX; float _EDX;
bool bComicsMode;
int __fastcall PDriverGetWidth(int a1)
{
int result; // eax@2
if (*(DWORD *)(a1 + 48))
result = *(DWORD *)(a1 + 52);
else
result = *(DWORD *)(a1 + 4);
ScreenWidth = result;
return result;
}
int __fastcall PDriverGetHeight(int a1)
{
int result; // eax@2
if (*(DWORD *)(a1 + 48))
result = *(DWORD *)(a1 + 56);
else
result = *(DWORD *)(a1 + 8);
ScreenHeight = result;
return result;
}
void __declspec(naked)PatchFOV()
{
__asm mov ebx, FOV
__asm push ebx //FOV value
__asm mov ecx, esi
__asm call ebp
__asm jmp jmpFOV
}
void __fastcall P_CameraSetFOV(DWORD P_Camera, float FOVvalue)
{
FOVvalue *= iniFOV;
if (*(float *)&FOVvalue != *(float *)(P_Camera + 284))
{
if (*(float *)&FOVvalue >= 0.0)
{
if (FOVvalue <= 3.1241393f)
{
*(BYTE *)(P_Camera + 236) |= 0x40u;
*(float *)(P_Camera + 284) = FOVvalue;
}
}
else
{
*(BYTE *)(P_Camera + 236) |= 0x40u;
*(DWORD *)(P_Camera + 284) = 0;
}
}
}
void __declspec(naked)ForceEntireViewport()
{
__asm mov ax, 1
__asm ret
}
void __declspec(naked)DisableSubViewport()
{
__asm ret 10h
}
void __declspec(naked)PCameraValidateHook()
{
__asm mov _EAX, eax
__asm mov _EBX, ebx
__asm mov edx, [esp + 4]
__asm mov _EDX, edx
__asm mov _nEDX, edx
if (!fDiffFactor)
{
fDiffFactor = fWidthFactor / _EDX;
}
else
{
if (_EDX >= 0.7f && _EDX <= 0.8f)
{
if ((_EBX == 1 && _EAX == 8) || (_EBX == 0 && _EAX != 8))
{
_EDX *= fDiffFactor;
__asm mov edx, _EDX
}
}
else
{
if (_EAX == 8 && _EDX < 0.7f)
{
_EDX *= fDiffFactor;
if (_EBX == 1 && _EAX == 8 && _nEDX != 0x3ED413CD) //0.414213568, it's to avoid comics stretching
__asm mov edx, _EDX
}
else
{
if ((_EDX > 0.8f && _EDX <= 1.5f) && _nEDX != 0x3F800000)
{
_EDX *= fDiffFactor;
if ((_EBX == 1 && _EAX == 8) || (_EBX == 0 && _EAX != 8))
__asm mov edx, _EDX
}
}
}
}
__asm mov[esi + 20Ch], edx
__asm jmp jmpAddress
}
DWORD WINAPI Thread(LPVOID)
{
CIniReader iniReader("");
iniFOV = iniReader.ReadFloat("MAIN", "FOV", 0.0f);
do
{
Sleep(100);
h_e2mfc_dll = GetModuleHandle("e2mfc.dll");
} while (h_e2mfc_dll == NULL);
CPatch::RedirectCall((DWORD)h_e2mfc_dll + 0x176AF, PDriverGetWidth);
CPatch::RedirectCall((DWORD)h_e2mfc_dll + 0x176F4, PDriverGetHeight);
CPatch::RedirectJump((DWORD)h_e2mfc_dll + 0x156A0, DisableSubViewport);
CPatch::RedirectJump((DWORD)h_e2mfc_dll + 0x14C80, ForceEntireViewport);
do
{
Sleep(0);
} while (ScreenWidth == 0 || ScreenHeight == 0);
/*if (iniFOV)
{
//FOV = iniFOV;
//jmpFOV = 0x428F86;
//CPatch::RedirectJump(0x428F81, PatchFOV); //fov hack
//CPatch::RedirectJump((DWORD)h_e2mfc_dll + 0x14E70, P_CameraSetFOV);
//CPatch::SetPointer(0x428F7B, P_CameraSetFOV);
}*/
fAspectRatio = static_cast<float>(ScreenWidth) / static_cast<float>(ScreenHeight);
//fWidthFactor = fAspectRatio / (16.0f / 9.0f);
fWidthFactor = 0.7673270702f / ((4.0f / 3.0f) / fAspectRatio);
if (fAspectRatio >= 1.4f)
{
jmpAddress = (DWORD)h_e2mfc_dll + 0x15041;
CPatch::RedirectJump((DWORD)h_e2mfc_dll + 0x15037, PCameraValidateHook);
//object disappearance fix
CPatch::SetFloat((DWORD)h_e2mfc_dll + 0x15B87 + 0x6, 0.0f);
stdViewPortSize = 640.0f;
CPatch::SetPointer((DWORD)h_e2mfc_dll + 0x176D4 + 0x2, &stdViewPortSize);
DWORD nComicsCheck = (DWORD)h_e2mfc_dll + 0x61183;
//doors graphics fix
fVisibilityFactor1 = 0.5f;
fVisibilityFactor2 = 1.5f;
//CPatch::SetPointer((DWORD)GetModuleHandle("X_GameObjectsMFC.dll") + 0xA8D0 + 0x4F5 + 0x2, &fVisibilityFactor4);
CPatch::SetPointer((DWORD)GetModuleHandle("X_GameObjectsMFC.dll") + 0xA8D0 + 0x4CE + 0x2, &fVisibilityFactor1);
//CPatch::SetPointer((DWORD)GetModuleHandle("X_GameObjectsMFC.dll") + 0xA8D0 + 0x4AC + 0x2, &fVisibilityFactor3);
CPatch::SetPointer((DWORD)GetModuleHandle("X_GameObjectsMFC.dll") + 0xA8D0 + 0x485 + 0x2, &fVisibilityFactor2);
//CPatch::SetPointer((DWORD)GetModuleHandle("X_GameObjectsMFC.dll") + 0x101F39 + 0x2, &fVisibilityFactor1);
//CPatch::SetPointer((DWORD)GetModuleHandle("X_GameObjectsMFC.dll") + 0x101F67 + 0x2, &fVisibilityFactor2);
if (iniReader.ReadInteger("MAIN", "COMICS_MODE", 0))
bComicsMode = !bComicsMode;
while (true)
{
Sleep(0);
if ((GetAsyncKeyState(VK_F2) & 1) && ((unsigned char)*(DWORD*)nComicsCheck == 0xAE))
{
bComicsMode = !bComicsMode;
iniReader.WriteInteger("MAIN", "COMICS_MODE", bComicsMode);
while ((GetAsyncKeyState(VK_F2) & 0x8000) > 0) { Sleep(0); }
}
if (bComicsMode)
{
Sleep(1);
if ((unsigned char)*(DWORD*)nComicsCheck == 0xAE)
{
stdViewPortSize = 480.0f * (fAspectRatio);
CPatch::SetFloat((DWORD)h_e2mfc_dll + 0x434F4, 480.0f); //480.0f
}
else
{
stdViewPortSize = 640.0f;
CPatch::SetFloat((DWORD)h_e2mfc_dll + 0x434F4, 480.0f); //480.0f
}
}
else
{
Sleep(1);
if ((unsigned char)*(DWORD*)nComicsCheck == 0xAE)
{
stdViewPortSize = (480.0f * (fAspectRatio) / 1.17936117936f);
CPatch::SetFloat((DWORD)h_e2mfc_dll + 0x434F4, 480.0f / 1.17936117936f); //480.0f
}
else
{
stdViewPortSize = 640.0f;
CPatch::SetFloat((DWORD)h_e2mfc_dll + 0x434F4, 480.0f); //480.0f
}
}
}
}
return 0;
}
BOOL APIENTRY DllMain(HMODULE /*hModule*/, DWORD reason, LPVOID /*lpReserved*/)
{
if (reason == DLL_PROCESS_ATTACH)
{
CreateThread(0, 0, (LPTHREAD_START_ROUTINE)&Thread, NULL, 0, NULL);
}
return TRUE;
}<|endoftext|> |
<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2013.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include <unordered_map>
#include "overview.hpp"
#include "console.hpp"
#include "accounts.hpp"
#include "expenses.hpp"
#include "budget_exception.hpp"
using namespace budget;
void budget::handle_overview(const std::vector<std::string>& args){
if(args.size() == 1){
month_overview();
} else {
auto& subcommand = args[1];
if(subcommand == L"month"){
if(args.size() == 2){
month_overview();
} else if(args.size() == 3){
month_overview(boost::gregorian::greg_month(to_number<unsigned short>(args[2])));
} else if(args.size() == 4){
month_overview(
boost::gregorian::greg_month(to_number<unsigned short>(args[2])),
boost::gregorian::greg_year(to_number<unsigned short>(args[3])));
} else {
throw budget_exception(L"Too many arguments to overview month");
}
} else if(subcommand == L"year"){
if(args.size() == 2){
year_overview();
} else if(args.size() == 3){
year_overview(boost::gregorian::greg_year(to_number<unsigned short>(args[2])));
} else {
throw budget_exception(L"Too many arguments to overview month");
}
} else {
throw budget_exception("Invalid subcommand \"" + subcommand + "\"");
}
}
}
void budget::month_overview(){
date today = boost::gregorian::day_clock::local_day();
month_overview(today.month(), today.year());
}
void budget::month_overview(boost::gregorian::greg_month month){
date today = boost::gregorian::day_clock::local_day();
month_overview(month, today.year());
}
void budget::month_overview(boost::gregorian::greg_month month, boost::gregorian::greg_year year){
load_accounts();
load_expenses();
auto& accounts = all_accounts();
std::wcout << L"Overview of " << month << " " << year << std::endl << std::endl;
std::vector<std::string> columns;
std::unordered_map<std::string, std::size_t> indexes;
std::vector<std::vector<std::string>> contents;
std::vector<money> totals;
for(auto& account : accounts){
indexes[account.name] = columns.size();
columns.push_back(account.name);
totals.push_back({});
}
std::vector<std::size_t> current(columns.size(), 0);
for(auto& expense : all_expenses()){
if(expense.expense_date.year() == year && expense.expense_date.month() == month){
std::size_t index = indexes[expense.account];
std::size_t& row = current[index];
if(contents.size() <= row){
contents.emplace_back(columns.size() * 3, L"");
}
contents[row][index * 3] = to_string(expense.expense_date.day());
contents[row][index * 3 + 1] = expense.name;
contents[row][index * 3 + 2] = to_string(expense.amount);
totals[index] += expense.amount;
++row;
}
}
//Empty line before totals
contents.emplace_back(columns.size() * 3, L"");
std::vector<std::wstring> total_line;
total_line.push_back("");
total_line.push_back("Total");
total_line.push_back(to_string(totals.front()));
for(std::size_t i = 1; i < totals.size(); ++i){
total_line.push_back("");
total_line.push_back("");
total_line.push_back(to_string(totals[i]));
}
contents.push_back(std::move(total_line));
//Empty line before budget
contents.emplace_back(columns.size() * 3, L"");
std::vector<std::wstring> budget_line;
budget_line.push_back("");
budget_line.push_back("Budget");
budget_line.push_back(to_string(accounts.front().amount));
for(std::size_t i = 1; i < accounts.size(); ++i){
budget_line.push_back("");
budget_line.push_back("");
budget_line.push_back(to_string(accounts[i].amount));
}
contents.push_back(std::move(budget_line));
std::vector<std::wstring> total_budget_line;
total_budget_line.push_back("");
total_budget_line.push_back("Budget total");
total_budget_line.push_back(to_string(accounts.front().amount));
for(std::size_t i = 1; i < accounts.size(); ++i){
total_budget_line.push_back("");
total_budget_line.push_back("");
total_budget_line.push_back("TODO");
}
contents.push_back(std::move(total_budget_line));
//Empty line before remainings
contents.emplace_back(columns.size() * 3, "");
std::vector<std::wstring> balance_line;
balance_line.push_back(L"");
balance_line.push_back(L"Balance");
balance_line.push_back(L"TODO");
for(std::size_t i = 1; i < accounts.size(); ++i){
balance_line.push_back(L"");
balance_line.push_back(L"");
balance_line.push_back(L"TODO");
}
contents.push_back(std::move(balance_line));
std::vector<std::wstring> local_balance_line;
local_balance_line.push_back(L"");
local_balance_line.push_back(L"Local Balance");
local_balance_line.push_back(L"TODO");
for(std::size_t i = 1; i < accounts.size(); ++i){
local_balance_line.push_back(L"");
local_balance_line.push_back(L"");
local_balance_line.push_back(L"TODO");
}
contents.push_back(std::move(local_balance_line));
display_table(columns, contents, 3);
std::cout << std::endl;
money total_expenses;
for(auto& total : totals){
total_expenses += total;
}
std::wcout << std::wstring(accounts.size() * 10, ' ') << L"Total expenses: " << total_expenses << std::endl;
std::wcout << std::wstring(accounts.size() * 10 + 7, ' ') << L"Balance: " << L"TODO" << std::endl;
}
void budget::year_overview(){
date today = boost::gregorian::day_clock::local_day();
year_overview(today.year());
}
void budget::year_overview(boost::gregorian::greg_year year){
load_accounts();
load_expenses();
std::wcout << "Overview of " << year << std::endl;
//TODO
}
<commit_msg>Cleanup<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2013.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include <unordered_map>
#include "overview.hpp"
#include "console.hpp"
#include "accounts.hpp"
#include "expenses.hpp"
#include "budget_exception.hpp"
using namespace budget;
void budget::handle_overview(const std::vector<std::string>& args){
if(args.size() == 1){
month_overview();
} else {
auto& subcommand = args[1];
if(subcommand == "month"){
if(args.size() == 2){
month_overview();
} else if(args.size() == 3){
month_overview(boost::gregorian::greg_month(to_number<unsigned short>(args[2])));
} else if(args.size() == 4){
month_overview(
boost::gregorian::greg_month(to_number<unsigned short>(args[2])),
boost::gregorian::greg_year(to_number<unsigned short>(args[3])));
} else {
throw budget_exception("Too many arguments to overview month");
}
} else if(subcommand == "year"){
if(args.size() == 2){
year_overview();
} else if(args.size() == 3){
year_overview(boost::gregorian::greg_year(to_number<unsigned short>(args[2])));
} else {
throw budget_exception("Too many arguments to overview month");
}
} else {
throw budget_exception("Invalid subcommand \"" + subcommand + "\"");
}
}
}
void budget::month_overview(){
date today = boost::gregorian::day_clock::local_day();
month_overview(today.month(), today.year());
}
void budget::month_overview(boost::gregorian::greg_month month){
date today = boost::gregorian::day_clock::local_day();
month_overview(month, today.year());
}
void budget::month_overview(boost::gregorian::greg_month month, boost::gregorian::greg_year year){
load_accounts();
load_expenses();
auto& accounts = all_accounts();
std::cout << "Overview of " << month << " " << year << std::endl << std::endl;
std::vector<std::string> columns;
std::unordered_map<std::string, std::size_t> indexes;
std::vector<std::vector<std::string>> contents;
std::vector<money> totals;
for(auto& account : accounts){
indexes[account.name] = columns.size();
columns.push_back(account.name);
totals.push_back({});
}
std::vector<std::size_t> current(columns.size(), 0);
for(auto& expense : all_expenses()){
if(expense.expense_date.year() == year && expense.expense_date.month() == month){
std::size_t index = indexes[expense.account];
std::size_t& row = current[index];
if(contents.size() <= row){
contents.emplace_back(columns.size() * 3, "");
}
contents[row][index * 3] = to_string(expense.expense_date.day());
contents[row][index * 3 + 1] = expense.name;
contents[row][index * 3 + 2] = to_string(expense.amount);
totals[index] += expense.amount;
++row;
}
}
//Empty line before totals
contents.emplace_back(columns.size() * 3, "");
std::vector<std::string> total_line;
total_line.push_back("");
total_line.push_back("Total");
total_line.push_back(to_string(totals.front()));
for(std::size_t i = 1; i < totals.size(); ++i){
total_line.push_back("");
total_line.push_back("");
total_line.push_back(to_string(totals[i]));
}
contents.push_back(std::move(total_line));
//Empty line before budget
contents.emplace_back(columns.size() * 3, "");
std::vector<std::string> budget_line;
budget_line.push_back("");
budget_line.push_back("Budget");
budget_line.push_back(to_string(accounts.front().amount));
for(std::size_t i = 1; i < accounts.size(); ++i){
budget_line.push_back("");
budget_line.push_back("");
budget_line.push_back(to_string(accounts[i].amount));
}
contents.push_back(std::move(budget_line));
std::vector<std::string> total_budget_line;
total_budget_line.push_back("");
total_budget_line.push_back("Budget total");
total_budget_line.push_back(to_string(accounts.front().amount));
for(std::size_t i = 1; i < accounts.size(); ++i){
total_budget_line.push_back("");
total_budget_line.push_back("");
total_budget_line.push_back("TODO");
}
contents.push_back(std::move(total_budget_line));
//Empty line before remainings
contents.emplace_back(columns.size() * 3, "");
std::vector<std::string> balance_line;
balance_line.push_back("");
balance_line.push_back("Balance");
balance_line.push_back("TODO");
for(std::size_t i = 1; i < accounts.size(); ++i){
balance_line.push_back("");
balance_line.push_back("");
balance_line.push_back("TODO");
}
contents.push_back(std::move(balance_line));
std::vector<std::string> local_balance_line;
local_balance_line.push_back("");
local_balance_line.push_back("Local Balance");
local_balance_line.push_back("TODO");
for(std::size_t i = 1; i < accounts.size(); ++i){
local_balance_line.push_back("");
local_balance_line.push_back("");
local_balance_line.push_back("TODO");
}
contents.push_back(std::move(local_balance_line));
display_table(columns, contents, 3);
std::cout << std::endl;
money total_expenses;
for(auto& total : totals){
total_expenses += total;
}
std::cout << std::string(accounts.size() * 10, ' ') << "Total expenses: " << total_expenses << std::endl;
std::cout << std::string(accounts.size() * 10 + 7, ' ') << "Balance: " << "TODO" << std::endl;
}
void budget::year_overview(){
date today = boost::gregorian::day_clock::local_day();
year_overview(today.year());
}
void budget::year_overview(boost::gregorian::greg_year year){
load_accounts();
load_expenses();
std::cout << "Overview of " << year << std::endl;
//TODO
}
<|endoftext|> |
<commit_before>/*
This file is part of WME Lite.
http://dead-code.org/redir.php?target=wmelite
Copyright (c) 2011 Jan Nedoma
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 "dcgf.h"
#include "BEvent.h"
#include "BParser.h"
namespace WinterMute {
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
IMPLEMENT_PERSISTENT(CBEvent, false)
//////////////////////////////////////////////////////////////////////////
CBEvent::CBEvent(CBGame *inGame): CBBase(inGame) {
m_Type = EVENT_NONE;
m_Script = NULL;
m_Name = NULL;
}
//////////////////////////////////////////////////////////////////////////
CBEvent::CBEvent(CBGame *inGame, TEventType Type, char *Script): CBBase(inGame) {
m_Type = Type;
m_Script = new char [strlen(Script) + 1];
if (m_Script) strcpy(m_Script, Script);
m_Name = NULL;
}
//////////////////////////////////////////////////////////////////////////
CBEvent::~CBEvent() {
SAFE_DELETE_ARRAY(m_Script);
SAFE_DELETE_ARRAY(m_Name);
}
//////////////////////////////////////////////////////////////////////////
const char *CBEvent::GetEventName(TEventType Type) {
switch (Type) {
case EVENT_INIT:
return "INIT";
case EVENT_SHUTDOWN:
return "SHUTDOWN";
case EVENT_LEFT_CLICK:
return "LEFT_CLICK";
case EVENT_RIGHT_CLICK:
return "RIGHT_CLICK";
case EVENT_MIDDLE_CLICK:
return "MIDDLE_CLICK";
case EVENT_LEFT_DBLCLICK:
return "LEFT_DBLCLICK";
case EVENT_PRESS:
return "PRESS";
case EVENT_IDLE:
return "IDLE";
case EVENT_MOUSE_OVER:
return "MOUSE_OVER";
case EVENT_LEFT_RELEASE:
return "LEFT_RELEASE";
case EVENT_RIGHT_RELEASE:
return "RIGHT_RELEASE";
case EVENT_MIDDLE_RELEASE:
return "MIDDLE_RELEASE";
default:
return "NONE";
}
}
//////////////////////////////////////////////////////////////////////////
void CBEvent::SetScript(char *Script) {
if (m_Script) delete [] m_Script;
m_Script = new char [strlen(Script) + 1];
if (m_Script) strcpy(m_Script, Script);
}
//////////////////////////////////////////////////////////////////////////
void CBEvent::SetName(char *Name) {
if (m_Name) delete [] m_Name;
m_Name = new char [strlen(Name) + 1];
if (m_Name) strcpy(m_Name, Name);
}
//////////////////////////////////////////////////////////////////////////
HRESULT CBEvent::LoadFile(char *Filename) {
BYTE *Buffer = Game->m_FileManager->ReadWholeFile(Filename);
if (Buffer == NULL) {
Game->LOG(0, "CBEvent::LoadFile failed for file '%s'", Filename);
return E_FAIL;
}
HRESULT ret;
if (FAILED(ret = LoadBuffer(Buffer, true))) Game->LOG(0, "Error parsing EVENT file '%s'", Filename);
delete [] Buffer;
return ret;
}
TOKEN_DEF_START
TOKEN_DEF(EVENT)
TOKEN_DEF(NAME)
TOKEN_DEF(SCRIPT)
TOKEN_DEF_END
//////////////////////////////////////////////////////////////////////////
HRESULT CBEvent::LoadBuffer(byte *Buffer, bool Complete) {
TOKEN_TABLE_START(commands)
TOKEN_TABLE(EVENT)
TOKEN_TABLE(NAME)
TOKEN_TABLE(SCRIPT)
TOKEN_TABLE_END
BYTE *params;
int cmd;
CBParser parser(Game);
if (Complete) {
if (parser.GetCommand((char **)&Buffer, commands, (char **)¶ms) != TOKEN_EVENT) {
Game->LOG(0, "'EVENT' keyword expected.");
return E_FAIL;
}
Buffer = params;
}
while ((cmd = parser.GetCommand((char **)&Buffer, commands, (char **)¶ms)) > 0) {
switch (cmd) {
case TOKEN_NAME:
SetName((char *)params);
break;
case TOKEN_SCRIPT:
SetScript((char *)params);
break;
}
}
if (cmd == PARSERR_TOKENNOTFOUND) {
Game->LOG(0, "Syntax error in EVENT definition");
return E_FAIL;
}
return S_OK;
}
//////////////////////////////////////////////////////////////////////////
HRESULT CBEvent::Persist(CBPersistMgr *PersistMgr) {
PersistMgr->Transfer(TMEMBER(Game));
PersistMgr->Transfer(TMEMBER(m_Script));
PersistMgr->Transfer(TMEMBER(m_Name));
PersistMgr->Transfer(TMEMBER_INT(m_Type));
return S_OK;
}
} // end of namespace WinterMute
<commit_msg>WINTERMUTE: Make BEvent indpendent from dcgf.<commit_after>/*
This file is part of WME Lite.
http://dead-code.org/redir.php?target=wmelite
Copyright (c) 2011 Jan Nedoma
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 "BGame.h"
#include "BFileManager.h"
#include "BEvent.h"
#include "BParser.h"
namespace WinterMute {
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
IMPLEMENT_PERSISTENT(CBEvent, false)
//////////////////////////////////////////////////////////////////////////
CBEvent::CBEvent(CBGame *inGame): CBBase(inGame) {
m_Type = EVENT_NONE;
m_Script = NULL;
m_Name = NULL;
}
//////////////////////////////////////////////////////////////////////////
CBEvent::CBEvent(CBGame *inGame, TEventType Type, char *Script): CBBase(inGame) {
m_Type = Type;
m_Script = new char [strlen(Script) + 1];
if (m_Script) strcpy(m_Script, Script);
m_Name = NULL;
}
//////////////////////////////////////////////////////////////////////////
CBEvent::~CBEvent() {
delete[] m_Script;
m_Script = NULL;
delete[] m_Name;
m_Name = NULL;
}
//////////////////////////////////////////////////////////////////////////
const char *CBEvent::GetEventName(TEventType Type) {
switch (Type) {
case EVENT_INIT:
return "INIT";
case EVENT_SHUTDOWN:
return "SHUTDOWN";
case EVENT_LEFT_CLICK:
return "LEFT_CLICK";
case EVENT_RIGHT_CLICK:
return "RIGHT_CLICK";
case EVENT_MIDDLE_CLICK:
return "MIDDLE_CLICK";
case EVENT_LEFT_DBLCLICK:
return "LEFT_DBLCLICK";
case EVENT_PRESS:
return "PRESS";
case EVENT_IDLE:
return "IDLE";
case EVENT_MOUSE_OVER:
return "MOUSE_OVER";
case EVENT_LEFT_RELEASE:
return "LEFT_RELEASE";
case EVENT_RIGHT_RELEASE:
return "RIGHT_RELEASE";
case EVENT_MIDDLE_RELEASE:
return "MIDDLE_RELEASE";
default:
return "NONE";
}
}
//////////////////////////////////////////////////////////////////////////
void CBEvent::SetScript(char *Script) {
if (m_Script) delete [] m_Script;
m_Script = new char [strlen(Script) + 1];
if (m_Script) strcpy(m_Script, Script);
}
//////////////////////////////////////////////////////////////////////////
void CBEvent::SetName(char *Name) {
if (m_Name) delete [] m_Name;
m_Name = new char [strlen(Name) + 1];
if (m_Name) strcpy(m_Name, Name);
}
//////////////////////////////////////////////////////////////////////////
HRESULT CBEvent::LoadFile(char *Filename) {
byte *Buffer = Game->m_FileManager->ReadWholeFile(Filename);
if (Buffer == NULL) {
Game->LOG(0, "CBEvent::LoadFile failed for file '%s'", Filename);
return E_FAIL;
}
HRESULT ret;
if (FAILED(ret = LoadBuffer(Buffer, true))) Game->LOG(0, "Error parsing EVENT file '%s'", Filename);
delete [] Buffer;
return ret;
}
TOKEN_DEF_START
TOKEN_DEF(EVENT)
TOKEN_DEF(NAME)
TOKEN_DEF(SCRIPT)
TOKEN_DEF_END
//////////////////////////////////////////////////////////////////////////
HRESULT CBEvent::LoadBuffer(byte *Buffer, bool Complete) {
TOKEN_TABLE_START(commands)
TOKEN_TABLE(EVENT)
TOKEN_TABLE(NAME)
TOKEN_TABLE(SCRIPT)
TOKEN_TABLE_END
BYTE *params;
int cmd;
CBParser parser(Game);
if (Complete) {
if (parser.GetCommand((char **)&Buffer, commands, (char **)¶ms) != TOKEN_EVENT) {
Game->LOG(0, "'EVENT' keyword expected.");
return E_FAIL;
}
Buffer = params;
}
while ((cmd = parser.GetCommand((char **)&Buffer, commands, (char **)¶ms)) > 0) {
switch (cmd) {
case TOKEN_NAME:
SetName((char *)params);
break;
case TOKEN_SCRIPT:
SetScript((char *)params);
break;
}
}
if (cmd == PARSERR_TOKENNOTFOUND) {
Game->LOG(0, "Syntax error in EVENT definition");
return E_FAIL;
}
return S_OK;
}
//////////////////////////////////////////////////////////////////////////
HRESULT CBEvent::Persist(CBPersistMgr *PersistMgr) {
PersistMgr->Transfer(TMEMBER(Game));
PersistMgr->Transfer(TMEMBER(m_Script));
PersistMgr->Transfer(TMEMBER(m_Name));
PersistMgr->Transfer(TMEMBER_INT(m_Type));
return S_OK;
}
} // end of namespace WinterMute
<|endoftext|> |
<commit_before># pragma once
# include <Siv3D.hpp>
namespace asc
{
using namespace s3d;
/// <summary>
/// 文字列を送受信可能な TCPClient, TCPServer
/// </summary>
/// <remarks>
/// 送受信は UTF-8 で行います。
/// </remarks>
template<class Socket>
class TCPString : public Socket
{
public:
/// <summary>
/// 1 文字読み込みます。
/// </summary>
/// <param name="to">
/// 読み込み先
/// </param>
/// <returns>
/// 読み込みに成功すれば true
/// </returns>
/// <remarks>
/// 日本語などの 1 バイトではない文字は正しく扱えません。
/// </remarks>
bool readChar(wchar& to)
{
std::string buffer;
if (!lookahead(buffer[0]))
return false;
skip(sizeof(std::string::value_type));
to = FromUTF8(std::move(buffer))[0];
return true;
}
/// <summary>
/// 文字数を指定して文字列を読み込みます。
/// </summary>
/// <param name="length">
/// 読み込む文字数
/// </param>
/// <param name="to">
/// 読み込み先
/// </param>
/// <returns>
/// 読み込みに成功すれば true
/// </returns>
/// <remarks>
/// 日本語などの 1 バイトではない文字は正しく扱えません。
/// </remarks>
bool readString(size_t length, String& to)
{
std::string buffer;
buffer.resize(length);
if (!lookahead(&buffer[0], buffer.size()))
return false;
skip(sizeof(std::string::value_type) * buffer.size());
to = FromUTF8(std::move(buffer));
return true;
}
/// <summary>
/// 1 行読み込みます。
/// </summary>
/// <param name="to">
/// 読み込み先
/// </param>
/// <returns>
/// 読み込みに成功すれば true
/// </returns>
/// <remarks>
/// 日本語などの 1 バイトではない文字も扱えます。
/// </remarks>
/// <remarks>
/// 改行コードは LF を使用します。
/// </remarks>
bool readLine(String& to)
{
return readUntil('\n', to);
}
/// <summary>
/// 指定した文字が来るまで読み込みます。
/// </summary>
/// <param name="end">
/// 指定する文字
/// </param>
/// <param name="to">
/// 読み込み先
/// </param>
/// <returns>
/// 読み込みに成功すれば true
/// </returns>
/// <remarks>
/// 日本語などの 1 バイトではない文字も扱えます。
/// </remarks>
bool readUntil(char end, String& to)
{
std::string buffer;
buffer.resize(available());
if (!lookahead(&buffer[0], buffer.size()))
return false;
const auto pos = buffer.find(end);
if (pos == buffer.npos)
return false;
buffer.resize(pos + 1);
skip(sizeof(std::string::value_type) * buffer.size());
to = FromUTF8(std::move(buffer));
return true;
}
/// <summary>
/// 指定した文字列が来るまで読み込みます。
/// </summary>
/// <param name="end">
/// 指定する文字列
/// </param>
/// <param name="to">
/// 読み込み先
/// </param>
/// <returns>
/// 読み込みに成功すれば true
/// </returns>
/// <remarks>
/// 日本語などの 1 バイトではない文字も扱えます。
/// </remarks>
bool readUntil(const String& end, String& to)
{
std::string buffer;
buffer.resize(available());
if (!lookahead(&buffer[0], buffer.size()))
return false;
const auto str = ToUTF8(end);
const auto pos = buffer.find(str);
if (pos == buffer.npos)
return false;
buffer.resize(pos + str.size());
skip(sizeof(std::string::value_type) * buffer.size());
to = FromUTF8(std::move(buffer));
return true;
}
/// <summary>
/// 文字を可能な限り読み込みます。
/// </summary>
/// <param name="to">
/// 読み込み先
/// </param>
/// <returns>
/// 読み込みに成功すれば true
/// </returns>
/// <remarks>
/// 日本語などの 1 バイトではない文字も扱えます。
/// </remarks>
bool readAll(String& to)
{
std::string buffer;
buffer.resize(available());
if (!lookahead(&buffer[0], buffer.size()))
return false;
skip(sizeof(std::string::value_type) * buffer.size());
to = FromUTF8(std::move(buffer));
return true;
}
/// <summary>
/// 文字列を送信します。
/// </summary>
/// <param name="data">
/// 送信する文字列
/// </param>
/// <returns>
/// 送信に成功すれば true
/// </returns>
/// <remarks>
/// 日本語などの 1 バイトではない文字も扱えます。
/// </remarks>
bool sendString(const String& data)
{
const auto str = ToUTF8(data);
return send(str.data(), sizeof(decltype(str)::value_type) * str.length());
}
};
using TCPStringClient = TCPString<TCPClient>;
using TCPStringServer = TCPString<TCPServer>;
}
<commit_msg>Resize buffer.<commit_after># pragma once
# include <Siv3D.hpp>
namespace asc
{
using namespace s3d;
/// <summary>
/// 文字列を送受信可能な TCPClient, TCPServer
/// </summary>
/// <remarks>
/// 送受信は UTF-8 で行います。
/// </remarks>
template<class Socket>
class TCPString : public Socket
{
public:
/// <summary>
/// 1 文字読み込みます。
/// </summary>
/// <param name="to">
/// 読み込み先
/// </param>
/// <returns>
/// 読み込みに成功すれば true
/// </returns>
/// <remarks>
/// 日本語などの 1 バイトではない文字は正しく扱えません。
/// </remarks>
bool readChar(wchar& to)
{
std::string buffer;
buffer.resize(1);
if (!lookahead(buffer[0]))
return false;
skip(sizeof(std::string::value_type));
to = FromUTF8(std::move(buffer))[0];
return true;
}
/// <summary>
/// 文字数を指定して文字列を読み込みます。
/// </summary>
/// <param name="length">
/// 読み込む文字数
/// </param>
/// <param name="to">
/// 読み込み先
/// </param>
/// <returns>
/// 読み込みに成功すれば true
/// </returns>
/// <remarks>
/// 日本語などの 1 バイトではない文字は正しく扱えません。
/// </remarks>
bool readString(size_t length, String& to)
{
std::string buffer;
buffer.resize(length);
if (!lookahead(&buffer[0], buffer.size()))
return false;
skip(sizeof(std::string::value_type) * buffer.size());
to = FromUTF8(std::move(buffer));
return true;
}
/// <summary>
/// 1 行読み込みます。
/// </summary>
/// <param name="to">
/// 読み込み先
/// </param>
/// <returns>
/// 読み込みに成功すれば true
/// </returns>
/// <remarks>
/// 日本語などの 1 バイトではない文字も扱えます。
/// </remarks>
/// <remarks>
/// 改行コードは LF を使用します。
/// </remarks>
bool readLine(String& to)
{
return readUntil('\n', to);
}
/// <summary>
/// 指定した文字が来るまで読み込みます。
/// </summary>
/// <param name="end">
/// 指定する文字
/// </param>
/// <param name="to">
/// 読み込み先
/// </param>
/// <returns>
/// 読み込みに成功すれば true
/// </returns>
/// <remarks>
/// 日本語などの 1 バイトではない文字も扱えます。
/// </remarks>
bool readUntil(char end, String& to)
{
std::string buffer;
buffer.resize(available());
if (!lookahead(&buffer[0], buffer.size()))
return false;
const auto pos = buffer.find(end);
if (pos == buffer.npos)
return false;
buffer.resize(pos + 1);
skip(sizeof(std::string::value_type) * buffer.size());
to = FromUTF8(std::move(buffer));
return true;
}
/// <summary>
/// 指定した文字列が来るまで読み込みます。
/// </summary>
/// <param name="end">
/// 指定する文字列
/// </param>
/// <param name="to">
/// 読み込み先
/// </param>
/// <returns>
/// 読み込みに成功すれば true
/// </returns>
/// <remarks>
/// 日本語などの 1 バイトではない文字も扱えます。
/// </remarks>
bool readUntil(const String& end, String& to)
{
std::string buffer;
buffer.resize(available());
if (!lookahead(&buffer[0], buffer.size()))
return false;
const auto str = ToUTF8(end);
const auto pos = buffer.find(str);
if (pos == buffer.npos)
return false;
buffer.resize(pos + str.size());
skip(sizeof(std::string::value_type) * buffer.size());
to = FromUTF8(std::move(buffer));
return true;
}
/// <summary>
/// 文字を可能な限り読み込みます。
/// </summary>
/// <param name="to">
/// 読み込み先
/// </param>
/// <returns>
/// 読み込みに成功すれば true
/// </returns>
/// <remarks>
/// 日本語などの 1 バイトではない文字も扱えます。
/// </remarks>
bool readAll(String& to)
{
std::string buffer;
buffer.resize(available());
if (!lookahead(&buffer[0], buffer.size()))
return false;
skip(sizeof(std::string::value_type) * buffer.size());
to = FromUTF8(std::move(buffer));
return true;
}
/// <summary>
/// 文字列を送信します。
/// </summary>
/// <param name="data">
/// 送信する文字列
/// </param>
/// <returns>
/// 送信に成功すれば true
/// </returns>
/// <remarks>
/// 日本語などの 1 バイトではない文字も扱えます。
/// </remarks>
bool sendString(const String& data)
{
const auto str = ToUTF8(data);
return send(str.data(), sizeof(decltype(str)::value_type) * str.length());
}
};
using TCPStringClient = TCPString<TCPClient>;
using TCPStringServer = TCPString<TCPServer>;
}
<|endoftext|> |
<commit_before>// This file was developed by Thomas Müller <thomas94@gmx.net>.
// It is published under the BSD 3-Clause License within the LICENSE file.
#include "../include/Common.h"
#include <algorithm>
#include <map>
#include <vector>
using namespace std;
TEV_NAMESPACE_BEGIN
vector<string> split(string text, const string& delim) {
vector<string> result;
while (true) {
size_t begin = text.rfind(delim);
if (begin == string::npos) {
result.emplace_back(text);
return result;
} else {
result.emplace_back(text.substr(begin + delim.length()));
text.resize(begin);
}
}
return result;
}
bool matches(string text, string filter) {
if (filter.empty()) {
return true;
}
// Perform matching on lowercase strings
transform(begin(text), end(text), begin(text), ::tolower);
transform(begin(filter), end(filter), begin(filter), ::tolower);
auto words = split(filter, " ");
// We don't want people entering multiple spaces in a row to match everything.
words.erase(remove(begin(words), end(words), ""), end(words));
// Match every word of the filter separately.
for (const auto& word : words) {
if (text.find(word) != string::npos) {
return true;
}
}
return false;
}
ETonemap toTonemap(string name) {
// Perform matching on uppercase strings
transform(begin(name), end(name), begin(name), ::toupper);
if (name == "SRGB") {
return SRGB;
} else if (name == "GAMMA") {
return Gamma;
} else if (name == "FALSECOLOR" || name == "FC") {
return FalseColor;
} else if (name == "POSITIVENEGATIVE" || name == "POSNEG" || name == "PN" ||name == "+-") {
return PositiveNegative;
} else {
return SRGB;
}
}
EMetric toMetric(string name) {
// Perform matching on uppercase strings
transform(begin(name), end(name), begin(name), ::toupper);
if (name == "E") {
return Error;
} else if (name == "AE") {
return AbsoluteError;
} else if (name == "SE") {
return SquaredError;
} else if (name == "RAE") {
return RelativeAbsoluteError;
} else if (name == "RSE") {
return RelativeSquaredError;
} else {
return Error;
}
}
TEV_NAMESPACE_END
<commit_msg>Fix incorrect matching behavior of just whitespaces<commit_after>// This file was developed by Thomas Müller <thomas94@gmx.net>.
// It is published under the BSD 3-Clause License within the LICENSE file.
#include "../include/Common.h"
#include <algorithm>
#include <map>
#include <vector>
using namespace std;
TEV_NAMESPACE_BEGIN
vector<string> split(string text, const string& delim) {
vector<string> result;
while (true) {
size_t begin = text.rfind(delim);
if (begin == string::npos) {
result.emplace_back(text);
return result;
} else {
result.emplace_back(text.substr(begin + delim.length()));
text.resize(begin);
}
}
return result;
}
bool matches(string text, string filter) {
if (filter.empty()) {
return true;
}
// Perform matching on lowercase strings
transform(begin(text), end(text), begin(text), ::tolower);
transform(begin(filter), end(filter), begin(filter), ::tolower);
auto words = split(filter, " ");
// We don't want people entering multiple spaces in a row to match everything.
words.erase(remove(begin(words), end(words), ""), end(words));
if (words.empty()) {
return true;
}
// Match every word of the filter separately.
for (const auto& word : words) {
if (text.find(word) != string::npos) {
return true;
}
}
return false;
}
ETonemap toTonemap(string name) {
// Perform matching on uppercase strings
transform(begin(name), end(name), begin(name), ::toupper);
if (name == "SRGB") {
return SRGB;
} else if (name == "GAMMA") {
return Gamma;
} else if (name == "FALSECOLOR" || name == "FC") {
return FalseColor;
} else if (name == "POSITIVENEGATIVE" || name == "POSNEG" || name == "PN" ||name == "+-") {
return PositiveNegative;
} else {
return SRGB;
}
}
EMetric toMetric(string name) {
// Perform matching on uppercase strings
transform(begin(name), end(name), begin(name), ::toupper);
if (name == "E") {
return Error;
} else if (name == "AE") {
return AbsoluteError;
} else if (name == "SE") {
return SquaredError;
} else if (name == "RAE") {
return RelativeAbsoluteError;
} else if (name == "RSE") {
return RelativeSquaredError;
} else {
return Error;
}
}
TEV_NAMESPACE_END
<|endoftext|> |
<commit_before>#include "dynet/nodes.h"
#include "dynet/dynet.h"
#include "dynet/training.h"
#include "dynet/timing.h"
#include "dynet/rnn.h"
#include "dynet/gru.h"
#include "dynet/lstm.h"
#include "dynet/fast-lstm.h"
#include "dynet/dict.h"
#include "dynet/expr.h"
#include <sys/stat.h>
#include <sys/types.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <type_traits>
#include <time.h>
#include <boost/serialization/vector.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/program_options.hpp>
#include "s2s/encdec.hpp"
#include "s2s/decode.hpp"
#include "s2s/define.hpp"
#include "s2s/comp.hpp"
#include "s2s/metrics.hpp"
#include "s2s/options.hpp"
namespace s2s {
void train(const s2s_options &opts){
s2s::dicts dicts;
s2s::parallel_corpus para_corp_train;
s2s::parallel_corpus para_corp_dev;
dicts.set(opts);
para_corp_train.load_src(opts.srcfile, dicts);
para_corp_train.load_trg(opts.trgfile, dicts);
para_corp_train.load_check();
para_corp_dev.load_src(opts.srcvalfile, dicts);
para_corp_dev.load_trg(opts.trgvalfile, dicts);
para_corp_dev.load_check();
if(opts.guided_alignment == true){
para_corp_train.load_align(opts.alignfile);
para_corp_train.load_check_with_align();
para_corp_dev.load_align(opts.alignvalfile);
para_corp_dev.load_check_with_align();
}
// for debug
dicts.save(opts);
// for debug
dynet::Model model;
encoder_decoder* encdec = new encoder_decoder(model, &opts);
encdec->enable_dropout();
dynet::Trainer* trainer = nullptr;
if(opts.optim == "sgd"){
trainer = new dynet::SimpleSGDTrainer(model);
}else if(opts.optim == "momentum_sgd"){
trainer = new dynet::MomentumSGDTrainer(model);
}else if(opts.optim == "adagrad"){
trainer = new dynet::AdagradTrainer(model);
}else if(opts.optim == "adadelta"){
trainer = new dynet::AdadeltaTrainer(model);
}else if(opts.optim == "adam"){
trainer = new dynet::AdamTrainer(model);
}else{
std::cerr << "Trainer does not exist !"<< std::endl;
assert(false);
}
trainer->eta0 = opts.learning_rate;
trainer->eta = opts.learning_rate;
trainer->clip_threshold = opts.clip_threshold;
trainer->clipping_enabled = opts.clipping_enabled;
unsigned int epoch = 0;
float align_w = opts.guided_alignment_weight;
while(epoch < opts.epochs){
// train
para_corp_train.shuffle();
batch one_batch;
unsigned int bid = 0;
while(para_corp_train.next_batch_para(one_batch, opts.max_batch_train, dicts)){
bid++;
auto chrono_start = std::chrono::system_clock::now();
dynet::ComputationGraph cg;
std::vector<dynet::expr::Expression> errs_att;
std::vector<dynet::expr::Expression> errs_out;
float loss_att = 0.0;
float loss_out = 0.0;
std::vector<dynet::expr::Expression> i_enc = encdec->encoder(one_batch, cg);
std::vector<dynet::expr::Expression> i_feed = encdec->init_feed(one_batch, cg);
for (unsigned int t = 0; t < one_batch.trg.size() - 1; ++t) {
dynet::expr::Expression i_att_t = encdec->decoder_attention(cg, one_batch.trg[t], i_feed[t], i_enc[0]);
if(opts.guided_alignment == true){
for(unsigned int i = 0; i < one_batch.align.at(t).size(); i++){
assert(0 <= one_batch.align.at(t).at(i) < one_batch.src.size());
}
dynet::expr::Expression i_err = pickneglogsoftmax(i_att_t, one_batch.align.at(t));
errs_att.push_back(i_err);
}
std::vector<dynet::expr::Expression> i_out_t = encdec->decoder_output(cg, i_att_t, i_enc[1]);
i_feed.push_back(i_out_t[1]);
dynet::expr::Expression i_err = pickneglogsoftmax(i_out_t[0], one_batch.trg[t+1]);
errs_out.push_back(i_err);
}
dynet::expr::Expression i_nerr_out = sum_batches(sum(errs_out));
loss_out = as_scalar(cg.forward(i_nerr_out));
dynet::expr::Expression i_nerr_all;
if(opts.guided_alignment == true){
dynet::expr::Expression i_nerr_att = sum_batches(sum(errs_att));
loss_att = as_scalar(cg.incremental_forward(i_nerr_att));
i_nerr_all = i_nerr_out + align_w * i_nerr_att;
}else{
i_nerr_all = i_nerr_out;
}
cg.incremental_forward(i_nerr_all);
cg.backward(i_nerr_all);
//cg.print_graphviz();
trainer->update(1.0 / double(one_batch.src.at(0).at(0).size()));
auto chrono_end = std::chrono::system_clock::now();
auto time_used = (double)std::chrono::duration_cast<std::chrono::milliseconds>(chrono_end - chrono_start).count() / (double)1000;
std::cerr << "batch: " << bid;
std::cerr << ",\tsize: " << one_batch.src.at(0).at(0).size();
std::cerr << ",\toutput loss: " << loss_out;
std::cerr << ",\tattention loss: " << loss_att;
std::cerr << ",\tsource length: " << one_batch.src.size();
std::cerr << ",\ttarget length: " << one_batch.trg.size();
std::cerr << ",\ttime: " << time_used << " [s]" << std::endl;
std::cerr << "[epoch=" << trainer->epoch << " eta=" << trainer->eta << " clips=" << trainer->clips_since_status << " updates=" << trainer->updates_since_status << "] " << std::endl;
}
para_corp_train.reset_index();
trainer->update_epoch();
trainer->status();
std::cerr << std::endl;
// dev
encdec->disable_dropout();
std::cerr << "dev" << std::endl;
ofstream dev_sents(opts.rootdir + "/dev_" + to_string(epoch) + ".txt");
while(para_corp_dev.next_batch_para(one_batch, opts.max_batch_pred, dicts)){
std::vector<std::vector<unsigned int> > osent;
s2s::greedy_decode(one_batch, osent, encdec, dicts, opts);
dev_sents << s2s::print_sents(osent, dicts);
}
dev_sents.close();
para_corp_dev.reset_index();
encdec->enable_dropout();
// save Model
ofstream model_out(opts.rootdir + "/" + opts.save_file + "_" + to_string(epoch) + ".model");
boost::archive::text_oarchive model_oa(model_out);
model_oa << model << *encdec;
model_out.close();
// preparation for next epoch
epoch++;
align_w *= opts.guided_alignment_decay;
if(epoch >= ops.guided_alignment_start_epoch){
trainer->eta *= opts.lr_decay;
}
}
}
void predict(const s2s_options &opts){
s2s::dicts dicts;
dicts.load(opts);
// load model
dynet::Model model;
encoder_decoder* encdec = new encoder_decoder(model, &opts);
//encdec->disable_dropout();
ifstream model_in(opts.modelfile);
boost::archive::text_iarchive model_ia(model_in);
model_ia >> model >> *encdec;
model_in.close();
// predict
s2s::monoling_corpus mono_corp;
mono_corp.load_src(opts.srcfile, dicts);
batch one_batch;
ofstream predict_sents(opts.trgfile);
encdec->disable_dropout();
while(mono_corp.next_batch_mono(one_batch, opts.max_batch_pred, dicts)){
std::vector<std::vector<unsigned int> > osent;
s2s::greedy_decode(one_batch, osent, encdec, dicts, opts);
predict_sents << s2s::print_sents(osent, dicts);
}
predict_sents.close();
}
};
int main(int argc, char** argv) {
namespace po = boost::program_options;
po::options_description bpo("h");
s2s::s2s_options opts;
s2s::set_s2s_options(&bpo, &opts);
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, bpo), vm);
po::notify(vm);
if(vm.at("mode").as<std::string>() == "train"){
s2s::add_s2s_options_train(&vm, &opts);
s2s::check_s2s_options_train(&vm, opts);
std::string file_name = opts.rootdir + "/options.txt";
struct stat st;
if(stat(opts.rootdir.c_str(), &st) != 0){
mkdir(opts.rootdir.c_str(), 0775);
}
ofstream out(file_name);
boost::archive::text_oarchive oa(out);
oa << opts;
out.close();
dynet::initialize(argc, argv);
s2s::train(opts);
}else if(vm.at("mode").as<std::string>() == "predict"){
ifstream in(opts.rootdir + "/options.txt");
boost::archive::text_iarchive ia(in);
ia >> opts;
in.close();
s2s::check_s2s_options_predict(&vm, opts);
dynet::initialize(argc, argv);
s2s::predict(opts);
}else if(vm.at("mode").as<std::string>() == "test"){
}else{
std::cerr << "Mode does not exist !"<< std::endl;
assert(false);
}
}
<commit_msg>spell miss fixed<commit_after>#include "dynet/nodes.h"
#include "dynet/dynet.h"
#include "dynet/training.h"
#include "dynet/timing.h"
#include "dynet/rnn.h"
#include "dynet/gru.h"
#include "dynet/lstm.h"
#include "dynet/fast-lstm.h"
#include "dynet/dict.h"
#include "dynet/expr.h"
#include <sys/stat.h>
#include <sys/types.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <type_traits>
#include <time.h>
#include <boost/serialization/vector.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/program_options.hpp>
#include "s2s/encdec.hpp"
#include "s2s/decode.hpp"
#include "s2s/define.hpp"
#include "s2s/comp.hpp"
#include "s2s/metrics.hpp"
#include "s2s/options.hpp"
namespace s2s {
void train(const s2s_options &opts){
s2s::dicts dicts;
s2s::parallel_corpus para_corp_train;
s2s::parallel_corpus para_corp_dev;
dicts.set(opts);
para_corp_train.load_src(opts.srcfile, dicts);
para_corp_train.load_trg(opts.trgfile, dicts);
para_corp_train.load_check();
para_corp_dev.load_src(opts.srcvalfile, dicts);
para_corp_dev.load_trg(opts.trgvalfile, dicts);
para_corp_dev.load_check();
if(opts.guided_alignment == true){
para_corp_train.load_align(opts.alignfile);
para_corp_train.load_check_with_align();
para_corp_dev.load_align(opts.alignvalfile);
para_corp_dev.load_check_with_align();
}
// for debug
dicts.save(opts);
// for debug
dynet::Model model;
encoder_decoder* encdec = new encoder_decoder(model, &opts);
encdec->enable_dropout();
dynet::Trainer* trainer = nullptr;
if(opts.optim == "sgd"){
trainer = new dynet::SimpleSGDTrainer(model);
}else if(opts.optim == "momentum_sgd"){
trainer = new dynet::MomentumSGDTrainer(model);
}else if(opts.optim == "adagrad"){
trainer = new dynet::AdagradTrainer(model);
}else if(opts.optim == "adadelta"){
trainer = new dynet::AdadeltaTrainer(model);
}else if(opts.optim == "adam"){
trainer = new dynet::AdamTrainer(model);
}else{
std::cerr << "Trainer does not exist !"<< std::endl;
assert(false);
}
trainer->eta0 = opts.learning_rate;
trainer->eta = opts.learning_rate;
trainer->clip_threshold = opts.clip_threshold;
trainer->clipping_enabled = opts.clipping_enabled;
unsigned int epoch = 0;
float align_w = opts.guided_alignment_weight;
while(epoch < opts.epochs){
// train
para_corp_train.shuffle();
batch one_batch;
unsigned int bid = 0;
while(para_corp_train.next_batch_para(one_batch, opts.max_batch_train, dicts)){
bid++;
auto chrono_start = std::chrono::system_clock::now();
dynet::ComputationGraph cg;
std::vector<dynet::expr::Expression> errs_att;
std::vector<dynet::expr::Expression> errs_out;
float loss_att = 0.0;
float loss_out = 0.0;
std::vector<dynet::expr::Expression> i_enc = encdec->encoder(one_batch, cg);
std::vector<dynet::expr::Expression> i_feed = encdec->init_feed(one_batch, cg);
for (unsigned int t = 0; t < one_batch.trg.size() - 1; ++t) {
dynet::expr::Expression i_att_t = encdec->decoder_attention(cg, one_batch.trg[t], i_feed[t], i_enc[0]);
if(opts.guided_alignment == true){
for(unsigned int i = 0; i < one_batch.align.at(t).size(); i++){
assert(0 <= one_batch.align.at(t).at(i) < one_batch.src.size());
}
dynet::expr::Expression i_err = pickneglogsoftmax(i_att_t, one_batch.align.at(t));
errs_att.push_back(i_err);
}
std::vector<dynet::expr::Expression> i_out_t = encdec->decoder_output(cg, i_att_t, i_enc[1]);
i_feed.push_back(i_out_t[1]);
dynet::expr::Expression i_err = pickneglogsoftmax(i_out_t[0], one_batch.trg[t+1]);
errs_out.push_back(i_err);
}
dynet::expr::Expression i_nerr_out = sum_batches(sum(errs_out));
loss_out = as_scalar(cg.forward(i_nerr_out));
dynet::expr::Expression i_nerr_all;
if(opts.guided_alignment == true){
dynet::expr::Expression i_nerr_att = sum_batches(sum(errs_att));
loss_att = as_scalar(cg.incremental_forward(i_nerr_att));
i_nerr_all = i_nerr_out + align_w * i_nerr_att;
}else{
i_nerr_all = i_nerr_out;
}
cg.incremental_forward(i_nerr_all);
cg.backward(i_nerr_all);
//cg.print_graphviz();
trainer->update(1.0 / double(one_batch.src.at(0).at(0).size()));
auto chrono_end = std::chrono::system_clock::now();
auto time_used = (double)std::chrono::duration_cast<std::chrono::milliseconds>(chrono_end - chrono_start).count() / (double)1000;
std::cerr << "batch: " << bid;
std::cerr << ",\tsize: " << one_batch.src.at(0).at(0).size();
std::cerr << ",\toutput loss: " << loss_out;
std::cerr << ",\tattention loss: " << loss_att;
std::cerr << ",\tsource length: " << one_batch.src.size();
std::cerr << ",\ttarget length: " << one_batch.trg.size();
std::cerr << ",\ttime: " << time_used << " [s]" << std::endl;
std::cerr << "[epoch=" << trainer->epoch << " eta=" << trainer->eta << " clips=" << trainer->clips_since_status << " updates=" << trainer->updates_since_status << "] " << std::endl;
}
para_corp_train.reset_index();
trainer->update_epoch();
trainer->status();
std::cerr << std::endl;
// dev
encdec->disable_dropout();
std::cerr << "dev" << std::endl;
ofstream dev_sents(opts.rootdir + "/dev_" + to_string(epoch) + ".txt");
while(para_corp_dev.next_batch_para(one_batch, opts.max_batch_pred, dicts)){
std::vector<std::vector<unsigned int> > osent;
s2s::greedy_decode(one_batch, osent, encdec, dicts, opts);
dev_sents << s2s::print_sents(osent, dicts);
}
dev_sents.close();
para_corp_dev.reset_index();
encdec->enable_dropout();
// save Model
ofstream model_out(opts.rootdir + "/" + opts.save_file + "_" + to_string(epoch) + ".model");
boost::archive::text_oarchive model_oa(model_out);
model_oa << model << *encdec;
model_out.close();
// preparation for next epoch
epoch++;
align_w *= opts.guided_alignment_decay;
if(epoch >= opts.guided_alignment_start_epoch){
trainer->eta *= opts.lr_decay;
}
}
}
void predict(const s2s_options &opts){
s2s::dicts dicts;
dicts.load(opts);
// load model
dynet::Model model;
encoder_decoder* encdec = new encoder_decoder(model, &opts);
//encdec->disable_dropout();
ifstream model_in(opts.modelfile);
boost::archive::text_iarchive model_ia(model_in);
model_ia >> model >> *encdec;
model_in.close();
// predict
s2s::monoling_corpus mono_corp;
mono_corp.load_src(opts.srcfile, dicts);
batch one_batch;
ofstream predict_sents(opts.trgfile);
encdec->disable_dropout();
while(mono_corp.next_batch_mono(one_batch, opts.max_batch_pred, dicts)){
std::vector<std::vector<unsigned int> > osent;
s2s::greedy_decode(one_batch, osent, encdec, dicts, opts);
predict_sents << s2s::print_sents(osent, dicts);
}
predict_sents.close();
}
};
int main(int argc, char** argv) {
namespace po = boost::program_options;
po::options_description bpo("h");
s2s::s2s_options opts;
s2s::set_s2s_options(&bpo, &opts);
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, bpo), vm);
po::notify(vm);
if(vm.at("mode").as<std::string>() == "train"){
s2s::add_s2s_options_train(&vm, &opts);
s2s::check_s2s_options_train(&vm, opts);
std::string file_name = opts.rootdir + "/options.txt";
struct stat st;
if(stat(opts.rootdir.c_str(), &st) != 0){
mkdir(opts.rootdir.c_str(), 0775);
}
ofstream out(file_name);
boost::archive::text_oarchive oa(out);
oa << opts;
out.close();
dynet::initialize(argc, argv);
s2s::train(opts);
}else if(vm.at("mode").as<std::string>() == "predict"){
ifstream in(opts.rootdir + "/options.txt");
boost::archive::text_iarchive ia(in);
ia >> opts;
in.close();
s2s::check_s2s_options_predict(&vm, opts);
dynet::initialize(argc, argv);
s2s::predict(opts);
}else if(vm.at("mode").as<std::string>() == "test"){
}else{
std::cerr << "Mode does not exist !"<< std::endl;
assert(false);
}
}
<|endoftext|> |
<commit_before>#include "gtest/gtest.h"
#include <rapidcheck/gtest.h>
#include <algorithm>
#include <stack>
#include <vector>
// Algorithm to be tested
// QUICK SORT
void quick_sort_helper(std::stack<int>& st, std::stack<int>& helper1, std::stack<int>& helper2, int size)
{
// Sort the size 1st elements of st using helper*
// At the end:
// - helper* has the same elements as before without any order change
// - elements of st deeper than size are not modified nor in value nor in order
if (size <= 1)
{
return;
}
--size;
const int pivot { st.top() };
st.pop();
// Partition the stack given the pivot
int num_less_eq { 0 };
for (int i = 0 ; i != size ; ++i)
{
const int current { st.top() };
st.pop();
if (current <= pivot)
{
helper1.push(current);
++num_less_eq;
}
else
{
helper2.push(current);
}
}
// num_sup 1st elements of helper2 are coming from st
// and are > pivot
const int num_sup { size - num_less_eq };
for (int i = 0 ; i != num_sup ; ++i)
{
st.push(helper2.top());
helper2.pop();
}
quick_sort_helper(st, helper1, helper2, num_sup);
// push pivot
st.push(pivot);
// num_less_eq 1st elements of helper1 are coming from st
// and are <= pivot
for (int i = 0 ; i != num_less_eq ; ++i)
{
st.push(helper1.top());
helper1.pop();
}
quick_sort_helper(st, helper1, helper2, num_less_eq);
}
void quick_sort_stack(std::stack<int>& st)
{
std::stack<int> helper1;
std::stack<int> helper2;
quick_sort_helper(st, helper1, helper2, st.size());
}
// MERGE SORT
template <bool reversed> inline bool merge_compare(int a, int b);
template <> inline bool merge_compare<false>(int a, int b) { return a < b; }
template <> inline bool merge_compare<true>(int a, int b) { return a > b; }
template <bool reversed>
void merge_sort_helper(std::stack<int>& st, std::stack<int>& helper1, std::stack<int>& helper2, int size)
{
// Sort the size 1st elements of st using helper*
// At the end:
// - helper* has the same elements as before without any order change
// - elements of st deeper than size are not modified nor in value nor in order
if (size <= 1)
{
return;
}
// Split stack into two others
for (int i = 0 ; i != size ; ++i)
{
const int current { st.top() };
st.pop();
if (i & 0x01)
{
helper1.push(current);
}
else
{
helper2.push(current);
}
}
const int num_in_1 { size / 2 };
const int num_in_2 { size - num_in_1 };
merge_sort_helper<!reversed>(helper1, st, helper2, num_in_1);
merge_sort_helper<!reversed>(helper2, st, helper1, num_in_2);
int taken_from_1 { 0 };
int taken_from_2 { 0 };
for (int i = 0 ; i != size ; ++i)
{
if (taken_from_1 < num_in_1)
{
if (taken_from_2 < num_in_2)
{
if (merge_compare<reversed>(helper1.top(), helper2.top()))
{
st.push(helper2.top());
helper2.pop();
++taken_from_2;
}
else
{
st.push(helper1.top());
helper1.pop();
++taken_from_1;
}
}
else
{
st.push(helper1.top());
helper1.pop();
}
}
else
{
st.push(helper2.top());
helper2.pop();
}
}
}
void merge_sort_stack(std::stack<int>& st)
{
std::stack<int> helper1;
std::stack<int> helper2;
merge_sort_helper<false>(st, helper1, helper2, st.size());
}
// SELECTION SORT
template <class T>
void selection_sort_stack(std::stack<T>& st)
{
const int size = st.size();
for (int i = 0 ; i != size ; ++i)
{
// At i-th step, st contains all the elements with the i-th last elements correctly ordered for final ascending
std::stack<T> helper;
T maxi = st.top();
st.pop();
// Find the max of the unsorted part
for (int j = i+1 ; j < size ; ++j)
{
if (maxi < st.top())
{
helper.push(maxi);
maxi = st.top();
}
else
{
helper.push(st.top());
}
st.pop();
}
st.push(maxi);
while (! helper.empty())
{
st.push(helper.top());
helper.pop();
}
}
}
template <class T>
inline void sort_stack(std::stack<T>& st)
{
#ifdef QUICK
return quick_sort_stack(st);
#elif MERGE
return merge_sort_stack(st);
#else
return selection_sort_stack(st);
#endif
}
// Tests helpers
template <class T> void test_stack(std::vector<T> const& expected, std::stack<T> &out);
template <class T> std::stack<T> make_stack(std::vector<T> const& elts);
// Running tests
TEST(Ascending, AlreadySorted)
{
std::stack<int> st = make_stack<int>({3,2,1});
sort_stack(st);
test_stack({1,2,3}, st);
}
TEST(Ascending, ReverseSorted)
{
std::stack<int> st = make_stack<int>({1,2,3});
sort_stack(st);
test_stack({1,2,3}, st);
}
TEST(Ascending, EmptyStack)
{
std::stack<int> st = make_stack<int>({});
sort_stack(st);
test_stack({}, st);
}
TEST(Ascending, DifferentElements)
{
std::stack<int> st = make_stack<int>({10,23,8,93,55,105});
sort_stack(st);
test_stack({8,10,23,55,93,105}, st);
}
TEST(Ascending, WithDuplicates)
{
std::stack<int> st = make_stack<int>({1,1,4,1,2,2,3});
sort_stack(st);
test_stack({1,1,1,2,2,3,4}, st);
}
TEST(Ascending, WithNullOrNegative)
{
std::stack<int> st = make_stack<int>({-10,-100,0,9,-3});
sort_stack(st);
test_stack({-100,-10,-3,0,9}, st);
}
RC_GTEST_PROP(Ascending, PropertyBasedTesting, (const std::vector<int>& _data))
{
std::vector<int> data = _data;
std::stack<int> st = make_stack<int>(data);
sort_stack(st);
std::sort(data.begin(), data.end());
test_stack(data, st);
}
int main(int argc, char **argv)
{
::testing::InitGoogleTest(&argc, argv);
int ret { RUN_ALL_TESTS() };
return ret;
}
// Tests helpers: implementation
template <class T>
void test_stack(std::vector<T> const& expected, std::stack<T> &out)
{
ASSERT_EQ(expected.size(), out.size());
for (auto elt : expected)
{
ASSERT_EQ(elt, out.top());
out.pop();
}
for (auto it = expected.crbegin() ; it != expected.crend() ; ++it)
{
out.push(*it);
}
}
template <class T>
std::stack<T> make_stack(std::vector<T> const& elts)
{
std::stack<T> st;
for (auto elt : elts)
{
st.push(elt);
}
return st;
}
<commit_msg>Rename test<commit_after>#include "gtest/gtest.h"
#include <rapidcheck/gtest.h>
#include <algorithm>
#include <stack>
#include <vector>
// Algorithm to be tested
// QUICK SORT
void quick_sort_helper(std::stack<int>& st, std::stack<int>& helper1, std::stack<int>& helper2, int size)
{
// Sort the size 1st elements of st using helper*
// At the end:
// - helper* has the same elements as before without any order change
// - elements of st deeper than size are not modified nor in value nor in order
if (size <= 1)
{
return;
}
--size;
const int pivot { st.top() };
st.pop();
// Partition the stack given the pivot
int num_less_eq { 0 };
for (int i = 0 ; i != size ; ++i)
{
const int current { st.top() };
st.pop();
if (current <= pivot)
{
helper1.push(current);
++num_less_eq;
}
else
{
helper2.push(current);
}
}
// num_sup 1st elements of helper2 are coming from st
// and are > pivot
const int num_sup { size - num_less_eq };
for (int i = 0 ; i != num_sup ; ++i)
{
st.push(helper2.top());
helper2.pop();
}
quick_sort_helper(st, helper1, helper2, num_sup);
// push pivot
st.push(pivot);
// num_less_eq 1st elements of helper1 are coming from st
// and are <= pivot
for (int i = 0 ; i != num_less_eq ; ++i)
{
st.push(helper1.top());
helper1.pop();
}
quick_sort_helper(st, helper1, helper2, num_less_eq);
}
void quick_sort_stack(std::stack<int>& st)
{
std::stack<int> helper1;
std::stack<int> helper2;
quick_sort_helper(st, helper1, helper2, st.size());
}
// MERGE SORT
template <bool reversed> inline bool merge_compare(int a, int b);
template <> inline bool merge_compare<false>(int a, int b) { return a < b; }
template <> inline bool merge_compare<true>(int a, int b) { return a > b; }
template <bool reversed>
void merge_sort_helper(std::stack<int>& st, std::stack<int>& helper1, std::stack<int>& helper2, int size)
{
// Sort the size 1st elements of st using helper*
// At the end:
// - helper* has the same elements as before without any order change
// - elements of st deeper than size are not modified nor in value nor in order
if (size <= 1)
{
return;
}
// Split stack into two others
for (int i = 0 ; i != size ; ++i)
{
const int current { st.top() };
st.pop();
if (i & 0x01)
{
helper1.push(current);
}
else
{
helper2.push(current);
}
}
const int num_in_1 { size / 2 };
const int num_in_2 { size - num_in_1 };
merge_sort_helper<!reversed>(helper1, st, helper2, num_in_1);
merge_sort_helper<!reversed>(helper2, st, helper1, num_in_2);
int taken_from_1 { 0 };
int taken_from_2 { 0 };
for (int i = 0 ; i != size ; ++i)
{
if (taken_from_1 < num_in_1)
{
if (taken_from_2 < num_in_2)
{
if (merge_compare<reversed>(helper1.top(), helper2.top()))
{
st.push(helper2.top());
helper2.pop();
++taken_from_2;
}
else
{
st.push(helper1.top());
helper1.pop();
++taken_from_1;
}
}
else
{
st.push(helper1.top());
helper1.pop();
}
}
else
{
st.push(helper2.top());
helper2.pop();
}
}
}
void merge_sort_stack(std::stack<int>& st)
{
std::stack<int> helper1;
std::stack<int> helper2;
merge_sort_helper<false>(st, helper1, helper2, st.size());
}
// SELECTION SORT
template <class T>
void selection_sort_stack(std::stack<T>& st)
{
const int size = st.size();
for (int i = 0 ; i != size ; ++i)
{
// At i-th step, st contains all the elements with the i-th last elements correctly ordered for final ascending
std::stack<T> helper;
T maxi = st.top();
st.pop();
// Find the max of the unsorted part
for (int j = i+1 ; j < size ; ++j)
{
if (maxi < st.top())
{
helper.push(maxi);
maxi = st.top();
}
else
{
helper.push(st.top());
}
st.pop();
}
st.push(maxi);
while (! helper.empty())
{
st.push(helper.top());
helper.pop();
}
}
}
template <class T>
inline void sort_stack(std::stack<T>& st)
{
#ifdef QUICK
return quick_sort_stack(st);
#elif MERGE
return merge_sort_stack(st);
#else
return selection_sort_stack(st);
#endif
}
// Tests helpers
template <class T> void test_stack(std::vector<T> const& expected, std::stack<T> &out);
template <class T> std::stack<T> make_stack(std::vector<T> const& elts);
// Running tests
TEST(Ascending, AlreadySorted)
{
std::stack<int> st = make_stack<int>({3,2,1});
sort_stack(st);
test_stack({1,2,3}, st);
}
TEST(Ascending, ReverseSorted)
{
std::stack<int> st = make_stack<int>({1,2,3});
sort_stack(st);
test_stack({1,2,3}, st);
}
TEST(Ascending, EmptyStack)
{
std::stack<int> st = make_stack<int>({});
sort_stack(st);
test_stack({}, st);
}
TEST(Ascending, DifferentElements)
{
std::stack<int> st = make_stack<int>({10,23,8,93,55,105});
sort_stack(st);
test_stack({8,10,23,55,93,105}, st);
}
TEST(Ascending, WithDuplicates)
{
std::stack<int> st = make_stack<int>({1,1,4,1,2,2,3});
sort_stack(st);
test_stack({1,1,1,2,2,3,4}, st);
}
TEST(Ascending, WithNullOrNegative)
{
std::stack<int> st = make_stack<int>({-10,-100,0,9,-3});
sort_stack(st);
test_stack({-100,-10,-3,0,9}, st);
}
RC_GTEST_PROP(Ascending, RandomData, (const std::vector<int>& _data))
{
std::vector<int> data = _data;
std::stack<int> st = make_stack<int>(data);
sort_stack(st);
std::sort(data.begin(), data.end());
test_stack(data, st);
}
int main(int argc, char **argv)
{
::testing::InitGoogleTest(&argc, argv);
int ret { RUN_ALL_TESTS() };
return ret;
}
// Tests helpers: implementation
template <class T>
void test_stack(std::vector<T> const& expected, std::stack<T> &out)
{
ASSERT_EQ(expected.size(), out.size());
for (auto elt : expected)
{
ASSERT_EQ(elt, out.top());
out.pop();
}
for (auto it = expected.crbegin() ; it != expected.crend() ; ++it)
{
out.push(*it);
}
}
template <class T>
std::stack<T> make_stack(std::vector<T> const& elts)
{
std::stack<T> st;
for (auto elt : elts)
{
st.push(elt);
}
return st;
}
<|endoftext|> |
<commit_before>#include "CommonData.hpp"
#include "EventOutputQueue.hpp"
#include "IOLogWrapper.hpp"
#include "KeyboardRepeat.hpp"
#include "ListHookedKeyboard.hpp"
#include "RemapClass.hpp"
namespace org_pqrs_Karabiner {
List KeyboardRepeat::queue_;
TimerWrapper KeyboardRepeat::fire_timer_;
int KeyboardRepeat::id_ = 0;
int KeyboardRepeat::keyRepeat_ = 0;
void
KeyboardRepeat::initialize(IOWorkLoop& workloop)
{
fire_timer_.initialize(&workloop, NULL, KeyboardRepeat::fire_timer_callback);
}
void
KeyboardRepeat::terminate(void)
{
fire_timer_.terminate();
queue_.clear();
}
void
KeyboardRepeat::cancel(void)
{
fire_timer_.cancelTimeout();
queue_.clear();
// Increase id_ at cancel for DependingPressingPeriodKeyToKey to detect keyboardRepeat canceling.
succID();
}
void
KeyboardRepeat::primitive_add(EventType eventType,
Flags flags,
KeyCode key,
KeyboardType keyboardType)
{
if (key == KeyCode::VK_NONE) return;
// ------------------------------------------------------------
Params_KeyboardEventCallBack::auto_ptr ptr(Params_KeyboardEventCallBack::alloc(eventType,
flags,
key,
keyboardType,
true));
if (! ptr) return;
Params_KeyboardEventCallBack& params = *ptr;
queue_.push_back(new Item(params));
}
void
KeyboardRepeat::primitive_add(EventType eventType,
Flags flags,
ConsumerKeyCode key)
{
if (key == ConsumerKeyCode::VK_NONE) return;
// ------------------------------------------------------------
Params_KeyboardSpecialEventCallback::auto_ptr ptr(Params_KeyboardSpecialEventCallback::alloc(eventType,
flags,
key,
true));
if (! ptr) return;
Params_KeyboardSpecialEventCallback& params = *ptr;
queue_.push_back(new Item(params));
}
void
KeyboardRepeat::primitive_add(Buttons button)
{
// ------------------------------------------------------------
Params_RelativePointerEventCallback::auto_ptr ptr(Params_RelativePointerEventCallback::alloc(button,
0,
0,
PointingButton::NONE,
false));
if (! ptr) return;
Params_RelativePointerEventCallback& params = *ptr;
queue_.push_back(new Item(params));
}
int
KeyboardRepeat::primitive_start(int delayUntilRepeat, int keyRepeat)
{
keyRepeat_ = keyRepeat;
fire_timer_.setTimeoutMS(delayUntilRepeat);
return succID();
}
void
KeyboardRepeat::set(EventType eventType,
Flags flags,
KeyCode key,
KeyboardType keyboardType,
int delayUntilRepeat,
int keyRepeat)
{
if (key == KeyCode::VK_NONE) return;
if (eventType == EventType::MODIFY) {
goto cancel;
} else if (eventType == EventType::UP) {
// The repetition of plural keys is controlled by manual operation.
// So, we ignore it.
if (queue_.size() != 1) return;
// We stop key repeat only when the repeating key is up.
KeyboardRepeat::Item* p = static_cast<KeyboardRepeat::Item*>(queue_.safe_front());
if (p) {
Params_KeyboardEventCallBack* params = (p->params).get_Params_KeyboardEventCallBack();
if (params && key == params->key) {
goto cancel;
}
}
} else if (eventType == EventType::DOWN) {
cancel();
primitive_add(eventType, flags, key, keyboardType);
primitive_start(delayUntilRepeat, keyRepeat);
IOLOG_DEVEL("KeyboardRepeat::set key:%d flags:0x%x\n", key.get(), flags.get());
} else {
goto cancel;
}
return;
cancel:
cancel();
}
void
KeyboardRepeat::set(EventType eventType,
Flags flags,
ConsumerKeyCode key,
int delayUntilRepeat,
int keyRepeat)
{
if (key == ConsumerKeyCode::VK_NONE) return;
if (eventType == EventType::UP) {
goto cancel;
} else if (eventType == EventType::DOWN) {
if (! key.isRepeatable()) {
goto cancel;
}
cancel();
primitive_add(eventType, flags, key);
primitive_start(delayUntilRepeat, keyRepeat);
IOLOG_DEVEL("KeyboardRepeat::set consumer key:%d flags:0x%x\n", key.get(), flags.get());
} else {
goto cancel;
}
return;
cancel:
cancel();
}
void
KeyboardRepeat::fire_timer_callback(OSObject* owner, IOTimerEventSource* sender)
{
IOLOG_DEVEL("KeyboardRepeat::fire queue_.size = %d\n", static_cast<int>(queue_.size()));
// ----------------------------------------
for (KeyboardRepeat::Item* p = static_cast<KeyboardRepeat::Item*>(queue_.safe_front()); p; p = static_cast<KeyboardRepeat::Item*>(p->getnext())) {
switch ((p->params).type) {
case ParamsUnion::KEYBOARD:
{
Params_KeyboardEventCallBack* params = (p->params).get_Params_KeyboardEventCallBack();
if (params) {
Params_KeyboardEventCallBack::auto_ptr ptr(
Params_KeyboardEventCallBack::alloc(params->eventType,
params->flags,
params->key,
params->keyboardType,
queue_.size() == 1 ? true : false));
if (ptr) {
EventOutputQueue::FireKey::fire(*ptr);
}
}
break;
}
case ParamsUnion::KEYBOARD_SPECIAL:
{
Params_KeyboardSpecialEventCallback* params = (p->params).get_Params_KeyboardSpecialEventCallback();
if (params) {
Params_KeyboardSpecialEventCallback::auto_ptr ptr(
Params_KeyboardSpecialEventCallback::alloc(params->eventType,
params->flags,
params->key,
queue_.size() == 1 ? true : false));
if (ptr) {
EventOutputQueue::FireConsumer::fire(*ptr);
}
}
break;
}
case ParamsUnion::RELATIVE_POINTER:
{
Params_RelativePointerEventCallback* params = (p->params).get_Params_RelativePointerEventCallback();
if (params) {
EventOutputQueue::FireRelativePointer::fire(params->buttons, params->dx, params->dy);
}
break;
}
case ParamsUnion::UPDATE_FLAGS:
case ParamsUnion::SCROLL_WHEEL:
case ParamsUnion::WAIT:
// do nothing
break;
}
}
fire_timer_.setTimeoutMS(keyRepeat_);
}
}
<commit_msg>alloc -> constructor<commit_after>#include "CommonData.hpp"
#include "EventOutputQueue.hpp"
#include "IOLogWrapper.hpp"
#include "KeyboardRepeat.hpp"
#include "ListHookedKeyboard.hpp"
#include "RemapClass.hpp"
namespace org_pqrs_Karabiner {
List KeyboardRepeat::queue_;
TimerWrapper KeyboardRepeat::fire_timer_;
int KeyboardRepeat::id_ = 0;
int KeyboardRepeat::keyRepeat_ = 0;
void
KeyboardRepeat::initialize(IOWorkLoop& workloop)
{
fire_timer_.initialize(&workloop, NULL, KeyboardRepeat::fire_timer_callback);
}
void
KeyboardRepeat::terminate(void)
{
fire_timer_.terminate();
queue_.clear();
}
void
KeyboardRepeat::cancel(void)
{
fire_timer_.cancelTimeout();
queue_.clear();
// Increase id_ at cancel for DependingPressingPeriodKeyToKey to detect keyboardRepeat canceling.
succID();
}
void
KeyboardRepeat::primitive_add(EventType eventType,
Flags flags,
KeyCode key,
KeyboardType keyboardType)
{
if (key == KeyCode::VK_NONE) return;
// ------------------------------------------------------------
Params_KeyboardEventCallBack params(eventType,
flags,
key,
keyboardType,
true);
queue_.push_back(new Item(params));
}
void
KeyboardRepeat::primitive_add(EventType eventType,
Flags flags,
ConsumerKeyCode key)
{
if (key == ConsumerKeyCode::VK_NONE) return;
// ------------------------------------------------------------
Params_KeyboardSpecialEventCallback params(eventType,
flags,
key,
true);
queue_.push_back(new Item(params));
}
void
KeyboardRepeat::primitive_add(Buttons button)
{
// ------------------------------------------------------------
Params_RelativePointerEventCallback::auto_ptr ptr(Params_RelativePointerEventCallback::alloc(button,
0,
0,
PointingButton::NONE,
false));
if (! ptr) return;
Params_RelativePointerEventCallback& params = *ptr;
queue_.push_back(new Item(params));
}
int
KeyboardRepeat::primitive_start(int delayUntilRepeat, int keyRepeat)
{
keyRepeat_ = keyRepeat;
fire_timer_.setTimeoutMS(delayUntilRepeat);
return succID();
}
void
KeyboardRepeat::set(EventType eventType,
Flags flags,
KeyCode key,
KeyboardType keyboardType,
int delayUntilRepeat,
int keyRepeat)
{
if (key == KeyCode::VK_NONE) return;
if (eventType == EventType::MODIFY) {
goto cancel;
} else if (eventType == EventType::UP) {
// The repetition of plural keys is controlled by manual operation.
// So, we ignore it.
if (queue_.size() != 1) return;
// We stop key repeat only when the repeating key is up.
KeyboardRepeat::Item* p = static_cast<KeyboardRepeat::Item*>(queue_.safe_front());
if (p) {
Params_KeyboardEventCallBack* params = (p->params).get_Params_KeyboardEventCallBack();
if (params && key == params->key) {
goto cancel;
}
}
} else if (eventType == EventType::DOWN) {
cancel();
primitive_add(eventType, flags, key, keyboardType);
primitive_start(delayUntilRepeat, keyRepeat);
IOLOG_DEVEL("KeyboardRepeat::set key:%d flags:0x%x\n", key.get(), flags.get());
} else {
goto cancel;
}
return;
cancel:
cancel();
}
void
KeyboardRepeat::set(EventType eventType,
Flags flags,
ConsumerKeyCode key,
int delayUntilRepeat,
int keyRepeat)
{
if (key == ConsumerKeyCode::VK_NONE) return;
if (eventType == EventType::UP) {
goto cancel;
} else if (eventType == EventType::DOWN) {
if (! key.isRepeatable()) {
goto cancel;
}
cancel();
primitive_add(eventType, flags, key);
primitive_start(delayUntilRepeat, keyRepeat);
IOLOG_DEVEL("KeyboardRepeat::set consumer key:%d flags:0x%x\n", key.get(), flags.get());
} else {
goto cancel;
}
return;
cancel:
cancel();
}
void
KeyboardRepeat::fire_timer_callback(OSObject* owner, IOTimerEventSource* sender)
{
IOLOG_DEVEL("KeyboardRepeat::fire queue_.size = %d\n", static_cast<int>(queue_.size()));
// ----------------------------------------
for (KeyboardRepeat::Item* p = static_cast<KeyboardRepeat::Item*>(queue_.safe_front()); p; p = static_cast<KeyboardRepeat::Item*>(p->getnext())) {
switch ((p->params).type) {
case ParamsUnion::KEYBOARD:
{
Params_KeyboardEventCallBack* params = (p->params).get_Params_KeyboardEventCallBack();
if (params) {
Params_KeyboardEventCallBack pr(params->eventType,
params->flags,
params->key,
params->keyboardType,
queue_.size() == 1 ? true : false);
EventOutputQueue::FireKey::fire(pr);
}
break;
}
case ParamsUnion::KEYBOARD_SPECIAL:
{
Params_KeyboardSpecialEventCallback* params = (p->params).get_Params_KeyboardSpecialEventCallback();
if (params) {
Params_KeyboardSpecialEventCallback::auto_ptr ptr(
Params_KeyboardSpecialEventCallback::alloc(params->eventType,
params->flags,
params->key,
queue_.size() == 1 ? true : false));
if (ptr) {
EventOutputQueue::FireConsumer::fire(*ptr);
}
}
break;
}
case ParamsUnion::RELATIVE_POINTER:
{
Params_RelativePointerEventCallback* params = (p->params).get_Params_RelativePointerEventCallback();
if (params) {
EventOutputQueue::FireRelativePointer::fire(params->buttons, params->dx, params->dy);
}
break;
}
case ParamsUnion::UPDATE_FLAGS:
case ParamsUnion::SCROLL_WHEEL:
case ParamsUnion::WAIT:
// do nothing
break;
}
}
fire_timer_.setTimeoutMS(keyRepeat_);
}
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <cmath>
#include <array>
#include <sndfile.hh>
int main() {
constexpr double pi = 3.14159265358979323846264338;
constexpr double freq = 440.0;
constexpr double duration = 1.0;
constexpr int samplerate = 48000;
constexpr double sample_duration = 1.0/samplerate;
constexpr int sample_count = samplerate * duration;
std::cout << "duration=" << duration << "\n";
std::cout << "samplerate=" << samplerate << "\n";
std::cout << "sample_count=" << sample_count << "\n";
std::cout << "sample_duration=" << sample_duration << "\n";
std::cout << "freq=" << freq;
std::cout << std::endl;
std::array<double, sample_count> buffer;
for (int k = 0; k < sample_count; k++) {
buffer[k] = sin(freq * 2 * k * pi / samplerate);
//std::cout << k << ": " << sample_duration*k << ": " << buffer[k] << "\n";
}
SndfileHandle sndfilehandle_pcm32("sine32.wav", SFM_WRITE, (SF_FORMAT_WAV | SF_FORMAT_PCM_32), 1, samplerate);
SndfileHandle sndfilehandle_pcm24("sine24.wav", SFM_WRITE, (SF_FORMAT_WAV | SF_FORMAT_PCM_24), 1, samplerate);
SndfileHandle sndfilehandle_pcm16("sine16.wav", SFM_WRITE, (SF_FORMAT_WAV | SF_FORMAT_PCM_16), 1, samplerate);
SndfileHandle sndfilehandle_pcmf ("sinef.wav", SFM_WRITE, (SF_FORMAT_WAV | SF_FORMAT_FLOAT), 1, samplerate);
SndfileHandle sndfilehandle_pcmd ("sined.wav", SFM_WRITE, (SF_FORMAT_WAV | SF_FORMAT_DOUBLE), 1, samplerate);
sndfilehandle_pcm32.write(buffer.data(), sample_count);
sndfilehandle_pcm24.write(buffer.data(), sample_count);
sndfilehandle_pcm16.write(buffer.data(), sample_count);
sndfilehandle_pcmf.write (buffer.data(), sample_count);
sndfilehandle_pcmd.write (buffer.data(), sample_count);
return 0;
}
<commit_msg>Rename output files.<commit_after>#include <iostream>
#include <cmath>
#include <array>
#include <sndfile.hh>
int main() {
constexpr double pi = 3.14159265358979323846264338;
constexpr double freq = 440.0;
constexpr double duration = 1.0;
constexpr int samplerate = 48000;
constexpr double sample_duration = 1.0/samplerate;
constexpr int sample_count = samplerate * duration;
std::cout << "duration=" << duration << "\n";
std::cout << "samplerate=" << samplerate << "\n";
std::cout << "sample_count=" << sample_count << "\n";
std::cout << "sample_duration=" << sample_duration << "\n";
std::cout << "freq=" << freq;
std::cout << std::endl;
std::array<double, sample_count> buffer;
for (int k = 0; k < sample_count; ++k) {
buffer[k] = sin(freq * 2 * k * pi / samplerate);
//std::cout << k << ": " << sample_duration*k << ": " << buffer[k] << "\n";
}
SndfileHandle sndfilehandle_pcm32("sine_" + std::to_string(freq) + "_" + std::to_string(samplerate) + "_pcm32.wav",
SFM_WRITE,
(SF_FORMAT_WAV | SF_FORMAT_PCM_32), 1, samplerate);
SndfileHandle sndfilehandle_pcm24("sine_" + std::to_string(freq) + "_" + std::to_string(samplerate) + "_pcm24.wav",
SFM_WRITE,
(SF_FORMAT_WAV | SF_FORMAT_PCM_24), 1, samplerate);
SndfileHandle sndfilehandle_pcm16("sine_" + std::to_string(freq) + "_" + std::to_string(samplerate) + "_pcm16.wav",
SFM_WRITE,
(SF_FORMAT_WAV | SF_FORMAT_PCM_16), 1, samplerate);
SndfileHandle sndfilehandle_pcmf("sine_" + std::to_string(freq) + "_" + std::to_string(samplerate) + "_float.wav",
SFM_WRITE,
(SF_FORMAT_WAV | SF_FORMAT_FLOAT), 1, samplerate);
SndfileHandle sndfilehandle_pcmd("sine_" + std::to_string(freq) + "_" + std::to_string(samplerate) + "_double.wav",
SFM_WRITE,
(SF_FORMAT_WAV | SF_FORMAT_DOUBLE), 1, samplerate);
sndfilehandle_pcm32.write(buffer.data(), buffer.size());
sndfilehandle_pcm24.write(buffer.data(), buffer.size());
sndfilehandle_pcm16.write(buffer.data(), buffer.size());
sndfilehandle_pcmf.write (buffer.data(), buffer.size());
sndfilehandle_pcmd.write (buffer.data(), buffer.size());
return 0;
}
<|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 <QString>
#include <QSize>
#include <QSettings>
#include <QFile>
#include <QDir>
#include <QDesktopWidget>
#ifdef HAVE_DBUS
#include <QDBusConnection>
#include <QDBusConnectionInterface>
#endif
#include "mdebug.h"
#include "mdeviceprofile.h"
#include "mdeviceprofile_p.h"
#include "mapplication.h"
#include "mcomponentdata.h"
#include "mcomponentdata_p.h"
#include "mgconfitem.h"
namespace{
#ifdef HAVE_DBUS
static const QString pixmapProviderDbusService = "com.meego.core.MStatusBar";
#endif
static const qreal mmPerInch = 25.4;
static const qreal pointsPerInch = 72.0;
static qreal dotsPerInch = 96.0;
}
MDeviceProfilePrivate::MDeviceProfilePrivate()
: q_ptr(0)
{
QString filename;
QString targetname = MApplication::deviceName();
#ifdef Q_WS_X11
dotsPerInch = QX11Info::appDpiX();
#endif
#ifdef Q_OS_WIN
QDir appDir(QCoreApplication::applicationDirPath());
appDir.cdUp();
appDir.cd("share");
appDir.cd("meegotouch");
appDir.cd("targets");
if(targetname.isEmpty())
filename = appDir.path().append(QDir::separator())
.append("Default.conf");
else
filename = appDir.path().append(QDir::separator())
.append(targetname).append(".conf");
#else //!Q_OS_WIN
if (targetname.isEmpty()) {
#ifdef HAVE_GCONF
MGConfItem targetNameItem("/meegotouch/target/name");
targetname = targetNameItem.value("Default").toString();
#else
targetname = "Default";
#endif //HAVE_GCONF
}
filename = M_TARGETS_CONF_DIR + QString("/") + targetname + ".conf";
#endif //Q_OS_WIN
if (!load(filename)) {
qCritical("Failed to load device profile '%s'", qPrintable(filename));
autodetection();
}
}
MDeviceProfilePrivate::~MDeviceProfilePrivate()
{
}
bool MDeviceProfilePrivate::load(const QString& filename)
{
if (!QFile::exists(filename))
return false;
QSettings settings(filename, QSettings::IniFormat);
if (settings.status() != QSettings::NoError)
return false;
if (settings.value("/resolution/X").toString() == "autodetect")
resolution.setWidth(QApplication::desktop()->screenGeometry().size().width());
else
resolution.setWidth(settings.value("/resolution/X", 0).toInt());
if (settings.value("/resolution/Y").toString() == "autodetect")
resolution.setHeight(QApplication::desktop()->screenGeometry().size().height());
else
resolution.setHeight(settings.value("/resolution/Y", 0).toInt());
if (settings.value("/ppi/X").toString() == "autodetect") {
int widthMM = QApplication::desktop()->widthMM();
if(widthMM){
int autodetectedPpiX = mmPerInch * QApplication::desktop()->screenGeometry().size().width() / widthMM;
pixelsPerInch.setWidth(autodetectedPpiX);
}
}
else
pixelsPerInch.setWidth(settings.value("/ppi/X", 0).toInt());
if (settings.value("/ppi/Y") == "autodetect") {
int heightMM = QApplication::desktop()->heightMM();
if(heightMM){
int autodetectedPpiY = mmPerInch * QApplication::desktop()->screenGeometry().size().height() / heightMM;
pixelsPerInch.setWidth(autodetectedPpiY);
}
}
else
pixelsPerInch.setHeight(settings.value("/ppi/Y", 0).toInt());
pixelsPerMm = pixelsPerInch.width() / mmPerInch;
pixelsPerMmF = pixelsPerInch.width() / mmPerInch;
pixelsPerPtF = dotsPerInch / pointsPerInch;
if (settings.value("/other/showStatusBar").toString() == "autodetect")
showStatusBar = hasStatusbarProvider();
else
showStatusBar=settings.value("/other/showStatusBar",false).toBool();
if (settings.value("/allowedOrientations/keyboardOpen").toString() == "autodetect"){
supportedOrientationsForKeyboardClosed << M::Angle0 << M::Angle90 << M::Angle180 << M::Angle270;
} else {
QStringList orientationsForDevOpen = settings.value("/allowedOrientations/keyboardOpen",
QStringList()).toStringList();
if (orientationsForDevOpen.contains("0"))
supportedOrientationsForKeyboardOpen << M::Angle0;
if (orientationsForDevOpen.contains("90"))
supportedOrientationsForKeyboardOpen << M::Angle90;
if (orientationsForDevOpen.contains("180"))
supportedOrientationsForKeyboardOpen << M::Angle180;
if (orientationsForDevOpen.contains("270"))
supportedOrientationsForKeyboardOpen << M::Angle270;
}
if (settings.value("/allowedOrientations/keyboardOpen", "").toString() == "autodetect"){
supportedOrientationsForKeyboardOpen << M::Angle0 << M::Angle90 << M::Angle180 << M::Angle270;
} else {
QStringList orientationsForDevClosed = settings.value("/allowedOrientations/keyboardClosed",
QStringList()).toStringList();
if (orientationsForDevClosed.contains("0"))
supportedOrientationsForKeyboardClosed << M::Angle0;
if (orientationsForDevClosed.contains("90"))
supportedOrientationsForKeyboardClosed << M::Angle90;
if (orientationsForDevClosed.contains("180"))
supportedOrientationsForKeyboardClosed << M::Angle180;
if (orientationsForDevClosed.contains("270"))
supportedOrientationsForKeyboardClosed << M::Angle270;
}
return true;
}
/*
* @return pointer to the singleton MDeviceProfile instance
*/
MDeviceProfile *MDeviceProfile::instance()
{
MComponentData *data = MComponentData::instance();
if (!data)
{
qFatal("There is no instance of MDeviceProfile. Please create MComponentData first.");
return 0;
}
else
{
return data->d_ptr->deviceProfile;
}
}
MDeviceProfile::MDeviceProfile(QObject *parent)
: QObject(parent),
d_ptr(new MDeviceProfilePrivate)
{
Q_D(MDeviceProfile);
d->q_ptr = this;
if (!MComponentData::instance())
qFatal("There is no instance of MComponentData. Please create MApplication first.");
if (MComponentData::instance()->d_ptr->deviceProfile)
qFatal("Device profile is already created. Please use MDeviceProfile::instance()");
}
MDeviceProfile::~MDeviceProfile()
{
delete d_ptr;
}
QSize MDeviceProfile::resolution() const
{
Q_D(const MDeviceProfile);
return d->resolution;
}
QSize MDeviceProfile::pixelsPerInch() const
{
Q_D(const MDeviceProfile);
return d->pixelsPerInch;
}
bool MDeviceProfile::showStatusbar() const
{
Q_D(const MDeviceProfile);
return d->showStatusBar;
}
M::Orientation MDeviceProfile::orientationFromAngle(M::OrientationAngle angle) const
{
Q_D(const MDeviceProfile);
M::Orientation orientation;
if (d->resolution.width() >= d->resolution.height()) {
// native display orientation is landscape
if (angle == M::Angle0 || angle == M::Angle180) {
orientation = M::Landscape;
} else {
orientation = M::Portrait;
}
} else {
// native display orientation is portrait
if (angle == M::Angle0 || angle == M::Angle180) {
orientation = M::Portrait;
} else {
orientation = M::Landscape;
}
}
return orientation;
}
bool MDeviceProfile::orientationAngleIsSupported(M::OrientationAngle angle, bool isKeyboardOpen) const
{
Q_D(const MDeviceProfile);
if (isKeyboardOpen)
return d->supportedOrientationsForKeyboardOpen.contains(angle);
else
return d->supportedOrientationsForKeyboardClosed.contains(angle);
}
void MDeviceProfilePrivate::autodetection()
{
QRect screenRect = QApplication::desktop()->screenGeometry();
resolution = screenRect.size();
pixelsPerInch.setHeight(QApplication::desktop()->physicalDpiY());
pixelsPerInch.setWidth(QApplication::desktop()->physicalDpiX());
showStatusBar = hasStatusbarProvider();
supportedOrientationsForKeyboardClosed << M::Angle0 << M::Angle90 << M::Angle180 << M::Angle270;
supportedOrientationsForKeyboardOpen << M::Angle0 << M::Angle90 << M::Angle180 << M::Angle270;
}
bool MDeviceProfilePrivate::hasStatusbarProvider()
{
#ifdef HAVE_DBUS
if (QDBusConnection::sessionBus().interface()->isServiceRegistered(pixmapProviderDbusService))
return true;
#endif
return false;
}
int MDeviceProfile::mmToPixels(qreal mm)
{
Q_D(const MDeviceProfile);
return mm * d->pixelsPerMm;
}
qreal MDeviceProfile::mmToPixelsF(qreal mm)
{
Q_D(const MDeviceProfile);
return mm * d->pixelsPerMmF;
}
int MDeviceProfile::ptToPixels(qreal pt)
{
Q_D(const MDeviceProfile);
return qRound(pt * d->pixelsPerPtF);
}
qreal MDeviceProfile::ptToPixelsF(qreal pt)
{
Q_D(const MDeviceProfile);
return pt * d->pixelsPerPtF;
}
int MDeviceProfile::pixelsToPt(int pixels)
{
Q_D(const MDeviceProfile);
return qRound(pixels / d->pixelsPerPtF);
}
qreal MDeviceProfile::pixelsToPtF(qreal pixels)
{
Q_D(const MDeviceProfile);
return pixels / d->pixelsPerPtF;
}
<commit_msg>Changes: fixing conversion of mmToPixels for x86 in certain cases<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 <QString>
#include <QSize>
#include <QSettings>
#include <QFile>
#include <QDir>
#include <QDesktopWidget>
#ifdef HAVE_DBUS
#include <QDBusConnection>
#include <QDBusConnectionInterface>
#endif
#include "mdebug.h"
#include "mdeviceprofile.h"
#include "mdeviceprofile_p.h"
#include "mapplication.h"
#include "mcomponentdata.h"
#include "mcomponentdata_p.h"
#include "mgconfitem.h"
namespace{
#ifdef HAVE_DBUS
static const QString pixmapProviderDbusService = "com.meego.core.MStatusBar";
#endif
static const qreal mmPerInch = 25.4;
static const qreal pointsPerInch = 72.0;
static qreal dotsPerInch = 96.0;
}
MDeviceProfilePrivate::MDeviceProfilePrivate()
: q_ptr(0)
{
QString filename;
QString targetname = MApplication::deviceName();
#ifdef Q_WS_X11
dotsPerInch = QX11Info::appDpiX();
#endif
#ifdef Q_OS_WIN
QDir appDir(QCoreApplication::applicationDirPath());
appDir.cdUp();
appDir.cd("share");
appDir.cd("meegotouch");
appDir.cd("targets");
if(targetname.isEmpty())
filename = appDir.path().append(QDir::separator())
.append("Default.conf");
else
filename = appDir.path().append(QDir::separator())
.append(targetname).append(".conf");
#else //!Q_OS_WIN
if (targetname.isEmpty()) {
#ifdef HAVE_GCONF
MGConfItem targetNameItem("/meegotouch/target/name");
targetname = targetNameItem.value("Default").toString();
#else
targetname = "Default";
#endif //HAVE_GCONF
}
filename = M_TARGETS_CONF_DIR + QString("/") + targetname + ".conf";
#endif //Q_OS_WIN
if (!load(filename)) {
qCritical("Failed to load device profile '%s'", qPrintable(filename));
autodetection();
}
}
MDeviceProfilePrivate::~MDeviceProfilePrivate()
{
}
bool MDeviceProfilePrivate::load(const QString& filename)
{
if (!QFile::exists(filename))
return false;
QSettings settings(filename, QSettings::IniFormat);
if (settings.status() != QSettings::NoError)
return false;
if (settings.value("/resolution/X").toString() == "autodetect")
resolution.setWidth(QApplication::desktop()->screenGeometry().size().width());
else
resolution.setWidth(settings.value("/resolution/X", 0).toInt());
if (settings.value("/resolution/Y").toString() == "autodetect")
resolution.setHeight(QApplication::desktop()->screenGeometry().size().height());
else
resolution.setHeight(settings.value("/resolution/Y", 0).toInt());
if (settings.value("/ppi/X").toString() == "autodetect") {
int widthMM = QApplication::desktop()->widthMM();
if(widthMM){
int autodetectedPpiX = mmPerInch * QApplication::desktop()->screenGeometry().size().width() / widthMM;
pixelsPerInch.setWidth(autodetectedPpiX);
}
}
else
pixelsPerInch.setWidth(settings.value("/ppi/X", 0).toInt());
if (settings.value("/ppi/Y") == "autodetect") {
int heightMM = QApplication::desktop()->heightMM();
if(heightMM){
int autodetectedPpiY = mmPerInch * QApplication::desktop()->screenGeometry().size().height() / heightMM;
pixelsPerInch.setWidth(autodetectedPpiY);
}
}
else
pixelsPerInch.setHeight(settings.value("/ppi/Y", 0).toInt());
pixelsPerMm = pixelsPerInch.width() / mmPerInch;
pixelsPerMmF = pixelsPerInch.width() / mmPerInch;
pixelsPerPtF = dotsPerInch / pointsPerInch;
if (settings.value("/other/showStatusBar").toString() == "autodetect")
showStatusBar = hasStatusbarProvider();
else
showStatusBar=settings.value("/other/showStatusBar",false).toBool();
if (settings.value("/allowedOrientations/keyboardOpen").toString() == "autodetect"){
supportedOrientationsForKeyboardClosed << M::Angle0 << M::Angle90 << M::Angle180 << M::Angle270;
} else {
QStringList orientationsForDevOpen = settings.value("/allowedOrientations/keyboardOpen",
QStringList()).toStringList();
if (orientationsForDevOpen.contains("0"))
supportedOrientationsForKeyboardOpen << M::Angle0;
if (orientationsForDevOpen.contains("90"))
supportedOrientationsForKeyboardOpen << M::Angle90;
if (orientationsForDevOpen.contains("180"))
supportedOrientationsForKeyboardOpen << M::Angle180;
if (orientationsForDevOpen.contains("270"))
supportedOrientationsForKeyboardOpen << M::Angle270;
}
if (settings.value("/allowedOrientations/keyboardOpen", "").toString() == "autodetect"){
supportedOrientationsForKeyboardOpen << M::Angle0 << M::Angle90 << M::Angle180 << M::Angle270;
} else {
QStringList orientationsForDevClosed = settings.value("/allowedOrientations/keyboardClosed",
QStringList()).toStringList();
if (orientationsForDevClosed.contains("0"))
supportedOrientationsForKeyboardClosed << M::Angle0;
if (orientationsForDevClosed.contains("90"))
supportedOrientationsForKeyboardClosed << M::Angle90;
if (orientationsForDevClosed.contains("180"))
supportedOrientationsForKeyboardClosed << M::Angle180;
if (orientationsForDevClosed.contains("270"))
supportedOrientationsForKeyboardClosed << M::Angle270;
}
return true;
}
/*
* @return pointer to the singleton MDeviceProfile instance
*/
MDeviceProfile *MDeviceProfile::instance()
{
MComponentData *data = MComponentData::instance();
if (!data)
{
qFatal("There is no instance of MDeviceProfile. Please create MComponentData first.");
return 0;
}
else
{
return data->d_ptr->deviceProfile;
}
}
MDeviceProfile::MDeviceProfile(QObject *parent)
: QObject(parent),
d_ptr(new MDeviceProfilePrivate)
{
Q_D(MDeviceProfile);
d->q_ptr = this;
if (!MComponentData::instance())
qFatal("There is no instance of MComponentData. Please create MApplication first.");
if (MComponentData::instance()->d_ptr->deviceProfile)
qFatal("Device profile is already created. Please use MDeviceProfile::instance()");
}
MDeviceProfile::~MDeviceProfile()
{
delete d_ptr;
}
QSize MDeviceProfile::resolution() const
{
Q_D(const MDeviceProfile);
return d->resolution;
}
QSize MDeviceProfile::pixelsPerInch() const
{
Q_D(const MDeviceProfile);
return d->pixelsPerInch;
}
bool MDeviceProfile::showStatusbar() const
{
Q_D(const MDeviceProfile);
return d->showStatusBar;
}
M::Orientation MDeviceProfile::orientationFromAngle(M::OrientationAngle angle) const
{
Q_D(const MDeviceProfile);
M::Orientation orientation;
if (d->resolution.width() >= d->resolution.height()) {
// native display orientation is landscape
if (angle == M::Angle0 || angle == M::Angle180) {
orientation = M::Landscape;
} else {
orientation = M::Portrait;
}
} else {
// native display orientation is portrait
if (angle == M::Angle0 || angle == M::Angle180) {
orientation = M::Portrait;
} else {
orientation = M::Landscape;
}
}
return orientation;
}
bool MDeviceProfile::orientationAngleIsSupported(M::OrientationAngle angle, bool isKeyboardOpen) const
{
Q_D(const MDeviceProfile);
if (isKeyboardOpen)
return d->supportedOrientationsForKeyboardOpen.contains(angle);
else
return d->supportedOrientationsForKeyboardClosed.contains(angle);
}
void MDeviceProfilePrivate::autodetection()
{
QRect screenRect = QApplication::desktop()->screenGeometry();
resolution = screenRect.size();
pixelsPerInch.setHeight(QApplication::desktop()->physicalDpiY());
pixelsPerInch.setWidth(QApplication::desktop()->physicalDpiX());
showStatusBar = hasStatusbarProvider();
supportedOrientationsForKeyboardClosed << M::Angle0 << M::Angle90 << M::Angle180 << M::Angle270;
supportedOrientationsForKeyboardOpen << M::Angle0 << M::Angle90 << M::Angle180 << M::Angle270;
}
bool MDeviceProfilePrivate::hasStatusbarProvider()
{
#ifdef HAVE_DBUS
if (QDBusConnection::sessionBus().interface()->isServiceRegistered(pixmapProviderDbusService))
return true;
#endif
return false;
}
int MDeviceProfile::mmToPixels(qreal mm)
{
Q_D(const MDeviceProfile);
return qRound(mm * d->pixelsPerMm);
}
qreal MDeviceProfile::mmToPixelsF(qreal mm)
{
Q_D(const MDeviceProfile);
return mm * d->pixelsPerMmF;
}
int MDeviceProfile::ptToPixels(qreal pt)
{
Q_D(const MDeviceProfile);
return qRound(pt * d->pixelsPerPtF);
}
qreal MDeviceProfile::ptToPixelsF(qreal pt)
{
Q_D(const MDeviceProfile);
return pt * d->pixelsPerPtF;
}
int MDeviceProfile::pixelsToPt(int pixels)
{
Q_D(const MDeviceProfile);
return qRound(pixels / d->pixelsPerPtF);
}
qreal MDeviceProfile::pixelsToPtF(qreal pixels)
{
Q_D(const MDeviceProfile);
return pixels / d->pixelsPerPtF;
}
<|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 <queue>
#include "base/message_loop.h"
#include "base/synchronization/lock.h"
#include "base/task.h"
#include "content/browser/device_orientation/data_fetcher.h"
#include "content/browser/device_orientation/orientation.h"
#include "content/browser/device_orientation/provider.h"
#include "content/browser/device_orientation/provider_impl.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace device_orientation {
namespace {
// Class for checking expectations on orientation updates from the Provider.
class UpdateChecker : public Provider::Observer {
public:
explicit UpdateChecker(int* expectations_count_ptr)
: expectations_count_ptr_(expectations_count_ptr) {
}
virtual ~UpdateChecker() {}
// From Provider::Observer.
virtual void OnOrientationUpdate(const Orientation& orientation) {
ASSERT_FALSE(expectations_queue_.empty());
Orientation expected = expectations_queue_.front();
expectations_queue_.pop();
EXPECT_EQ(expected.can_provide_alpha_, orientation.can_provide_alpha_);
EXPECT_EQ(expected.can_provide_beta_, orientation.can_provide_beta_);
EXPECT_EQ(expected.can_provide_gamma_, orientation.can_provide_gamma_);
if (expected.can_provide_alpha_)
EXPECT_EQ(expected.alpha_, orientation.alpha_);
if (expected.can_provide_beta_)
EXPECT_EQ(expected.beta_, orientation.beta_);
if (expected.can_provide_gamma_)
EXPECT_EQ(expected.gamma_, orientation.gamma_);
--(*expectations_count_ptr_);
if (*expectations_count_ptr_ == 0) {
MessageLoop::current()->PostTask(FROM_HERE, MessageLoop::QuitClosure());
}
}
void AddExpectation(const Orientation& orientation) {
expectations_queue_.push(orientation);
++(*expectations_count_ptr_);
}
private:
// Set up by the test fixture, which then blocks while it is accessed
// from OnOrientationUpdate which is executed on the test fixture's
// message_loop_.
int* expectations_count_ptr_;
std::queue<Orientation> expectations_queue_;
};
// Class for injecting test orientation data into the Provider.
class MockOrientationFactory : public base::RefCounted<MockOrientationFactory> {
public:
MockOrientationFactory() {
EXPECT_FALSE(instance_);
instance_ = this;
}
~MockOrientationFactory() {
instance_ = NULL;
}
static DataFetcher* CreateDataFetcher() {
EXPECT_TRUE(instance_);
return new MockDataFetcher(instance_);
}
void SetOrientation(const Orientation& orientation) {
base::AutoLock auto_lock(lock_);
orientation_ = orientation;
}
private:
// Owned by ProviderImpl. Holds a reference back to MockOrientationFactory.
class MockDataFetcher : public DataFetcher {
public:
explicit MockDataFetcher(MockOrientationFactory* orientation_factory)
: orientation_factory_(orientation_factory) { }
// From DataFetcher. Called by the Provider.
virtual bool GetOrientation(Orientation* orientation) {
base::AutoLock auto_lock(orientation_factory_->lock_);
*orientation = orientation_factory_->orientation_;
return true;
}
private:
scoped_refptr<MockOrientationFactory> orientation_factory_;
};
static MockOrientationFactory* instance_;
Orientation orientation_;
base::Lock lock_;
};
MockOrientationFactory* MockOrientationFactory::instance_;
// Mock DataFetcher that always fails to provide any orientation data.
class FailingDataFetcher : public DataFetcher {
public:
// Factory method; passed to and called by the ProviderImpl.
static DataFetcher* Create() {
return new FailingDataFetcher();
}
// From DataFetcher.
virtual bool GetOrientation(Orientation* orientation) {
return false;
}
private:
FailingDataFetcher() {}
};
class DeviceOrientationProviderTest : public testing::Test {
public:
DeviceOrientationProviderTest()
: pending_expectations_(0) {
}
virtual void TearDown() {
provider_ = NULL;
// Make sure it is really gone.
EXPECT_FALSE(Provider::GetInstanceForTests());
// Clean up in any case, so as to not break subsequent test.
Provider::SetInstanceForTests(NULL);
}
// Initialize the test fixture with a ProviderImpl that uses the
// DataFetcherFactories in the null-terminated factories array.
void Init(ProviderImpl::DataFetcherFactory* factories) {
provider_ = new ProviderImpl(factories);
Provider::SetInstanceForTests(provider_);
}
// Initialize the test fixture with a ProviderImpl that uses the
// DataFetcherFactory factory.
void Init(ProviderImpl::DataFetcherFactory factory) {
ProviderImpl::DataFetcherFactory factories[] = { factory, NULL };
Init(factories);
}
protected:
// Number of pending expectations.
int pending_expectations_;
// Provider instance under test.
scoped_refptr<Provider> provider_;
// Message loop for the test thread.
MessageLoop message_loop_;
};
TEST_F(DeviceOrientationProviderTest, FailingTest) {
Init(FailingDataFetcher::Create);
scoped_ptr<UpdateChecker> checker_a(
new UpdateChecker(&pending_expectations_));
scoped_ptr<UpdateChecker> checker_b(
new UpdateChecker(&pending_expectations_));
checker_a->AddExpectation(Orientation::Empty());
provider_->AddObserver(checker_a.get());
MessageLoop::current()->Run();
checker_b->AddExpectation(Orientation::Empty());
provider_->AddObserver(checker_b.get());
MessageLoop::current()->Run();
}
TEST_F(DeviceOrientationProviderTest, ProviderIsSingleton) {
Init(FailingDataFetcher::Create);
scoped_refptr<Provider> provider_a(Provider::GetInstance());
scoped_refptr<Provider> provider_b(Provider::GetInstance());
EXPECT_EQ(provider_a.get(), provider_b.get());
}
TEST_F(DeviceOrientationProviderTest, BasicPushTest) {
scoped_refptr<MockOrientationFactory> orientation_factory(
new MockOrientationFactory());
Init(MockOrientationFactory::CreateDataFetcher);
const Orientation kTestOrientation(true, 1, true, 2, true, 3);
scoped_ptr<UpdateChecker> checker(new UpdateChecker(&pending_expectations_));
checker->AddExpectation(kTestOrientation);
orientation_factory->SetOrientation(kTestOrientation);
provider_->AddObserver(checker.get());
MessageLoop::current()->Run();
provider_->RemoveObserver(checker.get());
}
TEST_F(DeviceOrientationProviderTest, MultipleObserversPushTest) {
scoped_refptr<MockOrientationFactory> orientation_factory(
new MockOrientationFactory());
Init(MockOrientationFactory::CreateDataFetcher);
const Orientation kTestOrientations[] = {
Orientation(true, 1, true, 2, true, 3),
Orientation(true, 4, true, 5, true, 6),
Orientation(true, 7, true, 8, true, 9)};
scoped_ptr<UpdateChecker> checker_a(
new UpdateChecker(&pending_expectations_));
scoped_ptr<UpdateChecker> checker_b(
new UpdateChecker(&pending_expectations_));
scoped_ptr<UpdateChecker> checker_c(
new UpdateChecker(&pending_expectations_));
checker_a->AddExpectation(kTestOrientations[0]);
orientation_factory->SetOrientation(kTestOrientations[0]);
provider_->AddObserver(checker_a.get());
MessageLoop::current()->Run();
checker_a->AddExpectation(kTestOrientations[1]);
checker_b->AddExpectation(kTestOrientations[0]);
checker_b->AddExpectation(kTestOrientations[1]);
orientation_factory->SetOrientation(kTestOrientations[1]);
provider_->AddObserver(checker_b.get());
MessageLoop::current()->Run();
provider_->RemoveObserver(checker_a.get());
checker_b->AddExpectation(kTestOrientations[2]);
checker_c->AddExpectation(kTestOrientations[1]);
checker_c->AddExpectation(kTestOrientations[2]);
orientation_factory->SetOrientation(kTestOrientations[2]);
provider_->AddObserver(checker_c.get());
MessageLoop::current()->Run();
provider_->RemoveObserver(checker_b.get());
provider_->RemoveObserver(checker_c.get());
}
#if defined(OS_LINUX)
// Flakily DCHECKs on Linux. See crbug.com/104950.
#define MAYBE_ObserverNotRemoved DISABLED_ObserverNotRemoved
#else
#define MAYBE_ObserverNotRemoved ObserverNotRemoved
#endif
TEST_F(DeviceOrientationProviderTest, MAYBE_ObserverNotRemoved) {
scoped_refptr<MockOrientationFactory> orientation_factory(
new MockOrientationFactory());
Init(MockOrientationFactory::CreateDataFetcher);
const Orientation kTestOrientation(true, 1, true, 2, true, 3);
const Orientation kTestOrientation2(true, 4, true, 5, true, 6);
scoped_ptr<UpdateChecker> checker(new UpdateChecker(&pending_expectations_));
checker->AddExpectation(kTestOrientation);
orientation_factory->SetOrientation(kTestOrientation);
provider_->AddObserver(checker.get());
MessageLoop::current()->Run();
checker->AddExpectation(kTestOrientation2);
orientation_factory->SetOrientation(kTestOrientation2);
MessageLoop::current()->Run();
// Note that checker is not removed. This should not be a problem.
}
TEST_F(DeviceOrientationProviderTest, StartFailing) {
scoped_refptr<MockOrientationFactory> orientation_factory(
new MockOrientationFactory());
Init(MockOrientationFactory::CreateDataFetcher);
const Orientation kTestOrientation(true, 1, true, 2, true, 3);
scoped_ptr<UpdateChecker> checker_a(new UpdateChecker(
&pending_expectations_));
scoped_ptr<UpdateChecker> checker_b(new UpdateChecker(
&pending_expectations_));
orientation_factory->SetOrientation(kTestOrientation);
checker_a->AddExpectation(kTestOrientation);
provider_->AddObserver(checker_a.get());
MessageLoop::current()->Run();
checker_a->AddExpectation(Orientation::Empty());
orientation_factory->SetOrientation(Orientation::Empty());
MessageLoop::current()->Run();
checker_b->AddExpectation(Orientation::Empty());
provider_->AddObserver(checker_b.get());
MessageLoop::current()->Run();
provider_->RemoveObserver(checker_a.get());
provider_->RemoveObserver(checker_b.get());
}
TEST_F(DeviceOrientationProviderTest, StartStopStart) {
scoped_refptr<MockOrientationFactory> orientation_factory(
new MockOrientationFactory());
Init(MockOrientationFactory::CreateDataFetcher);
const Orientation kTestOrientation(true, 1, true, 2, true, 3);
const Orientation kTestOrientation2(true, 4, true, 5, true, 6);
scoped_ptr<UpdateChecker> checker_a(new UpdateChecker(
&pending_expectations_));
scoped_ptr<UpdateChecker> checker_b(new UpdateChecker(
&pending_expectations_));
checker_a->AddExpectation(kTestOrientation);
orientation_factory->SetOrientation(kTestOrientation);
provider_->AddObserver(checker_a.get());
MessageLoop::current()->Run();
provider_->RemoveObserver(checker_a.get()); // This stops the Provider.
checker_b->AddExpectation(kTestOrientation2);
orientation_factory->SetOrientation(kTestOrientation2);
provider_->AddObserver(checker_b.get());
MessageLoop::current()->Run();
provider_->RemoveObserver(checker_b.get());
}
TEST_F(DeviceOrientationProviderTest, SignificantlyDifferent) {
scoped_refptr<MockOrientationFactory> orientation_factory(
new MockOrientationFactory());
Init(MockOrientationFactory::CreateDataFetcher);
// Values that should be well below or above the implementation's
// significane threshold.
const double kInsignificantDifference = 1e-6;
const double kSignificantDifference = 30;
const double kAlpha = 4, kBeta = 5, kGamma = 6;
const Orientation first_orientation(true, kAlpha, true, kBeta, true, kGamma);
const Orientation second_orientation(true, kAlpha + kInsignificantDifference,
true, kBeta + kInsignificantDifference,
true, kGamma + kInsignificantDifference);
const Orientation third_orientation(true, kAlpha + kSignificantDifference,
true, kBeta + kSignificantDifference,
true, kGamma + kSignificantDifference);
scoped_ptr<UpdateChecker> checker_a(new UpdateChecker(
&pending_expectations_));
scoped_ptr<UpdateChecker> checker_b(new UpdateChecker(
&pending_expectations_));
orientation_factory->SetOrientation(first_orientation);
checker_a->AddExpectation(first_orientation);
provider_->AddObserver(checker_a.get());
MessageLoop::current()->Run();
// The observers should not see this insignificantly different orientation.
orientation_factory->SetOrientation(second_orientation);
checker_b->AddExpectation(first_orientation);
provider_->AddObserver(checker_b.get());
MessageLoop::current()->Run();
orientation_factory->SetOrientation(third_orientation);
checker_a->AddExpectation(third_orientation);
checker_b->AddExpectation(third_orientation);
MessageLoop::current()->Run();
provider_->RemoveObserver(checker_a.get());
provider_->RemoveObserver(checker_b.get());
}
} // namespace
} // namespace device_orientation
<commit_msg>Mark DeviceOrientationProviderTest.ObserverNotRemoved|StartFailing FLAKY on OS_WIN.<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 <queue>
#include "base/message_loop.h"
#include "base/synchronization/lock.h"
#include "base/task.h"
#include "content/browser/device_orientation/data_fetcher.h"
#include "content/browser/device_orientation/orientation.h"
#include "content/browser/device_orientation/provider.h"
#include "content/browser/device_orientation/provider_impl.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace device_orientation {
namespace {
// Class for checking expectations on orientation updates from the Provider.
class UpdateChecker : public Provider::Observer {
public:
explicit UpdateChecker(int* expectations_count_ptr)
: expectations_count_ptr_(expectations_count_ptr) {
}
virtual ~UpdateChecker() {}
// From Provider::Observer.
virtual void OnOrientationUpdate(const Orientation& orientation) {
ASSERT_FALSE(expectations_queue_.empty());
Orientation expected = expectations_queue_.front();
expectations_queue_.pop();
EXPECT_EQ(expected.can_provide_alpha_, orientation.can_provide_alpha_);
EXPECT_EQ(expected.can_provide_beta_, orientation.can_provide_beta_);
EXPECT_EQ(expected.can_provide_gamma_, orientation.can_provide_gamma_);
if (expected.can_provide_alpha_)
EXPECT_EQ(expected.alpha_, orientation.alpha_);
if (expected.can_provide_beta_)
EXPECT_EQ(expected.beta_, orientation.beta_);
if (expected.can_provide_gamma_)
EXPECT_EQ(expected.gamma_, orientation.gamma_);
--(*expectations_count_ptr_);
if (*expectations_count_ptr_ == 0) {
MessageLoop::current()->PostTask(FROM_HERE, MessageLoop::QuitClosure());
}
}
void AddExpectation(const Orientation& orientation) {
expectations_queue_.push(orientation);
++(*expectations_count_ptr_);
}
private:
// Set up by the test fixture, which then blocks while it is accessed
// from OnOrientationUpdate which is executed on the test fixture's
// message_loop_.
int* expectations_count_ptr_;
std::queue<Orientation> expectations_queue_;
};
// Class for injecting test orientation data into the Provider.
class MockOrientationFactory : public base::RefCounted<MockOrientationFactory> {
public:
MockOrientationFactory() {
EXPECT_FALSE(instance_);
instance_ = this;
}
~MockOrientationFactory() {
instance_ = NULL;
}
static DataFetcher* CreateDataFetcher() {
EXPECT_TRUE(instance_);
return new MockDataFetcher(instance_);
}
void SetOrientation(const Orientation& orientation) {
base::AutoLock auto_lock(lock_);
orientation_ = orientation;
}
private:
// Owned by ProviderImpl. Holds a reference back to MockOrientationFactory.
class MockDataFetcher : public DataFetcher {
public:
explicit MockDataFetcher(MockOrientationFactory* orientation_factory)
: orientation_factory_(orientation_factory) { }
// From DataFetcher. Called by the Provider.
virtual bool GetOrientation(Orientation* orientation) {
base::AutoLock auto_lock(orientation_factory_->lock_);
*orientation = orientation_factory_->orientation_;
return true;
}
private:
scoped_refptr<MockOrientationFactory> orientation_factory_;
};
static MockOrientationFactory* instance_;
Orientation orientation_;
base::Lock lock_;
};
MockOrientationFactory* MockOrientationFactory::instance_;
// Mock DataFetcher that always fails to provide any orientation data.
class FailingDataFetcher : public DataFetcher {
public:
// Factory method; passed to and called by the ProviderImpl.
static DataFetcher* Create() {
return new FailingDataFetcher();
}
// From DataFetcher.
virtual bool GetOrientation(Orientation* orientation) {
return false;
}
private:
FailingDataFetcher() {}
};
class DeviceOrientationProviderTest : public testing::Test {
public:
DeviceOrientationProviderTest()
: pending_expectations_(0) {
}
virtual void TearDown() {
provider_ = NULL;
// Make sure it is really gone.
EXPECT_FALSE(Provider::GetInstanceForTests());
// Clean up in any case, so as to not break subsequent test.
Provider::SetInstanceForTests(NULL);
}
// Initialize the test fixture with a ProviderImpl that uses the
// DataFetcherFactories in the null-terminated factories array.
void Init(ProviderImpl::DataFetcherFactory* factories) {
provider_ = new ProviderImpl(factories);
Provider::SetInstanceForTests(provider_);
}
// Initialize the test fixture with a ProviderImpl that uses the
// DataFetcherFactory factory.
void Init(ProviderImpl::DataFetcherFactory factory) {
ProviderImpl::DataFetcherFactory factories[] = { factory, NULL };
Init(factories);
}
protected:
// Number of pending expectations.
int pending_expectations_;
// Provider instance under test.
scoped_refptr<Provider> provider_;
// Message loop for the test thread.
MessageLoop message_loop_;
};
TEST_F(DeviceOrientationProviderTest, FailingTest) {
Init(FailingDataFetcher::Create);
scoped_ptr<UpdateChecker> checker_a(
new UpdateChecker(&pending_expectations_));
scoped_ptr<UpdateChecker> checker_b(
new UpdateChecker(&pending_expectations_));
checker_a->AddExpectation(Orientation::Empty());
provider_->AddObserver(checker_a.get());
MessageLoop::current()->Run();
checker_b->AddExpectation(Orientation::Empty());
provider_->AddObserver(checker_b.get());
MessageLoop::current()->Run();
}
TEST_F(DeviceOrientationProviderTest, ProviderIsSingleton) {
Init(FailingDataFetcher::Create);
scoped_refptr<Provider> provider_a(Provider::GetInstance());
scoped_refptr<Provider> provider_b(Provider::GetInstance());
EXPECT_EQ(provider_a.get(), provider_b.get());
}
TEST_F(DeviceOrientationProviderTest, BasicPushTest) {
scoped_refptr<MockOrientationFactory> orientation_factory(
new MockOrientationFactory());
Init(MockOrientationFactory::CreateDataFetcher);
const Orientation kTestOrientation(true, 1, true, 2, true, 3);
scoped_ptr<UpdateChecker> checker(new UpdateChecker(&pending_expectations_));
checker->AddExpectation(kTestOrientation);
orientation_factory->SetOrientation(kTestOrientation);
provider_->AddObserver(checker.get());
MessageLoop::current()->Run();
provider_->RemoveObserver(checker.get());
}
TEST_F(DeviceOrientationProviderTest, MultipleObserversPushTest) {
scoped_refptr<MockOrientationFactory> orientation_factory(
new MockOrientationFactory());
Init(MockOrientationFactory::CreateDataFetcher);
const Orientation kTestOrientations[] = {
Orientation(true, 1, true, 2, true, 3),
Orientation(true, 4, true, 5, true, 6),
Orientation(true, 7, true, 8, true, 9)};
scoped_ptr<UpdateChecker> checker_a(
new UpdateChecker(&pending_expectations_));
scoped_ptr<UpdateChecker> checker_b(
new UpdateChecker(&pending_expectations_));
scoped_ptr<UpdateChecker> checker_c(
new UpdateChecker(&pending_expectations_));
checker_a->AddExpectation(kTestOrientations[0]);
orientation_factory->SetOrientation(kTestOrientations[0]);
provider_->AddObserver(checker_a.get());
MessageLoop::current()->Run();
checker_a->AddExpectation(kTestOrientations[1]);
checker_b->AddExpectation(kTestOrientations[0]);
checker_b->AddExpectation(kTestOrientations[1]);
orientation_factory->SetOrientation(kTestOrientations[1]);
provider_->AddObserver(checker_b.get());
MessageLoop::current()->Run();
provider_->RemoveObserver(checker_a.get());
checker_b->AddExpectation(kTestOrientations[2]);
checker_c->AddExpectation(kTestOrientations[1]);
checker_c->AddExpectation(kTestOrientations[2]);
orientation_factory->SetOrientation(kTestOrientations[2]);
provider_->AddObserver(checker_c.get());
MessageLoop::current()->Run();
provider_->RemoveObserver(checker_b.get());
provider_->RemoveObserver(checker_c.get());
}
#if defined(OS_LINUX)
// Flakily DCHECKs on Linux. See crbug.com/104950.
#define MAYBE_ObserverNotRemoved DISABLED_ObserverNotRemoved
#elif defined(OS_WIN)
// FLAKY on Win. See crbug.com/104950.
#define MAYBE_ObserverNotRemoved FLAKY_ObserverNotRemoved
#else
#define MAYBE_ObserverNotRemoved ObserverNotRemoved
#endif
TEST_F(DeviceOrientationProviderTest, MAYBE_ObserverNotRemoved) {
scoped_refptr<MockOrientationFactory> orientation_factory(
new MockOrientationFactory());
Init(MockOrientationFactory::CreateDataFetcher);
const Orientation kTestOrientation(true, 1, true, 2, true, 3);
const Orientation kTestOrientation2(true, 4, true, 5, true, 6);
scoped_ptr<UpdateChecker> checker(new UpdateChecker(&pending_expectations_));
checker->AddExpectation(kTestOrientation);
orientation_factory->SetOrientation(kTestOrientation);
provider_->AddObserver(checker.get());
MessageLoop::current()->Run();
checker->AddExpectation(kTestOrientation2);
orientation_factory->SetOrientation(kTestOrientation2);
MessageLoop::current()->Run();
// Note that checker is not removed. This should not be a problem.
}
#if defined(OS_WIN)
// FLAKY on Win. See crbug.com/104950.
#define MAYBE_StartFailing FLAKY_StartFailing
#else
#define MAYBE_StartFailing StartFailing
#endif
TEST_F(DeviceOrientationProviderTest, MAYBE_StartFailing) {
scoped_refptr<MockOrientationFactory> orientation_factory(
new MockOrientationFactory());
Init(MockOrientationFactory::CreateDataFetcher);
const Orientation kTestOrientation(true, 1, true, 2, true, 3);
scoped_ptr<UpdateChecker> checker_a(new UpdateChecker(
&pending_expectations_));
scoped_ptr<UpdateChecker> checker_b(new UpdateChecker(
&pending_expectations_));
orientation_factory->SetOrientation(kTestOrientation);
checker_a->AddExpectation(kTestOrientation);
provider_->AddObserver(checker_a.get());
MessageLoop::current()->Run();
checker_a->AddExpectation(Orientation::Empty());
orientation_factory->SetOrientation(Orientation::Empty());
MessageLoop::current()->Run();
checker_b->AddExpectation(Orientation::Empty());
provider_->AddObserver(checker_b.get());
MessageLoop::current()->Run();
provider_->RemoveObserver(checker_a.get());
provider_->RemoveObserver(checker_b.get());
}
TEST_F(DeviceOrientationProviderTest, StartStopStart) {
scoped_refptr<MockOrientationFactory> orientation_factory(
new MockOrientationFactory());
Init(MockOrientationFactory::CreateDataFetcher);
const Orientation kTestOrientation(true, 1, true, 2, true, 3);
const Orientation kTestOrientation2(true, 4, true, 5, true, 6);
scoped_ptr<UpdateChecker> checker_a(new UpdateChecker(
&pending_expectations_));
scoped_ptr<UpdateChecker> checker_b(new UpdateChecker(
&pending_expectations_));
checker_a->AddExpectation(kTestOrientation);
orientation_factory->SetOrientation(kTestOrientation);
provider_->AddObserver(checker_a.get());
MessageLoop::current()->Run();
provider_->RemoveObserver(checker_a.get()); // This stops the Provider.
checker_b->AddExpectation(kTestOrientation2);
orientation_factory->SetOrientation(kTestOrientation2);
provider_->AddObserver(checker_b.get());
MessageLoop::current()->Run();
provider_->RemoveObserver(checker_b.get());
}
TEST_F(DeviceOrientationProviderTest, SignificantlyDifferent) {
scoped_refptr<MockOrientationFactory> orientation_factory(
new MockOrientationFactory());
Init(MockOrientationFactory::CreateDataFetcher);
// Values that should be well below or above the implementation's
// significane threshold.
const double kInsignificantDifference = 1e-6;
const double kSignificantDifference = 30;
const double kAlpha = 4, kBeta = 5, kGamma = 6;
const Orientation first_orientation(true, kAlpha, true, kBeta, true, kGamma);
const Orientation second_orientation(true, kAlpha + kInsignificantDifference,
true, kBeta + kInsignificantDifference,
true, kGamma + kInsignificantDifference);
const Orientation third_orientation(true, kAlpha + kSignificantDifference,
true, kBeta + kSignificantDifference,
true, kGamma + kSignificantDifference);
scoped_ptr<UpdateChecker> checker_a(new UpdateChecker(
&pending_expectations_));
scoped_ptr<UpdateChecker> checker_b(new UpdateChecker(
&pending_expectations_));
orientation_factory->SetOrientation(first_orientation);
checker_a->AddExpectation(first_orientation);
provider_->AddObserver(checker_a.get());
MessageLoop::current()->Run();
// The observers should not see this insignificantly different orientation.
orientation_factory->SetOrientation(second_orientation);
checker_b->AddExpectation(first_orientation);
provider_->AddObserver(checker_b.get());
MessageLoop::current()->Run();
orientation_factory->SetOrientation(third_orientation);
checker_a->AddExpectation(third_orientation);
checker_b->AddExpectation(third_orientation);
MessageLoop::current()->Run();
provider_->RemoveObserver(checker_a.get());
provider_->RemoveObserver(checker_b.get());
}
} // namespace
} // namespace device_orientation
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "MainThread.h"
#include <process.h>
namespace GameServer
{
namespace Fixes
{
void CMainThread::load()
{
enable_hook(&ATF::CMainThread::CheckForceClose, &CMainThread::CheckForceClose);
enable_hook(&ATF::CMainThread::OnRun, &CMainThread::OnRun);
}
void CMainThread::unload()
{
if (m_thRuleThread.joinable())
m_thRuleThread.join();
cleanup_all_hook();
}
Yorozuya::Module::ModuleName_t CMainThread::get_name()
{
static const Yorozuya::Module::ModuleName_t name = "fix.main_thread";
return name;
}
void CMainThread::zone_start()
{
m_thRuleThread = std::move(std::thread([&]() {
CMainThread::MyRuleThread();
}));
}
void WINAPIV CMainThread::CheckForceClose(
ATF::CMainThread * pObj,
ATF::Info::CMainThreadCheckForceClose24_ptr next)
{
UNREFERENCED_PARAMETER(pObj);
UNREFERENCED_PARAMETER(next);
}
void WINAPIV CMainThread::OnRun(
ATF::CMainThread* pObj,
ATF::Info::CMainThreadOnRun130_ptr next)
{
ATF::Global::g_Network->OnLoop();
pObj->DQSCompleteProcess();
ATF::CCashDBWorkManager::Instance()->CompleteWork();
}
void WINAPIV CMainThread::MyRuleThread()
{
::srand(::time(nullptr));
int nTickCount = 0;
while (ATF::Global::g_MainThread->m_bRuleThread)
{
*ATF::Global::g_dwCurTime = timeGetTime();
ATF::Global::g_MainThread->m_MainFrameRate.CalcSpeedPerFrame();
CMainThread::MyOnRun();
if (!ATF::Global::g_MainThread->m_nSleepIgnore && ++nTickCount > ATF::Global::g_MainThread->m_nSleepTerm)
{
Sleep(ATF::Global::g_MainThread->m_nSleepValue);
nTickCount = 0;
}
}
}
void WINAPIV CMainThread::MyOnRun()
{
//ATF::CMapDisplay::DrawDisplay(&ATF::Global::g_MapDisplay);
ATF::Global::g_MapOper->OnLoop();
ATF::Global::g_HolySys->OnLoop();
/*
//CNetWorking::OnLoop(&g_Network.vfptr);
//CMainThread::DQSCompleteProcess(this);
//v4 = CTSingleton<CCashDBWorkManager>::Instance();
//CCashDBWorkManager::CompleteWork(v4);
*/
ATF::Global::g_MainThread->CheckAvatorState();
ATF::Global::g_MainThread->CheckAccountLineState();
ATF::Global::g_MainThread->ForceCloseUserInTiming();
bool pbChangeDay = 0;
ATF::Global::eUpdateEconomySystem(&pbChangeDay);
if ( pbChangeDay )
ATF::Global::g_GameStatistics->ConvertDay(
ATF::Global::g_MainThread->m_szWorldName);
ATF::CMoneySupplyMgr::Instance()->LoopMoneySupply();
ATF::Global::g_MainThread->CheckConnNumLog();
ATF::Global::g_MainThread->m_GameMsg.PumpMsgList();
ATF::CPvpUserAndGuildRankingSystem::Instance()->Loop();
ATF::Global::g_MainThread->ContUserSaveJobCheck();
ATF::Global::OnLoop_VoteSystem();
ATF::Global::OnLoop_GuildSystem(pbChangeDay);
ATF::Global::g_DarkHoleQuest->CheckQuestOnLoop();
ATF::CRaceBossMsgController::Instance()->OnLoop();
ATF::CReturnGateController::Instance()->OnLoop();
ATF::CRecallEffectController::Instance()->OnLoop();
ATF::Global::g_WorldSch->Loop();
for (int j = 0; j < 3; ++j)
ATF::Global::g_TransportShip[j].Loop();
ATF::CGuildBattleController::Instance()->Loop();
ATF::CTotalGuildRankManager::Instance()->Loop();
ATF::CWeeklyGuildRankManager::Instance()->Loop();
ATF::AutoMineMachineMng::Instance()->Loop();
if (*ATF::Global::g_dwCurTime - *ATF::Global::dwTime_AliveMonNum > 60000 )
{
*ATF::Global::dwTime_AliveMonNum = *ATF::Global::g_dwCurTime;
int nDiedMonster = 0;
for (int k = 0; k < 30000; ++k )
{
if ( !ATF::Global::g_Monster[k].m_bLive )
++nDiedMonster;
}
if (*ATF::Global::dwMaxMonNum < nDiedMonster)
{
*ATF::Global::dwMaxMonNum = nDiedMonster;
}
}
ATF::CUnmannedTraderController::Instance()->Loop();
ATF::CLogTypeDBTaskManager::Instance()->Loop();
ATF::Global::g_MainThread->CheckDayChangedPvpPointClear();
ATF::CGuildRoomSystem::GetInstance()->RentRoomTimer();
ATF::Global::g_MainThread->CheckRadarItemDelay();
ATF::CPostSystemManager::Instace()->Loop();
ATF::CItemStoreManager::Instance()->Loop();
ATF::PatriarchElectProcessor::Instance()->Loop();
ATF::CMoveMapLimitManager::Instance()->Loop();
ATF::CRaceBuffManager::Instance()->Loop();
ATF::CAsyncLogger::Instance()->Loop();
ATF::CNuclearBombMgr::Instance()->vfptr->Loop(ATF::CNuclearBombMgr::Instance());
ATF::CHonorGuild::Instance()->Loop();
ATF::COreAmountMgr::Instance()->Loop();
ATF::CExchangeEvent::Instance()->vfptr->Loop(ATF::CExchangeEvent::Instance());
ATF::Global::g_MainThread->m_GuildCreateEventInfo.Loop();
ATF::Global::g_MainThread->m_pRFEvent_ClassRefine->vfptr->Loop(
ATF::Global::g_MainThread->m_pRFEvent_ClassRefine);
ATF::CNationSettingManager::Instance()->Loop();
ATF::CLuaScriptMgr::Instance()->Loop();
ATF::Global::g_MainThread->CheckServerRateINIFile();
ATF::CashItemRemoteStore::Instance()->Loop_TatalCashEvent();
ATF::TimeLimitMgr::Instance()->Chack_Time();
ATF::CActionPointSystemMgr::Instance()->Check_Loop();
ATF::CGoldenBoxItemMgr::Instance()->Loop_Event();
}
}
}<commit_msg>Main thread optimization complete<commit_after>#include "stdafx.h"
#include "MainThread.h"
#include <process.h>
namespace GameServer
{
namespace Fixes
{
void CMainThread::load()
{
enable_hook(&ATF::CMainThread::CheckForceClose, &CMainThread::CheckForceClose);
enable_hook(&ATF::CMainThread::OnRun, &CMainThread::OnRun);
}
void CMainThread::unload()
{
if (m_thRuleThread.joinable())
m_thRuleThread.join();
cleanup_all_hook();
}
Yorozuya::Module::ModuleName_t CMainThread::get_name()
{
static const Yorozuya::Module::ModuleName_t name = "fix.main_thread";
return name;
}
void CMainThread::zone_start()
{
m_thRuleThread = std::move(std::thread([&]() {
CMainThread::MyRuleThread();
}));
}
void WINAPIV CMainThread::CheckForceClose(
ATF::CMainThread * pObj,
ATF::Info::CMainThreadCheckForceClose24_ptr next)
{
UNREFERENCED_PARAMETER(pObj);
UNREFERENCED_PARAMETER(next);
}
void WINAPIV CMainThread::OnRun(
ATF::CMainThread* pObj,
ATF::Info::CMainThreadOnRun130_ptr next)
{
ATF::Global::g_Network->OnLoop();
ATF::Global::g_MainThread->DQSCompleteProcess();
ATF::CCashDBWorkManager::Instance()->CompleteWork();
ATF::Global::g_MainThread->CheckAccountLineState();
}
void WINAPIV CMainThread::MyRuleThread()
{
::srand(::time(nullptr));
int nTickCount = 0;
while (ATF::Global::g_MainThread->m_bRuleThread)
{
*ATF::Global::g_dwCurTime = timeGetTime();
ATF::Global::g_MainThread->m_MainFrameRate.CalcSpeedPerFrame();
CMainThread::MyOnRun();
if (!ATF::Global::g_MainThread->m_nSleepIgnore &&
++nTickCount > ATF::Global::g_MainThread->m_nSleepTerm)
{
Sleep(ATF::Global::g_MainThread->m_nSleepValue);
nTickCount = 0;
}
}
}
void WINAPIV CMainThread::MyOnRun()
{
//ATF::CMapDisplay::DrawDisplay(&ATF::Global::g_MapDisplay);
ATF::Global::g_MapOper->OnLoop();
ATF::Global::g_HolySys->OnLoop();
ATF::Global::g_MainThread->CheckAvatorState();
ATF::Global::g_MainThread->ForceCloseUserInTiming();
bool pbChangeDay = false;
ATF::Global::eUpdateEconomySystem(&pbChangeDay);
if ( pbChangeDay )
ATF::Global::g_GameStatistics->ConvertDay(ATF::Global::g_MainThread->m_szWorldName);
ATF::CMoneySupplyMgr::Instance()->LoopMoneySupply();
ATF::Global::g_MainThread->CheckConnNumLog();
ATF::Global::g_MainThread->m_GameMsg.PumpMsgList();
ATF::CPvpUserAndGuildRankingSystem::Instance()->Loop();
ATF::Global::g_MainThread->ContUserSaveJobCheck();
ATF::Global::OnLoop_VoteSystem();
ATF::Global::OnLoop_GuildSystem(pbChangeDay);
ATF::Global::g_DarkHoleQuest->CheckQuestOnLoop();
ATF::CRaceBossMsgController::Instance()->OnLoop();
ATF::CReturnGateController::Instance()->OnLoop();
ATF::CRecallEffectController::Instance()->OnLoop();
ATF::Global::g_WorldSch->Loop();
for (int j = 0; j < 3; ++j)
ATF::Global::g_TransportShip[j].Loop();
ATF::CGuildBattleController::Instance()->Loop();
ATF::CTotalGuildRankManager::Instance()->Loop();
ATF::CWeeklyGuildRankManager::Instance()->Loop();
ATF::AutoMineMachineMng::Instance()->Loop();
if (ATF::Global::GetLoopTime() - *ATF::Global::dwTime_AliveMonNum > 60000 )
{
*ATF::Global::dwTime_AliveMonNum = ATF::Global::GetLoopTime();
int nDiedMonster = 0;
for (int k = 0; k < 30000; ++k )
{
if ( !ATF::Global::g_Monster[k].m_bLive )
++nDiedMonster;
}
if (*ATF::Global::dwMaxMonNum < nDiedMonster)
{
*ATF::Global::dwMaxMonNum = nDiedMonster;
}
}
ATF::CUnmannedTraderController::Instance()->Loop();
ATF::CLogTypeDBTaskManager::Instance()->Loop();
ATF::Global::g_MainThread->CheckDayChangedPvpPointClear();
ATF::CGuildRoomSystem::GetInstance()->RentRoomTimer();
ATF::Global::g_MainThread->CheckRadarItemDelay();
ATF::CPostSystemManager::Instace()->Loop();
ATF::CItemStoreManager::Instance()->Loop();
ATF::PatriarchElectProcessor::Instance()->Loop();
ATF::CMoveMapLimitManager::Instance()->Loop();
ATF::CRaceBuffManager::Instance()->Loop();
ATF::CAsyncLogger::Instance()->Loop();
ATF::CNuclearBombMgr::Instance()->vfptr->Loop(ATF::CNuclearBombMgr::Instance());
ATF::CHonorGuild::Instance()->Loop();
ATF::COreAmountMgr::Instance()->Loop();
ATF::CExchangeEvent::Instance()->vfptr->Loop(ATF::CExchangeEvent::Instance());
ATF::Global::g_MainThread->m_GuildCreateEventInfo.Loop();
ATF::Global::g_MainThread->m_pRFEvent_ClassRefine->vfptr->Loop(
ATF::Global::g_MainThread->m_pRFEvent_ClassRefine);
ATF::CNationSettingManager::Instance()->Loop();
ATF::CLuaScriptMgr::Instance()->Loop();
ATF::Global::g_MainThread->CheckServerRateINIFile();
ATF::CashItemRemoteStore::Instance()->Loop_TatalCashEvent();
ATF::TimeLimitMgr::Instance()->Chack_Time();
ATF::CActionPointSystemMgr::Instance()->Check_Loop();
ATF::CGoldenBoxItemMgr::Instance()->Loop_Event();
}
}
}<|endoftext|> |
<commit_before>/******************************************************************************
* Copyright 2017 The Apollo 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 <cmath>
#include <fstream>
#include <numeric>
#include "modules/prediction/evaluator/vehicle/mlp_evaluator.h"
#include "modules/prediction/common/prediction_gflags.h"
#include "modules/common/math/math_utils.h"
#include "modules/prediction/common/prediction_util.h"
#include "modules/map/proto/map_lane.pb.h"
namespace apollo {
namespace prediction {
using HDMapLane = apollo::hdmap::Lane;
MLPEvaluator::MLPEvaluator() {
LoadModel(FLAGS_vehicle_model_file);
}
void MLPEvaluator::Clear() {
obstacle_feature_values_map_.clear();
}
void MLPEvaluator::Evaluate(Obstacle* obstacle_ptr) {
AINFO << "Start mlp evaluate";
Clear();
if (obstacle_ptr == nullptr) {
AERROR << "Invalid obstacle.";
return;
}
int id = obstacle_ptr->id();
Feature latest_feature = obstacle_ptr->latest_feature();
if (!latest_feature.IsInitialized()) {
ADEBUG << "Obstacle [" << id << "] has no latest feature.";
return;
}
Lane* lane_ptr = latest_feature.mutable_lane();
if (!latest_feature.has_lane() || lane_ptr == nullptr) {
ADEBUG << "Obstacle [" << id << "] has no lane feature.";
return;
}
LaneGraph* lane_graph_ptr = lane_ptr->mutable_lane_graph();
if (!latest_feature.lane().has_lane_graph() || lane_graph_ptr == nullptr) {
ADEBUG << "Obstacle [" << id << "] has no lane graph.";
return;
}
if (latest_feature.lane().lane_graph().lane_sequence_size() == 0) {
ADEBUG << "Obstacle [" << id << "] has no lane sequences.";
return;
}
AINFO << "Start for-loop on lane sequences";
for (int i = 0;
i < latest_feature.lane().lane_graph().lane_sequence_size(); ++i) {
LaneSequence* lane_sequence_ptr = lane_graph_ptr->mutable_lane_sequence(i);
CHECK(lane_sequence_ptr != nullptr);
AINFO << "Start to extract feature values";
ExtractFeatureValues(obstacle_ptr, lane_sequence_ptr);
AINFO << "Start to compute probability";
double probability = ComputeProbability();
AINFO << "probability = " << probability;
lane_sequence_ptr->set_probability(probability);
AINFO << "probability set done";
}
}
void MLPEvaluator::ExtractFeatureValues(Obstacle* obstacle_ptr,
LaneSequence* lane_sequence_ptr) {
feature_values_.clear();
int id = obstacle_ptr->id();
std::vector<double> obstacle_feature_values;
if (obstacle_feature_values_map_.find(id) ==
obstacle_feature_values_map_.end()) {
SetObstacleFeatureValues(obstacle_ptr, &obstacle_feature_values);
} else {
obstacle_feature_values = obstacle_feature_values_map_[id];
}
if (obstacle_feature_values.size() != OBSTACLE_FEATURE_SIZE) {
ADEBUG << "Obstacle [" << id << "] has fewer than "
<< "expected obstacle feature_values "
<< obstacle_feature_values.size() << ".";
return;
}
std::vector<double> lane_feature_values;
SetLaneFeatureValues(obstacle_ptr, lane_sequence_ptr, &lane_feature_values);
if (lane_feature_values.size() != LANE_FEATURE_SIZE) {
ADEBUG << "Obstacle [" << id << "] has fewer than "
<< "expected lane feature_values"
<< lane_feature_values.size() << ".";
return;
}
feature_values_.insert(feature_values_.end(),
lane_feature_values.begin(), lane_feature_values.end());
feature_values_.insert(feature_values_.end(),
lane_feature_values.begin(), lane_feature_values.end());
}
void MLPEvaluator::SetObstacleFeatureValues(
Obstacle* obstacle_ptr, std::vector<double>* feature_values) {
feature_values->clear();
feature_values->reserve(OBSTACLE_FEATURE_SIZE);
std::vector<double> thetas;
std::vector<double> lane_ls;
std::vector<double> dist_lbs;
std::vector<double> dist_rbs;
std::vector<int> lane_types;
std::vector<double> speeds;
std::vector<double> timestamps;
double duration = obstacle_ptr->timestamp() - FLAGS_prediction_duration;
int count = 0;
for (std::size_t i = 0; i < obstacle_ptr->history_size(); ++i) {
const Feature& feature = obstacle_ptr->feature(i);
if (!feature.IsInitialized()) {
continue;
}
if (apollo::common::math::DoubleCompare(
feature.timestamp(), duration) < 0) {
break;
}
if (feature.has_lane() && feature.lane().has_lane_feature()) {
thetas.push_back(feature.lane().lane_feature().angle_diff());
lane_ls.push_back(feature.lane().lane_feature().lane_l());
dist_lbs.push_back(feature.lane().lane_feature().dist_to_left_boundary());
dist_rbs.push_back(
feature.lane().lane_feature().dist_to_right_boundary());
lane_types.push_back(feature.lane().lane_feature().lane_turn_type());
timestamps.push_back(feature.timestamp());
if (FLAGS_enable_kf_tracking) {
speeds.push_back(feature.t_speed());
} else {
speeds.push_back(feature.speed());
}
++count;
}
}
if (count <= 0) {
return;
}
double theta_mean =
std::accumulate(thetas.begin(), thetas.end(), 0.0) / thetas.size();
double theta_filtered =
(thetas.size() > 1) ? (thetas[0] + thetas[1]) / 2.0 : thetas[0];
double lane_l_mean =
std::accumulate(lane_ls.begin(), lane_ls.end(), 0.0) / lane_ls.size();
double lane_l_filtered =
(lane_ls.size() > 1) ? (lane_ls[0] + lane_ls[1]) / 2.0 : lane_ls[0];
double speed_mean =
std::accumulate(speeds.begin(), speeds.end(), 0.0) / speeds.size();
double speed_lateral = sin(theta_filtered) * speed_mean;
double speed_sign = (speed_lateral > 0) ? 1.0 : -1.0;
double time_to_lb = (abs(speed_lateral) > 0.05)
? dist_lbs[0] / speed_lateral
: 20 * dist_lbs[0] * speed_sign;
double time_to_rb = (abs(speed_lateral) > 0.05)
? -1 * dist_rbs[0] / speed_lateral
: -20 * dist_rbs[0] * speed_sign;
double time_diff = timestamps.front() - timestamps.back();
double dist_lb_rate = (timestamps.size() > 1)
? (dist_lbs.front() - dist_lbs.back()) / time_diff
: 0.0;
double dist_rb_rate = (timestamps.size() > 1)
? (dist_rbs.front() - dist_rbs.back()) / time_diff
: 0.0;
// setup obstacle feature values
feature_values->push_back(theta_filtered);
feature_values->push_back(theta_mean);
feature_values->push_back(theta_filtered - theta_mean);
feature_values->push_back((thetas.size() > 1) ? thetas[0] - thetas[1]
: thetas[0]);
feature_values->push_back(lane_l_filtered);
feature_values->push_back(lane_l_mean);
feature_values->push_back(lane_l_filtered - lane_l_mean);
feature_values->push_back(speed_mean);
feature_values->push_back(dist_lbs.front());
feature_values->push_back(dist_lb_rate);
feature_values->push_back(time_to_lb);
feature_values->push_back(dist_rbs.front());
feature_values->push_back(dist_rb_rate);
feature_values->push_back(time_to_rb);
feature_values->push_back(lane_types.front() == HDMapLane::NO_TURN ? 1.0
: 0.0);
feature_values->push_back(lane_types.front() == HDMapLane::LEFT_TURN ? 1.0
: 0.0);
feature_values->push_back(lane_types.front() == HDMapLane::RIGHT_TURN ? 1.0
: 0.0);
feature_values->push_back(lane_types.front() == HDMapLane::U_TURN ? 1.0
: 0.0);
}
void MLPEvaluator::SetLaneFeatureValues(Obstacle* obstacle_ptr,
LaneSequence* lane_sequence_ptr, std::vector<double>* feature_values) {
feature_values->clear();
feature_values->reserve(LANE_FEATURE_SIZE);
const Feature& feature = obstacle_ptr->latest_feature();
if (!feature.IsInitialized()) {
ADEBUG << "Obstacle [" << obstacle_ptr->id() << "] has no latest feature.";
return;
} else if (!feature.has_position()) {
ADEBUG << "Obstacle [" << obstacle_ptr->id() << "] has no position.";
return;
}
double heading = FLAGS_enable_kf_tracking ? feature.t_velocity_heading()
: feature.theta();
for (int i = 0; i < lane_sequence_ptr->lane_segment_size(); ++i) {
if (feature_values->size() >= LANE_FEATURE_SIZE) {
break;
}
const LaneSegment& lane_segment = lane_sequence_ptr->lane_segment(i);
for (int j = 0; j < lane_segment.lane_point_size(); ++j) {
if (feature_values->size() >= LANE_FEATURE_SIZE) {
break;
}
const LanePoint& lane_point = lane_segment.lane_point(j);
if (!lane_point.has_position()) {
AERROR << "Lane point has no position.";
continue;
}
double diff_x = lane_point.position().x() - feature.position().x();
double diff_y = lane_point.position().y() - feature.position().y();
double angle = std::atan2(diff_x, diff_y);
feature_values->push_back(std::sin(angle - heading));
feature_values->push_back(lane_point.relative_l());
feature_values->push_back(lane_point.heading());
feature_values->push_back(lane_point.angle_diff());
}
}
std::size_t size = feature_values->size();
while (size >= 4 && size < LANE_FEATURE_SIZE) {
double heading_diff = feature_values->operator[](size - 4);
double lane_l_diff = feature_values->operator[](size - 3);
double heading = feature_values->operator[](size - 2);
double angle_diff = feature_values->operator[](size - 1);
feature_values->push_back(heading_diff);
feature_values->push_back(lane_l_diff);
feature_values->push_back(heading);
feature_values->push_back(angle_diff);
size = feature_values->size();
}
}
void MLPEvaluator::LoadModel(const std::string& model_file) {
model_ptr_.reset(new FnnVehicleModel());
CHECK(model_ptr_ != nullptr);
std::fstream file_stream(model_file, std::ios::in | std::ios::binary);
if (!file_stream.good()) {
AERROR << "Unable to open the model file: " << model_file << ".";
return;
}
if (!model_ptr_->ParseFromIstream(&file_stream)) {
AERROR << "Unable to load the model file: " << model_file << ".";
return;
}
ADEBUG << "Succeeded in loading the model file: " << model_file << ".";
}
double MLPEvaluator::ComputeProbability() {
CHECK(model_ptr_.get() != nullptr);
double probability = 0.0;
if (model_ptr_->dim_input() != static_cast<int>(feature_values_.size())) {
AERROR << "Model feature size not consistent with model proto definition.";
return probability;
}
std::vector<double> layer_input;
layer_input.reserve(model_ptr_->dim_input());
std::vector<double> layer_output;
// normalization
for (int i = 0; i < model_ptr_->dim_input(); ++i) {
double mean = model_ptr_->samples_mean().columns(i);
double std = model_ptr_->samples_std().columns(i);
layer_input.push_back(
apollo::prediction::util::Normalize(feature_values_[i], mean, std));
}
for (int i = 0; i < model_ptr_->num_layer(); ++i) {
if (i > 0) {
layer_input.clear();
layer_output.swap(layer_output);
}
const Layer& layer = model_ptr_->layer(i);
for (int col = 0; col < layer.layer_output_dim(); ++col) {
double neuron_output = layer.layer_bias().columns(col);
for (int row = 0; row < layer.layer_input_dim(); ++row) {
double weight = layer.layer_input_weight().rows(row).columns(col);
neuron_output += (layer_input[row] * weight);
}
if (layer.layer_activation_type() == "relu") {
neuron_output = apollo::prediction::util::Relu(neuron_output);
} else if (layer.layer_activation_type() == "sigmoid") {
neuron_output = apollo::prediction::util::Sigmoid(neuron_output);
} else if (layer.layer_activation_type() == "tanh") {
neuron_output = std::tanh(neuron_output);
} else {
LOG(ERROR) << "Undefined activation func: "
<< layer.layer_activation_type()
<< ", and default sigmoid will be used instead.";
neuron_output = apollo::prediction::util::Sigmoid(neuron_output);
}
layer_output.push_back(neuron_output);
}
}
if (layer_output.size() != 1) {
AERROR << "Model output layer has incorrect # outputs: "
<< layer_output.size();
} else {
probability = layer_output[0];
}
return probability;
}
} // namespace prediction
} // namespace apollo
<commit_msg>fix a bug in prediction module<commit_after>/******************************************************************************
* Copyright 2017 The Apollo 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 <cmath>
#include <fstream>
#include <numeric>
#include "modules/prediction/evaluator/vehicle/mlp_evaluator.h"
#include "modules/prediction/common/prediction_gflags.h"
#include "modules/common/math/math_utils.h"
#include "modules/prediction/common/prediction_util.h"
#include "modules/map/proto/map_lane.pb.h"
namespace apollo {
namespace prediction {
using HDMapLane = apollo::hdmap::Lane;
MLPEvaluator::MLPEvaluator() {
LoadModel(FLAGS_vehicle_model_file);
}
void MLPEvaluator::Clear() {
obstacle_feature_values_map_.clear();
}
void MLPEvaluator::Evaluate(Obstacle* obstacle_ptr) {
AINFO << "Start mlp evaluate";
Clear();
if (obstacle_ptr == nullptr) {
AERROR << "Invalid obstacle.";
return;
}
int id = obstacle_ptr->id();
Feature latest_feature = obstacle_ptr->latest_feature();
if (!latest_feature.IsInitialized()) {
ADEBUG << "Obstacle [" << id << "] has no latest feature.";
return;
}
Lane* lane_ptr = latest_feature.mutable_lane();
if (!latest_feature.has_lane() || lane_ptr == nullptr) {
ADEBUG << "Obstacle [" << id << "] has no lane feature.";
return;
}
LaneGraph* lane_graph_ptr = lane_ptr->mutable_lane_graph();
if (!latest_feature.lane().has_lane_graph() || lane_graph_ptr == nullptr) {
ADEBUG << "Obstacle [" << id << "] has no lane graph.";
return;
}
if (latest_feature.lane().lane_graph().lane_sequence_size() == 0) {
ADEBUG << "Obstacle [" << id << "] has no lane sequences.";
return;
}
AINFO << "Start for-loop on lane sequences";
for (int i = 0;
i < latest_feature.lane().lane_graph().lane_sequence_size(); ++i) {
LaneSequence* lane_sequence_ptr = lane_graph_ptr->mutable_lane_sequence(i);
CHECK(lane_sequence_ptr != nullptr);
AINFO << "Start to extract feature values";
ExtractFeatureValues(obstacle_ptr, lane_sequence_ptr);
AINFO << "Start to compute probability";
double probability = ComputeProbability();
AINFO << "probability = " << probability;
lane_sequence_ptr->set_probability(probability);
AINFO << "probability set done";
}
}
void MLPEvaluator::ExtractFeatureValues(Obstacle* obstacle_ptr,
LaneSequence* lane_sequence_ptr) {
feature_values_.clear();
int id = obstacle_ptr->id();
std::vector<double> obstacle_feature_values;
if (obstacle_feature_values_map_.find(id) ==
obstacle_feature_values_map_.end()) {
SetObstacleFeatureValues(obstacle_ptr, &obstacle_feature_values);
} else {
obstacle_feature_values = obstacle_feature_values_map_[id];
}
if (obstacle_feature_values.size() != OBSTACLE_FEATURE_SIZE) {
ADEBUG << "Obstacle [" << id << "] has fewer than "
<< "expected obstacle feature_values "
<< obstacle_feature_values.size() << ".";
return;
}
std::vector<double> lane_feature_values;
SetLaneFeatureValues(obstacle_ptr, lane_sequence_ptr, &lane_feature_values);
if (lane_feature_values.size() != LANE_FEATURE_SIZE) {
ADEBUG << "Obstacle [" << id << "] has fewer than "
<< "expected lane feature_values"
<< lane_feature_values.size() << ".";
return;
}
feature_values_.insert(feature_values_.end(),
obstacle_feature_values.begin(), obstacle_feature_values.end());
feature_values_.insert(feature_values_.end(),
lane_feature_values.begin(), lane_feature_values.end());
}
void MLPEvaluator::SetObstacleFeatureValues(
Obstacle* obstacle_ptr, std::vector<double>* feature_values) {
feature_values->clear();
feature_values->reserve(OBSTACLE_FEATURE_SIZE);
std::vector<double> thetas;
std::vector<double> lane_ls;
std::vector<double> dist_lbs;
std::vector<double> dist_rbs;
std::vector<int> lane_types;
std::vector<double> speeds;
std::vector<double> timestamps;
double duration = obstacle_ptr->timestamp() - FLAGS_prediction_duration;
int count = 0;
for (std::size_t i = 0; i < obstacle_ptr->history_size(); ++i) {
const Feature& feature = obstacle_ptr->feature(i);
if (!feature.IsInitialized()) {
continue;
}
if (apollo::common::math::DoubleCompare(
feature.timestamp(), duration) < 0) {
break;
}
if (feature.has_lane() && feature.lane().has_lane_feature()) {
thetas.push_back(feature.lane().lane_feature().angle_diff());
lane_ls.push_back(feature.lane().lane_feature().lane_l());
dist_lbs.push_back(feature.lane().lane_feature().dist_to_left_boundary());
dist_rbs.push_back(
feature.lane().lane_feature().dist_to_right_boundary());
lane_types.push_back(feature.lane().lane_feature().lane_turn_type());
timestamps.push_back(feature.timestamp());
if (FLAGS_enable_kf_tracking) {
speeds.push_back(feature.t_speed());
} else {
speeds.push_back(feature.speed());
}
++count;
}
}
if (count <= 0) {
return;
}
double theta_mean =
std::accumulate(thetas.begin(), thetas.end(), 0.0) / thetas.size();
double theta_filtered =
(thetas.size() > 1) ? (thetas[0] + thetas[1]) / 2.0 : thetas[0];
double lane_l_mean =
std::accumulate(lane_ls.begin(), lane_ls.end(), 0.0) / lane_ls.size();
double lane_l_filtered =
(lane_ls.size() > 1) ? (lane_ls[0] + lane_ls[1]) / 2.0 : lane_ls[0];
double speed_mean =
std::accumulate(speeds.begin(), speeds.end(), 0.0) / speeds.size();
double speed_lateral = sin(theta_filtered) * speed_mean;
double speed_sign = (speed_lateral > 0) ? 1.0 : -1.0;
double time_to_lb = (abs(speed_lateral) > 0.05)
? dist_lbs[0] / speed_lateral
: 20 * dist_lbs[0] * speed_sign;
double time_to_rb = (abs(speed_lateral) > 0.05)
? -1 * dist_rbs[0] / speed_lateral
: -20 * dist_rbs[0] * speed_sign;
double time_diff = timestamps.front() - timestamps.back();
double dist_lb_rate = (timestamps.size() > 1)
? (dist_lbs.front() - dist_lbs.back()) / time_diff
: 0.0;
double dist_rb_rate = (timestamps.size() > 1)
? (dist_rbs.front() - dist_rbs.back()) / time_diff
: 0.0;
// setup obstacle feature values
feature_values->push_back(theta_filtered);
feature_values->push_back(theta_mean);
feature_values->push_back(theta_filtered - theta_mean);
feature_values->push_back((thetas.size() > 1) ? thetas[0] - thetas[1]
: thetas[0]);
feature_values->push_back(lane_l_filtered);
feature_values->push_back(lane_l_mean);
feature_values->push_back(lane_l_filtered - lane_l_mean);
feature_values->push_back(speed_mean);
feature_values->push_back(dist_lbs.front());
feature_values->push_back(dist_lb_rate);
feature_values->push_back(time_to_lb);
feature_values->push_back(dist_rbs.front());
feature_values->push_back(dist_rb_rate);
feature_values->push_back(time_to_rb);
feature_values->push_back(lane_types.front() == HDMapLane::NO_TURN ? 1.0
: 0.0);
feature_values->push_back(lane_types.front() == HDMapLane::LEFT_TURN ? 1.0
: 0.0);
feature_values->push_back(lane_types.front() == HDMapLane::RIGHT_TURN ? 1.0
: 0.0);
feature_values->push_back(lane_types.front() == HDMapLane::U_TURN ? 1.0
: 0.0);
}
void MLPEvaluator::SetLaneFeatureValues(Obstacle* obstacle_ptr,
LaneSequence* lane_sequence_ptr, std::vector<double>* feature_values) {
feature_values->clear();
feature_values->reserve(LANE_FEATURE_SIZE);
const Feature& feature = obstacle_ptr->latest_feature();
if (!feature.IsInitialized()) {
ADEBUG << "Obstacle [" << obstacle_ptr->id() << "] has no latest feature.";
return;
} else if (!feature.has_position()) {
ADEBUG << "Obstacle [" << obstacle_ptr->id() << "] has no position.";
return;
}
double heading = FLAGS_enable_kf_tracking ? feature.t_velocity_heading()
: feature.theta();
for (int i = 0; i < lane_sequence_ptr->lane_segment_size(); ++i) {
if (feature_values->size() >= LANE_FEATURE_SIZE) {
break;
}
const LaneSegment& lane_segment = lane_sequence_ptr->lane_segment(i);
for (int j = 0; j < lane_segment.lane_point_size(); ++j) {
if (feature_values->size() >= LANE_FEATURE_SIZE) {
break;
}
const LanePoint& lane_point = lane_segment.lane_point(j);
if (!lane_point.has_position()) {
AERROR << "Lane point has no position.";
continue;
}
double diff_x = lane_point.position().x() - feature.position().x();
double diff_y = lane_point.position().y() - feature.position().y();
double angle = std::atan2(diff_x, diff_y);
feature_values->push_back(std::sin(angle - heading));
feature_values->push_back(lane_point.relative_l());
feature_values->push_back(lane_point.heading());
feature_values->push_back(lane_point.angle_diff());
}
}
std::size_t size = feature_values->size();
while (size >= 4 && size < LANE_FEATURE_SIZE) {
double heading_diff = feature_values->operator[](size - 4);
double lane_l_diff = feature_values->operator[](size - 3);
double heading = feature_values->operator[](size - 2);
double angle_diff = feature_values->operator[](size - 1);
feature_values->push_back(heading_diff);
feature_values->push_back(lane_l_diff);
feature_values->push_back(heading);
feature_values->push_back(angle_diff);
size = feature_values->size();
}
}
void MLPEvaluator::LoadModel(const std::string& model_file) {
model_ptr_.reset(new FnnVehicleModel());
CHECK(model_ptr_ != nullptr);
std::fstream file_stream(model_file, std::ios::in | std::ios::binary);
if (!file_stream.good()) {
AERROR << "Unable to open the model file: " << model_file << ".";
return;
}
if (!model_ptr_->ParseFromIstream(&file_stream)) {
AERROR << "Unable to load the model file: " << model_file << ".";
return;
}
ADEBUG << "Succeeded in loading the model file: " << model_file << ".";
}
double MLPEvaluator::ComputeProbability() {
CHECK(model_ptr_.get() != nullptr);
double probability = 0.0;
if (model_ptr_->dim_input() != static_cast<int>(feature_values_.size())) {
AERROR << "Model feature size not consistent with model proto definition.";
return probability;
}
std::vector<double> layer_input;
layer_input.reserve(model_ptr_->dim_input());
std::vector<double> layer_output;
// normalization
for (int i = 0; i < model_ptr_->dim_input(); ++i) {
double mean = model_ptr_->samples_mean().columns(i);
double std = model_ptr_->samples_std().columns(i);
layer_input.push_back(
apollo::prediction::util::Normalize(feature_values_[i], mean, std));
}
for (int i = 0; i < model_ptr_->num_layer(); ++i) {
if (i > 0) {
layer_input.clear();
layer_output.swap(layer_output);
}
const Layer& layer = model_ptr_->layer(i);
for (int col = 0; col < layer.layer_output_dim(); ++col) {
double neuron_output = layer.layer_bias().columns(col);
for (int row = 0; row < layer.layer_input_dim(); ++row) {
double weight = layer.layer_input_weight().rows(row).columns(col);
neuron_output += (layer_input[row] * weight);
}
if (layer.layer_activation_type() == "relu") {
neuron_output = apollo::prediction::util::Relu(neuron_output);
} else if (layer.layer_activation_type() == "sigmoid") {
neuron_output = apollo::prediction::util::Sigmoid(neuron_output);
} else if (layer.layer_activation_type() == "tanh") {
neuron_output = std::tanh(neuron_output);
} else {
LOG(ERROR) << "Undefined activation func: "
<< layer.layer_activation_type()
<< ", and default sigmoid will be used instead.";
neuron_output = apollo::prediction::util::Sigmoid(neuron_output);
}
layer_output.push_back(neuron_output);
}
}
if (layer_output.size() != 1) {
AERROR << "Model output layer has incorrect # outputs: "
<< layer_output.size();
} else {
probability = layer_output[0];
}
return probability;
}
} // namespace prediction
} // namespace apollo
<|endoftext|> |
<commit_before>/* This file is part of Strigi Desktop Search
*
* Copyright (C) 2007 Flavio Castelli <flavio.castelli@gmail.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "famlistener.h"
#include "analyzerconfiguration.h"
#include "combinedindexmanager.h"
#include "event.h"
#include "eventlistenerqueue.h"
#include "filelister.h"
#include "indexreader.h"
#include "../strigilogging.h"
#include <cerrno>
#include <sys/resource.h>
#include <sys/select.h>
#include <sys/types.h>
#include <vector>
using namespace std;
using namespace Strigi;
class MatchString {
string m_fixed_val;
public:
MatchString (string fixed_val) {m_fixed_val = fixed_val;}
bool operator() (pair<FAMRequest,string> val) {
return (m_fixed_val.compare(val.second) == 0 ? true : false);
}
};
bool operator< (const FAMRequest& f1, const FAMRequest& f2)
{
return f1.reqnum < f2.reqnum;
}
FamEvent::FamEvent (const string& watchName, FAMEvent event)
: FsEvent (watchName, event.filename)
m_event(event),
m_watchName (watchName)
{
bool doStat = true;
switch (event.code)
{
case FAMChanged:
m_type = UPDATE;
break;
case FAMMoved:
case FAMDeleted:
m_type = DELETE;
break;
case FAMCreated:
m_type = CREATE;
break;
default:
STRIGI_LOG_DEBUG ("strigi.FamEvent.FamEvent",
"unuseful event");
doStat = false;
break;
}
if (!doStat)
return;
struct stat status;
string path = m_watchName;
if (path[path.length() - 1] != '/')
path += "/";
path += event.filename;
if ( stat( path.c_str(), &status) == 0) {
if (S_ISDIR(status.st_mode))
m_regardsDir = true;
else
m_regardsDir = false;
}
else {
string msg;
msg = "unable to execute stat() on FAMEvent.filename because of: ";
msg += strerror (errno);
STRIGI_LOG_ERROR ("strigi.FamEvent", msg)
}
}
char* FamEvent::name()
{
return m_event.filename;
}
const string FamEvent::description()
{
string message;
switch (m_event.code)
{
case FAMChanged:
message += "FAMChanged";
break;
case FAMMoved:
message += "FAMMoved";
break;
case FAMDeleted:
message += "FAMDeleted";
break;
case FAMCreated:
message += "FAMCreated";
break;
case FAMExists:
message += "FAMExists";
break;
case FAMEndExist:
message += "FAMEndExist";
break;
case FAMAcknowledge:
message += "FAMAcknowledge";
break;
case FAMStartExecuting:
message += "FAMStartExecuting";
break;
case FAMStopExecuting:
message += "FAMStopExecuting";
break;
}
message += " event regarding ";
message += (m_regardsDir) ? "dir " : "file ";
message += m_event.filename;
message += " ; associated watch description: " + m_watchName;
return message;
}
bool FamEvent::regardsDir()
{
return m_regardsDir;
}
class FamListener::Private
{
public:
Private();
virtual ~Private();
bool init();
void stopMonitoring();
bool isEventInteresting (FsEvent * event);
bool isEventValid(FsEvent* event);
// event methods
void pendingEvent(vector<FsEvent*>& events, unsigned int& counter);
// dir methods
void dirRemoved (string dir);
// watches methods
bool addWatch (const std::string& path);
void addWatches (const std::set<std::string>& watches);
void rmWatch(FAMRequest& famRequest, std::string path);
void rmWatches(std::map<FAMRequest, std::string>& watchesToRemove);
void rmWatches(std::set<std::string>& watchesToRemove);
void clearWatches();
private:
FAMConnection m_famConnection;
std::map<FAMRequest, std::string> m_watches; //!< map containing all inotify watches added by FamListener. Key is watch descriptor, value is dir path
};
bool FamListener::Private::init()
{
if (FAMOpen(&m_famConnection) == -1)
return false;
return true;
}
FamListener::Private::Private()
{
}
FamListener::Private::~Private()
{
clearWatches();
if (FAMClose (&m_famConnection) == -1)
STRIGI_LOG_ERROR ("strigi.FamListener",
"Error during FAM close procedure");
}
void FamListener::Private::pendingEvent(vector<FsEvent*>& events,
unsigned int& counter)
{
sleep (1);
if (FAMPending(&m_famConnection)) {
FAMEvent event;
if (FAMNextEvent (&m_famConnection, &event) == -1) {
STRIGI_LOG_ERROR ("strigi.FamListener.pendingEvent",
"Fam event retrieval failed");
return;
}
if ((event.code == FAMChanged) || (event.code == FAMMoved) ||
(event.code == FAMDeleted) || (event.code == FAMCreated))
{
map<FAMRequest, string>::iterator match;
match = m_watches.find (event.fr);
if (match != m_watches.end()) {
events.push_back (new FamEvent (match->second, event));
counter++;
}
}
}
}
bool FamListener::Private::isEventValid(FsEvent* event)
{
FamEvent* famEvent = dynamic_cast<FamEvent*> (event);
if (famEvent == 0)
return false;
map<FAMRequest, string>::iterator match = m_watches.find(famEvent->fr());
return (match != m_watches.end());
}
bool FamListener::Private::addWatch (const string& path)
{
map<FAMRequest, string>::iterator iter;
for (iter = m_watches.begin(); iter != m_watches.end(); iter++) {
if ((iter->second).compare (path) == 0) // dir is already watched
return true;
}
FAMRequest famRequest;
if (FAMMonitorDirectory (&m_famConnection, path.c_str(), &famRequest, 0) == 0) {
m_watches.insert(make_pair(famRequest, path));
return true;
}
else
return false;
}
void FamListener::Private::rmWatch(FAMRequest& famRequest, string path)
{
if (FAMCancelMonitor (&m_famConnection, &famRequest) == -1)
STRIGI_LOG_ERROR ("strigi.FamListener.Private.rmWatch",
string("Error removing watch associated to path: ") + path)
else
STRIGI_LOG_DEBUG ("strigi.FamListener.Private.rmWatch",
string("Removed watch associated to path: ") + path)
map<FAMRequest, string>::iterator match = m_watches.find(famRequest);
if (match != m_watches.end() && (path.compare(match->second) == 0))
m_watches.erase (match);
else
STRIGI_LOG_ERROR ("strigi.FamListener.Private.rmWatch",
"unable to remove internal watch reference for " + path)
}
void FamListener::Private::rmWatches(map<FAMRequest, string>& watchesToRemove)
{
for (map<FAMRequest,string>::iterator it = watchesToRemove.begin();
it != watchesToRemove.end(); it++)
{
map<FAMRequest,string>::iterator match = m_watches.find (it->first);
if (match != m_watches.end()) {
FAMRequest famRequest = it->first;
rmWatch ( famRequest, it->second);
}
else
STRIGI_LOG_WARNING ("strigi.FamListener.Private.rmWatches",
"unable to remove watch associated to " + it->second);
}
}
void FamListener::Private::rmWatches(set<string>& watchesToRemove)
{
map<FAMRequest, string> removedWatches;
// find all pairs <watch-id, watch-name> that have to be removed
for (set<string>::iterator it = watchesToRemove.begin();
it != watchesToRemove.end(); it++)
{
MatchString finder (*it);
map<FAMRequest, string>::iterator match;
match = find_if (m_watches.begin(), m_watches.end(), finder);
if (match != m_watches.end())
removedWatches.insert (make_pair (match->first, match->second));
else
STRIGI_LOG_WARNING ("strigi.FamListener.Private.rmWatches",
"unable to find the watch associated to " + *it)
}
rmWatches (removedWatches);
}
void FamListener::Private::clearWatches ()
{
map<FAMRequest, string>::iterator iter;
for (iter = m_watches.begin(); iter != m_watches.end(); iter++) {
FAMRequest famRequest = iter->first;
if (FAMCancelMonitor (&m_famConnection, &famRequest) == -1)
STRIGI_LOG_ERROR ("strigi.FamListener.rmWatch",
string("Error removing watch associated to path: ") + iter->second)
else
STRIGI_LOG_DEBUG ("strigi.FamListener.rmWatch",
string("Removed watch associated to path: ") + iter->second)
}
m_watches.clear();
}
void FamListener::Private::dirRemoved (string dir)
{
map<FAMRequest, string> watchesToRemove;
// remove inotify watches over no more indexed dirs
for (map<FAMRequest, string>::iterator mi = m_watches.begin();
mi != m_watches.end(); mi++)
{
if ((mi->second).find (dir,0) == 0)
watchesToRemove.insert (make_pair (mi->first, mi->second));
}
rmWatches (watchesToRemove);
}
// END FamListener::Private
FamListener::FamListener(set<string>& indexedDirs)
:FsListener("FamListener", indexedDirs)
{
p = new Private();
}
FamListener::~FamListener()
{
delete p;
}
bool FamListener::init()
{
if (!p->init()) {
STRIGI_LOG_ERROR ("strigi.FamListener.init",
"Error during FAM initialization");
return false;
}
m_bInitialized = true;
STRIGI_LOG_DEBUG ("strigi.FamListener.init", "successfully initialized");
return true;
}
FsEvent* FamListener:: retrieveEvent()
{
if (m_events.empty())
return 0;
vector<FsEvent*>::iterator iter = m_events.begin();
FsEvent* event = *iter;
m_events.erase(iter);
return event;
}
bool FamListener::pendingEvent()
{
unsigned int counter = 0;
p->pendingEvent (m_events, counter);
if (counter > 0) {
char buff [20];
snprintf(buff, 20 * sizeof (char), "%i", counter);
string message = "Caught ";
message += buff;
message += " FAM event(s)";
STRIGI_LOG_DEBUG ("strigi.FamListener.pendingEvent", message)
}
return !m_events.empty();
}
bool FamListener::isEventInteresting (FsEvent* event)
{
FamEvent* famEvent = dynamic_cast<FamEvent*> (event);
if (famEvent == 0)
return false;
// ignore directories starting with '.'
if ((famEvent->regardsDir()) &&
(strlen (famEvent->name()) > 0) && (famEvent->name())[0] == '.')
return false;
if (m_pAnalyzerConfiguration == NULL) {
STRIGI_LOG_WARNING ("strigi.FamListener.isEventInteresting",
"AnalyzerConfiguration == NULL")
return true;
}
string path = famEvent->watchName();
if (path[path.length() - 1] != '/')
path += "/";
path += famEvent->name();
if (famEvent->regardsDir())
return m_pAnalyzerConfiguration->indexDir( path.c_str(),
famEvent->name());
else
return m_pAnalyzerConfiguration->indexFile( path.c_str(),
famEvent->name());
}
bool FamListener::isEventValid(FsEvent* event)
{
return p->isEventValid ( event);
}
bool FamListener::addWatch (const string& path)
{
if (p->addWatch (path)) {
STRIGI_LOG_INFO ("strigi.FamListener.addWatch",
"added watch for " + path);
return true;
}
else {
STRIGI_LOG_ERROR ("strigi.FamListener.addWatch",
"Failed to watch " + path)
return false;
}
}
void FamListener::clearWatches ()
{
p->clearWatches();
}
void FamListener::dirRemoved (string dir, vector<Event*>& events)
{
map<FAMRequest, string> watchesToRemove;
STRIGI_LOG_DEBUG ("strigi.FamListener.dirRemoved", dir +
" is no longer watched, removing all indexed files contained")
// we've to de-index all files contained into the deleted/moved directory
if (m_pManager)
{
// all indexed files contained into directory
map<string, time_t> indexedFiles;
m_pManager->indexReader()->getChildren(dir, indexedFiles);
// remove all entries that were contained into the removed directory
for (map<string, time_t>::iterator it = indexedFiles.begin();
it != indexedFiles.end(); it++)
{
Event* event = new Event (Event::DELETED, it->first);
events.push_back (event);
}
}
else
STRIGI_LOG_WARNING ("strigi.FamListener.dirRemoved",
"m_pManager == NULL!");
p->dirRemoved (dir);
}
<commit_msg>Fixed build error<commit_after>/* This file is part of Strigi Desktop Search
*
* Copyright (C) 2007 Flavio Castelli <flavio.castelli@gmail.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "famlistener.h"
#include "analyzerconfiguration.h"
#include "combinedindexmanager.h"
#include "event.h"
#include "eventlistenerqueue.h"
#include "filelister.h"
#include "indexreader.h"
#include "../strigilogging.h"
#include <cerrno>
#include <sys/resource.h>
#include <sys/select.h>
#include <sys/types.h>
#include <vector>
using namespace std;
using namespace Strigi;
class MatchString {
string m_fixed_val;
public:
MatchString (string fixed_val) {m_fixed_val = fixed_val;}
bool operator() (pair<FAMRequest,string> val) {
return (m_fixed_val.compare(val.second) == 0 ? true : false);
}
};
bool operator< (const FAMRequest& f1, const FAMRequest& f2)
{
return f1.reqnum < f2.reqnum;
}
FamEvent::FamEvent (const string& watchName, FAMEvent event)
: FsEvent (watchName, event.filename),
m_event(event),
m_watchName (watchName)
{
bool doStat = true;
switch (event.code)
{
case FAMChanged:
m_type = UPDATE;
break;
case FAMMoved:
case FAMDeleted:
m_type = DELETE;
break;
case FAMCreated:
m_type = CREATE;
break;
default:
STRIGI_LOG_DEBUG ("strigi.FamEvent.FamEvent",
"unuseful event");
doStat = false;
break;
}
if (!doStat)
return;
struct stat status;
string path = m_watchName;
if (path[path.length() - 1] != '/')
path += "/";
path += event.filename;
if ( stat( path.c_str(), &status) == 0) {
if (S_ISDIR(status.st_mode))
m_regardsDir = true;
else
m_regardsDir = false;
}
else {
string msg;
msg = "unable to execute stat() on FAMEvent.filename because of: ";
msg += strerror (errno);
STRIGI_LOG_ERROR ("strigi.FamEvent", msg)
}
}
char* FamEvent::name()
{
return m_event.filename;
}
const string FamEvent::description()
{
string message;
switch (m_event.code)
{
case FAMChanged:
message += "FAMChanged";
break;
case FAMMoved:
message += "FAMMoved";
break;
case FAMDeleted:
message += "FAMDeleted";
break;
case FAMCreated:
message += "FAMCreated";
break;
case FAMExists:
message += "FAMExists";
break;
case FAMEndExist:
message += "FAMEndExist";
break;
case FAMAcknowledge:
message += "FAMAcknowledge";
break;
case FAMStartExecuting:
message += "FAMStartExecuting";
break;
case FAMStopExecuting:
message += "FAMStopExecuting";
break;
}
message += " event regarding ";
message += (m_regardsDir) ? "dir " : "file ";
message += m_event.filename;
message += " ; associated watch description: " + m_watchName;
return message;
}
bool FamEvent::regardsDir()
{
return m_regardsDir;
}
class FamListener::Private
{
public:
Private();
virtual ~Private();
bool init();
void stopMonitoring();
bool isEventInteresting (FsEvent * event);
bool isEventValid(FsEvent* event);
// event methods
void pendingEvent(vector<FsEvent*>& events, unsigned int& counter);
// dir methods
void dirRemoved (string dir);
// watches methods
bool addWatch (const std::string& path);
void addWatches (const std::set<std::string>& watches);
void rmWatch(FAMRequest& famRequest, std::string path);
void rmWatches(std::map<FAMRequest, std::string>& watchesToRemove);
void rmWatches(std::set<std::string>& watchesToRemove);
void clearWatches();
private:
FAMConnection m_famConnection;
std::map<FAMRequest, std::string> m_watches; //!< map containing all inotify watches added by FamListener. Key is watch descriptor, value is dir path
};
bool FamListener::Private::init()
{
if (FAMOpen(&m_famConnection) == -1)
return false;
return true;
}
FamListener::Private::Private()
{
}
FamListener::Private::~Private()
{
clearWatches();
if (FAMClose (&m_famConnection) == -1)
STRIGI_LOG_ERROR ("strigi.FamListener",
"Error during FAM close procedure");
}
void FamListener::Private::pendingEvent(vector<FsEvent*>& events,
unsigned int& counter)
{
sleep (1);
if (FAMPending(&m_famConnection)) {
FAMEvent event;
if (FAMNextEvent (&m_famConnection, &event) == -1) {
STRIGI_LOG_ERROR ("strigi.FamListener.pendingEvent",
"Fam event retrieval failed");
return;
}
if ((event.code == FAMChanged) || (event.code == FAMMoved) ||
(event.code == FAMDeleted) || (event.code == FAMCreated))
{
map<FAMRequest, string>::iterator match;
match = m_watches.find (event.fr);
if (match != m_watches.end()) {
events.push_back (new FamEvent (match->second, event));
counter++;
}
}
}
}
bool FamListener::Private::isEventValid(FsEvent* event)
{
FamEvent* famEvent = dynamic_cast<FamEvent*> (event);
if (famEvent == 0)
return false;
map<FAMRequest, string>::iterator match = m_watches.find(famEvent->fr());
return (match != m_watches.end());
}
bool FamListener::Private::addWatch (const string& path)
{
map<FAMRequest, string>::iterator iter;
for (iter = m_watches.begin(); iter != m_watches.end(); iter++) {
if ((iter->second).compare (path) == 0) // dir is already watched
return true;
}
FAMRequest famRequest;
if (FAMMonitorDirectory (&m_famConnection, path.c_str(), &famRequest, 0) == 0) {
m_watches.insert(make_pair(famRequest, path));
return true;
}
else
return false;
}
void FamListener::Private::rmWatch(FAMRequest& famRequest, string path)
{
if (FAMCancelMonitor (&m_famConnection, &famRequest) == -1)
STRIGI_LOG_ERROR ("strigi.FamListener.Private.rmWatch",
string("Error removing watch associated to path: ") + path)
else
STRIGI_LOG_DEBUG ("strigi.FamListener.Private.rmWatch",
string("Removed watch associated to path: ") + path)
map<FAMRequest, string>::iterator match = m_watches.find(famRequest);
if (match != m_watches.end() && (path.compare(match->second) == 0))
m_watches.erase (match);
else
STRIGI_LOG_ERROR ("strigi.FamListener.Private.rmWatch",
"unable to remove internal watch reference for " + path)
}
void FamListener::Private::rmWatches(map<FAMRequest, string>& watchesToRemove)
{
for (map<FAMRequest,string>::iterator it = watchesToRemove.begin();
it != watchesToRemove.end(); it++)
{
map<FAMRequest,string>::iterator match = m_watches.find (it->first);
if (match != m_watches.end()) {
FAMRequest famRequest = it->first;
rmWatch ( famRequest, it->second);
}
else
STRIGI_LOG_WARNING ("strigi.FamListener.Private.rmWatches",
"unable to remove watch associated to " + it->second);
}
}
void FamListener::Private::rmWatches(set<string>& watchesToRemove)
{
map<FAMRequest, string> removedWatches;
// find all pairs <watch-id, watch-name> that have to be removed
for (set<string>::iterator it = watchesToRemove.begin();
it != watchesToRemove.end(); it++)
{
MatchString finder (*it);
map<FAMRequest, string>::iterator match;
match = find_if (m_watches.begin(), m_watches.end(), finder);
if (match != m_watches.end())
removedWatches.insert (make_pair (match->first, match->second));
else
STRIGI_LOG_WARNING ("strigi.FamListener.Private.rmWatches",
"unable to find the watch associated to " + *it)
}
rmWatches (removedWatches);
}
void FamListener::Private::clearWatches ()
{
map<FAMRequest, string>::iterator iter;
for (iter = m_watches.begin(); iter != m_watches.end(); iter++) {
FAMRequest famRequest = iter->first;
if (FAMCancelMonitor (&m_famConnection, &famRequest) == -1)
STRIGI_LOG_ERROR ("strigi.FamListener.rmWatch",
string("Error removing watch associated to path: ") + iter->second)
else
STRIGI_LOG_DEBUG ("strigi.FamListener.rmWatch",
string("Removed watch associated to path: ") + iter->second)
}
m_watches.clear();
}
void FamListener::Private::dirRemoved (string dir)
{
map<FAMRequest, string> watchesToRemove;
// remove inotify watches over no more indexed dirs
for (map<FAMRequest, string>::iterator mi = m_watches.begin();
mi != m_watches.end(); mi++)
{
if ((mi->second).find (dir,0) == 0)
watchesToRemove.insert (make_pair (mi->first, mi->second));
}
rmWatches (watchesToRemove);
}
// END FamListener::Private
FamListener::FamListener(set<string>& indexedDirs)
:FsListener("FamListener", indexedDirs)
{
p = new Private();
}
FamListener::~FamListener()
{
delete p;
}
bool FamListener::init()
{
if (!p->init()) {
STRIGI_LOG_ERROR ("strigi.FamListener.init",
"Error during FAM initialization");
return false;
}
m_bInitialized = true;
STRIGI_LOG_DEBUG ("strigi.FamListener.init", "successfully initialized");
return true;
}
FsEvent* FamListener:: retrieveEvent()
{
if (m_events.empty())
return 0;
vector<FsEvent*>::iterator iter = m_events.begin();
FsEvent* event = *iter;
m_events.erase(iter);
return event;
}
bool FamListener::pendingEvent()
{
unsigned int counter = 0;
p->pendingEvent (m_events, counter);
if (counter > 0) {
char buff [20];
snprintf(buff, 20 * sizeof (char), "%i", counter);
string message = "Caught ";
message += buff;
message += " FAM event(s)";
STRIGI_LOG_DEBUG ("strigi.FamListener.pendingEvent", message)
}
return !m_events.empty();
}
bool FamListener::isEventInteresting (FsEvent* event)
{
FamEvent* famEvent = dynamic_cast<FamEvent*> (event);
if (famEvent == 0)
return false;
// ignore directories starting with '.'
if ((famEvent->regardsDir()) &&
(strlen (famEvent->name()) > 0) && (famEvent->name())[0] == '.')
return false;
if (m_pAnalyzerConfiguration == NULL) {
STRIGI_LOG_WARNING ("strigi.FamListener.isEventInteresting",
"AnalyzerConfiguration == NULL")
return true;
}
string path = famEvent->watchName();
if (path[path.length() - 1] != '/')
path += "/";
path += famEvent->name();
if (famEvent->regardsDir())
return m_pAnalyzerConfiguration->indexDir( path.c_str(),
famEvent->name());
else
return m_pAnalyzerConfiguration->indexFile( path.c_str(),
famEvent->name());
}
bool FamListener::isEventValid(FsEvent* event)
{
return p->isEventValid ( event);
}
bool FamListener::addWatch (const string& path)
{
if (p->addWatch (path)) {
STRIGI_LOG_INFO ("strigi.FamListener.addWatch",
"added watch for " + path);
return true;
}
else {
STRIGI_LOG_ERROR ("strigi.FamListener.addWatch",
"Failed to watch " + path)
return false;
}
}
void FamListener::clearWatches ()
{
p->clearWatches();
}
void FamListener::dirRemoved (string dir, vector<Event*>& events)
{
map<FAMRequest, string> watchesToRemove;
STRIGI_LOG_DEBUG ("strigi.FamListener.dirRemoved", dir +
" is no longer watched, removing all indexed files contained")
// we've to de-index all files contained into the deleted/moved directory
if (m_pManager)
{
// all indexed files contained into directory
map<string, time_t> indexedFiles;
m_pManager->indexReader()->getChildren(dir, indexedFiles);
// remove all entries that were contained into the removed directory
for (map<string, time_t>::iterator it = indexedFiles.begin();
it != indexedFiles.end(); it++)
{
Event* event = new Event (Event::DELETED, it->first);
events.push_back (event);
}
}
else
STRIGI_LOG_WARNING ("strigi.FamListener.dirRemoved",
"m_pManager == NULL!");
p->dirRemoved (dir);
}
<|endoftext|> |
<commit_before>#include "TextRenderer.h"
#ifdef WIN32
#include <gl/gl.h>
#include <SDL/SDL_ttf.h>
#else
#include <OpenGL/gl.h>
#include <SDL_ttf/SDL_ttf.h>
#endif
#include <SDL/SDL.h>
#include "Apollo.h"
#include <map>
#include "Utilities/ResourceManager.h"
#include "Utilities/GameTime.h"
#include "Logging.h"
namespace
{
uint32_t Hash ( const std::string& input )
{
uint32_t base = 0xBAADF00D;
uint32_t a = 0, b = 0x8D470010;
const unsigned char* data = (const unsigned char*)input.data();
size_t len = input.length();
for (size_t i = 0; i < len; i++)
{
a <<= 5;
b ^= data[i];
a ^= b;
base ^= a;
a += b;
if (i != 0)
a ^= (data[i - 1] << 16);
}
return b ^ a;
}
struct TextEntry
{
uint32_t hash;
SDL_Surface* surface;
GLuint texID;
float lastUse;
~TextEntry ()
{
SDL_FreeSurface(surface);
if (texID)
glDeleteTextures(1, &texID);
}
};
typedef std::map<uint32_t, TextEntry*> TextEntryTable;
TextEntryTable textEntries;
std::map<std::string, TTF_Font*> fonts;
#define DEFAULT_FONT "CrystalClear"
static bool ttf_initted = false;
// [ADAM, ALISTAIR]: this is where size affects things... how would we figure out how to correct the size?
TTF_Font* GetFont ( const std::string& name, float size )
{
if (!ttf_initted)
{
TTF_Init();
ttf_initted = true;
}
std::map<std::string, TTF_Font*>::iterator iter = fonts.find(name);
if (iter != fonts.end())
{
return iter->second;
}
SDL_RWops* rwops = ResourceManager::OpenFile("Fonts/" + name + ".ttf");
TTF_Font* loadedFont;
if (!rwops)
goto loadFail;
loadedFont = TTF_OpenFontRW(rwops, 1, size);
if (!loadedFont)
goto loadFail;
fonts[name] = loadedFont;
return loadedFont;
loadFail:
if (name == DEFAULT_FONT)
{
LOG("Graphics::TextRenderer", LOG_ERROR, "Unable to load default font: %s", DEFAULT_FONT);
exit(1);
}
loadedFont = GetFont(DEFAULT_FONT, size);
fonts[name] = loadedFont;
LOG("Graphics::TextRenderer", LOG_WARNING, "Unable to load font '%s', defaulted to '%s'", name.c_str(), DEFAULT_FONT);
return loadedFont;
}
TextEntry* GetEntry ( const std::string& font, const std::string& text, float size )
{
uint32_t hash = Hash(font + "@" + text);
TextEntryTable::iterator iter;
iter = textEntries.find(hash);
if (iter != textEntries.end())
{
return iter->second;
}
else
{
TextEntry* newEntry = new TextEntry;
newEntry->hash = hash;
newEntry->texID = 0;
newEntry->surface = NULL;
newEntry->lastUse = 0.0f;
TTF_Font* fontObject = GetFont(font, size);
const SDL_Color fg = { 0xFF, 0xFF, 0xFF, 0xFF };
newEntry->surface = TTF_RenderUTF8_Blended(fontObject, text.c_str(), fg);
assert(newEntry->surface);
// generate textures
glGenTextures(1, &(newEntry->texID));
glBindTexture(GL_TEXTURE_RECTANGLE_ARB, newEntry->texID);
#ifdef __BIG_ENDIAN__
glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, GL_RGBA, newEntry->surface->w, newEntry->surface->h, 0, GL_ABGR_EXT, GL_UNSIGNED_BYTE, newEntry->surface->pixels);
#else
glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, GL_RGBA, newEntry->surface->w, newEntry->surface->h, 0, GL_RGBA, GL_UNSIGNED_BYTE, newEntry->surface->pixels);
#endif
textEntries[hash] = newEntry;
return newEntry;
}
}
}
namespace Graphics
{
namespace TextRenderer
{
vec2 TextDimensions ( const std::string& font, const std::string& text, float size )
{
int xcoord = 0;
int ycoord = 0;
TTF_Font* fontObject = GetFont(font, size);
if (TTF_SizeUTF8(fontObject, text.c_str(), &xcoord, &ycoord) != 0)
{
printf("Trouble with text '%s', line %d\n", text.c_str(), __LINE__);
}
return vec2(xcoord, ycoord);
}
GLuint TextObject ( const std::string& font, const std::string& text, float size )
{
TextEntry* entry = GetEntry(font, text, size);
assert(entry);
entry->lastUse = GameTime();
return entry->texID;
}
void Prune ()
{
float time = GameTime();
for (TextEntryTable::iterator iter = textEntries.begin(); iter != textEntries.end(); iter++)
{
if (time - iter->second->lastUse > 14.0f) // text objects expire in 14 seconds
{
delete iter->second;
textEntries.erase(iter);
return; // difficulties arise here with the iterator once erased, might as well just prune one per pass
}
}
}
void Flush ()
{
for (TextEntryTable::iterator iter = textEntries.begin(); iter != textEntries.end(); iter++)
{
delete iter->second;
}
textEntries.clear();
}
}
}
<commit_msg>Fixed panels to draw at a fixed size. (all content of panels has been temporarily removed until I can adjust it) The panels are also now using the transparent variety.<commit_after>#include "TextRenderer.h"
#ifdef WIN32
#include <gl/gl.h>
#include <SDL/SDL_ttf.h>
#else
#include <OpenGL/gl.h>
#include <SDL_ttf/SDL_ttf.h>
#endif
#include <SDL/SDL.h>
#include "Apollo.h"
#include <map>
#include "Utilities/ResourceManager.h"
#include "Utilities/GameTime.h"
#include "Logging.h"
namespace
{
uint32_t Hash ( const std::string& input )
{
uint32_t base = 0xBAADF00D;
uint32_t a = 0, b = 0x8D470010;
const unsigned char* data = (const unsigned char*)input.data();
size_t len = input.length();
for (size_t i = 0; i < len; i++)
{
a <<= 5;
b ^= data[i];
a ^= b;
base ^= a;
a += b;
if (i != 0)
a ^= (data[i - 1] << 16);
}
return b ^ a;
}
struct TextEntry
{
uint32_t hash;
SDL_Surface* surface;
GLuint texID;
float lastUse;
~TextEntry ()
{
SDL_FreeSurface(surface);
if (texID)
glDeleteTextures(1, &texID);
}
};
typedef std::map<uint32_t, TextEntry*> TextEntryTable;
TextEntryTable textEntries;
std::map<std::string, TTF_Font*> fonts;
#define DEFAULT_FONT "prototype"
static bool ttf_initted = false;
// [ADAM, ALISTAIR]: this is where size affects things... how would we figure out how to correct the size?
TTF_Font* GetFont ( const std::string& name, float size )
{
if (!ttf_initted)
{
TTF_Init();
ttf_initted = true;
}
std::map<std::string, TTF_Font*>::iterator iter = fonts.find(name);
if (iter != fonts.end())
{
return iter->second;
}
SDL_RWops* rwops = ResourceManager::OpenFile("Fonts/" + name + ".ttf");
TTF_Font* loadedFont;
if (!rwops)
goto loadFail;
loadedFont = TTF_OpenFontRW(rwops, 1, size);
if (!loadedFont)
goto loadFail;
fonts[name] = loadedFont;
return loadedFont;
loadFail:
if (name == DEFAULT_FONT)
{
LOG("Graphics::TextRenderer", LOG_ERROR, "Unable to load default font: %s", DEFAULT_FONT);
exit(1);
}
loadedFont = GetFont(DEFAULT_FONT, size);
fonts[name] = loadedFont;
LOG("Graphics::TextRenderer", LOG_WARNING, "Unable to load font '%s', defaulted to '%s'", name.c_str(), DEFAULT_FONT);
return loadedFont;
}
TextEntry* GetEntry ( const std::string& font, const std::string& text, float size )
{
uint32_t hash = Hash(font + "@" + text);
TextEntryTable::iterator iter;
iter = textEntries.find(hash);
if (iter != textEntries.end())
{
return iter->second;
}
else
{
TextEntry* newEntry = new TextEntry;
newEntry->hash = hash;
newEntry->texID = 0;
newEntry->surface = NULL;
newEntry->lastUse = 0.0f;
TTF_Font* fontObject = GetFont(font, size);
const SDL_Color fg = { 0xFF, 0xFF, 0xFF, 0xFF };
newEntry->surface = TTF_RenderUTF8_Blended(fontObject, text.c_str(), fg);
assert(newEntry->surface);
// generate textures
glGenTextures(1, &(newEntry->texID));
glBindTexture(GL_TEXTURE_RECTANGLE_ARB, newEntry->texID);
#ifdef __BIG_ENDIAN__
glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, GL_RGBA, newEntry->surface->w, newEntry->surface->h, 0, GL_ABGR_EXT, GL_UNSIGNED_BYTE, newEntry->surface->pixels);
#else
glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, GL_RGBA, newEntry->surface->w, newEntry->surface->h, 0, GL_RGBA, GL_UNSIGNED_BYTE, newEntry->surface->pixels);
#endif
textEntries[hash] = newEntry;
return newEntry;
}
}
}
namespace Graphics
{
namespace TextRenderer
{
vec2 TextDimensions ( const std::string& font, const std::string& text, float size )
{
int xcoord = 0;
int ycoord = 0;
TTF_Font* fontObject = GetFont(font, size);
if (TTF_SizeUTF8(fontObject, text.c_str(), &xcoord, &ycoord) != 0)
{
printf("Trouble with text '%s', line %d\n", text.c_str(), __LINE__);
}
return vec2(xcoord, ycoord);
}
GLuint TextObject ( const std::string& font, const std::string& text, float size )
{
TextEntry* entry = GetEntry(font, text, size);
assert(entry);
entry->lastUse = GameTime();
return entry->texID;
}
void Prune ()
{
float time = GameTime();
for (TextEntryTable::iterator iter = textEntries.begin(); iter != textEntries.end(); iter++)
{
if (time - iter->second->lastUse > 14.0f) // text objects expire in 14 seconds
{
delete iter->second;
textEntries.erase(iter);
return; // difficulties arise here with the iterator once erased, might as well just prune one per pass
}
}
}
void Flush ()
{
for (TextEntryTable::iterator iter = textEntries.begin(); iter != textEntries.end(); iter++)
{
delete iter->second;
}
textEntries.clear();
}
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2011 ARM Limited
* All rights reserved.
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Copyright (c) 2002-2005 The Regents of The University of Michigan
* Copyright (c) 2009 The University of Edinburgh
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders 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.
*
* Authors: Gabe Black
* Timothy M. Jones
*/
#ifndef __CPU_TRANSLATION_HH__
#define __CPU_TRANSLATION_HH__
#include "sim/faults.hh"
#include "sim/tlb.hh"
/**
* This class captures the state of an address translation. A translation
* can be split in two if the ISA supports it and the memory access crosses
* a page boundary. In this case, this class is shared by two data
* translations (below). Otherwise it is used by a single data translation
* class. When each part of the translation is finished, the finish
* function is called which will indicate whether the whole translation is
* completed or not. There are also functions for accessing parts of the
* translation state which deal with the possible split correctly.
*/
class WholeTranslationState
{
protected:
int outstanding;
Fault faults[2];
public:
bool delay;
bool isSplit;
RequestPtr mainReq;
RequestPtr sreqLow;
RequestPtr sreqHigh;
uint8_t *data;
uint64_t *res;
BaseTLB::Mode mode;
/**
* Single translation state. We set the number of outstanding
* translations to one and indicate that it is not split.
*/
WholeTranslationState(RequestPtr _req, uint8_t *_data, uint64_t *_res,
BaseTLB::Mode _mode)
: outstanding(1), delay(false), isSplit(false), mainReq(_req),
sreqLow(NULL), sreqHigh(NULL), data(_data), res(_res), mode(_mode)
{
faults[0] = faults[1] = NoFault;
assert(mode == BaseTLB::Read || mode == BaseTLB::Write);
}
/**
* Split translation state. We copy all state into this class, set the
* number of outstanding translations to two and then mark this as a
* split translation.
*/
WholeTranslationState(RequestPtr _req, RequestPtr _sreqLow,
RequestPtr _sreqHigh, uint8_t *_data, uint64_t *_res,
BaseTLB::Mode _mode)
: outstanding(2), delay(false), isSplit(true), mainReq(_req),
sreqLow(_sreqLow), sreqHigh(_sreqHigh), data(_data), res(_res),
mode(_mode)
{
faults[0] = faults[1] = NoFault;
assert(mode == BaseTLB::Read || mode == BaseTLB::Write);
}
/**
* Finish part of a translation. If there is only one request then this
* translation is completed. If the request has been split in two then
* the outstanding count determines whether the translation is complete.
* In this case, flags from the split request are copied to the main
* request to make it easier to access them later on.
*/
bool
finish(Fault fault, int index)
{
assert(outstanding);
faults[index] = fault;
outstanding--;
if (isSplit && outstanding == 0) {
// For ease later, we copy some state to the main request.
if (faults[0] == NoFault) {
mainReq->setPaddr(sreqLow->getPaddr());
}
mainReq->setFlags(sreqLow->getFlags());
mainReq->setFlags(sreqHigh->getFlags());
}
return outstanding == 0;
}
/**
* Determine whether this translation produced a fault. Both parts of the
* translation must be checked if this is a split translation.
*/
Fault
getFault() const
{
if (!isSplit)
return faults[0];
else if (faults[0] != NoFault)
return faults[0];
else if (faults[1] != NoFault)
return faults[1];
else
return NoFault;
}
/** Remove all faults from the translation. */
void
setNoFault()
{
faults[0] = faults[1] = NoFault;
}
/**
* Check if this request is uncacheable. We only need to check the main
* request because the flags will have been copied here on a split
* translation.
*/
bool
isUncacheable() const
{
return mainReq->isUncacheable();
}
/**
* Check if this request is a prefetch. We only need to check the main
* request because the flags will have been copied here on a split
* translation.
*/
bool
isPrefetch() const
{
return mainReq->isPrefetch();
}
/** Get the physical address of this request. */
Addr
getPaddr() const
{
return mainReq->getPaddr();
}
/**
* Get the flags associated with this request. We only need to access
* the main request because the flags will have been copied here on a
* split translation.
*/
unsigned
getFlags()
{
return mainReq->getFlags();
}
/** Delete all requests that make up this translation. */
void
deleteReqs()
{
delete mainReq;
if (isSplit) {
delete sreqLow;
delete sreqHigh;
}
}
};
/**
* This class represents part of a data address translation. All state for
* the translation is held in WholeTranslationState (above). Therefore this
* class does not need to know whether the translation is split or not. The
* index variable determines this but is simply passed on to the state class.
* When this part of the translation is completed, finish is called. If the
* translation state class indicate that the whole translation is complete
* then the execution context is informed.
*/
template <class ExecContextPtr>
class DataTranslation : public BaseTLB::Translation
{
protected:
ExecContextPtr xc;
WholeTranslationState *state;
int index;
public:
DataTranslation(ExecContextPtr _xc, WholeTranslationState* _state)
: xc(_xc), state(_state), index(0)
{
}
DataTranslation(ExecContextPtr _xc, WholeTranslationState* _state,
int _index)
: xc(_xc), state(_state), index(_index)
{
}
/**
* Signal the translation state that the translation has been delayed due
* to a hw page table walk. Split requests are transparently handled.
*/
void
markDelayed()
{
state->delay = true;
}
/**
* Finish this part of the translation and indicate that the whole
* translation is complete if the state says so.
*/
void
finish(Fault fault, RequestPtr req, ThreadContext *tc,
BaseTLB::Mode mode)
{
assert(state);
assert(mode == state->mode);
if (state->finish(fault, index)) {
xc->finishTranslation(state);
req->setTranslateLatency();
}
delete this;
}
bool
squashed() const
{
return xc->isSquashed();
}
};
#endif // __CPU_TRANSLATION_HH__
<commit_msg>cpu: Fix setTranslateLatency() bug for squashed instructions<commit_after>/*
* Copyright (c) 2011 ARM Limited
* All rights reserved.
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Copyright (c) 2002-2005 The Regents of The University of Michigan
* Copyright (c) 2009 The University of Edinburgh
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders 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.
*
* Authors: Gabe Black
* Timothy M. Jones
*/
#ifndef __CPU_TRANSLATION_HH__
#define __CPU_TRANSLATION_HH__
#include "sim/faults.hh"
#include "sim/tlb.hh"
/**
* This class captures the state of an address translation. A translation
* can be split in two if the ISA supports it and the memory access crosses
* a page boundary. In this case, this class is shared by two data
* translations (below). Otherwise it is used by a single data translation
* class. When each part of the translation is finished, the finish
* function is called which will indicate whether the whole translation is
* completed or not. There are also functions for accessing parts of the
* translation state which deal with the possible split correctly.
*/
class WholeTranslationState
{
protected:
int outstanding;
Fault faults[2];
public:
bool delay;
bool isSplit;
RequestPtr mainReq;
RequestPtr sreqLow;
RequestPtr sreqHigh;
uint8_t *data;
uint64_t *res;
BaseTLB::Mode mode;
/**
* Single translation state. We set the number of outstanding
* translations to one and indicate that it is not split.
*/
WholeTranslationState(RequestPtr _req, uint8_t *_data, uint64_t *_res,
BaseTLB::Mode _mode)
: outstanding(1), delay(false), isSplit(false), mainReq(_req),
sreqLow(NULL), sreqHigh(NULL), data(_data), res(_res), mode(_mode)
{
faults[0] = faults[1] = NoFault;
assert(mode == BaseTLB::Read || mode == BaseTLB::Write);
}
/**
* Split translation state. We copy all state into this class, set the
* number of outstanding translations to two and then mark this as a
* split translation.
*/
WholeTranslationState(RequestPtr _req, RequestPtr _sreqLow,
RequestPtr _sreqHigh, uint8_t *_data, uint64_t *_res,
BaseTLB::Mode _mode)
: outstanding(2), delay(false), isSplit(true), mainReq(_req),
sreqLow(_sreqLow), sreqHigh(_sreqHigh), data(_data), res(_res),
mode(_mode)
{
faults[0] = faults[1] = NoFault;
assert(mode == BaseTLB::Read || mode == BaseTLB::Write);
}
/**
* Finish part of a translation. If there is only one request then this
* translation is completed. If the request has been split in two then
* the outstanding count determines whether the translation is complete.
* In this case, flags from the split request are copied to the main
* request to make it easier to access them later on.
*/
bool
finish(Fault fault, int index)
{
assert(outstanding);
faults[index] = fault;
outstanding--;
if (isSplit && outstanding == 0) {
// For ease later, we copy some state to the main request.
if (faults[0] == NoFault) {
mainReq->setPaddr(sreqLow->getPaddr());
}
mainReq->setFlags(sreqLow->getFlags());
mainReq->setFlags(sreqHigh->getFlags());
}
return outstanding == 0;
}
/**
* Determine whether this translation produced a fault. Both parts of the
* translation must be checked if this is a split translation.
*/
Fault
getFault() const
{
if (!isSplit)
return faults[0];
else if (faults[0] != NoFault)
return faults[0];
else if (faults[1] != NoFault)
return faults[1];
else
return NoFault;
}
/** Remove all faults from the translation. */
void
setNoFault()
{
faults[0] = faults[1] = NoFault;
}
/**
* Check if this request is uncacheable. We only need to check the main
* request because the flags will have been copied here on a split
* translation.
*/
bool
isUncacheable() const
{
return mainReq->isUncacheable();
}
/**
* Check if this request is a prefetch. We only need to check the main
* request because the flags will have been copied here on a split
* translation.
*/
bool
isPrefetch() const
{
return mainReq->isPrefetch();
}
/** Get the physical address of this request. */
Addr
getPaddr() const
{
return mainReq->getPaddr();
}
/**
* Get the flags associated with this request. We only need to access
* the main request because the flags will have been copied here on a
* split translation.
*/
unsigned
getFlags()
{
return mainReq->getFlags();
}
/** Delete all requests that make up this translation. */
void
deleteReqs()
{
delete mainReq;
if (isSplit) {
delete sreqLow;
delete sreqHigh;
}
}
};
/**
* This class represents part of a data address translation. All state for
* the translation is held in WholeTranslationState (above). Therefore this
* class does not need to know whether the translation is split or not. The
* index variable determines this but is simply passed on to the state class.
* When this part of the translation is completed, finish is called. If the
* translation state class indicate that the whole translation is complete
* then the execution context is informed.
*/
template <class ExecContextPtr>
class DataTranslation : public BaseTLB::Translation
{
protected:
ExecContextPtr xc;
WholeTranslationState *state;
int index;
public:
DataTranslation(ExecContextPtr _xc, WholeTranslationState* _state)
: xc(_xc), state(_state), index(0)
{
}
DataTranslation(ExecContextPtr _xc, WholeTranslationState* _state,
int _index)
: xc(_xc), state(_state), index(_index)
{
}
/**
* Signal the translation state that the translation has been delayed due
* to a hw page table walk. Split requests are transparently handled.
*/
void
markDelayed()
{
state->delay = true;
}
/**
* Finish this part of the translation and indicate that the whole
* translation is complete if the state says so.
*/
void
finish(Fault fault, RequestPtr req, ThreadContext *tc,
BaseTLB::Mode mode)
{
assert(state);
assert(mode == state->mode);
if (state->finish(fault, index)) {
if (state->getFault() == NoFault) {
// Don't access the request if faulted (due to squash)
req->setTranslateLatency();
}
xc->finishTranslation(state);
}
delete this;
}
bool
squashed() const
{
return xc->isSquashed();
}
};
#endif // __CPU_TRANSLATION_HH__
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2008-2016 the MRtrix3 contributors
*
* 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/
*
* MRtrix is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* For more details, see www.mrtrix.org
*
*/
#include "app.h"
#include "progressbar.h"
#ifdef MRTRIX_WINDOWS
# define CLEAR_LINE_CODE
#else
# define CLEAR_LINE_CODE "\033[0K"
#endif
namespace MR
{
extern bool __need_newline;
namespace
{
const char* busy[] = {
". ",
" . ",
" . ",
" .",
" . ",
" . "
};
void display_func_terminal (ProgressInfo& p)
{
__need_newline = true;
if (p.multiplier)
__print_stderr (printf ("\r%s: [%3zu%%] %s%s" CLEAR_LINE_CODE,
App::NAME.c_str(), p.value, p.text.c_str(), p.ellipsis.c_str()));
else
__print_stderr (printf ("\r%s: [%s] %s%s" CLEAR_LINE_CODE,
App::NAME.c_str(), busy[p.value%6], p.text.c_str(), p.ellipsis.c_str()));
}
void done_func_terminal (ProgressInfo& p)
{
if (p.multiplier)
__print_stderr (printf ("\r%s: [100%%] %s" CLEAR_LINE_CODE "\n",
App::NAME.c_str(), p.text.c_str()));
else
__print_stderr (printf ("\r%s: [done] %s" CLEAR_LINE_CODE "\n",
App::NAME.c_str(), p.text.c_str()));
__need_newline = false;
}
void display_func_redirect (ProgressInfo& p)
{
static size_t next_update_at = 0;
// need to update whole line since text may have changed:
if (p.text_has_been_modified) {
__need_newline = false;
if (p.value == 0)
next_update_at = 0;
// only update for zero or power of two (to reduce frequency of updates):
if (p.value == next_update_at) {
if (p.multiplier) {
__print_stderr (printf ("%s: [%3zu%%] %s%s\n",
App::NAME.c_str(), p.value, p.text.c_str(), p.ellipsis.c_str()));;
}
else {
__print_stderr (printf ("%s: [%s] %s%s\n",
App::NAME.c_str(), busy[p.value%6], p.text.c_str(), p.ellipsis.c_str()));
}
if (next_update_at)
next_update_at *= 2;
else
next_update_at = 1;
}
}
// text is static - can simply append to the current line:
else {
__need_newline = true;
if (p.multiplier) {
if (p.value == 0) {
__print_stderr (printf ("%s: %s%s [",
App::NAME.c_str(), p.text.c_str(), p.ellipsis.c_str()));;
}
else if (p.value%2 == 0) {
__print_stderr (printf ("="));
}
}
else {
if (p.value == 0) {
__print_stderr (printf ("%s: %s%s ",
App::NAME.c_str(), p.text.c_str(), p.ellipsis.c_str()));;
}
else if (!(p.value & (p.value-1))) {
__print_stderr (".");
}
}
}
}
void done_func_redirect (ProgressInfo& p)
{
if (p.text_has_been_modified) {
if (p.multiplier) {
__print_stderr (printf ("%s: [100%%] %s\n", App::NAME.c_str(), p.text.c_str()));;
}
else {
__print_stderr (printf ("%s: [done] %s\n", App::NAME.c_str(), p.text.c_str()));
}
}
else {
if (p.multiplier)
__print_stderr (printf ("]\n"));
else
__print_stderr (printf (" done\n"));
}
__need_newline = false;
}
}
void (*ProgressInfo::display_func) (ProgressInfo& p) = display_func_terminal;
void (*ProgressInfo::done_func) (ProgressInfo& p) = done_func_terminal;
bool ProgressBar::set_update_method ()
{
bool stderr_to_file = false;
struct stat buf;
if (fstat (STDERR_FILENO, &buf)) {
DEBUG ("Unable to determine nature of stderr; assuming socket");
stderr_to_file = false;
}
else
stderr_to_file = S_ISREG (buf.st_mode);
if (stderr_to_file) {
ProgressInfo::display_func = display_func_redirect;
ProgressInfo::done_func = done_func_redirect;
}
else {
ProgressInfo::display_func = display_func_terminal;
ProgressInfo::done_func = done_func_terminal;
}
return stderr_to_file;
}
}
<commit_msg>IO redirect handling: minor modification<commit_after>/*
* Copyright (c) 2008-2016 the MRtrix3 contributors
*
* 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/
*
* MRtrix is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* For more details, see www.mrtrix.org
*
*/
#include "app.h"
#include "progressbar.h"
#ifdef MRTRIX_WINDOWS
# define CLEAR_LINE_CODE
#else
# define CLEAR_LINE_CODE "\033[0K"
#endif
namespace MR
{
extern bool __need_newline;
namespace
{
const char* busy[] = {
". ",
" . ",
" . ",
" .",
" . ",
" . "
};
void display_func_terminal (ProgressInfo& p)
{
__need_newline = true;
if (p.multiplier)
__print_stderr (printf ("\r%s: [%3zu%%] %s%s" CLEAR_LINE_CODE,
App::NAME.c_str(), p.value, p.text.c_str(), p.ellipsis.c_str()));
else
__print_stderr (printf ("\r%s: [%s] %s%s" CLEAR_LINE_CODE,
App::NAME.c_str(), busy[p.value%6], p.text.c_str(), p.ellipsis.c_str()));
}
void done_func_terminal (ProgressInfo& p)
{
if (p.multiplier)
__print_stderr (printf ("\r%s: [100%%] %s" CLEAR_LINE_CODE "\n",
App::NAME.c_str(), p.text.c_str()));
else
__print_stderr (printf ("\r%s: [done] %s" CLEAR_LINE_CODE "\n",
App::NAME.c_str(), p.text.c_str()));
__need_newline = false;
}
void display_func_redirect (ProgressInfo& p)
{
static size_t count = 0;
static size_t next_update_at = 0;
// need to update whole line since text may have changed:
if (p.text_has_been_modified) {
__need_newline = false;
if (p.value == 0 && p.current_val == 0)
count = next_update_at = 0;
if (count++ == next_update_at) {
if (p.multiplier) {
__print_stderr (printf ("%s: [%3zu%%] %s%s\n",
App::NAME.c_str(), p.value, p.text.c_str(), p.ellipsis.c_str()));;
}
else {
__print_stderr (printf ("%s: [%s] %s%s\n",
App::NAME.c_str(), busy[p.value%6], p.text.c_str(), p.ellipsis.c_str()));
}
if (next_update_at)
next_update_at *= 2;
else
next_update_at = 1;
}
}
// text is static - can simply append to the current line:
else {
__need_newline = true;
if (p.multiplier) {
if (p.value == 0) {
__print_stderr (printf ("%s: %s%s [",
App::NAME.c_str(), p.text.c_str(), p.ellipsis.c_str()));;
}
else if (p.value%2 == 0) {
__print_stderr (printf ("="));
}
}
else {
if (p.value == 0) {
__print_stderr (printf ("%s: %s%s ",
App::NAME.c_str(), p.text.c_str(), p.ellipsis.c_str()));;
}
else if (!(p.value & (p.value-1))) {
__print_stderr (".");
}
}
}
}
void done_func_redirect (ProgressInfo& p)
{
if (p.text_has_been_modified) {
if (p.multiplier) {
__print_stderr (printf ("%s: [100%%] %s\n", App::NAME.c_str(), p.text.c_str()));;
}
else {
__print_stderr (printf ("%s: [done] %s\n", App::NAME.c_str(), p.text.c_str()));
}
}
else {
if (p.multiplier)
__print_stderr (printf ("]\n"));
else
__print_stderr (printf (" done\n"));
}
__need_newline = false;
}
}
void (*ProgressInfo::display_func) (ProgressInfo& p) = display_func_terminal;
void (*ProgressInfo::done_func) (ProgressInfo& p) = done_func_terminal;
bool ProgressBar::set_update_method ()
{
bool stderr_to_file = false;
struct stat buf;
if (fstat (STDERR_FILENO, &buf)) {
DEBUG ("Unable to determine nature of stderr; assuming socket");
stderr_to_file = false;
}
else
stderr_to_file = S_ISREG (buf.st_mode);
if (stderr_to_file) {
ProgressInfo::display_func = display_func_redirect;
ProgressInfo::done_func = done_func_redirect;
}
else {
ProgressInfo::display_func = display_func_terminal;
ProgressInfo::done_func = done_func_terminal;
}
return stderr_to_file;
}
}
<|endoftext|> |
<commit_before>// -*- mode:C++; tab-width:4; c-basic-offset:4; indent-tabs-mode:nil -*-
//Copyright: Universidad Carlos III de Madrid (C) 2016
//Authors: jgvictores, raulfdzbis, smorante
#include "CgdaExecutionIET.hpp"
namespace teo
{
/************************************************************************/
bool CgdaExecutionIET::init() {
timespec tsStart; //Start first timer
clock_gettime(CLOCK_REALTIME, &tsStart);
portNum = -1;
bool open = false;
while( ! open )
{
portNum++;
std::string s("/good");
std::stringstream ss;
ss << portNum;
s.append(ss.str());
open = port.open(s);
}
std::stringstream ss;
ss << portNum;
//-- MENTAL ROBOT ARM
yarp::os::Property mentalOptions;
mentalOptions.put("device","remote_controlboard");
std::string remoteMental("/");
remoteMental.append( ss.str() );
remoteMental.append( "/teoSim/rightArm" );
mentalOptions.put("remote",remoteMental);
std::string localMental("/cgdaMental/");
localMental.append( ss.str() );
localMental.append( "/teoSim/rightArm" );
mentalOptions.put("local",localMental);
mentalDevice.open(mentalOptions);
if(!mentalDevice.isValid()) {
CD_ERROR("Mental robot device not available.\n");
mentalDevice.close();
yarp::os::Network::fini();
return 1;
}
CD_SUCCESS("Mental robot device available.\n");
// //-- REAL ROBOT ARM
// yarp::os::Property realOptions;
// realOptions.put("device","remote_controlboard");
// std::string realRemote;
// bool realRealRemote = true;
// if( realRealRemote )
// {
// realRemote.append( "/teo/rightArm" );
// }
// else
// {
// realRemote.append( "/1/teoSim/rightArm" );
// }
// realOptions.put("remote",realRemote);
// std::string realLocal("/cgdaReal/");
// realLocal.append( ss.str() );
// realLocal.append( "/teo/rightArm" );
// realOptions.put("local",realLocal);
// realDevice.open(realOptions);
// if(!realDevice.isValid()) {
// CD_ERROR("Real robot device not available.\n");
// realDevice.close();
// yarp::os::Network::fini();
// return 1;
// }
// CD_SUCCESS("Real robot device available.\n");
//-- Paint server
std::string remotePaint("/");
remotePaint.append( ss.str() );
remotePaint.append( "/openraveYarpPaintSquares/rpc:s" );
std::string localPaint("/cgda/");
localPaint.append( ss.str() );
localPaint.append( "/openraveYarpPaintSquares/rpc:c" );
rpcClient.open(localPaint);
do {
yarp::os::Network::connect(localPaint,remotePaint);
printf("Wait to connect to paint server...\n");
yarp::os::Time::delay(DEFAULT_DELAY_S);
} while( rpcClient.getOutputCount() == 0 );
CD_SUCCESS("Paint server available.\n");
CD_SUCCESS("----- All good for %d.\n",portNum);
vector< double > results;
vector< double >* presults= &results;
//int const_evaluations;
//int* pconst_evaluations= &const_evaluations;
//*pconst_evaluations=0;
double evaluations;
double fit;
double ev_time_n[NTPOINTS];
int ev_time_s[NTPOINTS];
for(unsigned int i=0; i<NTPOINTS; i++) {
timespec tsEvStart; //Start second timer
clock_gettime(CLOCK_REALTIME, &tsEvStart);
StateP state (new State);
//PSOInheritance
// PSOInheritanceP nalg1 = (PSOInheritanceP) new PSOInheritance;
// state->addAlgorithm(nalg1);
// //PSOFuzzy
// PSOFuzzyP nalg2 = (PSOFuzzyP) new PSOFuzzy;
// state->addAlgorithm(nalg2);
// //ConstrainedSST
// ConstrainedSSTP nalg3 = (ConstrainedSSTP) new ConstrainedSST;
// state->addAlgorithm(nalg3);
// set the evaluation operator
CgdaPaintFitnessFunction* functionMinEvalOp = new CgdaPaintFitnessFunction;
//CgdaWaxFitnessFunction* functionMinEvalOp = new CgdaWaxFitnessFunction;
//Constrained Cost functions
//CgdaConstrainedPaintFitnessFunction* functionMinEvalOp = new CgdaConstrainedPaintFitnessFunction;
//CgdaConstrainedWaxFitnessFunction* functionMinEvalOp = new CgdaConstrainedWaxFitnessFunction;
//functionMinEvalOp->setEvaluations(pconst_evaluations); //Uncomment only if CgdaFitnessFunction is uncomment
mentalDevice.view(functionMinEvalOp->mentalPositionControl);
functionMinEvalOp->setPRpcClient(&rpcClient);
functionMinEvalOp->setResults(presults);
//Uncomment only for CgdaConstrained
state->setEvalOp(functionMinEvalOp);
unsigned int* pIter= &i;
functionMinEvalOp->setIter(pIter);
printf("---------------------------> i:%d\n",i);
int newArgc = 2;
//PAINT
char *newArgv[2] = { (char*)"unusedFirstParam", "../../programs/cgdaExecutionIET/conf/evMono_ecf_params.xml" };
//WAX
//char *newArgv[2] = { (char*)"unusedFirstParam", "../../programs/cgdaExecutionIET/conf/evMono_ecf_params_WAX.xml" };
state->initialize(newArgc, newArgv);
state->run();
vector<IndividualP> bestInd;
FloatingPoint::FloatingPoint* genBest;
vector<double> bestPoints;
bestInd = state->getHoF()->getBest();
genBest = (FloatingPoint::FloatingPoint*) bestInd.at(0)->getGenotype().get();
bestPoints = genBest->realValue;
results.push_back(bestPoints[0]);
results.push_back(bestPoints[1]);
results.push_back(bestPoints[2]);
evaluations+=state->getEvaluations(); // Evaluations is the sum of all the evluations for each iter.
fit=bestInd[0]->fitness->getValue(); //Fit current gen.
// std::cout<<"EL NUMERO DE EVALUACIONES ES::::"<<const_evaluations<<std::endl;
// nalg1.reset();
// nalg2.reset();
// nalg3.reset();
state.reset();
delete functionMinEvalOp;
timespec tsEvEnd;
clock_gettime(CLOCK_REALTIME, &tsEvEnd);
ev_time_n[i]=(tsEvEnd.tv_nsec-tsEvStart.tv_nsec);
ev_time_n[i]=ev_time_n[i]/1000000000;
ev_time_s[i]=(tsEvEnd.tv_sec-tsEvStart.tv_sec);
}
std::vector<double> percentage;
CgdaPaintFitnessFunction* functionMinEvalOp = new CgdaPaintFitnessFunction;
percentage=functionMinEvalOp->trajectoryExecution(results);
//Total time
double total_time=0;
timespec tsEnd;
clock_gettime(CLOCK_REALTIME, &tsEnd);
total_time=(tsEnd.tv_sec-tsStart.tv_sec);
std::cout<<"TOTAL TIME IS: "<<total_time<<std::endl;
//*******************************************************************************************//
// FILE OUTPUT FOR DEBUGGING //
//*******************************************************************************************//
std::cout<<std::endl<<"THE TOTAL NUMBER OF EVALUATIONS IS: "<<evaluations<<std::endl;
std::ofstream myfile1;
myfile1.open("DataIET.txt", std::ios_base::app);
if (myfile1.is_open()){
myfile1<<"0: ";
myfile1<<evaluations<<" ";
myfile1<<fit<<" "; //Take only the fit of the last gen.
for(int i=0; i<NTPOINTS;i++){
myfile1<<percentage[i]<<" ";
}
for(int i=0; i<NTPOINTS;i++){
if(ev_time_s[i]==0){
myfile1<<ev_time_n[i]<<" ";
}
else{
myfile1<<ev_time_s[i]<<" ";
}
}
myfile1<<total_time<<" "<<std::endl;
}
// std::ofstream myfile2;
// myfile2.open("PercentageWall.txt", std::ios_base::app);
// if (myfile2.is_open()){
// myfile2<<std::endl;
// }
// std::ofstream myfile3;
// myfile3.open("X.txt", std::ios_base::app);
// if (myfile3.is_open()){
// myfile3<<std::endl;
// }
// std::ofstream myfile4;
// myfile4.open("Y.txt", std::ios_base::app);
// if (myfile4.is_open()){
// myfile4<<std::endl;
// }
// std::ofstream myfile5;
// myfile5.open("Z.txt", std::ios_base::app);
// if (myfile5.is_open()){
// myfile5<<std::endl;
// }
//*******************************************************************************************//
//*******************************************************************************************//
// END //
//*******************************************************************************************//
printf("-begin-\n");
for(unsigned int i=0;i<results.size();i++) printf("%f, ",results[i]);
printf("\n-end-\n");
return true;
}
/************************************************************************/
} //namespace TEO
<commit_msg>Changed IET to work without parallel simulations<commit_after>// -*- mode:C++; tab-width:4; c-basic-offset:4; indent-tabs-mode:nil -*-
//Copyright: Universidad Carlos III de Madrid (C) 2016
//Authors: jgvictores, raulfdzbis, smorante
#include "CgdaExecutionIET.hpp"
namespace teo
{
/************************************************************************/
bool CgdaExecutionIET::init() {
timespec tsStart; //Start first timer
clock_gettime(CLOCK_REALTIME, &tsStart);
// portNum = -1;
// bool open = false;
// while( ! open )
// {
// portNum++;
// std::string s("/good");
// std::stringstream ss;
// ss << portNum;
// s.append(ss.str());
// open = port.open(s);
// }
// std::stringstream ss;
// ss << portNum;
//-- MENTAL ROBOT ARM
yarp::os::Property mentalOptions;
mentalOptions.put("device","remote_controlboard");
//std::string remoteMental("/");
//remoteMental.append( ss.str() );
//remoteMental.append( "/teoSim/rightArm" );
std::string remoteMental( "/teoSim/rightArm" );
mentalOptions.put("remote",remoteMental);
std::string localMental("/cgdaMental");
//localMental.append( ss.str() );
localMental.append( "/teoSim/rightArm" );
mentalOptions.put("local",localMental);
mentalDevice.open(mentalOptions);
if(!mentalDevice.isValid()) {
CD_ERROR("Mental robot device not available.\n");
mentalDevice.close();
yarp::os::Network::fini();
return 1;
}
CD_SUCCESS("Mental robot device available.\n");
// //-- REAL ROBOT ARM
// yarp::os::Property realOptions;
// realOptions.put("device","remote_controlboard");
// std::string realRemote;
// bool realRealRemote = true;
// if( realRealRemote )
// {
// realRemote.append( "/teo/rightArm" );
// }
// else
// {
// realRemote.append( "/1/teoSim/rightArm" );
// }
// realOptions.put("remote",realRemote);
// std::string realLocal("/cgdaReal/");
// realLocal.append( ss.str() );
// realLocal.append( "/teo/rightArm" );
// realOptions.put("local",realLocal);
// realDevice.open(realOptions);
// if(!realDevice.isValid()) {
// CD_ERROR("Real robot device not available.\n");
// realDevice.close();
// yarp::os::Network::fini();
// return 1;
// }
// CD_SUCCESS("Real robot device available.\n");
//-- Paint server
//std::string remotePaint("/");
//remotePaint.append( ss.str() );
//remotePaint.append( "/openraveYarpPaintSquares/rpc:s" );
std::string remotePaint( "/openraveYarpPaintSquares/rpc:s" );
std::string localPaint("/cgda");
//localPaint.append( ss.str() );
localPaint.append( "/openraveYarpPaintSquares/rpc:c" );
rpcClient.open(localPaint);
do {
yarp::os::Network::connect(localPaint,remotePaint);
printf("Wait to connect to paint server...\n");
yarp::os::Time::delay(DEFAULT_DELAY_S);
} while( rpcClient.getOutputCount() == 0 );
CD_SUCCESS("Paint server available.\n");
CD_SUCCESS("----- All good for %d.\n",portNum);
vector< double > results;
vector< double >* presults= &results;
//int const_evaluations;
//int* pconst_evaluations= &const_evaluations;
//*pconst_evaluations=0;
double evaluations;
double fit;
double ev_time_n[NTPOINTS];
int ev_time_s[NTPOINTS];
for(unsigned int i=0; i<NTPOINTS; i++) {
timespec tsEvStart; //Start second timer
clock_gettime(CLOCK_REALTIME, &tsEvStart);
StateP state (new State);
//PSOInheritance
// PSOInheritanceP nalg1 = (PSOInheritanceP) new PSOInheritance;
// state->addAlgorithm(nalg1);
// //PSOFuzzy
// PSOFuzzyP nalg2 = (PSOFuzzyP) new PSOFuzzy;
// state->addAlgorithm(nalg2);
// //ConstrainedSST
// ConstrainedSSTP nalg3 = (ConstrainedSSTP) new ConstrainedSST;
// state->addAlgorithm(nalg3);
// set the evaluation operator
CgdaPaintFitnessFunction* functionMinEvalOp = new CgdaPaintFitnessFunction;
//CgdaWaxFitnessFunction* functionMinEvalOp = new CgdaWaxFitnessFunction;
//Constrained Cost functions
//CgdaConstrainedPaintFitnessFunction* functionMinEvalOp = new CgdaConstrainedPaintFitnessFunction;
//CgdaConstrainedWaxFitnessFunction* functionMinEvalOp = new CgdaConstrainedWaxFitnessFunction;
//functionMinEvalOp->setEvaluations(pconst_evaluations); //Uncomment only if CgdaFitnessFunction is uncomment
mentalDevice.view(functionMinEvalOp->mentalPositionControl);
functionMinEvalOp->setPRpcClient(&rpcClient);
functionMinEvalOp->setResults(presults);
//Uncomment only for CgdaConstrained
state->setEvalOp(functionMinEvalOp);
unsigned int* pIter= &i;
functionMinEvalOp->setIter(pIter);
printf("---------------------------> i:%d\n",i);
int newArgc = 2;
//PAINT
char *newArgv[2] = { (char*)"unusedFirstParam", "../../programs/cgdaExecutionIET/conf/evMono_ecf_params.xml" };
//WAX
//char *newArgv[2] = { (char*)"unusedFirstParam", "../../programs/cgdaExecutionIET/conf/evMono_ecf_params_WAX.xml" };
state->initialize(newArgc, newArgv);
state->run();
vector<IndividualP> bestInd;
FloatingPoint::FloatingPoint* genBest;
vector<double> bestPoints;
bestInd = state->getHoF()->getBest();
genBest = (FloatingPoint::FloatingPoint*) bestInd.at(0)->getGenotype().get();
bestPoints = genBest->realValue;
results.push_back(bestPoints[0]);
results.push_back(bestPoints[1]);
results.push_back(bestPoints[2]);
evaluations+=state->getEvaluations(); // Evaluations is the sum of all the evluations for each iter.
fit=bestInd[0]->fitness->getValue(); //Fit current gen.
// std::cout<<"EL NUMERO DE EVALUACIONES ES::::"<<const_evaluations<<std::endl;
// nalg1.reset();
// nalg2.reset();
// nalg3.reset();
state.reset();
delete functionMinEvalOp;
timespec tsEvEnd;
clock_gettime(CLOCK_REALTIME, &tsEvEnd);
ev_time_n[i]=(tsEvEnd.tv_nsec-tsEvStart.tv_nsec);
ev_time_n[i]=ev_time_n[i]/1000000000;
ev_time_s[i]=(tsEvEnd.tv_sec-tsEvStart.tv_sec);
}
std::vector<double> percentage;
CgdaPaintFitnessFunction* functionMinEvalOp = new CgdaPaintFitnessFunction;
percentage=functionMinEvalOp->trajectoryExecution(results);
//Total time
double total_time=0;
timespec tsEnd;
clock_gettime(CLOCK_REALTIME, &tsEnd);
total_time=(tsEnd.tv_sec-tsStart.tv_sec);
std::cout<<"TOTAL TIME IS: "<<total_time<<std::endl;
//*******************************************************************************************//
// FILE OUTPUT FOR DEBUGGING //
//*******************************************************************************************//
std::cout<<std::endl<<"THE TOTAL NUMBER OF EVALUATIONS IS: "<<evaluations<<std::endl;
std::ofstream myfile1;
myfile1.open("DataIET.txt", std::ios_base::app);
if (myfile1.is_open()){
myfile1<<"0: ";
myfile1<<evaluations<<" ";
myfile1<<fit<<" "; //Take only the fit of the last gen.
for(int i=0; i<NTPOINTS;i++){
myfile1<<percentage[i]<<" ";
}
for(int i=0; i<NTPOINTS;i++){
if(ev_time_s[i]==0){
myfile1<<ev_time_n[i]<<" ";
}
else{
myfile1<<ev_time_s[i]<<" ";
}
}
myfile1<<total_time<<" "<<std::endl;
}
// std::ofstream myfile2;
// myfile2.open("PercentageWall.txt", std::ios_base::app);
// if (myfile2.is_open()){
// myfile2<<std::endl;
// }
// std::ofstream myfile3;
// myfile3.open("X.txt", std::ios_base::app);
// if (myfile3.is_open()){
// myfile3<<std::endl;
// }
// std::ofstream myfile4;
// myfile4.open("Y.txt", std::ios_base::app);
// if (myfile4.is_open()){
// myfile4<<std::endl;
// }
// std::ofstream myfile5;
// myfile5.open("Z.txt", std::ios_base::app);
// if (myfile5.is_open()){
// myfile5<<std::endl;
// }
//*******************************************************************************************//
//*******************************************************************************************//
// END //
//*******************************************************************************************//
printf("-begin-\n");
for(unsigned int i=0;i<results.size();i++) printf("%f, ",results[i]);
printf("\n-end-\n");
return true;
}
/************************************************************************/
} //namespace TEO
<|endoftext|> |
<commit_before>/*
* (C) 2002 Jack Lloyd
*
* Distributed under the terms of the Botan license
*/
/*
Generate an RSA key of a specified bitlength, and put it into a pair of key
files. One is the public key in X.509 format (PEM encoded), the private key is
in PKCS #8 format (also PEM encoded).
*/
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include <memory>
#include <botan/botan.h>
#include <botan/rsa.h>
using namespace Botan;
int main(int argc, char* argv[])
{
if(argc != 2 && argc != 3)
{
std::cout << "Usage: " << argv[0] << " bitsize [passphrase]"
<< std::endl;
return 1;
}
u32bit bits = std::atoi(argv[1]);
if(bits < 1024 || bits > 4096)
{
std::cout << "Invalid argument for bitsize" << std::endl;
return 1;
}
Botan::LibraryInitializer init;
std::ofstream pub("rsapub.pem");
std::ofstream priv("rsapriv.pem");
if(!priv || !pub)
{
std::cout << "Couldn't write output files" << std::endl;
return 1;
}
try
{
AutoSeeded_RNG rng;
RSA_PrivateKey key(rng, bits);
pub << X509::PEM_encode(key);
if(argc == 2)
priv << PKCS8::PEM_encode(key);
else
priv << PKCS8::PEM_encode(key, rng, argv[2]);
}
catch(std::exception& e)
{
std::cout << "Exception caught: " << e.what() << std::endl;
}
return 0;
}
<commit_msg>Allow generating larger keys in rsa_kgen example (up to 16K bits)<commit_after>/*
* (C) 2002 Jack Lloyd
*
* Distributed under the terms of the Botan license
*/
/*
Generate an RSA key of a specified bitlength, and put it into a pair of key
files. One is the public key in X.509 format (PEM encoded), the private key is
in PKCS #8 format (also PEM encoded).
*/
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include <memory>
#include <botan/botan.h>
#include <botan/rsa.h>
using namespace Botan;
int main(int argc, char* argv[])
{
if(argc != 2 && argc != 3)
{
std::cout << "Usage: " << argv[0] << " bitsize [passphrase]"
<< std::endl;
return 1;
}
u32bit bits = std::atoi(argv[1]);
if(bits < 1024 || bits > 16384)
{
std::cout << "Invalid argument for bitsize" << std::endl;
return 1;
}
Botan::LibraryInitializer init;
std::ofstream pub("rsapub.pem");
std::ofstream priv("rsapriv.pem");
if(!priv || !pub)
{
std::cout << "Couldn't write output files" << std::endl;
return 1;
}
try
{
AutoSeeded_RNG rng;
RSA_PrivateKey key(rng, bits);
pub << X509::PEM_encode(key);
if(argc == 2)
priv << PKCS8::PEM_encode(key);
else
priv << PKCS8::PEM_encode(key, rng, argv[2]);
}
catch(std::exception& e)
{
std::cout << "Exception caught: " << e.what() << std::endl;
}
return 0;
}
<|endoftext|> |
<commit_before>#pragma once
#include <string>
#include <algorithm>
#include "gsl/span.hpp"
#include "gsl/assert.hpp"
namespace cryptic::base64 {
inline constexpr char to_character_set(std::byte b)
{
assert(b < std::byte{65});
constexpr char set[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
return set[std::to_integer<std::size_t>(b)];
}
inline constexpr char to_index(char c)
{
assert((c >= 'A' and c <= 'Z') or
(c >= 'a' and c <= 'z') or
(c >= '0' and c <= '9') or
c == '+' or c == '/' or c == '=');
if(c == '=') return 64;
if(c >= 'a') return ('Z'-'A') + 1 + (c - 'a');
if(c >= 'A') return (c - 'A');
if(c >= '0') return ('Z'-'A') + ('z'-'a') + 2 + (c - '0');
if(c == '+') return 62;
if(c == '/') return 63;
return 64;
}
inline std::string encode(gsl::span<const std::byte> source)
{
auto encoded = std::string{};
while(source.size() > 0)
{
auto index1 = (source[0] bitand std::byte{0b11111100}) >> 2,
index2 = (source[0] bitand std::byte{0b00000011}) << 4,
index3 = std::byte{64},
index4 = std::byte{64};
if(source.size() > 1)
{
index2 |= (source[1] bitand std::byte{0b11110000}) >> 4;
index3 = (source[1] bitand std::byte{0b00001111}) << 2;
}
if(source.size() > 2)
{
index3 |= (source[2] bitand std::byte{0b11000000}) >> 6;
index4 = (source[2] bitand std::byte{0b00111111});
}
encoded.push_back(to_character_set(index1));
encoded.push_back(to_character_set(index2));
encoded.push_back(to_character_set(index3));
encoded.push_back(to_character_set(index4));
source = source.subspan(std::min(3l,source.size()));
}
return encoded;
}
inline std::string decode(std::string_view source)
{
auto decoded = std::string{};
while(source.size() > 3)
{
auto index1 = to_index(source[0]),
index2 = to_index(source[1]),
index3 = to_index(source[2]),
index4 = to_index(source[3]);
decoded.push_back((index1 << 2) | (index2 >> 4));
if(index3 < 64)
decoded.push_back((index2 << 4) | (index3 >> 2));
if(index4 < 64)
decoded.push_back((index3 << 6) | index4);
source.remove_prefix(std::min(4ul,source.size()));
}
return decoded;
}
} // namespace http::base64
<commit_msg>assert -> Ensures<commit_after>#pragma once
#include <string>
#include <algorithm>
#include "gsl/span.hpp"
namespace cryptic::base64 {
inline constexpr char to_character_set(std::byte b)
{
Ensures(b < std::byte{65});
constexpr char set[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
return set[std::to_integer<std::size_t>(b)];
}
inline constexpr char to_index(char c)
{
Ensures((c >= 'A' and c <= 'Z') or
(c >= 'a' and c <= 'z') or
(c >= '0' and c <= '9') or
c == '+' or c == '/' or c == '=');
if(c == '=') return 64;
if(c >= 'a') return ('Z'-'A') + 1 + (c - 'a');
if(c >= 'A') return (c - 'A');
if(c >= '0') return ('Z'-'A') + ('z'-'a') + 2 + (c - '0');
if(c == '+') return 62;
if(c == '/') return 63;
return 64;
}
inline std::string encode(gsl::span<const std::byte> source)
{
auto encoded = std::string{};
while(source.size() > 0)
{
auto index1 = (source[0] bitand std::byte{0b11111100}) >> 2,
index2 = (source[0] bitand std::byte{0b00000011}) << 4,
index3 = std::byte{64},
index4 = std::byte{64};
if(source.size() > 1)
{
index2 |= (source[1] bitand std::byte{0b11110000}) >> 4;
index3 = (source[1] bitand std::byte{0b00001111}) << 2;
}
if(source.size() > 2)
{
index3 |= (source[2] bitand std::byte{0b11000000}) >> 6;
index4 = (source[2] bitand std::byte{0b00111111});
}
encoded.push_back(to_character_set(index1));
encoded.push_back(to_character_set(index2));
encoded.push_back(to_character_set(index3));
encoded.push_back(to_character_set(index4));
source = source.subspan(std::min(3l,source.size()));
}
return encoded;
}
inline std::string decode(std::string_view source)
{
auto decoded = std::string{};
while(source.size() > 3)
{
auto index1 = to_index(source[0]),
index2 = to_index(source[1]),
index3 = to_index(source[2]),
index4 = to_index(source[3]);
decoded.push_back((index1 << 2) | (index2 >> 4));
if(index3 < 64)
decoded.push_back((index2 << 4) | (index3 >> 2));
if(index4 < 64)
decoded.push_back((index3 << 6) | index4);
source.remove_prefix(std::min(4ul,source.size()));
}
return decoded;
}
} // namespace http::base64
<|endoftext|> |
<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// author: Baozeng Ding <sploving1@gmail.com>
// author: Vassil Vassilev <vasil.georgiev.vasilev@cern.ch>
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------
#include "NullDerefProtectionTransformer.h"
#include "cling/Interpreter/Interpreter.h"
#include "cling/Utils/AST.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/AST/Expr.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Sema/Lookup.h"
#include <bitset>
using namespace clang;
namespace {
using namespace cling;
class PointerCheckInjector : public RecursiveASTVisitor<PointerCheckInjector> {
private:
Interpreter& m_Interp;
Sema& m_Sema;
typedef llvm::DenseMap<clang::FunctionDecl*, std::bitset<32> > decl_map_t;
llvm::DenseMap<clang::FunctionDecl*, std::bitset<32> > m_NonNullArgIndexs;
///\brief Needed for the AST transformations, owned by Sema.
///
ASTContext& m_Context;
///\brief cling_runtime_internal_throwIfInvalidPointer cache.
///
LookupResult* m_clingthrowIfInvalidPointerCache;
public:
PointerCheckInjector(Interpreter& I)
: m_Interp(I), m_Sema(I.getCI()->getSema()),
m_Context(I.getCI()->getASTContext()),
m_clingthrowIfInvalidPointerCache(0) {}
~PointerCheckInjector() {
delete m_clingthrowIfInvalidPointerCache;
}
bool VisitUnaryOperator(UnaryOperator* UnOp) {
Expr* SubExpr = UnOp->getSubExpr();
VisitStmt(SubExpr);
if (UnOp->getOpcode() == UO_Deref
&& !llvm::isa<clang::CXXThisExpr>(SubExpr)
&& SubExpr->getType().getTypePtr()->isPointerType())
UnOp->setSubExpr(SynthesizeCheck(SubExpr));
return true;
}
bool VisitMemberExpr(MemberExpr* ME) {
Expr* Base = ME->getBase();
VisitStmt(Base);
if (ME->isArrow()
&& !llvm::isa<clang::CXXThisExpr>(Base)
&& ME->getMemberDecl()->isCXXInstanceMember())
ME->setBase(SynthesizeCheck(Base));
return true;
}
bool VisitCallExpr(CallExpr* CE) {
VisitStmt(CE->getCallee());
FunctionDecl* FDecl = CE->getDirectCallee();
if (FDecl && isDeclCandidate(FDecl)) {
decl_map_t::const_iterator it = m_NonNullArgIndexs.find(FDecl);
const std::bitset<32>& ArgIndexs = it->second;
Sema::ContextRAII pushedDC(m_Sema, FDecl);
for (int index = 0; index < 32; ++index) {
if (ArgIndexs.test(index)) {
// Get the argument with the nonnull attribute.
Expr* Arg = CE->getArg(index);
if (Arg->getType().getTypePtr()->isPointerType()
&& !llvm::isa<clang::CXXThisExpr>(Arg))
CE->setArg(index, SynthesizeCheck(Arg));
}
}
}
return true;
}
bool TraverseFunctionDecl(FunctionDecl* FD) {
// We cannot synthesize when there is a const expr
// and if it is a function template (we will do the transformation on
// the instance).
if (!FD->isConstexpr() && !FD->getDescribedFunctionTemplate())
RecursiveASTVisitor::TraverseFunctionDecl(FD);
return true;
}
bool TraverseCXXMethodDecl(CXXMethodDecl* CXXMD) {
// We cannot synthesize when there is a const expr.
if (!CXXMD->isConstexpr())
RecursiveASTVisitor::TraverseCXXMethodDecl(CXXMD);
return true;
}
private:
Expr* SynthesizeCheck(Expr* Arg) {
assert(Arg && "Cannot call with Arg=0");
if(!m_clingthrowIfInvalidPointerCache)
FindAndCacheRuntimeLookupResult();
SourceLocation Loc = Arg->getLocStart();
Expr* VoidSemaArg = utils::Synthesize::CStyleCastPtrExpr(&m_Sema,
m_Context.VoidPtrTy,
(uintptr_t)&m_Interp);
Expr* VoidExprArg = utils::Synthesize::CStyleCastPtrExpr(&m_Sema,
m_Context.VoidPtrTy,
(uintptr_t)Arg);
Scope* S = m_Sema.getScopeForContext(m_Sema.CurContext);
CXXScopeSpec CSS;
Expr* checkCall
= m_Sema.BuildDeclarationNameExpr(CSS,
*m_clingthrowIfInvalidPointerCache,
/*ADL*/ false).get();
const clang::FunctionProtoType* checkCallType
= llvm::dyn_cast<const clang::FunctionProtoType>(
checkCall->getType().getTypePtr());
TypeSourceInfo* constVoidPtrTSI = m_Context.getTrivialTypeSourceInfo(
checkCallType->getParamType(2), Loc);
// It is unclear whether this is the correct cast if the type
// is dependent. Hence, For now, we do not expect SynthesizeCheck to
// be run on a function template. It should be run only on function
// instances.
// When this is actually insert in a function template, it seems that
// clang r272382 when instantiating the templates drops one of the part
// of the implicit cast chain.
// Namely in:
/*
`-ImplicitCastExpr 0x1010cea90 <col:4> 'const void *' <BitCast>
`-ImplicitCastExpr 0x1026e0bc0 <col:4> 'const class TAttMarker *'
<UncheckedDerivedToBase (TAttMarker)>
`-ImplicitCastExpr 0x1026e0b48 <col:4> 'class TGraph *' <LValueToRValue>
`-DeclRefExpr 0x1026e0b20 <col:4> 'class TGraph *' lvalue Var 0x1026e09c0
'g5' 'class TGraph *'
*/
// It drops the 2nd lines (ImplicitCastExpr UncheckedDerivedToBase)
// clang r227800 seems to actually keep that lines during instantiation.
Expr* voidPtrArg
= m_Sema.BuildCStyleCastExpr(Loc, constVoidPtrTSI, Loc, Arg).get();
Expr *args[] = {VoidSemaArg, VoidExprArg, voidPtrArg};
if (Expr* call = m_Sema.ActOnCallExpr(S, checkCall,
Loc, args, Loc).get())
{
// It is unclear whether this is the correct cast if the type
// is dependent. Hence, For now, we do not expect SynthesizeCheck to
// be run on a function template. It should be run only on function
// instances.
clang::TypeSourceInfo* argTSI = m_Context.getTrivialTypeSourceInfo(
Arg->getType(), Loc);
Expr* castExpr = m_Sema.BuildCStyleCastExpr(Loc, argTSI,
Loc, call).get();
return castExpr;
}
return voidPtrArg;
}
bool isDeclCandidate(FunctionDecl * FDecl) {
if (m_NonNullArgIndexs.count(FDecl))
return true;
if (llvm::isa<CXXRecordDecl>(FDecl))
return true;
std::bitset<32> ArgIndexs;
for (specific_attr_iterator<NonNullAttr>
I = FDecl->specific_attr_begin<NonNullAttr>(),
E = FDecl->specific_attr_end<NonNullAttr>(); I != E; ++I) {
NonNullAttr *NonNull = *I;
for (NonNullAttr::args_iterator i = NonNull->args_begin(),
e = NonNull->args_end(); i != e; ++i) {
ArgIndexs.set(*i);
}
}
if (ArgIndexs.any()) {
m_NonNullArgIndexs.insert(std::make_pair(FDecl, ArgIndexs));
return true;
}
return false;
}
void FindAndCacheRuntimeLookupResult() {
assert(!m_clingthrowIfInvalidPointerCache && "Called multiple times!?");
DeclarationName Name
= &m_Context.Idents.get("cling_runtime_internal_throwIfInvalidPointer");
SourceLocation noLoc;
m_clingthrowIfInvalidPointerCache = new LookupResult(m_Sema, Name, noLoc,
Sema::LookupOrdinaryName,
Sema::ForRedeclaration);
m_Sema.LookupQualifiedName(*m_clingthrowIfInvalidPointerCache,
m_Context.getTranslationUnitDecl());
assert(!m_clingthrowIfInvalidPointerCache->empty() &&
"Lookup of cling_runtime_internal_throwIfInvalidPointer failed!");
}
};
}
namespace cling {
NullDerefProtectionTransformer::NullDerefProtectionTransformer(Interpreter* I)
: ASTTransformer(&I->getCI()->getSema()), m_Interp(I) {
}
NullDerefProtectionTransformer::~NullDerefProtectionTransformer()
{ }
bool NullDerefProtectionTransformer::shouldTransform(const clang::Decl* D) {
if (D->isFromASTFile())
return false;
if (D->isTemplateDecl())
return false;
auto Loc = D->getLocation();
if (Loc.isInvalid())
return false;
SourceManager& SM = m_Interp->getSema().getSourceManager();
auto FID = SM.getFileID(Loc);
if (FID.isInvalid())
return false;
auto FE = SM.getFileEntryForID(FID);
if (!FE)
return false;
auto Dir = FE->getDir();
if (!Dir)
return false;
auto IterAndInserted = m_ShouldVisitDir.try_emplace(Dir, true);
if (IterAndInserted.second == false)
return IterAndInserted.first->second;
if (llvm::sys::fs::can_write(Dir->getName()))
return true; // `true` is already emplaced above.
// Remember that this dir is not writable and should not be visited.
IterAndInserted.first->second = false;
return false;
}
ASTTransformer::Result
NullDerefProtectionTransformer::Transform(clang::Decl* D) {
if (getCompilationOpts().CheckPointerValidity && shouldTransform(D)) {
PointerCheckInjector injector(*m_Interp);
injector.TraverseDecl(D);
}
return Result(D, true);
}
} // end namespace cling
<commit_msg>[cling] Check file is C_User before hitting disk. Thanks, Vassil!<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// author: Baozeng Ding <sploving1@gmail.com>
// author: Vassil Vassilev <vasil.georgiev.vasilev@cern.ch>
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------
#include "NullDerefProtectionTransformer.h"
#include "cling/Interpreter/Interpreter.h"
#include "cling/Utils/AST.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/AST/Expr.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Sema/Lookup.h"
#include <bitset>
using namespace clang;
namespace {
using namespace cling;
class PointerCheckInjector : public RecursiveASTVisitor<PointerCheckInjector> {
private:
Interpreter& m_Interp;
Sema& m_Sema;
typedef llvm::DenseMap<clang::FunctionDecl*, std::bitset<32> > decl_map_t;
llvm::DenseMap<clang::FunctionDecl*, std::bitset<32> > m_NonNullArgIndexs;
///\brief Needed for the AST transformations, owned by Sema.
///
ASTContext& m_Context;
///\brief cling_runtime_internal_throwIfInvalidPointer cache.
///
LookupResult* m_clingthrowIfInvalidPointerCache;
public:
PointerCheckInjector(Interpreter& I)
: m_Interp(I), m_Sema(I.getCI()->getSema()),
m_Context(I.getCI()->getASTContext()),
m_clingthrowIfInvalidPointerCache(0) {}
~PointerCheckInjector() {
delete m_clingthrowIfInvalidPointerCache;
}
bool VisitUnaryOperator(UnaryOperator* UnOp) {
Expr* SubExpr = UnOp->getSubExpr();
VisitStmt(SubExpr);
if (UnOp->getOpcode() == UO_Deref
&& !llvm::isa<clang::CXXThisExpr>(SubExpr)
&& SubExpr->getType().getTypePtr()->isPointerType())
UnOp->setSubExpr(SynthesizeCheck(SubExpr));
return true;
}
bool VisitMemberExpr(MemberExpr* ME) {
Expr* Base = ME->getBase();
VisitStmt(Base);
if (ME->isArrow()
&& !llvm::isa<clang::CXXThisExpr>(Base)
&& ME->getMemberDecl()->isCXXInstanceMember())
ME->setBase(SynthesizeCheck(Base));
return true;
}
bool VisitCallExpr(CallExpr* CE) {
VisitStmt(CE->getCallee());
FunctionDecl* FDecl = CE->getDirectCallee();
if (FDecl && isDeclCandidate(FDecl)) {
decl_map_t::const_iterator it = m_NonNullArgIndexs.find(FDecl);
const std::bitset<32>& ArgIndexs = it->second;
Sema::ContextRAII pushedDC(m_Sema, FDecl);
for (int index = 0; index < 32; ++index) {
if (ArgIndexs.test(index)) {
// Get the argument with the nonnull attribute.
Expr* Arg = CE->getArg(index);
if (Arg->getType().getTypePtr()->isPointerType()
&& !llvm::isa<clang::CXXThisExpr>(Arg))
CE->setArg(index, SynthesizeCheck(Arg));
}
}
}
return true;
}
bool TraverseFunctionDecl(FunctionDecl* FD) {
// We cannot synthesize when there is a const expr
// and if it is a function template (we will do the transformation on
// the instance).
if (!FD->isConstexpr() && !FD->getDescribedFunctionTemplate())
RecursiveASTVisitor::TraverseFunctionDecl(FD);
return true;
}
bool TraverseCXXMethodDecl(CXXMethodDecl* CXXMD) {
// We cannot synthesize when there is a const expr.
if (!CXXMD->isConstexpr())
RecursiveASTVisitor::TraverseCXXMethodDecl(CXXMD);
return true;
}
private:
Expr* SynthesizeCheck(Expr* Arg) {
assert(Arg && "Cannot call with Arg=0");
if(!m_clingthrowIfInvalidPointerCache)
FindAndCacheRuntimeLookupResult();
SourceLocation Loc = Arg->getLocStart();
Expr* VoidSemaArg = utils::Synthesize::CStyleCastPtrExpr(&m_Sema,
m_Context.VoidPtrTy,
(uintptr_t)&m_Interp);
Expr* VoidExprArg = utils::Synthesize::CStyleCastPtrExpr(&m_Sema,
m_Context.VoidPtrTy,
(uintptr_t)Arg);
Scope* S = m_Sema.getScopeForContext(m_Sema.CurContext);
CXXScopeSpec CSS;
Expr* checkCall
= m_Sema.BuildDeclarationNameExpr(CSS,
*m_clingthrowIfInvalidPointerCache,
/*ADL*/ false).get();
const clang::FunctionProtoType* checkCallType
= llvm::dyn_cast<const clang::FunctionProtoType>(
checkCall->getType().getTypePtr());
TypeSourceInfo* constVoidPtrTSI = m_Context.getTrivialTypeSourceInfo(
checkCallType->getParamType(2), Loc);
// It is unclear whether this is the correct cast if the type
// is dependent. Hence, For now, we do not expect SynthesizeCheck to
// be run on a function template. It should be run only on function
// instances.
// When this is actually insert in a function template, it seems that
// clang r272382 when instantiating the templates drops one of the part
// of the implicit cast chain.
// Namely in:
/*
`-ImplicitCastExpr 0x1010cea90 <col:4> 'const void *' <BitCast>
`-ImplicitCastExpr 0x1026e0bc0 <col:4> 'const class TAttMarker *'
<UncheckedDerivedToBase (TAttMarker)>
`-ImplicitCastExpr 0x1026e0b48 <col:4> 'class TGraph *' <LValueToRValue>
`-DeclRefExpr 0x1026e0b20 <col:4> 'class TGraph *' lvalue Var 0x1026e09c0
'g5' 'class TGraph *'
*/
// It drops the 2nd lines (ImplicitCastExpr UncheckedDerivedToBase)
// clang r227800 seems to actually keep that lines during instantiation.
Expr* voidPtrArg
= m_Sema.BuildCStyleCastExpr(Loc, constVoidPtrTSI, Loc, Arg).get();
Expr *args[] = {VoidSemaArg, VoidExprArg, voidPtrArg};
if (Expr* call = m_Sema.ActOnCallExpr(S, checkCall,
Loc, args, Loc).get())
{
// It is unclear whether this is the correct cast if the type
// is dependent. Hence, For now, we do not expect SynthesizeCheck to
// be run on a function template. It should be run only on function
// instances.
clang::TypeSourceInfo* argTSI = m_Context.getTrivialTypeSourceInfo(
Arg->getType(), Loc);
Expr* castExpr = m_Sema.BuildCStyleCastExpr(Loc, argTSI,
Loc, call).get();
return castExpr;
}
return voidPtrArg;
}
bool isDeclCandidate(FunctionDecl * FDecl) {
if (m_NonNullArgIndexs.count(FDecl))
return true;
if (llvm::isa<CXXRecordDecl>(FDecl))
return true;
std::bitset<32> ArgIndexs;
for (specific_attr_iterator<NonNullAttr>
I = FDecl->specific_attr_begin<NonNullAttr>(),
E = FDecl->specific_attr_end<NonNullAttr>(); I != E; ++I) {
NonNullAttr *NonNull = *I;
for (NonNullAttr::args_iterator i = NonNull->args_begin(),
e = NonNull->args_end(); i != e; ++i) {
ArgIndexs.set(*i);
}
}
if (ArgIndexs.any()) {
m_NonNullArgIndexs.insert(std::make_pair(FDecl, ArgIndexs));
return true;
}
return false;
}
void FindAndCacheRuntimeLookupResult() {
assert(!m_clingthrowIfInvalidPointerCache && "Called multiple times!?");
DeclarationName Name
= &m_Context.Idents.get("cling_runtime_internal_throwIfInvalidPointer");
SourceLocation noLoc;
m_clingthrowIfInvalidPointerCache = new LookupResult(m_Sema, Name, noLoc,
Sema::LookupOrdinaryName,
Sema::ForRedeclaration);
m_Sema.LookupQualifiedName(*m_clingthrowIfInvalidPointerCache,
m_Context.getTranslationUnitDecl());
assert(!m_clingthrowIfInvalidPointerCache->empty() &&
"Lookup of cling_runtime_internal_throwIfInvalidPointer failed!");
}
};
}
namespace cling {
NullDerefProtectionTransformer::NullDerefProtectionTransformer(Interpreter* I)
: ASTTransformer(&I->getCI()->getSema()), m_Interp(I) {
}
NullDerefProtectionTransformer::~NullDerefProtectionTransformer()
{ }
bool NullDerefProtectionTransformer::shouldTransform(const clang::Decl* D) {
if (D->isFromASTFile())
return false;
if (D->isTemplateDecl())
return false;
auto Loc = D->getLocation();
if (Loc.isInvalid())
return false;
SourceManager& SM = m_Interp->getSema().getSourceManager();
auto Characteristic = SM.getFileCharacteristic(Loc);
if (Characteristic != clang::SrcMgr::C_User)
return false;
auto FID = SM.getFileID(Loc);
if (FID.isInvalid())
return false;
auto FE = SM.getFileEntryForID(FID);
if (!FE)
return false;
auto Dir = FE->getDir();
if (!Dir)
return false;
auto IterAndInserted = m_ShouldVisitDir.try_emplace(Dir, true);
if (IterAndInserted.second == false)
return IterAndInserted.first->second;
if (llvm::sys::fs::can_write(Dir->getName()))
return true; // `true` is already emplaced above.
// Remember that this dir is not writable and should not be visited.
IterAndInserted.first->second = false;
return false;
}
ASTTransformer::Result
NullDerefProtectionTransformer::Transform(clang::Decl* D) {
if (getCompilationOpts().CheckPointerValidity && shouldTransform(D)) {
PointerCheckInjector injector(*m_Interp);
injector.TraverseDecl(D);
}
return Result(D, true);
}
} // end namespace cling
<|endoftext|> |
<commit_before>#include "compiler.h"
#include <assert.h>
#include "ast.h"
#include "opcode.h"
class Emitter {
class Label {
public:
Label(): target(-1) {}
std::vector<int> fixups;
int target;
};
public:
void emit(unsigned char b);
void emit(const std::vector<unsigned char> &instr);
std::vector<unsigned char> getObject();
unsigned int global(const std::string &s);
unsigned int str(const std::string &s);
Label create_label();
void emit_jump(unsigned char b, Label &label);
void jump_target(Label &label);
private:
std::vector<unsigned char> code;
std::vector<std::string> strings;
std::vector<std::string> globals;
};
void Emitter::emit(unsigned char b)
{
code.push_back(b);
}
void Emitter::emit(const std::vector<unsigned char> &instr)
{
std::copy(instr.begin(), instr.end(), std::back_inserter(code));
}
std::vector<unsigned char> Emitter::getObject()
{
std::vector<unsigned char> strtable;
for (auto s: strings) {
std::copy(s.begin(), s.end(), std::back_inserter(strtable));
strtable.push_back(0);
}
std::vector<unsigned char> obj;
obj.push_back(strtable.size() >> 8);
obj.push_back(strtable.size());
std::copy(strtable.begin(), strtable.end(), std::back_inserter(obj));
std::copy(code.begin(), code.end(), std::back_inserter(obj));
return obj;
}
unsigned int Emitter::global(const std::string &s)
{
auto i = find(globals.begin(), globals.end(), s);
if (i == globals.end()) {
globals.push_back(s);
i = globals.end() - 1;
}
return i - globals.begin();
}
unsigned int Emitter::str(const std::string &s)
{
auto i = find(strings.begin(), strings.end(), s);
if (i == strings.end()) {
strings.push_back(s);
i = strings.end() - 1;
}
return i - strings.begin();
}
Emitter::Label Emitter::create_label()
{
return Label();
}
void Emitter::emit_jump(unsigned char b, Label &label)
{
emit(b);
if (label.target >= 0) {
emit(label.target >> 24);
emit(label.target >> 16);
emit(label.target >> 8);
emit(label.target);
} else {
label.fixups.push_back(code.size());
emit(0);
emit(0);
emit(0);
emit(0);
}
}
void Emitter::jump_target(Label &label)
{
assert(label.target < 0);
label.target = code.size();
for (auto offset: label.fixups) {
code[offset] = label.target >> 24;
code[offset+1] = label.target >> 16;
code[offset+2] = label.target >> 8;
code[offset+3] = label.target;
}
}
void ConstantExpression::generate(Emitter &emitter) const
{
emitter.emit(PUSHI);
emitter.emit(value >> 24);
emitter.emit(value >> 16);
emitter.emit(value >> 8);
emitter.emit(value);
}
void UnaryMinusExpression::generate(Emitter &emitter) const
{
value->generate(emitter);
emitter.emit(NEGI);
}
void AdditionExpression::generate(Emitter &emitter) const
{
left->generate(emitter);
right->generate(emitter);
emitter.emit(ADDI);
}
void SubtractionExpression::generate(Emitter &emitter) const
{
left->generate(emitter);
right->generate(emitter);
emitter.emit(SUBI);
}
void MultiplicationExpression::generate(Emitter &emitter) const
{
left->generate(emitter);
right->generate(emitter);
emitter.emit(MULI);
}
void DivisionExpression::generate(Emitter &emitter) const
{
left->generate(emitter);
right->generate(emitter);
emitter.emit(DIVI);
}
void ScalarVariableReference::generate(Emitter &emitter) const
{
unsigned int index = emitter.global(name);
emitter.emit(PUSHI);
emitter.emit(index >> 24);
emitter.emit(index >> 16);
emitter.emit(index >> 8);
emitter.emit(index);
}
void FunctionReference::generate(Emitter &emitter) const
{
unsigned int index = emitter.str(name);
emitter.emit(PUSHI);
emitter.emit(index >> 24);
emitter.emit(index >> 16);
emitter.emit(index >> 8);
emitter.emit(index);
}
void VariableExpression::generate(Emitter &emitter) const
{
var->generate(emitter);
emitter.emit(LOADI);
}
void FunctionCall::generate(Emitter &emitter) const
{
for (auto arg: args) {
arg->generate(emitter);
}
func->generate(emitter);
emitter.emit(CALL);
}
void AssignmentStatement::generate(Emitter &emitter) const
{
expr->generate(emitter);
variable->generate(emitter);
emitter.emit(STOREI);
}
void ExpressionStatement::generate(Emitter &emitter) const
{
expr->generate(emitter);
}
void IfStatement::generate(Emitter &emitter) const
{
condition->generate(emitter);
auto skip = emitter.create_label();
emitter.emit_jump(JZ, skip);
for (auto stmt: statements) {
stmt->generate(emitter);
}
emitter.jump_target(skip);
}
void WhileStatement::generate(Emitter &emitter) const
{
auto top = emitter.create_label();
emitter.jump_target(top);
condition->generate(emitter);
auto skip = emitter.create_label();
emitter.emit_jump(JZ, skip);
for (auto stmt: statements) {
stmt->generate(emitter);
}
emitter.emit_jump(JUMP, top);
emitter.jump_target(skip);
}
void Program::generate(Emitter &emitter) const
{
for (auto stmt: statements) {
stmt->generate(emitter);
}
}
std::vector<unsigned char> compile(const Program *p)
{
Emitter emitter;
p->generate(emitter);
return emitter.getObject();
}
<commit_msg>make members of label private<commit_after>#include "compiler.h"
#include <assert.h>
#include "ast.h"
#include "opcode.h"
class Emitter {
class Label {
friend class Emitter;
Label(): target(-1) {}
std::vector<int> fixups;
int target;
};
public:
void emit(unsigned char b);
void emit(const std::vector<unsigned char> &instr);
std::vector<unsigned char> getObject();
unsigned int global(const std::string &s);
unsigned int str(const std::string &s);
Label create_label();
void emit_jump(unsigned char b, Label &label);
void jump_target(Label &label);
private:
std::vector<unsigned char> code;
std::vector<std::string> strings;
std::vector<std::string> globals;
};
void Emitter::emit(unsigned char b)
{
code.push_back(b);
}
void Emitter::emit(const std::vector<unsigned char> &instr)
{
std::copy(instr.begin(), instr.end(), std::back_inserter(code));
}
std::vector<unsigned char> Emitter::getObject()
{
std::vector<unsigned char> strtable;
for (auto s: strings) {
std::copy(s.begin(), s.end(), std::back_inserter(strtable));
strtable.push_back(0);
}
std::vector<unsigned char> obj;
obj.push_back(strtable.size() >> 8);
obj.push_back(strtable.size());
std::copy(strtable.begin(), strtable.end(), std::back_inserter(obj));
std::copy(code.begin(), code.end(), std::back_inserter(obj));
return obj;
}
unsigned int Emitter::global(const std::string &s)
{
auto i = find(globals.begin(), globals.end(), s);
if (i == globals.end()) {
globals.push_back(s);
i = globals.end() - 1;
}
return i - globals.begin();
}
unsigned int Emitter::str(const std::string &s)
{
auto i = find(strings.begin(), strings.end(), s);
if (i == strings.end()) {
strings.push_back(s);
i = strings.end() - 1;
}
return i - strings.begin();
}
Emitter::Label Emitter::create_label()
{
return Label();
}
void Emitter::emit_jump(unsigned char b, Label &label)
{
emit(b);
if (label.target >= 0) {
emit(label.target >> 24);
emit(label.target >> 16);
emit(label.target >> 8);
emit(label.target);
} else {
label.fixups.push_back(code.size());
emit(0);
emit(0);
emit(0);
emit(0);
}
}
void Emitter::jump_target(Label &label)
{
assert(label.target < 0);
label.target = code.size();
for (auto offset: label.fixups) {
code[offset] = label.target >> 24;
code[offset+1] = label.target >> 16;
code[offset+2] = label.target >> 8;
code[offset+3] = label.target;
}
}
void ConstantExpression::generate(Emitter &emitter) const
{
emitter.emit(PUSHI);
emitter.emit(value >> 24);
emitter.emit(value >> 16);
emitter.emit(value >> 8);
emitter.emit(value);
}
void UnaryMinusExpression::generate(Emitter &emitter) const
{
value->generate(emitter);
emitter.emit(NEGI);
}
void AdditionExpression::generate(Emitter &emitter) const
{
left->generate(emitter);
right->generate(emitter);
emitter.emit(ADDI);
}
void SubtractionExpression::generate(Emitter &emitter) const
{
left->generate(emitter);
right->generate(emitter);
emitter.emit(SUBI);
}
void MultiplicationExpression::generate(Emitter &emitter) const
{
left->generate(emitter);
right->generate(emitter);
emitter.emit(MULI);
}
void DivisionExpression::generate(Emitter &emitter) const
{
left->generate(emitter);
right->generate(emitter);
emitter.emit(DIVI);
}
void ScalarVariableReference::generate(Emitter &emitter) const
{
unsigned int index = emitter.global(name);
emitter.emit(PUSHI);
emitter.emit(index >> 24);
emitter.emit(index >> 16);
emitter.emit(index >> 8);
emitter.emit(index);
}
void FunctionReference::generate(Emitter &emitter) const
{
unsigned int index = emitter.str(name);
emitter.emit(PUSHI);
emitter.emit(index >> 24);
emitter.emit(index >> 16);
emitter.emit(index >> 8);
emitter.emit(index);
}
void VariableExpression::generate(Emitter &emitter) const
{
var->generate(emitter);
emitter.emit(LOADI);
}
void FunctionCall::generate(Emitter &emitter) const
{
for (auto arg: args) {
arg->generate(emitter);
}
func->generate(emitter);
emitter.emit(CALL);
}
void AssignmentStatement::generate(Emitter &emitter) const
{
expr->generate(emitter);
variable->generate(emitter);
emitter.emit(STOREI);
}
void ExpressionStatement::generate(Emitter &emitter) const
{
expr->generate(emitter);
}
void IfStatement::generate(Emitter &emitter) const
{
condition->generate(emitter);
auto skip = emitter.create_label();
emitter.emit_jump(JZ, skip);
for (auto stmt: statements) {
stmt->generate(emitter);
}
emitter.jump_target(skip);
}
void WhileStatement::generate(Emitter &emitter) const
{
auto top = emitter.create_label();
emitter.jump_target(top);
condition->generate(emitter);
auto skip = emitter.create_label();
emitter.emit_jump(JZ, skip);
for (auto stmt: statements) {
stmt->generate(emitter);
}
emitter.emit_jump(JUMP, top);
emitter.jump_target(skip);
}
void Program::generate(Emitter &emitter) const
{
for (auto stmt: statements) {
stmt->generate(emitter);
}
}
std::vector<unsigned char> compile(const Program *p)
{
Emitter emitter;
p->generate(emitter);
return emitter.getObject();
}
<|endoftext|> |
<commit_before>/* -*- Mode: C++; c-basic-offset: 4; indent-tabs-mode: t; tab-width: 4 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public 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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Value-Profiling Utility.
*
* The Initial Developer of the Original Code is
* Intel Corporation.
* Portions created by the Initial Developer are Copyright (C) 2008
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Mohammad R. Haghighat [mohammad.r.haghighat@intel.com]
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "VMPI.h"
// Note, this is not supported in configurations with more than one AvmCore running
// in the same process.
#ifdef WIN32
#include "windows.h"
#else
#define __cdecl
#include <stdarg.h>
#include <string.h>
#endif
#include "vprof.h"
#define MIN(x,y) ((x) <= (y) ? x : y)
#define MAX(x,y) ((x) >= (y) ? x : y)
#ifndef MAXINT
#define MAXINT int(unsigned(-1)>>1)
#endif
#ifndef MAXINT64
#define MAXINT64 int64_t(uint64_t(-1)>>1)
#endif
#ifndef __STDC_WANT_SECURE_LIB__
#define sprintf_s(b,size,fmt,...) sprintf((b),(fmt),__VA_ARGS__)
#endif
#if THREADED
#define DO_LOCK(lock) Lock(lock); {
#define DO_UNLOCK(lock) }; Unlock(lock)
#else
#define DO_LOCK(lock) { (void)(lock);
#define DO_UNLOCK(lock) }
#endif
#if THREAD_SAFE
#define LOCK(lock) DO_LOCK(lock)
#define UNLOCK(lock) DO_UNLOCK(lock)
#else
#define LOCK(lock) { (void)(lock);
#define UNLOCK(lock) }
#endif
static entry* entries = NULL;
static bool notInitialized = true;
static long glock = LOCK_IS_FREE;
#define Lock(lock) while (_InterlockedCompareExchange(lock, LOCK_IS_TAKEN, LOCK_IS_FREE) == LOCK_IS_TAKEN){};
#define Unlock(lock) _InterlockedCompareExchange(lock, LOCK_IS_FREE, LOCK_IS_TAKEN);
#if defined(WIN32) && !defined(UNDER_CE)
static void vprof_printf(const char* format, ...)
{
va_list args;
va_start(args, format);
char buf[1024];
vsnprintf(buf, sizeof(buf), format, args);
va_end(args);
printf(buf);
::OutputDebugStringA(buf);
}
#else
#define vprof_printf printf
#endif
inline static entry* reverse (entry* s)
{
entry_t e, n, p;
p = NULL;
for (e = s; e; e = n) {
n = e->next;
e->next = p;
p = e;
}
return p;
}
static char* f (double d)
{
static char s[80];
char* p;
sprintf_s (s, sizeof(s), "%lf", d);
p = s+VMPI_strlen(s)-1;
while (*p == '0') {
*p = '\0';
p--;
if (p == s) break;
}
if (*p == '.') *p = '\0';
return s;
}
static void dumpProfile (void)
{
entry_t e;
entries = reverse(entries);
vprof_printf ("event avg [min : max] total count\n");
for (e = entries; e; e = e->next) {
if (e->count == 0) continue; // ignore entries with zero count.
vprof_printf ("%s", e->file);
if (e->line >= 0) {
vprof_printf (":%d", e->line);
}
vprof_printf (" %s [%lld : %lld] %lld %lld ",
f(((double)e->sum)/((double)e->count)), (long long int)e->min, (long long int)e->max, (long long int)e->sum, (long long int)e->count);
if (e->h) {
int j = MAXINT;
for (j = 0; j < e->h->nbins; j ++) {
vprof_printf ("(%lld < %lld) ", (long long int)e->h->count[j], (long long int)e->h->lb[j]);
}
vprof_printf ("(%lld >= %lld) ", (long long int)e->h->count[e->h->nbins], (long long int)e->h->lb[e->h->nbins-1]);
}
if (e->func) {
int j;
for (j = 0; j < NUM_EVARS; j++) {
if (e->ivar[j] != 0) {
vprof_printf ("IVAR%d %d ", j, e->ivar[j]);
}
}
for (j = 0; j < NUM_EVARS; j++) {
if (e->i64var[j] != 0) {
vprof_printf ("I64VAR%d %lld ", j, (long long int)e->i64var[j]);
}
}
for (j = 0; j < NUM_EVARS; j++) {
if (e->dvar[j] != 0) {
vprof_printf ("DVAR%d %lf ", j, e->dvar[j]);
}
}
}
vprof_printf ("\n");
}
entries = reverse(entries);
}
inline static entry_t findEntry (char* file, int line)
{
for (entry_t e = entries; e; e = e->next) {
if ((e->line == line) && (VMPI_strcmp (e->file, file) == 0)) {
return e;
}
}
return NULL;
}
// Initialize the location pointed to by 'id' to a new value profile entry
// associated with 'file' and 'line', or do nothing if already initialized.
// An optional final argument provides a user-defined probe function.
int initValueProfile(void** id, char* file, int line, ...)
{
DO_LOCK (&glock);
entry_t e = (entry_t) *id;
if (notInitialized) {
atexit (dumpProfile);
notInitialized = false;
}
if (e == NULL) {
e = findEntry (file, line);
if (e) {
*id = e;
}
}
if (e == NULL) {
va_list va;
e = (entry_t) malloc (sizeof(entry));
e->lock = LOCK_IS_FREE;
e->file = file;
e->line = line;
e->value = 0;
e->sum = 0;
e->count = 0;
e->min = 0;
e->max = 0;
// optional probe function argument
va_start (va, line);
e->func = (void (__cdecl*)(void*)) va_arg (va, void*);
va_end (va);
e->h = NULL;
e->genptr = NULL;
VMPI_memset (&e->ivar, 0, sizeof(e->ivar));
VMPI_memset (&e->i64var, 0, sizeof(e->i64var));
VMPI_memset (&e->dvar, 0, sizeof(e->dvar));
e->next = entries;
entries = e;
*id = e;
}
DO_UNLOCK (&glock);
return 0;
}
// Record a value profile event.
int profileValue(void* id, int64_t value)
{
entry_t e = (entry_t) id;
long* lock = &(e->lock);
LOCK (lock);
e->value = value;
if (e->count == 0) {
e->sum = value;
e->count = 1;
e->min = value;
e->max = value;
} else {
e->sum += value;
e->count ++;
e->min = MIN (e->min, value);
e->max = MAX (e->max, value);
}
if (e->func) e->func (e);
UNLOCK (lock);
return 0;
}
// Initialize the location pointed to by 'id' to a new histogram profile entry
// associated with 'file' and 'line', or do nothing if already initialized.
int initHistProfile(void** id, char* file, int line, int nbins, ...)
{
DO_LOCK (&glock);
entry_t e = (entry_t) *id;
if (notInitialized) {
atexit (dumpProfile);
notInitialized = false;
}
if (e == NULL) {
e = findEntry (file, line);
if (e) {
*id = e;
}
}
if (e == NULL) {
va_list va;
hist_t h;
int b, n, s;
int64_t* lb;
e = (entry_t) malloc (sizeof(entry));
e->lock = LOCK_IS_FREE;
e->file = file;
e->line = line;
e->value = 0;
e->sum = 0;
e->count = 0;
e->min = 0;
e->max = 0;
e->func = NULL;
e->h = h = (hist_t) malloc (sizeof(hist));
n = 1+MAX(nbins,0);
h->nbins = n-1;
s = n*sizeof(int64_t);
lb = (int64_t*) malloc (s);
h->lb = lb;
VMPI_memset (h->lb, 0, s);
h->count = (int64_t*) malloc (s);
VMPI_memset (h->count, 0, s);
va_start (va, nbins);
for (b = 0; b < nbins; b++) {
//lb[b] = va_arg (va, int64_t);
lb[b] = va_arg (va, int);
}
lb[b] = MAXINT64;
va_end (va);
e->genptr = NULL;
VMPI_memset (&e->ivar, 0, sizeof(e->ivar));
VMPI_memset (&e->i64var, 0, sizeof(e->i64var));
VMPI_memset (&e->dvar, 0, sizeof(e->dvar));
e->next = entries;
entries = e;
*id = e;
}
DO_UNLOCK (&glock);
return 0;
}
// Record a histogram profile event.
int histValue(void* id, int64_t value)
{
entry_t e = (entry_t) id;
long* lock = &(e->lock);
hist_t h = e->h;
int nbins = h->nbins;
int64_t* lb = h->lb;
int b;
LOCK (lock);
e->value = value;
if (e->count == 0) {
e->sum = value;
e->count = 1;
e->min = value;
e->max = value;
} else {
e->sum += value;
e->count ++;
e->min = MIN (e->min, value);
e->max = MAX (e->max, value);
}
for (b = 0; b < nbins; b ++) {
if (value < lb[b]) break;
}
h->count[b] ++;
UNLOCK (lock);
return 0;
}
#if defined(_MSC_VER) && defined(_M_IX86)
uint64_t readTimestampCounter()
{
// read the cpu cycle counter. 1 tick = 1 cycle on IA32
_asm rdtsc;
}
#elif defined(__GNUC__) && (__i386__ || __x86_64__)
uint64_t readTimestampCounter()
{
uint32_t lo, hi;
__asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
return (uint64_t(hi) << 32) | lo;
}
#else
// add stub for platforms without it, so fat builds don't fail
uint64_t readTimestampCounter() { return 0; }
#endif
<commit_msg>Bug 624442: ifndef-guard MIN/MAX macro definitions in vprof.cpp (r=fklockii)<commit_after>/* -*- Mode: C++; c-basic-offset: 4; indent-tabs-mode: t; tab-width: 4 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public 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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Value-Profiling Utility.
*
* The Initial Developer of the Original Code is
* Intel Corporation.
* Portions created by the Initial Developer are Copyright (C) 2008
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Mohammad R. Haghighat [mohammad.r.haghighat@intel.com]
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "VMPI.h"
// Note, this is not supported in configurations with more than one AvmCore running
// in the same process.
#ifdef WIN32
#include "windows.h"
#else
#define __cdecl
#include <stdarg.h>
#include <string.h>
#endif
#include "vprof.h"
#ifndef MIN
#define MIN(x,y) ((x) <= (y) ? x : y)
#endif
#ifndef MAX
#define MAX(x,y) ((x) >= (y) ? x : y)
#endif
#ifndef MAXINT
#define MAXINT int(unsigned(-1)>>1)
#endif
#ifndef MAXINT64
#define MAXINT64 int64_t(uint64_t(-1)>>1)
#endif
#ifndef __STDC_WANT_SECURE_LIB__
#define sprintf_s(b,size,fmt,...) sprintf((b),(fmt),__VA_ARGS__)
#endif
#if THREADED
#define DO_LOCK(lock) Lock(lock); {
#define DO_UNLOCK(lock) }; Unlock(lock)
#else
#define DO_LOCK(lock) { (void)(lock);
#define DO_UNLOCK(lock) }
#endif
#if THREAD_SAFE
#define LOCK(lock) DO_LOCK(lock)
#define UNLOCK(lock) DO_UNLOCK(lock)
#else
#define LOCK(lock) { (void)(lock);
#define UNLOCK(lock) }
#endif
static entry* entries = NULL;
static bool notInitialized = true;
static long glock = LOCK_IS_FREE;
#define Lock(lock) while (_InterlockedCompareExchange(lock, LOCK_IS_TAKEN, LOCK_IS_FREE) == LOCK_IS_TAKEN){};
#define Unlock(lock) _InterlockedCompareExchange(lock, LOCK_IS_FREE, LOCK_IS_TAKEN);
#if defined(WIN32) && !defined(UNDER_CE)
static void vprof_printf(const char* format, ...)
{
va_list args;
va_start(args, format);
char buf[1024];
vsnprintf(buf, sizeof(buf), format, args);
va_end(args);
printf(buf);
::OutputDebugStringA(buf);
}
#else
#define vprof_printf printf
#endif
inline static entry* reverse (entry* s)
{
entry_t e, n, p;
p = NULL;
for (e = s; e; e = n) {
n = e->next;
e->next = p;
p = e;
}
return p;
}
static char* f (double d)
{
static char s[80];
char* p;
sprintf_s (s, sizeof(s), "%lf", d);
p = s+VMPI_strlen(s)-1;
while (*p == '0') {
*p = '\0';
p--;
if (p == s) break;
}
if (*p == '.') *p = '\0';
return s;
}
static void dumpProfile (void)
{
entry_t e;
entries = reverse(entries);
vprof_printf ("event avg [min : max] total count\n");
for (e = entries; e; e = e->next) {
if (e->count == 0) continue; // ignore entries with zero count.
vprof_printf ("%s", e->file);
if (e->line >= 0) {
vprof_printf (":%d", e->line);
}
vprof_printf (" %s [%lld : %lld] %lld %lld ",
f(((double)e->sum)/((double)e->count)), (long long int)e->min, (long long int)e->max, (long long int)e->sum, (long long int)e->count);
if (e->h) {
int j = MAXINT;
for (j = 0; j < e->h->nbins; j ++) {
vprof_printf ("(%lld < %lld) ", (long long int)e->h->count[j], (long long int)e->h->lb[j]);
}
vprof_printf ("(%lld >= %lld) ", (long long int)e->h->count[e->h->nbins], (long long int)e->h->lb[e->h->nbins-1]);
}
if (e->func) {
int j;
for (j = 0; j < NUM_EVARS; j++) {
if (e->ivar[j] != 0) {
vprof_printf ("IVAR%d %d ", j, e->ivar[j]);
}
}
for (j = 0; j < NUM_EVARS; j++) {
if (e->i64var[j] != 0) {
vprof_printf ("I64VAR%d %lld ", j, (long long int)e->i64var[j]);
}
}
for (j = 0; j < NUM_EVARS; j++) {
if (e->dvar[j] != 0) {
vprof_printf ("DVAR%d %lf ", j, e->dvar[j]);
}
}
}
vprof_printf ("\n");
}
entries = reverse(entries);
}
inline static entry_t findEntry (char* file, int line)
{
for (entry_t e = entries; e; e = e->next) {
if ((e->line == line) && (VMPI_strcmp (e->file, file) == 0)) {
return e;
}
}
return NULL;
}
// Initialize the location pointed to by 'id' to a new value profile entry
// associated with 'file' and 'line', or do nothing if already initialized.
// An optional final argument provides a user-defined probe function.
int initValueProfile(void** id, char* file, int line, ...)
{
DO_LOCK (&glock);
entry_t e = (entry_t) *id;
if (notInitialized) {
atexit (dumpProfile);
notInitialized = false;
}
if (e == NULL) {
e = findEntry (file, line);
if (e) {
*id = e;
}
}
if (e == NULL) {
va_list va;
e = (entry_t) malloc (sizeof(entry));
e->lock = LOCK_IS_FREE;
e->file = file;
e->line = line;
e->value = 0;
e->sum = 0;
e->count = 0;
e->min = 0;
e->max = 0;
// optional probe function argument
va_start (va, line);
e->func = (void (__cdecl*)(void*)) va_arg (va, void*);
va_end (va);
e->h = NULL;
e->genptr = NULL;
VMPI_memset (&e->ivar, 0, sizeof(e->ivar));
VMPI_memset (&e->i64var, 0, sizeof(e->i64var));
VMPI_memset (&e->dvar, 0, sizeof(e->dvar));
e->next = entries;
entries = e;
*id = e;
}
DO_UNLOCK (&glock);
return 0;
}
// Record a value profile event.
int profileValue(void* id, int64_t value)
{
entry_t e = (entry_t) id;
long* lock = &(e->lock);
LOCK (lock);
e->value = value;
if (e->count == 0) {
e->sum = value;
e->count = 1;
e->min = value;
e->max = value;
} else {
e->sum += value;
e->count ++;
e->min = MIN (e->min, value);
e->max = MAX (e->max, value);
}
if (e->func) e->func (e);
UNLOCK (lock);
return 0;
}
// Initialize the location pointed to by 'id' to a new histogram profile entry
// associated with 'file' and 'line', or do nothing if already initialized.
int initHistProfile(void** id, char* file, int line, int nbins, ...)
{
DO_LOCK (&glock);
entry_t e = (entry_t) *id;
if (notInitialized) {
atexit (dumpProfile);
notInitialized = false;
}
if (e == NULL) {
e = findEntry (file, line);
if (e) {
*id = e;
}
}
if (e == NULL) {
va_list va;
hist_t h;
int b, n, s;
int64_t* lb;
e = (entry_t) malloc (sizeof(entry));
e->lock = LOCK_IS_FREE;
e->file = file;
e->line = line;
e->value = 0;
e->sum = 0;
e->count = 0;
e->min = 0;
e->max = 0;
e->func = NULL;
e->h = h = (hist_t) malloc (sizeof(hist));
n = 1+MAX(nbins,0);
h->nbins = n-1;
s = n*sizeof(int64_t);
lb = (int64_t*) malloc (s);
h->lb = lb;
VMPI_memset (h->lb, 0, s);
h->count = (int64_t*) malloc (s);
VMPI_memset (h->count, 0, s);
va_start (va, nbins);
for (b = 0; b < nbins; b++) {
//lb[b] = va_arg (va, int64_t);
lb[b] = va_arg (va, int);
}
lb[b] = MAXINT64;
va_end (va);
e->genptr = NULL;
VMPI_memset (&e->ivar, 0, sizeof(e->ivar));
VMPI_memset (&e->i64var, 0, sizeof(e->i64var));
VMPI_memset (&e->dvar, 0, sizeof(e->dvar));
e->next = entries;
entries = e;
*id = e;
}
DO_UNLOCK (&glock);
return 0;
}
// Record a histogram profile event.
int histValue(void* id, int64_t value)
{
entry_t e = (entry_t) id;
long* lock = &(e->lock);
hist_t h = e->h;
int nbins = h->nbins;
int64_t* lb = h->lb;
int b;
LOCK (lock);
e->value = value;
if (e->count == 0) {
e->sum = value;
e->count = 1;
e->min = value;
e->max = value;
} else {
e->sum += value;
e->count ++;
e->min = MIN (e->min, value);
e->max = MAX (e->max, value);
}
for (b = 0; b < nbins; b ++) {
if (value < lb[b]) break;
}
h->count[b] ++;
UNLOCK (lock);
return 0;
}
#if defined(_MSC_VER) && defined(_M_IX86)
uint64_t readTimestampCounter()
{
// read the cpu cycle counter. 1 tick = 1 cycle on IA32
_asm rdtsc;
}
#elif defined(__GNUC__) && (__i386__ || __x86_64__)
uint64_t readTimestampCounter()
{
uint32_t lo, hi;
__asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
return (uint64_t(hi) << 32) | lo;
}
#else
// add stub for platforms without it, so fat builds don't fail
uint64_t readTimestampCounter() { return 0; }
#endif
<|endoftext|> |
<commit_before>#include <string>
#include <vector>
#include "vtrc-server/vtrc-application.h"
#include "boost/program_options.hpp"
#include "boost/algorithm/string.hpp"
#include "vtrc-common/vtrc-pool-pair.h"
#include "vtrc-common/vtrc-rpc-service-wrapper.h"
#include "vtrc-server/vtrc-listener-tcp.h"
#include "vtrc-server/vtrc-listener-local.h"
namespace po = boost::program_options;
using namespace vtrc;
void get_options( po::options_description& desc )
{
desc.add_options( )
("help,?", "help message")
("server,s", po::value<std::vector< std::string> >( ),
"endpoint name; <tcp address>:<port> or <pipe/file name>")
("io-pool-size,i", po::value<unsigned>( ), "threads for io operations"
"; default = 1")
("rpc-pool-size,r", po::value<unsigned>( ), "threads for rpc calls"
"; default = 1")
;
}
server::listener_sptr create_from_string( const std::string &name,
server::application &app)
{
/// result endpoint
server::listener_sptr result;
std::vector<std::string> params;
size_t delim_pos = name.find_last_of( ':' );
if( delim_pos == std::string::npos ) {
/// local: <localname>
params.push_back( name );
} else {
/// tcp: <addres>:<port>
params.push_back( std::string( name.begin( ),
name.begin( ) + delim_pos ) );
params.push_back( std::string( name.begin( ) + delim_pos + 1,
name.end( ) ) );
}
if( params.size( ) == 1 ) { /// local endpoint
#ifndef _WIN32
::unlink( params[0].c_str( ) ); /// unlink old file socket
#endif
result = server::listeners::local::create( app, params[0] );
} else if( params.size( ) == 2 ) { /// TCP
result = server::listeners::tcp::create( app,
params[0],
boost::lexical_cast<unsigned short>(params[1]));
}
return result;
}
int start( const po::variables_map ¶ms )
{
if( params.count( "server" ) == 0 ) {
throw std::runtime_error("Server endpoint is not defined;\n"
"Use --help for details");
}
unsigned io_size = params.count( "io-pool-size" )
? params["io-pool-size"].as<unsigned>( )
: 1;
if( io_size < 1 ) {
throw std::runtime_error( "io-pool-size must be at least 1" );
}
unsigned rpc_size = params.count( "rpc-pool-size" )
? params["rpc-pool-size"].as<unsigned>( )
: 1;
if( rpc_size < 1 ) {
throw std::runtime_error( "rpc-pool-size must be at least 1" );
}
// typedef std::vector<std::string> string_vector;
// string_vector servers = params["server"].as<string_vector>( );
common::pool_pair pp( io_size - 1, rpc_size );
// lukki_db::application app( pp );
// for( string_vector::const_iterator b(servers.begin( )), e(servers.end( ));
// b != e; ++b)
// {
// std::cout << "Starting listener at '" << *b << "'...";
// app.attach_start_listener( create_from_string( *b, app ) );
// std::cout << "Ok\n";
// }
pp.get_io_pool( ).attach( );
pp.join_all( );
return 0;
}
<commit_msg>examples<commit_after>#include <string>
#include <vector>
#include "vtrc-server/vtrc-application.h"
#include "boost/program_options.hpp"
#include "boost/algorithm/string.hpp"
#include "vtrc-common/vtrc-pool-pair.h"
#include "vtrc-common/vtrc-rpc-service-wrapper.h"
#include "vtrc-server/vtrc-listener-tcp.h"
#include "vtrc-server/vtrc-listener-local.h"
namespace po = boost::program_options;
using namespace vtrc;
void get_options( po::options_description& desc )
{
desc.add_options( )
("help,?", "help message")
("server,s", po::value<std::vector< std::string> >( ),
"endpoint name; <tcp address>:<port> or <pipe/file name>")
("io-pool-size,i", po::value<unsigned>( ), "threads for io operations"
"; default = 1")
("rpc-pool-size,r", po::value<unsigned>( ), "threads for rpc calls"
"; default = 1")
("tcp-nodelay,t", po::value<unsigned>( ), "sets TCP_NODELAY flag"
" for tcp sockets")
;
}
server::listener_sptr create_from_string( const std::string &name,
server::application &app)
{
/// result endpoint
server::listener_sptr result;
std::vector<std::string> params;
size_t delim_pos = name.find_last_of( ':' );
if( delim_pos == std::string::npos ) {
/// local: <localname>
params.push_back( name );
} else {
/// tcp: <addres>:<port>
params.push_back( std::string( name.begin( ),
name.begin( ) + delim_pos ) );
params.push_back( std::string( name.begin( ) + delim_pos + 1,
name.end( ) ) );
}
if( params.size( ) == 1 ) { /// local endpoint
#ifndef _WIN32
::unlink( params[0].c_str( ) ); /// unlink old file socket
#endif
result = server::listeners::local::create( app, params[0] );
} else if( params.size( ) == 2 ) { /// TCP
result = server::listeners::tcp::create( app,
params[0],
boost::lexical_cast<unsigned short>(params[1]));
}
return result;
}
int start( const po::variables_map ¶ms )
{
if( params.count( "server" ) == 0 ) {
throw std::runtime_error("Server endpoint is not defined;\n"
"Use --help for details");
}
unsigned io_size = params.count( "io-pool-size" )
? params["io-pool-size"].as<unsigned>( )
: 1;
if( io_size < 1 ) {
throw std::runtime_error( "io-pool-size must be at least 1" );
}
unsigned rpc_size = params.count( "rpc-pool-size" )
? params["rpc-pool-size"].as<unsigned>( )
: 1;
if( rpc_size < 1 ) {
throw std::runtime_error( "rpc-pool-size must be at least 1" );
}
// typedef std::vector<std::string> string_vector;
// string_vector servers = params["server"].as<string_vector>( );
common::pool_pair pp( io_size - 1, rpc_size );
// lukki_db::application app( pp );
// for( string_vector::const_iterator b(servers.begin( )), e(servers.end( ));
// b != e; ++b)
// {
// std::cout << "Starting listener at '" << *b << "'...";
// app.attach_start_listener( create_from_string( *b, app ) );
// std::cout << "Ok\n";
// }
pp.get_io_pool( ).attach( );
pp.join_all( );
return 0;
}
<|endoftext|> |
<commit_before>/*
* loadervtk.cpp
*
* Created on: Apr 5, 2013
* Author: schurade
*/
#include "loadervtk.h"
#include <QDir>
#include <QTextStream>
#include <QDebug>
#include <vtkGenericDataObjectReader.h>
#include <vtkSmartPointer.h>
#include <vtkPolyData.h>
#include <vtkPointData.h>
#include <vtkCellData.h>
#include <vtkCellArray.h>
#include <vtkDoubleArray.h>
#include <vtkFloatArray.h>
LoaderVTK::LoaderVTK( QString fn ) :
m_filename( fn ),
m_primitiveType( 0 ),
m_numPoints( 0 ),
m_numLines( 0 ),
m_numPolys( 0 ),
m_hasPointData( false ),
m_hasPrimitiveData( false ),
m_hasPointColors( false ),
m_hasPrimitiveColors( false )
{
m_status.push_back( "ok" );
}
LoaderVTK::~LoaderVTK()
{
//m_points->clear();
m_lines.clear();
m_polys.clear();
m_pointData.clear();
m_pointDataNames.clear();
m_pointColors.clear();
}
QStringList LoaderVTK::getStatus()
{
return m_status;
}
int LoaderVTK::getPrimitiveType()
{
return m_primitiveType;
}
std::vector<float>* LoaderVTK::getPoints()
{
return m_points;
}
std::vector<int> LoaderVTK::getLines()
{
return m_lines;
}
std::vector<int> LoaderVTK::getPolys()
{
return m_polys;
}
std::vector<std::vector<float> > LoaderVTK::getPointData()
{
return m_pointData;
}
std::vector<unsigned char> LoaderVTK::getPointColors()
{
return m_pointColors;
}
std::vector<unsigned char> LoaderVTK::getPrimitiveColors()
{
return m_primitiveColors;
}
QList<QString>LoaderVTK::getPointDataNames()
{
return m_pointDataNames;
}
int LoaderVTK::getNumPoints()
{
return m_numPoints;
}
int LoaderVTK::getNumLines()
{
return m_numLines;
}
int LoaderVTK::getNumPolys()
{
return m_numPolys;
}
bool LoaderVTK::load()
{
if ( !exists() )
{
return false;
}
if ( !open() )
{
return false;
}
return true;
}
bool LoaderVTK::exists()
{
QDir dir( m_filename );
if ( !dir.exists( dir.absolutePath() ) )
{
m_status.push_back( "*ERROR* file " + m_filename + " doesn't exist" );
return false;
}
else
{
return true;
}
}
bool LoaderVTK::open()
{
vtkSmartPointer<vtkGenericDataObjectReader> reader = vtkSmartPointer<vtkGenericDataObjectReader>::New();
reader->SetFileName( m_filename.toStdString().c_str() );
reader->Update();
// All of the standard data types can be checked and obtained like this:
if ( reader->IsFilePolyData() )
{
qDebug() << "vtk file is a polydata";
vtkPolyData* output = reader->GetPolyDataOutput();
qDebug() << "vtk file has " << output->GetNumberOfPoints() << " points.";
qDebug() << "vtk file has " << output->GetNumberOfLines() << " lines.";
qDebug() << "vtk file has " << output->GetNumberOfPolys() << " polys.";
m_numPoints = output->GetNumberOfPoints();
m_numLines = output->GetNumberOfLines();
m_numPolys = output->GetNumberOfPolys();
if ( m_numPolys > 0 )
{
m_primitiveType = 1;
}
else if ( m_numLines > 0 )
{
m_primitiveType = 2;
}
else
{
return false;
}
double p[3];
m_points = new std::vector<float>();
m_points->reserve( m_numPoints * 3 );
for ( vtkIdType i = 0; i < output->GetNumberOfPoints(); ++i )
{
output->GetPoint( i, p );
m_points->push_back( p[0] );
m_points->push_back( p[1] );
m_points->push_back( p[2] );
}
if ( m_numPolys > 0 )
{
output->GetPolys()->InitTraversal();
vtkSmartPointer<vtkIdList> idList = vtkSmartPointer<vtkIdList>::New();
while ( output->GetPolys()->GetNextCell( idList ) )
{
m_polys.push_back( idList->GetNumberOfIds() );
for ( vtkIdType pointId = 0; pointId < idList->GetNumberOfIds(); ++pointId )
{
m_polys.push_back( idList->GetId( pointId ) );
}
}
}
if ( m_numLines > 0 )
{
m_lines.reserve( m_numLines + m_numPoints );
output->GetLines()->InitTraversal();
vtkSmartPointer<vtkIdList> idList = vtkSmartPointer<vtkIdList>::New();
while ( output->GetLines()->GetNextCell( idList ) )
{
m_lines.push_back( idList->GetNumberOfIds() );
for ( vtkIdType pointId = 0; pointId < idList->GetNumberOfIds(); ++pointId )
{
m_lines.push_back( idList->GetId( pointId ) );
}
}
///////// Get cell colors ///////////
vtkSmartPointer<vtkUnsignedCharArray> array = vtkUnsignedCharArray::SafeDownCast( output->GetCellData()->GetArray("CellColors" ) );
if ( array )
{
m_primitiveColors.reserve( m_numLines *3 );
for ( int i = 0; i < m_numLines * 3; ++i )
{
m_primitiveColors.push_back( array->GetValue( i ) );
}
m_hasPrimitiveColors = true;
} //end if(array)
else
{
m_primitiveColors.resize( m_numLines * 3 );
for ( unsigned int i = 0; i < m_primitiveColors.size(); ++i )
{
m_primitiveColors[i] = 255;
}
qDebug() << "no cell color array.";
}
}
///////// Get point colors ///////////
vtkSmartPointer<vtkUnsignedCharArray> array = vtkUnsignedCharArray::SafeDownCast( output->GetPointData()->GetArray("Colors" ) );
if ( array )
{
m_pointColors.reserve( m_numPoints * 3 );
for ( int i = 0; i < m_numPoints * 3; ++i )
{
m_pointColors.push_back( array->GetValue( i ) );
}
m_hasPointColors = true;
} //end if(array)
else
{
m_pointColors.resize( m_numPoints * 3 );
for ( unsigned int i = 0; i < m_pointColors.size(); ++i )
{
m_pointColors[i] = 255;
}
qDebug() << "no point color array.";
}
unsigned int numberOfArrays = output->GetPointData()->GetNumberOfArrays();
qDebug() << "NumArrays: " << numberOfArrays;
//qDebug() << "key: ";
//more values can be found in <VTK_DIR>/Common/vtkSetGet.h
// qDebug() << VTK_UNSIGNED_CHAR << " unsigned char";
// qDebug() << VTK_UNSIGNED_INT << " unsigned int";
// qDebug() << VTK_FLOAT << " float";
// qDebug() << VTK_DOUBLE << " double";
for ( unsigned int i = 0; i < numberOfArrays; ++i )
{
//the following two lines are equivalent
//arrayNames.push_back(polydata->GetPointData()->GetArray(i)->GetName());
int dataTypeID = output->GetPointData()->GetArray( i )->GetDataType();
// if ( dataTypeID == VTK_FLOAT )
// {
m_pointDataNames.push_back( output->GetPointData()->GetArrayName( i ) );
qDebug() << "Array " << i << ": " << m_pointDataNames.back() << " (type: " << dataTypeID << ")";
std::vector<float>data( m_numPoints );
//vtkSmartPointer<vtkFloatArray> dataArray = vtkFloatArray::SafeDownCast( output->GetPointData()->GetArray( i ) );
vtkSmartPointer<vtkDataArray> dataArray = output->GetPointData()->GetArray( i );
if ( dataArray )
{
for ( int k = 0; k < m_numPoints; ++k )
{
data[k] = dataArray->GetVariantValue( k ).ToFloat();
}
m_hasPointData = true;
}
m_pointData.push_back( data );
// }
}
numberOfArrays = output->GetCellData()->GetNumberOfArrays();
qDebug() << "NumCellArrays: " << numberOfArrays;
for ( unsigned int i = 0; i < numberOfArrays; ++i )
{
//the following two lines are equivalent
//arrayNames.push_back(polydata->GetPointData()->GetArray(i)->GetName());
int dataTypeID = output->GetCellData()->GetArray( i )->GetDataType();
// if ( dataTypeID == VTK_FLOAT )
// {
m_pointDataNames.push_back( output->GetCellData()->GetArrayName( i ) );
qDebug() << "Array " << i << ": " << m_pointDataNames.back() << " (type: " << dataTypeID << ")";
std::vector<float>data;
data.reserve( m_numPoints );
//vtkSmartPointer<vtkFloatArray> dataArray = vtkFloatArray::SafeDownCast( output->GetCellData()->GetArray( i ) );
vtkSmartPointer<vtkDataArray> dataArray = output->GetCellData()->GetArray( i );
if ( dataArray )
{
int lc = 0;
for ( int k = 0; k < m_numLines; ++k )
{
int lineSize = m_lines[lc];
for ( int l = 0; l < lineSize; ++l )
{
data.push_back( dataArray->GetVariantValue( k ).ToFloat() );
}
}
m_hasPointData = true;
}
m_pointData.push_back( data );
// }
}
return true;
}
return false;
}
<commit_msg>fix crash when trying to load a vtk file without any point declaration<commit_after>/*
* loadervtk.cpp
*
* Created on: Apr 5, 2013
* Author: schurade
*/
#include "loadervtk.h"
#include <QDir>
#include <QTextStream>
#include <QDebug>
#include <vtkGenericDataObjectReader.h>
#include <vtkSmartPointer.h>
#include <vtkPolyData.h>
#include <vtkPointData.h>
#include <vtkCellData.h>
#include <vtkCellArray.h>
#include <vtkDoubleArray.h>
#include <vtkFloatArray.h>
LoaderVTK::LoaderVTK( QString fn ) :
m_filename( fn ),
m_primitiveType( 0 ),
m_numPoints( 0 ),
m_numLines( 0 ),
m_numPolys( 0 ),
m_hasPointData( false ),
m_hasPrimitiveData( false ),
m_hasPointColors( false ),
m_hasPrimitiveColors( false )
{
m_status.push_back( "ok" );
}
LoaderVTK::~LoaderVTK()
{
//m_points->clear();
m_lines.clear();
m_polys.clear();
m_pointData.clear();
m_pointDataNames.clear();
m_pointColors.clear();
}
QStringList LoaderVTK::getStatus()
{
return m_status;
}
int LoaderVTK::getPrimitiveType()
{
return m_primitiveType;
}
std::vector<float>* LoaderVTK::getPoints()
{
return m_points;
}
std::vector<int> LoaderVTK::getLines()
{
return m_lines;
}
std::vector<int> LoaderVTK::getPolys()
{
return m_polys;
}
std::vector<std::vector<float> > LoaderVTK::getPointData()
{
return m_pointData;
}
std::vector<unsigned char> LoaderVTK::getPointColors()
{
return m_pointColors;
}
std::vector<unsigned char> LoaderVTK::getPrimitiveColors()
{
return m_primitiveColors;
}
QList<QString>LoaderVTK::getPointDataNames()
{
return m_pointDataNames;
}
int LoaderVTK::getNumPoints()
{
return m_numPoints;
}
int LoaderVTK::getNumLines()
{
return m_numLines;
}
int LoaderVTK::getNumPolys()
{
return m_numPolys;
}
bool LoaderVTK::load()
{
if ( !exists() )
{
return false;
}
if ( !open() )
{
return false;
}
return true;
}
bool LoaderVTK::exists()
{
QDir dir( m_filename );
if ( !dir.exists( dir.absolutePath() ) )
{
m_status.push_back( "*ERROR* file " + m_filename + " doesn't exist" );
return false;
}
else
{
return true;
}
}
bool LoaderVTK::open()
{
vtkSmartPointer<vtkGenericDataObjectReader> reader = vtkSmartPointer<vtkGenericDataObjectReader>::New();
reader->SetFileName( m_filename.toStdString().c_str() );
reader->Update();
// All of the standard data types can be checked and obtained like this:
if ( reader->IsFilePolyData() )
{
qDebug() << "vtk file is a polydata";
vtkPolyData* output = reader->GetPolyDataOutput();
m_numPoints = output->GetNumberOfPoints();
m_numLines = output->GetNumberOfLines();
m_numPolys = output->GetNumberOfPolys();
qDebug() << "vtk file has " << m_numPoints << " points.";
qDebug() << "vtk file has " << m_numLines << " lines.";
qDebug() << "vtk file has " << m_numPolys << " polys.";
if( m_numPoints <= 0 )
{
return false;
}
if ( m_numPolys > 0 )
{
m_primitiveType = 1;
}
else if ( m_numLines > 0 )
{
m_primitiveType = 2;
}
else
{
return false;
}
double p[3];
m_points = new std::vector<float>();
m_points->reserve( m_numPoints * 3 );
for ( vtkIdType i = 0; i < output->GetNumberOfPoints(); ++i )
{
output->GetPoint( i, p );
m_points->push_back( p[0] );
m_points->push_back( p[1] );
m_points->push_back( p[2] );
}
if ( m_numPolys > 0 )
{
output->GetPolys()->InitTraversal();
vtkSmartPointer<vtkIdList> idList = vtkSmartPointer<vtkIdList>::New();
while ( output->GetPolys()->GetNextCell( idList ) )
{
m_polys.push_back( idList->GetNumberOfIds() );
for ( vtkIdType pointId = 0; pointId < idList->GetNumberOfIds(); ++pointId )
{
m_polys.push_back( idList->GetId( pointId ) );
}
}
}
if ( m_numLines > 0 )
{
m_lines.reserve( m_numLines + m_numPoints );
output->GetLines()->InitTraversal();
vtkSmartPointer<vtkIdList> idList = vtkSmartPointer<vtkIdList>::New();
while ( output->GetLines()->GetNextCell( idList ) )
{
m_lines.push_back( idList->GetNumberOfIds() );
for ( vtkIdType pointId = 0; pointId < idList->GetNumberOfIds(); ++pointId )
{
m_lines.push_back( idList->GetId( pointId ) );
}
}
///////// Get cell colors ///////////
vtkSmartPointer<vtkUnsignedCharArray> array = vtkUnsignedCharArray::SafeDownCast( output->GetCellData()->GetArray("CellColors" ) );
if ( array )
{
m_primitiveColors.reserve( m_numLines *3 );
for ( int i = 0; i < m_numLines * 3; ++i )
{
m_primitiveColors.push_back( array->GetValue( i ) );
}
m_hasPrimitiveColors = true;
} //end if(array)
else
{
m_primitiveColors.resize( m_numLines * 3 );
for ( unsigned int i = 0; i < m_primitiveColors.size(); ++i )
{
m_primitiveColors[i] = 255;
}
qDebug() << "no cell color array.";
}
}
///////// Get point colors ///////////
vtkSmartPointer<vtkUnsignedCharArray> array = vtkUnsignedCharArray::SafeDownCast( output->GetPointData()->GetArray("Colors" ) );
if ( array )
{
m_pointColors.reserve( m_numPoints * 3 );
for ( int i = 0; i < m_numPoints * 3; ++i )
{
m_pointColors.push_back( array->GetValue( i ) );
}
m_hasPointColors = true;
} //end if(array)
else
{
m_pointColors.resize( m_numPoints * 3 );
for ( unsigned int i = 0; i < m_pointColors.size(); ++i )
{
m_pointColors[i] = 255;
}
qDebug() << "no point color array.";
}
unsigned int numberOfArrays = output->GetPointData()->GetNumberOfArrays();
qDebug() << "NumArrays: " << numberOfArrays;
//qDebug() << "key: ";
//more values can be found in <VTK_DIR>/Common/vtkSetGet.h
// qDebug() << VTK_UNSIGNED_CHAR << " unsigned char";
// qDebug() << VTK_UNSIGNED_INT << " unsigned int";
// qDebug() << VTK_FLOAT << " float";
// qDebug() << VTK_DOUBLE << " double";
for ( unsigned int i = 0; i < numberOfArrays; ++i )
{
//the following two lines are equivalent
//arrayNames.push_back(polydata->GetPointData()->GetArray(i)->GetName());
int dataTypeID = output->GetPointData()->GetArray( i )->GetDataType();
// if ( dataTypeID == VTK_FLOAT )
// {
m_pointDataNames.push_back( output->GetPointData()->GetArrayName( i ) );
qDebug() << "Array " << i << ": " << m_pointDataNames.back() << " (type: " << dataTypeID << ")";
std::vector<float>data( m_numPoints );
//vtkSmartPointer<vtkFloatArray> dataArray = vtkFloatArray::SafeDownCast( output->GetPointData()->GetArray( i ) );
vtkSmartPointer<vtkDataArray> dataArray = output->GetPointData()->GetArray( i );
if ( dataArray )
{
for ( int k = 0; k < m_numPoints; ++k )
{
data[k] = dataArray->GetVariantValue( k ).ToFloat();
}
m_hasPointData = true;
}
m_pointData.push_back( data );
// }
}
numberOfArrays = output->GetCellData()->GetNumberOfArrays();
qDebug() << "NumCellArrays: " << numberOfArrays;
for ( unsigned int i = 0; i < numberOfArrays; ++i )
{
//the following two lines are equivalent
//arrayNames.push_back(polydata->GetPointData()->GetArray(i)->GetName());
int dataTypeID = output->GetCellData()->GetArray( i )->GetDataType();
// if ( dataTypeID == VTK_FLOAT )
// {
m_pointDataNames.push_back( output->GetCellData()->GetArrayName( i ) );
qDebug() << "Array " << i << ": " << m_pointDataNames.back() << " (type: " << dataTypeID << ")";
std::vector<float>data;
data.reserve( m_numPoints );
//vtkSmartPointer<vtkFloatArray> dataArray = vtkFloatArray::SafeDownCast( output->GetCellData()->GetArray( i ) );
vtkSmartPointer<vtkDataArray> dataArray = output->GetCellData()->GetArray( i );
if ( dataArray )
{
int lc = 0;
for ( int k = 0; k < m_numLines; ++k )
{
int lineSize = m_lines[lc];
for ( int l = 0; l < lineSize; ++l )
{
data.push_back( dataArray->GetVariantValue( k ).ToFloat() );
}
}
m_hasPointData = true;
}
m_pointData.push_back( data );
// }
}
return true;
}
return false;
}
<|endoftext|> |
<commit_before>#ifndef _OSL_FILE_HXX_
#include <osl/file.hxx>
#endif
#ifndef _VOS_MODULE_HXX_
#include <vos/module.hxx>
#endif
#ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_
#include <com/sun/star/frame/XModel.hpp>
#endif
#ifndef _COM_SUN_STAR_DOCUMENT_XVIEWDATASUPPLIER_HPP_
#include <com/sun/star/document/XViewDataSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XINDEXACCESS_HPP_
#include <com/sun/star/container/XIndexAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_H_
#include <com/sun/star/uno/Sequence.h>
#endif
#ifndef _COM_SUN_STAR_UNO_ANY_H_
#include <com/sun/star/uno/Any.h>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYACCESS_HPP_
#include <com/sun/star/beans/XPropertyAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XEXECUTABLEDIALOG_HPP_
#include <com/sun/star/ui/dialogs/XExecutableDialog.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_EXECUTABLEDIALOGRESULTS_HPP_
#include <com/sun/star/ui/dialogs/ExecutableDialogResults.hpp>
#endif
#ifndef _COM_SUN_STAR_DOCUMENT_XEXPORTER_HPP_
#include <com/sun/star/document/XExporter.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE5_HXX_
#include <cppuhelper/implbase5.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
using namespace rtl;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::document;
using namespace com::sun::star::beans;
using namespace com::sun::star::container;
using namespace com::sun::star::frame;
using namespace com::sun::star::ui::dialogs;
#include "pres.hxx"
#include "pubdlg.hxx"
class SdHtmlOptionsDialog : public cppu::WeakImplHelper5
<
XExporter,
XExecutableDialog,
XPropertyAccess,
XInitialization,
XServiceInfo
>
{
const Reference< XMultiServiceFactory > &mrxMgr;
Sequence< PropertyValue > maMediaDescriptor;
Sequence< PropertyValue > maFilterDataSequence;
OUString aDialogTitle;
DocumentType meDocType;
public:
SdHtmlOptionsDialog( const Reference< XMultiServiceFactory >& _rxORB );
~SdHtmlOptionsDialog();
// XInterface
virtual void SAL_CALL acquire() throw();
virtual void SAL_CALL release() throw();
// XInitialization
virtual void SAL_CALL initialize( const Sequence< Any > & aArguments ) throw ( Exception, RuntimeException );
// XServiceInfo
virtual OUString SAL_CALL getImplementationName() throw ( RuntimeException );
virtual sal_Bool SAL_CALL supportsService( const OUString& ServiceName ) throw ( RuntimeException );
virtual Sequence< OUString > SAL_CALL getSupportedServiceNames() throw ( RuntimeException );
// XPropertyAccess
virtual Sequence< PropertyValue > SAL_CALL getPropertyValues() throw ( RuntimeException );
virtual void SAL_CALL setPropertyValues( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > & aProps )
throw ( ::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException,
::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException,
::com::sun::star::uno::RuntimeException );
// XExecuteDialog
virtual sal_Int16 SAL_CALL execute()
throw ( com::sun::star::uno::RuntimeException );
virtual void SAL_CALL setTitle( const ::rtl::OUString& aTitle )
throw ( ::com::sun::star::uno::RuntimeException );
// XExporter
virtual void SAL_CALL setSourceDocument( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent >& xDoc )
throw ( ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException );
};
// -------------------------
// - SdHtmlOptionsDialog -
// -------------------------
Reference< XInterface >
SAL_CALL SdHtmlOptionsDialog_CreateInstance(
const Reference< XMultiServiceFactory > & _rxFactory )
{
return static_cast< ::cppu::OWeakObject* > ( new SdHtmlOptionsDialog( _rxFactory ) );
}
OUString SdHtmlOptionsDialog_getImplementationName()
throw( RuntimeException )
{
return OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.comp.draw.SdHtmlOptionsDialog" ) );
}
#define SERVICE_NAME "com.sun.star.ui.dialog.FilterOptionsDialog"
sal_Bool SAL_CALL SdHtmlOptionsDialog_supportsService( const OUString& ServiceName )
throw( RuntimeException )
{
return ServiceName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( SERVICE_NAME ) );
}
Sequence< OUString > SAL_CALL SdHtmlOptionsDialog_getSupportedServiceNames()
throw( RuntimeException )
{
Sequence< OUString > aRet(1);
OUString* pArray = aRet.getArray();
pArray[0] = OUString( RTL_CONSTASCII_USTRINGPARAM( SERVICE_NAME ) );
return aRet;
}
#undef SERVICE_NAME
// -----------------------------------------------------------------------------
SdHtmlOptionsDialog::SdHtmlOptionsDialog( const Reference< XMultiServiceFactory > & xMgr ) :
mrxMgr ( xMgr ),
meDocType ( DOCUMENT_TYPE_DRAW )
{
}
// -----------------------------------------------------------------------------
SdHtmlOptionsDialog::~SdHtmlOptionsDialog()
{
}
// -----------------------------------------------------------------------------
void SAL_CALL SdHtmlOptionsDialog::acquire() throw()
{
OWeakObject::acquire();
}
// -----------------------------------------------------------------------------
void SAL_CALL SdHtmlOptionsDialog::release() throw()
{
OWeakObject::release();
}
// XInitialization
void SAL_CALL SdHtmlOptionsDialog::initialize( const Sequence< Any > & aArguments )
throw ( Exception, RuntimeException )
{
}
// XServiceInfo
OUString SAL_CALL SdHtmlOptionsDialog::getImplementationName()
throw( RuntimeException )
{
return SdHtmlOptionsDialog_getImplementationName();
}
sal_Bool SAL_CALL SdHtmlOptionsDialog::supportsService( const OUString& rServiceName )
throw( RuntimeException )
{
return SdHtmlOptionsDialog_supportsService( rServiceName );
}
Sequence< OUString > SAL_CALL SdHtmlOptionsDialog::getSupportedServiceNames()
throw ( RuntimeException )
{
return SdHtmlOptionsDialog_getSupportedServiceNames();
}
// XPropertyAccess
Sequence< PropertyValue > SdHtmlOptionsDialog::getPropertyValues()
throw ( RuntimeException )
{
sal_Int32 i, nCount;
for ( i = 0, nCount = maMediaDescriptor.getLength(); i < nCount; i++ )
{
if ( maMediaDescriptor[ i ].Name.equalsAscii( "FilterData" ) )
break;
}
if ( i == nCount )
maMediaDescriptor.realloc( ++nCount );
// the "FilterData" Property is an Any that will contain our PropertySequence of Values
maMediaDescriptor[ i ].Name = OUString( RTL_CONSTASCII_USTRINGPARAM( "FilterData" ) );
maMediaDescriptor[ i ].Value <<= maFilterDataSequence;
return maMediaDescriptor;
}
void SdHtmlOptionsDialog::setPropertyValues( const Sequence< PropertyValue > & aProps )
throw ( UnknownPropertyException, PropertyVetoException,
IllegalArgumentException, WrappedTargetException,
RuntimeException )
{
maMediaDescriptor = aProps;
sal_Int32 i, nCount;
for ( i = 0, nCount = maMediaDescriptor.getLength(); i < nCount; i++ )
{
if ( maMediaDescriptor[ i ].Name.equalsAscii( "FilterData" ) )
{
maMediaDescriptor[ i ].Value >>= maFilterDataSequence;
break;
}
}
}
// XExecutableDialog
void SdHtmlOptionsDialog::setTitle( const OUString& aTitle )
throw ( RuntimeException )
{
aDialogTitle = aTitle;
}
sal_Int16 SdHtmlOptionsDialog::execute()
throw ( RuntimeException )
{
SdPublishingDlg aDlg( Application::GetDefDialogParent(), meDocType );
if( aDlg.Execute() )
{
aDlg.GetParameterSequence( maFilterDataSequence );
return ExecutableDialogResults::OK;
}
else
{
return ExecutableDialogResults::CANCEL;
}
}
// XEmporter
void SdHtmlOptionsDialog::setSourceDocument( const Reference< XComponent >& xDoc )
throw ( IllegalArgumentException, RuntimeException )
{
// try to set the corresponding metric unit
String aConfigPath;
Reference< XServiceInfo > xServiceInfo
( xDoc, UNO_QUERY );
if ( xServiceInfo.is() )
{
if ( xServiceInfo->supportsService( OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.presentation.PresentationDocument" ) ) ) )
{
meDocType = DOCUMENT_TYPE_IMPRESS;
return;
}
else if ( xServiceInfo->supportsService( OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.drawing.DrawingDocument" ) ) ) )
{
meDocType = DOCUMENT_TYPE_DRAW;
return;
}
}
throw IllegalArgumentException();
}
<commit_msg>INTEGRATION: CWS dialogdiet01 (1.1.344); FILE MERGED 2004/04/22 02:01:26 mwu 1.1.344.1: dialogdiet01 m33 sd 20040422<commit_after>#ifndef _OSL_FILE_HXX_
#include <osl/file.hxx>
#endif
#ifndef _VOS_MODULE_HXX_
#include <vos/module.hxx>
#endif
#ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_
#include <com/sun/star/frame/XModel.hpp>
#endif
#ifndef _COM_SUN_STAR_DOCUMENT_XVIEWDATASUPPLIER_HPP_
#include <com/sun/star/document/XViewDataSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XINDEXACCESS_HPP_
#include <com/sun/star/container/XIndexAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_H_
#include <com/sun/star/uno/Sequence.h>
#endif
#ifndef _COM_SUN_STAR_UNO_ANY_H_
#include <com/sun/star/uno/Any.h>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYACCESS_HPP_
#include <com/sun/star/beans/XPropertyAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XEXECUTABLEDIALOG_HPP_
#include <com/sun/star/ui/dialogs/XExecutableDialog.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_EXECUTABLEDIALOGRESULTS_HPP_
#include <com/sun/star/ui/dialogs/ExecutableDialogResults.hpp>
#endif
#ifndef _COM_SUN_STAR_DOCUMENT_XEXPORTER_HPP_
#include <com/sun/star/document/XExporter.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE5_HXX_
#include <cppuhelper/implbase5.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
using namespace rtl;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::document;
using namespace com::sun::star::beans;
using namespace com::sun::star::container;
using namespace com::sun::star::frame;
using namespace com::sun::star::ui::dialogs;
#include "pres.hxx"
//CHINA001 #include "pubdlg.hxx"
#include "sdabstdlg.hxx" //CHINA001
#include "pubdlg.hrc" //CHINA001
#include "tools/debug.hxx" //CHINA001
class SdHtmlOptionsDialog : public cppu::WeakImplHelper5
<
XExporter,
XExecutableDialog,
XPropertyAccess,
XInitialization,
XServiceInfo
>
{
const Reference< XMultiServiceFactory > &mrxMgr;
Sequence< PropertyValue > maMediaDescriptor;
Sequence< PropertyValue > maFilterDataSequence;
OUString aDialogTitle;
DocumentType meDocType;
public:
SdHtmlOptionsDialog( const Reference< XMultiServiceFactory >& _rxORB );
~SdHtmlOptionsDialog();
// XInterface
virtual void SAL_CALL acquire() throw();
virtual void SAL_CALL release() throw();
// XInitialization
virtual void SAL_CALL initialize( const Sequence< Any > & aArguments ) throw ( Exception, RuntimeException );
// XServiceInfo
virtual OUString SAL_CALL getImplementationName() throw ( RuntimeException );
virtual sal_Bool SAL_CALL supportsService( const OUString& ServiceName ) throw ( RuntimeException );
virtual Sequence< OUString > SAL_CALL getSupportedServiceNames() throw ( RuntimeException );
// XPropertyAccess
virtual Sequence< PropertyValue > SAL_CALL getPropertyValues() throw ( RuntimeException );
virtual void SAL_CALL setPropertyValues( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > & aProps )
throw ( ::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException,
::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException,
::com::sun::star::uno::RuntimeException );
// XExecuteDialog
virtual sal_Int16 SAL_CALL execute()
throw ( com::sun::star::uno::RuntimeException );
virtual void SAL_CALL setTitle( const ::rtl::OUString& aTitle )
throw ( ::com::sun::star::uno::RuntimeException );
// XExporter
virtual void SAL_CALL setSourceDocument( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent >& xDoc )
throw ( ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException );
};
// -------------------------
// - SdHtmlOptionsDialog -
// -------------------------
Reference< XInterface >
SAL_CALL SdHtmlOptionsDialog_CreateInstance(
const Reference< XMultiServiceFactory > & _rxFactory )
{
return static_cast< ::cppu::OWeakObject* > ( new SdHtmlOptionsDialog( _rxFactory ) );
}
OUString SdHtmlOptionsDialog_getImplementationName()
throw( RuntimeException )
{
return OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.comp.draw.SdHtmlOptionsDialog" ) );
}
#define SERVICE_NAME "com.sun.star.ui.dialog.FilterOptionsDialog"
sal_Bool SAL_CALL SdHtmlOptionsDialog_supportsService( const OUString& ServiceName )
throw( RuntimeException )
{
return ServiceName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( SERVICE_NAME ) );
}
Sequence< OUString > SAL_CALL SdHtmlOptionsDialog_getSupportedServiceNames()
throw( RuntimeException )
{
Sequence< OUString > aRet(1);
OUString* pArray = aRet.getArray();
pArray[0] = OUString( RTL_CONSTASCII_USTRINGPARAM( SERVICE_NAME ) );
return aRet;
}
#undef SERVICE_NAME
// -----------------------------------------------------------------------------
SdHtmlOptionsDialog::SdHtmlOptionsDialog( const Reference< XMultiServiceFactory > & xMgr ) :
mrxMgr ( xMgr ),
meDocType ( DOCUMENT_TYPE_DRAW )
{
}
// -----------------------------------------------------------------------------
SdHtmlOptionsDialog::~SdHtmlOptionsDialog()
{
}
// -----------------------------------------------------------------------------
void SAL_CALL SdHtmlOptionsDialog::acquire() throw()
{
OWeakObject::acquire();
}
// -----------------------------------------------------------------------------
void SAL_CALL SdHtmlOptionsDialog::release() throw()
{
OWeakObject::release();
}
// XInitialization
void SAL_CALL SdHtmlOptionsDialog::initialize( const Sequence< Any > & aArguments )
throw ( Exception, RuntimeException )
{
}
// XServiceInfo
OUString SAL_CALL SdHtmlOptionsDialog::getImplementationName()
throw( RuntimeException )
{
return SdHtmlOptionsDialog_getImplementationName();
}
sal_Bool SAL_CALL SdHtmlOptionsDialog::supportsService( const OUString& rServiceName )
throw( RuntimeException )
{
return SdHtmlOptionsDialog_supportsService( rServiceName );
}
Sequence< OUString > SAL_CALL SdHtmlOptionsDialog::getSupportedServiceNames()
throw ( RuntimeException )
{
return SdHtmlOptionsDialog_getSupportedServiceNames();
}
// XPropertyAccess
Sequence< PropertyValue > SdHtmlOptionsDialog::getPropertyValues()
throw ( RuntimeException )
{
sal_Int32 i, nCount;
for ( i = 0, nCount = maMediaDescriptor.getLength(); i < nCount; i++ )
{
if ( maMediaDescriptor[ i ].Name.equalsAscii( "FilterData" ) )
break;
}
if ( i == nCount )
maMediaDescriptor.realloc( ++nCount );
// the "FilterData" Property is an Any that will contain our PropertySequence of Values
maMediaDescriptor[ i ].Name = OUString( RTL_CONSTASCII_USTRINGPARAM( "FilterData" ) );
maMediaDescriptor[ i ].Value <<= maFilterDataSequence;
return maMediaDescriptor;
}
void SdHtmlOptionsDialog::setPropertyValues( const Sequence< PropertyValue > & aProps )
throw ( UnknownPropertyException, PropertyVetoException,
IllegalArgumentException, WrappedTargetException,
RuntimeException )
{
maMediaDescriptor = aProps;
sal_Int32 i, nCount;
for ( i = 0, nCount = maMediaDescriptor.getLength(); i < nCount; i++ )
{
if ( maMediaDescriptor[ i ].Name.equalsAscii( "FilterData" ) )
{
maMediaDescriptor[ i ].Value >>= maFilterDataSequence;
break;
}
}
}
// XExecutableDialog
void SdHtmlOptionsDialog::setTitle( const OUString& aTitle )
throw ( RuntimeException )
{
aDialogTitle = aTitle;
}
sal_Int16 SdHtmlOptionsDialog::execute()
throw ( RuntimeException )
{
//CHINA001 SdPublishingDlg aDlg( Application::GetDefDialogParent(), meDocType );
SdAbstractDialogFactory* pFact = SdAbstractDialogFactory::Create();//CHINA001
DBG_ASSERT(pFact, "SdAbstractDialogFactory fail!");//CHINA001
AbstractSdPublishingDlg* pDlg = pFact->CreateSdPublishingDlg(ResId( DLG_PUBLISHING ), Application::GetDefDialogParent(), meDocType );
DBG_ASSERT(pDlg, "Dialogdiet fail!");//CHINA001
if( pDlg->Execute() ) //CHINA001 if( aDlg.Execute() )
{
pDlg->GetParameterSequence( maFilterDataSequence ); //CHINA001 aDlg.GetParameterSequence( maFilterDataSequence );
return ExecutableDialogResults::OK;
}
else
{
return ExecutableDialogResults::CANCEL;
}
delete pDlg; //add by CHINA001
}
// XEmporter
void SdHtmlOptionsDialog::setSourceDocument( const Reference< XComponent >& xDoc )
throw ( IllegalArgumentException, RuntimeException )
{
// try to set the corresponding metric unit
String aConfigPath;
Reference< XServiceInfo > xServiceInfo
( xDoc, UNO_QUERY );
if ( xServiceInfo.is() )
{
if ( xServiceInfo->supportsService( OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.presentation.PresentationDocument" ) ) ) )
{
meDocType = DOCUMENT_TYPE_IMPRESS;
return;
}
else if ( xServiceInfo->supportsService( OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.drawing.DrawingDocument" ) ) ) )
{
meDocType = DOCUMENT_TYPE_DRAW;
return;
}
}
throw IllegalArgumentException();
}
<|endoftext|> |
<commit_before>/** \copyright
* Copyright (c) 2021, Balazs Racz
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* \file SPIFlash.cxx
*
* Shared implementation for operating spiflash devices. This class is intended
* to be used by other device drivers.
*
* @author Balazs Racz
* @date 4 Dec 2021
*/
//#define LOGLEVEL INFO
#include "freertos_drivers/common/SPIFlash.hxx"
#include <fcntl.h>
#include <spi/spidev.h>
#include <stropts.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include "os/OS.hxx"
#include "utils/logging.h"
/// Conditional OSMutexLock which can handle a nullptr as mutex (in which case
/// it does not lock anything).
class LockIfExists
{
public:
LockIfExists(OSMutex *mu)
: mu_(mu)
{
if (mu_)
{
mu_->lock();
}
}
~LockIfExists()
{
if (mu_)
{
mu_->unlock();
}
}
private:
OSMutex *mu_;
};
#define LockIfExists(l) int error_omitted_mutex_lock_variable[-1]
void SPIFlash::init(const char *dev_name)
{
spiFd_ = ::open(dev_name, O_RDWR);
HASSERT(spiFd_ >= 0);
uint8_t spi_bpw = 8;
int ret;
ret = ::ioctl(spiFd_, SPI_IOC_WR_MODE, &cfg_->spiMode_);
HASSERT(ret == 0);
ret = ::ioctl(spiFd_, SPI_IOC_WR_BITS_PER_WORD, &spi_bpw);
HASSERT(ret == 0);
ret = ::ioctl(spiFd_, SPI_IOC_WR_MAX_SPEED_HZ, &cfg_->speedHz_);
HASSERT(ret == 0);
}
void SPIFlash::get_id(char id_out[3])
{
LockIfExists l(lock_);
struct spi_ioc_transfer xfer[2] = {0, 0};
xfer[0].tx_buf = (uintptr_t)&cfg_->idCommand_;
xfer[0].len = 1;
xfer[1].rx_buf = (uintptr_t)id_out;
xfer[1].len = 3;
xfer[1].cs_change = true;
::ioctl(spiFd_, SPI_IOC_MESSAGE(2), xfer);
}
void SPIFlash::read(uint32_t addr, void *buf, size_t len)
{
LockIfExists l(lock_);
struct spi_ioc_transfer xfer[2] = {0, 0};
uint8_t rdreq[5];
rdreq[0] = cfg_->readCommand_;
rdreq[1] = (addr >> 16) & 0xff;
rdreq[2] = (addr >> 8) & 0xff;
rdreq[3] = (addr)&0xff;
rdreq[4] = 0;
xfer[0].tx_buf = (uintptr_t)rdreq;
xfer[0].len = 4 + cfg_->readNeedsStuffing_;
xfer[1].rx_buf = (uintptr_t)buf;
xfer[1].len = len;
xfer[1].cs_change = true;
::ioctl(spiFd_, SPI_IOC_MESSAGE(2), xfer);
auto db = (const uint8_t *)buf;
LOG(INFO, "read [%x]=%02x%02x%02x%02x, %u bytes success", (unsigned)addr,
db[0], db[1], db[2], db[3], len);
}
void SPIFlash::write(uint32_t addr, const void *buf, size_t len)
{
HASSERT((addr & cfg_->pageSizeMask_) ==
((addr + len - 1) & cfg_->pageSizeMask_));
LockIfExists l(lock_);
struct spi_ioc_transfer xfer[3] = {0, 0, 0};
uint8_t wreq[4];
wreq[0] = cfg_->writeCommand_;
wreq[1] = (addr >> 16) & 0xff;
wreq[2] = (addr >> 8) & 0xff;
wreq[3] = addr & 0xff;
xfer[0].tx_buf = (uintptr_t)&cfg_->writeEnableCommand_;
xfer[0].len = 1;
xfer[0].cs_change = true;
xfer[1].tx_buf = (uintptr_t)wreq;
xfer[1].len = 4;
xfer[2].tx_buf = (uintptr_t)buf;
xfer[2].len = len;
xfer[2].cs_change = true;
::ioctl(spiFd_, SPI_IOC_MESSAGE(3), xfer);
unsigned waitcount = wait_for_write();
auto db = (const uint8_t *)buf;
LOG(INFO, "write [%x]=%02x%02x%02x%02x, %u bytes success after %u iter",
(unsigned)addr, db[0], db[1], db[2], db[3], len, waitcount);
}
unsigned SPIFlash::wait_for_write()
{
// Now we wait for the write to be complete.
unsigned waitcount = 0;
while (true)
{
struct spi_ioc_transfer sxfer = {0};
uint8_t streq[2];
streq[0] = cfg_->statusReadCommand_;
streq[1] = 0xFF;
sxfer.tx_buf = (uintptr_t)streq;
sxfer.rx_buf = (uintptr_t)streq;
sxfer.len = 2;
sxfer.cs_change = true;
::ioctl(spiFd_, SPI_IOC_MESSAGE(1), &sxfer);
if ((streq[1] & cfg_->statusWritePendingBit_) == 0)
{
return waitcount;
}
waitcount++;
}
}
void SPIFlash::erase(uint32_t addr, size_t len)
{
size_t end = addr + len;
while (addr < end)
{
struct spi_ioc_transfer xfer[2] = {0, 0};
uint8_t ereq[4];
ereq[0] = cfg_->eraseCommand_;
ereq[1] = (addr >> 16) & 0xff;
ereq[2] = (addr >> 8) & 0xff;
ereq[3] = (addr)&0xff;
xfer[0].tx_buf = (uintptr_t)&cfg_->writeEnableCommand_;
xfer[0].len = 1;
xfer[0].cs_change = true;
xfer[1].tx_buf = (uintptr_t)ereq;
xfer[1].len = 4;
xfer[1].cs_change = true;
::ioctl(spiFd_, SPI_IOC_MESSAGE(2), &xfer);
unsigned waitcount = wait_for_write();
LOG(INFO, "erase at %x, success after %u iter", (unsigned)addr,
waitcount);
addr += cfg_->sectorSize_;
}
}
<commit_msg>Adds implementation of chip_erase() to SpiFlash driver. (#676)<commit_after>/** \copyright
* Copyright (c) 2021, Balazs Racz
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* \file SPIFlash.cxx
*
* Shared implementation for operating spiflash devices. This class is intended
* to be used by other device drivers.
*
* @author Balazs Racz
* @date 4 Dec 2021
*/
//#define LOGLEVEL INFO
#include "freertos_drivers/common/SPIFlash.hxx"
#include <fcntl.h>
#include <spi/spidev.h>
#include <stropts.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include "os/OS.hxx"
#include "utils/logging.h"
/// Conditional OSMutexLock which can handle a nullptr as mutex (in which case
/// it does not lock anything).
class LockIfExists
{
public:
LockIfExists(OSMutex *mu)
: mu_(mu)
{
if (mu_)
{
mu_->lock();
}
}
~LockIfExists()
{
if (mu_)
{
mu_->unlock();
}
}
private:
OSMutex *mu_;
};
#define LockIfExists(l) int error_omitted_mutex_lock_variable[-1]
void SPIFlash::init(const char *dev_name)
{
spiFd_ = ::open(dev_name, O_RDWR);
HASSERT(spiFd_ >= 0);
uint8_t spi_bpw = 8;
int ret;
ret = ::ioctl(spiFd_, SPI_IOC_WR_MODE, &cfg_->spiMode_);
HASSERT(ret == 0);
ret = ::ioctl(spiFd_, SPI_IOC_WR_BITS_PER_WORD, &spi_bpw);
HASSERT(ret == 0);
ret = ::ioctl(spiFd_, SPI_IOC_WR_MAX_SPEED_HZ, &cfg_->speedHz_);
HASSERT(ret == 0);
}
void SPIFlash::get_id(char id_out[3])
{
LockIfExists l(lock_);
struct spi_ioc_transfer xfer[2] = {0, 0};
xfer[0].tx_buf = (uintptr_t)&cfg_->idCommand_;
xfer[0].len = 1;
xfer[1].rx_buf = (uintptr_t)id_out;
xfer[1].len = 3;
xfer[1].cs_change = true;
::ioctl(spiFd_, SPI_IOC_MESSAGE(2), xfer);
}
void SPIFlash::read(uint32_t addr, void *buf, size_t len)
{
LockIfExists l(lock_);
struct spi_ioc_transfer xfer[2] = {0, 0};
uint8_t rdreq[5];
rdreq[0] = cfg_->readCommand_;
rdreq[1] = (addr >> 16) & 0xff;
rdreq[2] = (addr >> 8) & 0xff;
rdreq[3] = (addr)&0xff;
rdreq[4] = 0;
xfer[0].tx_buf = (uintptr_t)rdreq;
xfer[0].len = 4 + cfg_->readNeedsStuffing_;
xfer[1].rx_buf = (uintptr_t)buf;
xfer[1].len = len;
xfer[1].cs_change = true;
::ioctl(spiFd_, SPI_IOC_MESSAGE(2), xfer);
auto db = (const uint8_t *)buf;
LOG(INFO, "read [%x]=%02x%02x%02x%02x, %u bytes success", (unsigned)addr,
db[0], db[1], db[2], db[3], len);
}
void SPIFlash::write(uint32_t addr, const void *buf, size_t len)
{
HASSERT((addr & cfg_->pageSizeMask_) ==
((addr + len - 1) & cfg_->pageSizeMask_));
LockIfExists l(lock_);
struct spi_ioc_transfer xfer[3] = {0, 0, 0};
uint8_t wreq[4];
wreq[0] = cfg_->writeCommand_;
wreq[1] = (addr >> 16) & 0xff;
wreq[2] = (addr >> 8) & 0xff;
wreq[3] = addr & 0xff;
xfer[0].tx_buf = (uintptr_t)&cfg_->writeEnableCommand_;
xfer[0].len = 1;
xfer[0].cs_change = true;
xfer[1].tx_buf = (uintptr_t)wreq;
xfer[1].len = 4;
xfer[2].tx_buf = (uintptr_t)buf;
xfer[2].len = len;
xfer[2].cs_change = true;
::ioctl(spiFd_, SPI_IOC_MESSAGE(3), xfer);
unsigned waitcount = wait_for_write();
auto db = (const uint8_t *)buf;
LOG(INFO, "write [%x]=%02x%02x%02x%02x, %u bytes success after %u iter",
(unsigned)addr, db[0], db[1], db[2], db[3], len, waitcount);
}
unsigned SPIFlash::wait_for_write()
{
// Now we wait for the write to be complete.
unsigned waitcount = 0;
while (true)
{
struct spi_ioc_transfer sxfer = {0};
uint8_t streq[2];
streq[0] = cfg_->statusReadCommand_;
streq[1] = 0xFF;
sxfer.tx_buf = (uintptr_t)streq;
sxfer.rx_buf = (uintptr_t)streq;
sxfer.len = 2;
sxfer.cs_change = true;
::ioctl(spiFd_, SPI_IOC_MESSAGE(1), &sxfer);
if ((streq[1] & cfg_->statusWritePendingBit_) == 0)
{
return waitcount;
}
waitcount++;
}
}
void SPIFlash::erase(uint32_t addr, size_t len)
{
size_t end = addr + len;
while (addr < end)
{
struct spi_ioc_transfer xfer[2] = {0, 0};
uint8_t ereq[4];
ereq[0] = cfg_->eraseCommand_;
ereq[1] = (addr >> 16) & 0xff;
ereq[2] = (addr >> 8) & 0xff;
ereq[3] = (addr)&0xff;
xfer[0].tx_buf = (uintptr_t)&cfg_->writeEnableCommand_;
xfer[0].len = 1;
xfer[0].cs_change = true;
xfer[1].tx_buf = (uintptr_t)ereq;
xfer[1].len = 4;
xfer[1].cs_change = true;
::ioctl(spiFd_, SPI_IOC_MESSAGE(2), &xfer);
unsigned waitcount = wait_for_write();
LOG(INFO, "erase at %x, success after %u iter", (unsigned)addr,
waitcount);
addr += cfg_->sectorSize_;
}
}
void SPIFlash::chip_erase()
{
struct spi_ioc_transfer xfer[2] = {0, 0};
xfer[0].tx_buf = (uintptr_t)&cfg_->writeEnableCommand_;
xfer[0].len = 1;
xfer[0].cs_change = true;
xfer[1].tx_buf = (uintptr_t)&cfg_->chipEraseCommand_;
xfer[1].len = 1;
xfer[1].cs_change = true;
::ioctl(spiFd_, SPI_IOC_MESSAGE(2), &xfer);
unsigned waitcount = wait_for_write();
LOG(INFO, "chip-erase, success after %u iter", waitcount);
}
<|endoftext|> |
<commit_before>// Copyright 2016 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "rclcpp/node_interfaces/node_parameters.hpp"
#include <map>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "rcl_interfaces/srv/list_parameters.hpp"
#include "rclcpp/create_publisher.hpp"
#include "rmw/qos_profiles.h"
using rclcpp::node_interfaces::NodeParameters;
NodeParameters::NodeParameters(
rclcpp::node_interfaces::NodeTopicsInterface * node_topics,
bool use_intra_process)
: node_topics_(node_topics)
{
using MessageT = rcl_interfaces::msg::ParameterEvent;
using PublisherT = rclcpp::publisher::Publisher<MessageT>;
using AllocatorT = std::allocator<void>;
// TODO(wjwwood): expose this allocator through the Parameter interface.
auto allocator = std::make_shared<AllocatorT>();
events_publisher_ = rclcpp::create_publisher<MessageT, AllocatorT, PublisherT>(
node_topics_,
"parameter_events",
rmw_qos_profile_parameter_events,
use_intra_process,
allocator);
}
NodeParameters::~NodeParameters()
{}
std::vector<rcl_interfaces::msg::SetParametersResult>
NodeParameters::set_parameters(
const std::vector<rclcpp::parameter::ParameterVariant> & parameters)
{
std::vector<rcl_interfaces::msg::SetParametersResult> results;
for (auto p : parameters) {
auto result = set_parameters_atomically({{p}});
results.push_back(result);
}
return results;
}
rcl_interfaces::msg::SetParametersResult
NodeParameters::set_parameters_atomically(
const std::vector<rclcpp::parameter::ParameterVariant> & parameters)
{
std::lock_guard<std::mutex> lock(mutex_);
std::map<std::string, rclcpp::parameter::ParameterVariant> tmp_map;
auto parameter_event = std::make_shared<rcl_interfaces::msg::ParameterEvent>();
// TODO(jacquelinekay): handle parameter constraints
rcl_interfaces::msg::SetParametersResult result;
if (parameters_callback_) {
result = parameters_callback_(parameters);
} else {
result.successful = true;
}
if (!result.successful) {
return result;
}
for (auto p : parameters) {
if (parameters_.find(p.get_name()) == parameters_.end()) {
if (p.get_type() != rclcpp::parameter::ParameterType::PARAMETER_NOT_SET) {
// case: parameter not set before, and input is something other than "NOT_SET"
parameter_event->new_parameters.push_back(p.to_parameter());
}
} else if (p.get_type() != rclcpp::parameter::ParameterType::PARAMETER_NOT_SET) {
// case: parameter was set before, and input is something other than "NOT_SET"
parameter_event->changed_parameters.push_back(p.to_parameter());
} else {
// case: parameter was set before, and input is "NOT_SET"
// therefore we will "unset" the previously set parameter
// it is not necessary to erase the parameter from parameters_
// because the new value for this key (p.get_name()) will be a
// ParameterVariant with type "NOT_SET"
parameter_event->deleted_parameters.push_back(p.to_parameter());
}
tmp_map[p.get_name()] = p;
}
// std::map::insert will not overwrite elements, so we'll keep the new
// ones and add only those that already exist in the Node's internal map
tmp_map.insert(parameters_.begin(), parameters_.end());
std::swap(tmp_map, parameters_);
events_publisher_->publish(parameter_event);
return result;
}
std::vector<rclcpp::parameter::ParameterVariant>
NodeParameters::get_parameters(const std::vector<std::string> & names) const
{
std::lock_guard<std::mutex> lock(mutex_);
std::vector<rclcpp::parameter::ParameterVariant> results;
for (auto & name : names) {
if (std::any_of(parameters_.cbegin(), parameters_.cend(),
[&name](const std::pair<std::string, rclcpp::parameter::ParameterVariant> & kv) {
return name == kv.first;
}))
{
results.push_back(parameters_.at(name));
}
}
return results;
}
rclcpp::parameter::ParameterVariant
NodeParameters::get_parameter(const std::string & name) const
{
rclcpp::parameter::ParameterVariant parameter;
if (get_parameter(name, parameter)) {
return parameter;
} else {
throw std::out_of_range("Parameter '" + name + "' not set");
}
}
bool
NodeParameters::get_parameter(
const std::string & name,
rclcpp::parameter::ParameterVariant & parameter) const
{
std::lock_guard<std::mutex> lock(mutex_);
if (parameters_.count(name)) {
parameter = parameters_.at(name);
return true;
} else {
return false;
}
}
std::vector<rcl_interfaces::msg::ParameterDescriptor>
NodeParameters::describe_parameters(const std::vector<std::string> & names) const
{
std::lock_guard<std::mutex> lock(mutex_);
std::vector<rcl_interfaces::msg::ParameterDescriptor> results;
for (auto & kv : parameters_) {
if (std::any_of(names.cbegin(), names.cend(), [&kv](const std::string & name) {
return name == kv.first;
}))
{
rcl_interfaces::msg::ParameterDescriptor parameter_descriptor;
parameter_descriptor.name = kv.first;
parameter_descriptor.type = kv.second.get_type();
results.push_back(parameter_descriptor);
}
}
return results;
}
std::vector<uint8_t>
NodeParameters::get_parameter_types(const std::vector<std::string> & names) const
{
std::lock_guard<std::mutex> lock(mutex_);
std::vector<uint8_t> results;
for (auto & kv : parameters_) {
if (std::any_of(names.cbegin(), names.cend(), [&kv](const std::string & name) {
return name == kv.first;
}))
{
results.push_back(kv.second.get_type());
} else {
results.push_back(rcl_interfaces::msg::ParameterType::PARAMETER_NOT_SET);
}
}
return results;
}
rcl_interfaces::msg::ListParametersResult
NodeParameters::list_parameters(const std::vector<std::string> & prefixes, uint64_t depth) const
{
std::lock_guard<std::mutex> lock(mutex_);
rcl_interfaces::msg::ListParametersResult result;
// TODO(esteve): define parameter separator, use "." for now
for (auto & kv : parameters_) {
if (((prefixes.size() == 0) &&
((depth == rcl_interfaces::srv::ListParameters::Request::DEPTH_RECURSIVE) ||
(static_cast<uint64_t>(std::count(kv.first.begin(), kv.first.end(), '.')) < depth))) ||
(std::any_of(prefixes.cbegin(), prefixes.cend(), [&kv, &depth](const std::string & prefix) {
if (kv.first == prefix) {
return true;
} else if (kv.first.find(prefix + ".") == 0) {
size_t length = prefix.length();
std::string substr = kv.first.substr(length);
// Cast as unsigned integer to avoid warning
return (depth == rcl_interfaces::srv::ListParameters::Request::DEPTH_RECURSIVE) ||
(static_cast<uint64_t>(std::count(substr.begin(), substr.end(), '.')) < depth);
}
return false;
})))
{
result.names.push_back(kv.first);
size_t last_separator = kv.first.find_last_of('.');
if (std::string::npos != last_separator) {
std::string prefix = kv.first.substr(0, last_separator);
if (std::find(result.prefixes.cbegin(), result.prefixes.cend(), prefix) ==
result.prefixes.cend())
{
result.prefixes.push_back(prefix);
}
}
}
}
return result;
}
void
NodeParameters::register_param_change_callback(ParametersCallbackFunction callback)
{
if (parameters_callback_) {
fprintf(stderr, "Warning: param_change_callback already registered, "
"overwriting previous callback\n");
}
parameters_callback_ = callback;
}
<commit_msg>change parameter separator to forward slash (#367)<commit_after>// Copyright 2016 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "rclcpp/node_interfaces/node_parameters.hpp"
#include <map>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "rcl_interfaces/srv/list_parameters.hpp"
#include "rclcpp/create_publisher.hpp"
#include "rcutils/logging_macros.h"
#include "rmw/qos_profiles.h"
using rclcpp::node_interfaces::NodeParameters;
NodeParameters::NodeParameters(
rclcpp::node_interfaces::NodeTopicsInterface * node_topics,
bool use_intra_process)
: node_topics_(node_topics)
{
using MessageT = rcl_interfaces::msg::ParameterEvent;
using PublisherT = rclcpp::publisher::Publisher<MessageT>;
using AllocatorT = std::allocator<void>;
// TODO(wjwwood): expose this allocator through the Parameter interface.
auto allocator = std::make_shared<AllocatorT>();
events_publisher_ = rclcpp::create_publisher<MessageT, AllocatorT, PublisherT>(
node_topics_,
"parameter_events",
rmw_qos_profile_parameter_events,
use_intra_process,
allocator);
}
NodeParameters::~NodeParameters()
{}
std::vector<rcl_interfaces::msg::SetParametersResult>
NodeParameters::set_parameters(
const std::vector<rclcpp::parameter::ParameterVariant> & parameters)
{
std::vector<rcl_interfaces::msg::SetParametersResult> results;
for (auto p : parameters) {
auto result = set_parameters_atomically({{p}});
results.push_back(result);
}
return results;
}
rcl_interfaces::msg::SetParametersResult
NodeParameters::set_parameters_atomically(
const std::vector<rclcpp::parameter::ParameterVariant> & parameters)
{
std::lock_guard<std::mutex> lock(mutex_);
std::map<std::string, rclcpp::parameter::ParameterVariant> tmp_map;
auto parameter_event = std::make_shared<rcl_interfaces::msg::ParameterEvent>();
// TODO(jacquelinekay): handle parameter constraints
rcl_interfaces::msg::SetParametersResult result;
if (parameters_callback_) {
result = parameters_callback_(parameters);
} else {
result.successful = true;
}
if (!result.successful) {
return result;
}
for (auto p : parameters) {
if (parameters_.find(p.get_name()) == parameters_.end()) {
if (p.get_type() != rclcpp::parameter::ParameterType::PARAMETER_NOT_SET) {
// case: parameter not set before, and input is something other than "NOT_SET"
parameter_event->new_parameters.push_back(p.to_parameter());
}
} else if (p.get_type() != rclcpp::parameter::ParameterType::PARAMETER_NOT_SET) {
// case: parameter was set before, and input is something other than "NOT_SET"
parameter_event->changed_parameters.push_back(p.to_parameter());
} else {
// case: parameter was set before, and input is "NOT_SET"
// therefore we will "unset" the previously set parameter
// it is not necessary to erase the parameter from parameters_
// because the new value for this key (p.get_name()) will be a
// ParameterVariant with type "NOT_SET"
parameter_event->deleted_parameters.push_back(p.to_parameter());
}
tmp_map[p.get_name()] = p;
}
// std::map::insert will not overwrite elements, so we'll keep the new
// ones and add only those that already exist in the Node's internal map
tmp_map.insert(parameters_.begin(), parameters_.end());
std::swap(tmp_map, parameters_);
events_publisher_->publish(parameter_event);
return result;
}
std::vector<rclcpp::parameter::ParameterVariant>
NodeParameters::get_parameters(const std::vector<std::string> & names) const
{
std::lock_guard<std::mutex> lock(mutex_);
std::vector<rclcpp::parameter::ParameterVariant> results;
for (auto & name : names) {
if (std::any_of(parameters_.cbegin(), parameters_.cend(),
[&name](const std::pair<std::string, rclcpp::parameter::ParameterVariant> & kv) {
return name == kv.first;
}))
{
results.push_back(parameters_.at(name));
}
}
return results;
}
rclcpp::parameter::ParameterVariant
NodeParameters::get_parameter(const std::string & name) const
{
rclcpp::parameter::ParameterVariant parameter;
if (get_parameter(name, parameter)) {
return parameter;
} else {
throw std::out_of_range("Parameter '" + name + "' not set");
}
}
bool
NodeParameters::get_parameter(
const std::string & name,
rclcpp::parameter::ParameterVariant & parameter) const
{
std::lock_guard<std::mutex> lock(mutex_);
if (parameters_.count(name)) {
parameter = parameters_.at(name);
return true;
} else {
return false;
}
}
std::vector<rcl_interfaces::msg::ParameterDescriptor>
NodeParameters::describe_parameters(const std::vector<std::string> & names) const
{
std::lock_guard<std::mutex> lock(mutex_);
std::vector<rcl_interfaces::msg::ParameterDescriptor> results;
for (auto & kv : parameters_) {
if (std::any_of(names.cbegin(), names.cend(), [&kv](const std::string & name) {
return name == kv.first;
}))
{
rcl_interfaces::msg::ParameterDescriptor parameter_descriptor;
parameter_descriptor.name = kv.first;
parameter_descriptor.type = kv.second.get_type();
results.push_back(parameter_descriptor);
}
}
return results;
}
std::vector<uint8_t>
NodeParameters::get_parameter_types(const std::vector<std::string> & names) const
{
std::lock_guard<std::mutex> lock(mutex_);
std::vector<uint8_t> results;
for (auto & kv : parameters_) {
if (std::any_of(names.cbegin(), names.cend(), [&kv](const std::string & name) {
return name == kv.first;
}))
{
results.push_back(kv.second.get_type());
} else {
results.push_back(rcl_interfaces::msg::ParameterType::PARAMETER_NOT_SET);
}
}
return results;
}
rcl_interfaces::msg::ListParametersResult
NodeParameters::list_parameters(const std::vector<std::string> & prefixes, uint64_t depth) const
{
std::lock_guard<std::mutex> lock(mutex_);
rcl_interfaces::msg::ListParametersResult result;
const char separator = '/';
for (auto & kv : parameters_) {
bool get_all = (prefixes.size() == 0) &&
((depth == rcl_interfaces::srv::ListParameters::Request::DEPTH_RECURSIVE) ||
(static_cast<uint64_t>(std::count(kv.first.begin(), kv.first.end(), separator)) < depth));
bool prefix_matches = std::any_of(prefixes.cbegin(), prefixes.cend(),
[&kv, &depth, &separator](const std::string & prefix) {
if (kv.first == prefix) {
return true;
} else if (kv.first.find(prefix + separator) == 0) {
size_t length = prefix.length();
std::string substr = kv.first.substr(length);
// Cast as unsigned integer to avoid warning
return (depth == rcl_interfaces::srv::ListParameters::Request::DEPTH_RECURSIVE) ||
(static_cast<uint64_t>(std::count(substr.begin(), substr.end(), separator)) < depth);
}
return false;
});
if (get_all || prefix_matches) {
result.names.push_back(kv.first);
size_t last_separator = kv.first.find_last_of(separator);
if (std::string::npos != last_separator) {
std::string prefix = kv.first.substr(0, last_separator);
if (std::find(result.prefixes.cbegin(), result.prefixes.cend(), prefix) ==
result.prefixes.cend())
{
result.prefixes.push_back(prefix);
}
}
}
}
return result;
}
void
NodeParameters::register_param_change_callback(ParametersCallbackFunction callback)
{
if (parameters_callback_) {
RCUTILS_LOG_WARN("param_change_callback already registered, "
"overwriting previous callback")
}
parameters_callback_ = callback;
}
<|endoftext|> |
<commit_before>#include "engine/plugins/isochrone.hpp"
#include "engine/api/isochrone_api.hpp"
#include "engine/phantom_node.hpp"
#include "util/concave_hull.hpp"
#include "util/coordinate_calculation.hpp"
#include "util/graph_loader.hpp"
#include "util/monotone_chain.hpp"
#include "util/simple_logger.hpp"
#include "util/timing_util.hpp"
#include <algorithm>
namespace osrm
{
namespace engine
{
namespace plugins
{
IsochronePlugin::IsochronePlugin(datafacade::BaseDataFacade &facade, const std::string base)
: BasePlugin{facade}, base{base}
{
// Loads Graph into memory
if (!base.empty())
{
number_of_nodes = loadGraph(base, coordinate_list, graph_edge_list);
}
tbb::parallel_sort(graph_edge_list.begin(), graph_edge_list.end());
graph = std::make_shared<engine::plugins::SimpleGraph>(number_of_nodes, graph_edge_list);
graph_edge_list.clear();
graph_edge_list.shrink_to_fit();
}
Status IsochronePlugin::HandleRequest(const api::IsochroneParameters ¶ms,
util::json::Object &json_result)
{
BOOST_ASSERT(params.IsValid());
if (!CheckAllCoordinates(params.coordinates))
return Error("InvalidOptions", "Coordinates are invalid", json_result);
if (params.coordinates.size() != 1)
{
return Error("InvalidOptions", "Only one input coordinate is supported", json_result);
}
if (params.distance != 0 && params.duration != 0)
{
return Error("InvalidOptions", "Only distance or duration should be set", json_result);
}
if (params.concavehull == true && params.convexhull == false)
{
return Error(
"InvalidOptions", "If concavehull is set, convexhull must be set too", json_result);
}
auto phantomnodes = GetPhantomNodes(params, 1);
if (phantomnodes.front().size() <= 0)
{
return Error("PhantomNode", "PhantomNode couldnt be found for coordinate", json_result);
}
auto phantom = phantomnodes.front();
std::vector<NodeID> forward_id_vector;
facade.GetUncompressedGeometry(phantom.front().phantom_node.reverse_packed_geometry_id,
forward_id_vector);
auto source = forward_id_vector[0];
IsochroneVector isochroneVector;
IsochroneVector convexhull;
IsochroneVector concavehull;
if (params.duration != 0)
{
TIMER_START(DIJKSTRA);
dijkstraByDuration(isochroneVector, source, params.duration);
TIMER_STOP(DIJKSTRA);
util::SimpleLogger().Write() << "DijkstraByDuration took: " << TIMER_MSEC(DIJKSTRA) << "ms";
TIMER_START(SORTING);
std::sort(isochroneVector.begin(),
isochroneVector.end(),
[&](const IsochroneNode n1, const IsochroneNode n2) {
return n1.duration < n2.duration;
});
TIMER_STOP(SORTING);
util::SimpleLogger().Write() << "SORTING took: " << TIMER_MSEC(SORTING) << "ms";
}
if (params.distance != 0)
{
TIMER_START(DIJKSTRA);
dijkstraByDistance(isochroneVector, source, params.distance);
TIMER_STOP(DIJKSTRA);
util::SimpleLogger().Write() << "DijkstraByDistance took: " << TIMER_MSEC(DIJKSTRA) << "ms";
TIMER_START(SORTING);
std::sort(isochroneVector.begin(),
isochroneVector.end(),
[&](const IsochroneNode n1, const IsochroneNode n2) {
return n1.distance < n2.distance;
});
TIMER_STOP(SORTING);
util::SimpleLogger().Write() << "SORTING took: " << TIMER_MSEC(SORTING) << "ms";
}
util::SimpleLogger().Write() << "Nodes Found: " << isochroneVector.size();
// Optional param for calculating Convex Hull
if (params.convexhull)
{
TIMER_START(CONVEXHULL);
convexhull = util::monotoneChain(isochroneVector);
TIMER_STOP(CONVEXHULL);
util::SimpleLogger().Write() << "CONVEXHULL took: " << TIMER_MSEC(CONVEXHULL) << "ms";
}
if (params.concavehull && params.convexhull)
{
TIMER_START(CONCAVEHULL);
concavehull = util::concavehull(convexhull, params.threshold, isochroneVector);
TIMER_STOP(CONCAVEHULL);
util::SimpleLogger().Write() << "CONCAVEHULL took: " << TIMER_MSEC(CONCAVEHULL) << "ms";
}
TIMER_START(RESPONSE);
api::IsochroneAPI isochroneAPI(facade, params);
isochroneAPI.MakeResponse(isochroneVector, convexhull, concavehull, json_result);
TIMER_STOP(RESPONSE);
util::SimpleLogger().Write() << "RESPONSE took: " << TIMER_MSEC(RESPONSE) << "ms";
isochroneVector.clear();
isochroneVector.shrink_to_fit();
convexhull.clear();
convexhull.shrink_to_fit();
concavehull.clear();
concavehull.shrink_to_fit();
return Status::Ok;
}
void IsochronePlugin::dijkstraByDuration(IsochroneVector &isochroneSet,
NodeID &source,
int duration)
{
QueryHeap heap(number_of_nodes);
heap.Insert(source, 0, source);
isochroneSet.emplace_back(
IsochroneNode(coordinate_list[source], coordinate_list[source], 0, 0));
int MAX_DURATION = duration * 60 * 10;
{
// Standard Dijkstra search, terminating when path length > MAX
while (!heap.Empty())
{
const NodeID source = heap.DeleteMin();
const std::int32_t weight = heap.GetKey(source);
for (const auto current_edge : graph->GetAdjacentEdgeRange(source))
{
const auto target = graph->GetTarget(current_edge);
if (target != SPECIAL_NODEID)
{
const auto data = graph->GetEdgeData(current_edge);
if (data.real)
{
int to_duration = weight + data.weight;
if (to_duration > MAX_DURATION)
{
continue;
}
else if (!heap.WasInserted(target))
{
heap.Insert(target, to_duration, source);
isochroneSet.emplace_back(IsochroneNode(
coordinate_list[target], coordinate_list[source], 0, to_duration));
}
else if (to_duration < heap.GetKey(target))
{
heap.GetData(target).parent = source;
heap.DecreaseKey(target, to_duration);
update(isochroneSet,
IsochroneNode(coordinate_list[target],
coordinate_list[source],
0,
to_duration));
}
}
}
}
}
}
}
void IsochronePlugin::dijkstraByDistance(IsochroneVector &isochroneSet,
NodeID &source,
double distance)
{
QueryHeap heap(number_of_nodes);
heap.Insert(source, 0, source);
isochroneSet.emplace_back(
IsochroneNode(coordinate_list[source], coordinate_list[source], 0, 0));
int MAX_DISTANCE = distance;
{
// Standard Dijkstra search, terminating when path length > MAX
while (!heap.Empty())
{
NodeID source = heap.DeleteMin();
std::int32_t weight = heap.GetKey(source);
for (const auto current_edge : graph->GetAdjacentEdgeRange(source))
{
const auto target = graph->GetTarget(current_edge);
if (target != SPECIAL_NODEID)
{
const auto data = graph->GetEdgeData(current_edge);
if (data.real)
{
Coordinate s(coordinate_list[source].lon, coordinate_list[source].lat);
Coordinate t(coordinate_list[target].lon, coordinate_list[target].lat);
// FIXME this might not be accurate enough
int to_distance =
static_cast<int>(
util::coordinate_calculation::haversineDistance(s, t)) +
weight;
if (to_distance > MAX_DISTANCE)
{
continue;
}
else if (!heap.WasInserted(target))
{
heap.Insert(target, to_distance, source);
isochroneSet.emplace_back(IsochroneNode(
coordinate_list[target], coordinate_list[source], to_distance, 0));
}
else if (to_distance < heap.GetKey(target))
{
heap.GetData(target).parent = source;
heap.DecreaseKey(target, to_distance);
update(isochroneSet,
IsochroneNode(coordinate_list[target],
coordinate_list[source],
to_distance,
0));
}
}
}
}
}
}
}
std::size_t IsochronePlugin::loadGraph(const std::string &path,
std::vector<extractor::QueryNode> &coordinate_list,
std::vector<SimpleEdge> &graph_edge_list)
{
std::ifstream input_stream(path, std::ifstream::in | std::ifstream::binary);
if (!input_stream.is_open())
{
throw util::exception("Cannot open osrm file");
}
// load graph data
std::vector<extractor::NodeBasedEdge> edge_list;
std::vector<NodeID> traffic_light_node_list;
std::vector<NodeID> barrier_node_list;
auto number_of_nodes = util::loadNodesFromFile(
input_stream, barrier_node_list, traffic_light_node_list, coordinate_list);
util::loadEdgesFromFile(input_stream, edge_list);
traffic_light_node_list.clear();
traffic_light_node_list.shrink_to_fit();
// Building an node-based graph
for (const auto &input_edge : edge_list)
{
if (input_edge.source == input_edge.target)
{
continue;
}
// forward edge
graph_edge_list.emplace_back(
input_edge.source, input_edge.target, input_edge.weight, input_edge.forward);
// backward edge
graph_edge_list.emplace_back(
input_edge.target, input_edge.source, input_edge.weight, input_edge.backward);
}
return number_of_nodes;
}
void IsochronePlugin::update(IsochroneVector &v, IsochroneNode n)
{
for (auto node : v)
{
if (node.node.node_id == n.node.node_id)
{
node = n;
}
}
}
}
}
}
<commit_msg>timing<commit_after>#include "engine/plugins/isochrone.hpp"
#include "engine/api/isochrone_api.hpp"
#include "engine/phantom_node.hpp"
#include "util/concave_hull.hpp"
#include "util/coordinate_calculation.hpp"
#include "util/graph_loader.hpp"
#include "util/monotone_chain.hpp"
#include "util/simple_logger.hpp"
#include "util/timing_util.hpp"
#include <algorithm>
namespace osrm
{
namespace engine
{
namespace plugins
{
IsochronePlugin::IsochronePlugin(datafacade::BaseDataFacade &facade, const std::string base)
: BasePlugin{facade}, base{base}
{
// Loads Graph into memory
if (!base.empty())
{
number_of_nodes = loadGraph(base, coordinate_list, graph_edge_list);
}
tbb::parallel_sort(graph_edge_list.begin(), graph_edge_list.end());
graph = std::make_shared<engine::plugins::SimpleGraph>(number_of_nodes, graph_edge_list);
graph_edge_list.clear();
graph_edge_list.shrink_to_fit();
}
Status IsochronePlugin::HandleRequest(const api::IsochroneParameters ¶ms,
util::json::Object &json_result)
{
BOOST_ASSERT(params.IsValid());
if (!CheckAllCoordinates(params.coordinates))
return Error("InvalidOptions", "Coordinates are invalid", json_result);
if (params.coordinates.size() != 1)
{
return Error("InvalidOptions", "Only one input coordinate is supported", json_result);
}
if (params.distance != 0 && params.duration != 0)
{
return Error("InvalidOptions", "Only distance or duration should be set", json_result);
}
if (params.concavehull == true && params.convexhull == false)
{
return Error(
"InvalidOptions", "If concavehull is set, convexhull must be set too", json_result);
}
auto phantomnodes = GetPhantomNodes(params, 1);
if (phantomnodes.front().size() <= 0)
{
return Error("PhantomNode", "PhantomNode couldnt be found for coordinate", json_result);
}
auto phantom = phantomnodes.front();
std::vector<NodeID> forward_id_vector;
facade.GetUncompressedGeometry(phantom.front().phantom_node.reverse_packed_geometry_id,
forward_id_vector);
auto source = forward_id_vector[0];
IsochroneVector isochroneVector;
IsochroneVector convexhull;
IsochroneVector concavehull;
if (params.duration != 0)
{
TIMER_START(DIJKSTRA);
dijkstraByDuration(isochroneVector, source, params.duration);
TIMER_STOP(DIJKSTRA);
util::SimpleLogger().Write() << "DijkstraByDuration took: " << TIMER_MSEC(DIJKSTRA) << "ms";
TIMER_START(SORTING);
std::sort(isochroneVector.begin(),
isochroneVector.end(),
[&](const IsochroneNode n1, const IsochroneNode n2) {
return n1.duration < n2.duration;
});
TIMER_STOP(SORTING);
util::SimpleLogger().Write() << "SORTING took: " << TIMER_MSEC(SORTING) << "ms";
}
if (params.distance != 0)
{
TIMER_START(DIJKSTRA);
dijkstraByDistance(isochroneVector, source, params.distance);
TIMER_STOP(DIJKSTRA);
util::SimpleLogger().Write() << "DijkstraByDistance took: " << TIMER_MSEC(DIJKSTRA) << "ms";
TIMER_START(SORTING);
std::sort(isochroneVector.begin(),
isochroneVector.end(),
[&](const IsochroneNode n1, const IsochroneNode n2) {
return n1.distance < n2.distance;
});
TIMER_STOP(SORTING);
util::SimpleLogger().Write() << "SORTING took: " << TIMER_MSEC(SORTING) << "ms";
}
util::SimpleLogger().Write() << "Nodes Found: " << isochroneVector.size();
// Optional param for calculating Convex Hull
if (params.convexhull)
{
TIMER_START(CONVEXHULL);
convexhull = util::monotoneChain(isochroneVector);
TIMER_STOP(CONVEXHULL);
util::SimpleLogger().Write() << "CONVEXHULL took: " << TIMER_MSEC(CONVEXHULL) << "ms";
}
if (params.concavehull && params.convexhull)
{
TIMER_START(CONCAVEHULL);
concavehull = util::concavehull(convexhull, params.threshold, isochroneVector);
TIMER_STOP(CONCAVEHULL);
util::SimpleLogger().Write() << "CONCAVEHULL took: " << TIMER_MSEC(CONCAVEHULL) << "ms";
}
TIMER_START(RESPONSE);
api::IsochroneAPI isochroneAPI(facade, params);
isochroneAPI.MakeResponse(isochroneVector, convexhull, concavehull, json_result);
TIMER_STOP(RESPONSE);
util::SimpleLogger().Write() << "RESPONSE took: " << TIMER_MSEC(RESPONSE) << "ms";
isochroneVector.clear();
isochroneVector.shrink_to_fit();
convexhull.clear();
convexhull.shrink_to_fit();
concavehull.clear();
concavehull.shrink_to_fit();
return Status::Ok;
}
void IsochronePlugin::dijkstraByDuration(IsochroneVector &isochroneSet,
NodeID &source,
int duration)
{
QueryHeap heap(number_of_nodes);
heap.Insert(source, 0, source);
isochroneSet.emplace_back(
IsochroneNode(coordinate_list[source], coordinate_list[source], 0, 0));
int steps = 0;
int MAX_DURATION = duration * 60 * 10;
{
// Standard Dijkstra search, terminating when path length > MAX
while (!heap.Empty())
{
steps++;
const NodeID source = heap.DeleteMin();
const std::int32_t weight = heap.GetKey(source);
for (const auto current_edge : graph->GetAdjacentEdgeRange(source))
{
const auto target = graph->GetTarget(current_edge);
if (target != SPECIAL_NODEID)
{
const auto data = graph->GetEdgeData(current_edge);
if (data.real)
{
int to_duration = weight + data.weight;
if (to_duration > MAX_DURATION)
{
continue;
}
else if (!heap.WasInserted(target))
{
heap.Insert(target, to_duration, source);
isochroneSet.emplace_back(IsochroneNode(
coordinate_list[target], coordinate_list[source], 0, to_duration));
}
else if (to_duration < heap.GetKey(target))
{
heap.GetData(target).parent = source;
heap.DecreaseKey(target, to_duration);
update(isochroneSet,
IsochroneNode(coordinate_list[target],
coordinate_list[source],
0,
to_duration));
}
}
}
}
}
}
util::SimpleLogger().Write() << "Steps took: " << steps;
}
void IsochronePlugin::dijkstraByDistance(IsochroneVector &isochroneSet,
NodeID &source,
double distance)
{
QueryHeap heap(number_of_nodes);
heap.Insert(source, 0, source);
isochroneSet.emplace_back(
IsochroneNode(coordinate_list[source], coordinate_list[source], 0, 0));
int steps = 0;
int MAX_DISTANCE = distance;
{
// Standard Dijkstra search, terminating when path length > MAX
while (!heap.Empty())
{
steps++;
NodeID source = heap.DeleteMin();
std::int32_t weight = heap.GetKey(source);
for (const auto current_edge : graph->GetAdjacentEdgeRange(source))
{
const auto target = graph->GetTarget(current_edge);
if (target != SPECIAL_NODEID)
{
const auto data = graph->GetEdgeData(current_edge);
if (data.real)
{
Coordinate s(coordinate_list[source].lon, coordinate_list[source].lat);
Coordinate t(coordinate_list[target].lon, coordinate_list[target].lat);
// FIXME this might not be accurate enough
int to_distance =
static_cast<int>(
util::coordinate_calculation::haversineDistance(s, t)) +
weight;
if (to_distance > MAX_DISTANCE)
{
continue;
}
else if (!heap.WasInserted(target))
{
heap.Insert(target, to_distance, source);
isochroneSet.emplace_back(IsochroneNode(
coordinate_list[target], coordinate_list[source], to_distance, 0));
}
else if (to_distance < heap.GetKey(target))
{
heap.GetData(target).parent = source;
heap.DecreaseKey(target, to_distance);
update(isochroneSet,
IsochroneNode(coordinate_list[target],
coordinate_list[source],
to_distance,
0));
}
}
}
}
}
}
util::SimpleLogger().Write() << "Steps took: " << steps;
}
std::size_t IsochronePlugin::loadGraph(const std::string &path,
std::vector<extractor::QueryNode> &coordinate_list,
std::vector<SimpleEdge> &graph_edge_list)
{
std::ifstream input_stream(path, std::ifstream::in | std::ifstream::binary);
if (!input_stream.is_open())
{
throw util::exception("Cannot open osrm file");
}
// load graph data
std::vector<extractor::NodeBasedEdge> edge_list;
std::vector<NodeID> traffic_light_node_list;
std::vector<NodeID> barrier_node_list;
auto number_of_nodes = util::loadNodesFromFile(
input_stream, barrier_node_list, traffic_light_node_list, coordinate_list);
util::loadEdgesFromFile(input_stream, edge_list);
traffic_light_node_list.clear();
traffic_light_node_list.shrink_to_fit();
// Building an node-based graph
for (const auto &input_edge : edge_list)
{
if (input_edge.source == input_edge.target)
{
continue;
}
// forward edge
graph_edge_list.emplace_back(
input_edge.source, input_edge.target, input_edge.weight, input_edge.forward);
// backward edge
graph_edge_list.emplace_back(
input_edge.target, input_edge.source, input_edge.weight, input_edge.backward);
}
return number_of_nodes;
}
void IsochronePlugin::update(IsochroneVector &v, IsochroneNode n)
{
for (auto node : v)
{
if (node.node.node_id == n.node.node_id)
{
node = n;
}
}
}
}
}
}
<|endoftext|> |
<commit_before>// tests the inclusion algorithm for all 2D and 3D elements
#include "FemusInit.hpp"
#include "Marker.hpp"
#include "Line.hpp"
#include "MultiLevelMesh.hpp"
#include "VTKWriter.hpp"
#include "NonLinearImplicitSystem.hpp"
#include "MyVector.hpp"
using namespace femus;
// 2D CASE rigid rotation
// double InitalValueU(const std::vector < double >& x) {
// return -x[1];
// }
//
// double InitalValueV(const std::vector < double >& x) {
// return x[0];
// }
//
// double InitalValueW(const std::vector < double >& x) {
// return 0.;
// }
//3D CASE rotation
// double InitalValueU(const std::vector < double >& x)
// {
// return (-x[1] + x[2]) / sqrt(3);
// }
//
// double InitalValueV(const std::vector < double >& x)
// {
// return (x[0] - x[2]) / sqrt(3);
// }
//
// double InitalValueW(const std::vector < double >& x)
// {
// return (x[1] - x[0]) / sqrt(3);
// }
// //2D CASE with vorticity
// double pi = acos(-1.);
//
// double InitalValueU(const std::vector < double >& x) {
// double time = (x.size() == 4) ? x[3] : 0.;
// return 2. * sin(pi * (x[0] + 0.5)) * sin(pi * (x[0] + 0.5)) * sin(pi * (x[1] + 0.5)) * cos(pi * (x[1] + 0.5)) * cos(time);
// }
//
// double InitalValueV(const std::vector < double >& x) {
// double time = (x.size() == 4) ? x[3] : 0.;
// return -2. * sin(pi * (x[1] + 0.5)) * sin(pi * (x[1] + 0.5)) * sin(pi * (x[0] + 0.5)) * cos(pi * (x[0] + 0.5)) * cos(time);
// }
//
// double InitalValueW(const std::vector < double >& x) {
// double time = (x.size() == 4) ? x[3] : 0.;
// return 0.;
// }
// 3D CASE with vorticity
double pi = acos(-1.);
double InitalValueU(const std::vector < double >& x) {
double time = (x.size() == 4) ? x[3] : 0.;
return
2.*(sin(pi * (x[0] + 0.5)) * sin(pi * (x[0] + 0.5)) *
( sin(pi * (x[1] + 0.5)) * cos(pi * (x[1] + 0.5)) - sin(pi * (x[2] + 0.5)) * cos(pi * (x[2] + 0.5)) )
)* cos(time);
}
double InitalValueV(const std::vector < double >& x) {
double time = (x.size() == 4) ? x[3] : 0.;
return
2.*(sin(pi * (x[1] + 0.5)) * sin(pi * (x[1] + 0.5)) *
( sin(pi * (x[2] + 0.5)) * cos(pi * (x[2] + 0.5)) - sin(pi * (x[0] + 0.5)) * cos(pi * (x[0] + 0.5)) )
)* cos(time);
}
double InitalValueW(const std::vector < double >& x) {
double time = (x.size() == 4) ? x[3] : 0.;
return
2.*( sin(pi * (x[2] + 0.5)) * sin(pi * (x[2] + 0.5)) *
( sin(pi * (x[0] + 0.5)) * cos(pi * (x[0] + 0.5)) - sin(pi * (x[1] + 0.5)) * cos(pi * (x[1] + 0.5)) )
)* cos(time);
return 0.;
}
bool SetRefinementFlag(const std::vector < double >& x, const int& elemgroupnumber, const int& level)
{
bool refine = 0;
if (elemgroupnumber == 6 && level < 4) refine = 1;
if (elemgroupnumber == 7 && level < 5) refine = 1;
if (elemgroupnumber == 8 && level < 6) refine = 1;
return refine;
}
int main(int argc, char** args)
{
// init Petsc-MPI communicator
FemusInit mpinit(argc, args, MPI_COMM_WORLD);
MultiLevelMesh mlMsh;
double scalingFactor = 1.;
unsigned numberOfUniformLevels = 3; //for refinement in 3D
//unsigned numberOfUniformLevels = 1;
unsigned numberOfSelectiveLevels = 0;
std::vector < std::string > variablesToBePrinted;
/* element types
0 = HEX
1 = TET
2 = WEDGE
3 = QUAD
4 = TRI
*/
unsigned solType = 2;
std::cout << " -------------------------------------------------- TEST --------------------------------------------------" << std::endl;
//mlMsh.ReadCoarseMesh("./input/prism3D.neu", "seventh", scalingFactor);
//mlMsh.ReadCoarseMesh("./input/square.neu", "seventh", scalingFactor);
//mlMsh.ReadCoarseMesh("./input/tri2.neu", "seventh", scalingFactor);
//mlMsh.ReadCoarseMesh("./input/cubeMixed.neu", "seventh", scalingFactor);
mlMsh.ReadCoarseMesh("./input/test3Dbis.neu", "seventh", scalingFactor);
//mlMsh.ReadCoarseMesh("./input/test2Dbis.neu", "seventh", scalingFactor);
//mlMsh.ReadCoarseMesh("./input/test2D.neu", "seventh", scalingFactor);
//mlMsh.ReadCoarseMesh("./input/cubeTet.neu", "seventh", scalingFactor);
mlMsh.RefineMesh(numberOfUniformLevels + numberOfSelectiveLevels, numberOfUniformLevels , SetRefinementFlag);
unsigned dim = mlMsh.GetDimension();
// unsigned size = 100;
// std::vector < std::vector < double > > x; // marker
// std::vector < MarkerType > markerType;
//
// x.resize(size);
// markerType.resize(size);
//
// for(unsigned j = 0; j < size; j++) {
// x[j].assign(dim, 0);
// markerType[j] = VOLUME;
// }
//
// double pi = acos(-1.);
// for(unsigned j = 0; j < size; j++) {
// x[j][0] = 0. + 0.125 * cos(2.*pi / size * j);
// x[j][1] = .25 + 0.125 * sin(2.*pi / size * j);
// // x[j][2] = 0.;
// }
//
// Line linea(x, markerType, mlMsh.GetLevel(numberOfUniformLevels - 1), solType);
//BEGIN TEST FOR UPDATE LINE: to use it, make _particles public and initialize as the identity printList in UpdateLine
// std::vector <Marker* > particles(size);
//
// for(unsigned j = 0; j < size; j++) {
// std::vector <double> y(dim);
// y[0] = -0.15 + 0.2 * cos(2.*pi / size * j);
// y[1] = 0. + 0.2 * sin(2.*pi / size * j);
// particles[j] = new Marker(y, VOLUME, mlMsh.GetLevel(numberOfUniformLevels - 1), solType, true);
// }
//
// for(unsigned i=0; i<size; i++){
// linea._particles[i] = particles[i];
// }
//
// linea.UpdateLine();
//END
// PrintLine(DEFAULT_OUTPUTDIR, linea.GetLine(), false, 0);
MultiLevelSolution mlSol(&mlMsh);
// add variables to mlSol
mlSol.AddSolution("U", LAGRANGE, SECOND, 2);
mlSol.AddSolution("V", LAGRANGE, SECOND, 2);
if (dim == 3) mlSol.AddSolution("W", LAGRANGE, SECOND, 2);
mlSol.Initialize("U" , InitalValueU);
mlSol.Initialize("V" , InitalValueV);
if (dim == 3) mlSol.Initialize("W", InitalValueW);
std::cout << " --------------------------------------------------------------------------------------------- " << std::endl;
// Marker a1Quad(x, VOLUME, mlMsh.GetLevel(0), solType, true);
//Marker a( x, VOLUME, mlMsh.GetLevel(numberOfUniformLevels + numberOfSelectiveLevels -1) );
//std::cout << " The coordinates of the marker are " << x[0] << " ," << x[1] << " ," << x[2] << std::endl;
//std::cout << " The marker type is " << a1Quad.GetMarkerType() << std::endl;
variablesToBePrinted.push_back("All");
VTKWriter vtkIO(&mlSol);
vtkIO.SetDebugOutput(true);
vtkIO.Write(DEFAULT_OUTPUTDIR, "biquadratic", variablesToBePrinted);
clock_t start_time = clock();
clock_t init_time = clock();
unsigned size = 10000;
std::vector < std::vector < double > > x; // marker
std::vector < MarkerType > markerType;
x.resize(size);
markerType.resize(size);
std::vector < std::vector < std::vector < double > > > line(1);
std::vector < std::vector < std::vector < double > > > line0(1);
for (unsigned j = 0; j < size; j++) {
x[j].assign(dim, 0.);
markerType[j] = VOLUME;
}
// srand(2); //TODO 3D n=10, problem at iteration 6 with seed srand(1);
double pi = acos(-1.);
for (unsigned j = 0; j < size; j++) {
//BEGIN random initialization
// double r_rad = static_cast <double> (rand()) / RAND_MAX;
// r_rad = 0.4 * (1. - r_rad * r_rad * r_rad);
// double r_theta = static_cast <double> (rand()) / RAND_MAX * 2 * pi;
// double r_phi = static_cast <double> (rand()) / RAND_MAX * pi;
//
// x[j][0] = r_rad * sin(r_phi) * cos(r_theta);
// x[j][1] = r_rad * sin(r_phi) * sin(r_theta);
// if (dim == 3) {
// x[j][2] = r_rad * cos(r_phi);
// }
//END
x[j][0] = 0. + 0.125 * cos(2.*pi / size * j);
x[j][1] = .25 + 0.125 * sin(2.*pi / size * j);
if (dim == 3) {
x[j][2] = 0.;
}
}
Line linea(x, markerType, mlMsh.GetLevel(numberOfUniformLevels - 1), solType);
linea.GetLine(line0[0]);
PrintLine(DEFAULT_OUTPUTDIR, line0, false, 0);
double T = 2 * acos(-1.);
unsigned n = 16;
std::cout << std::endl << " init in " << std::setw(11) << std::setprecision(6) << std::fixed
<< static_cast<double>((clock() - init_time)) / CLOCKS_PER_SEC << " s" << std::endl;
clock_t advection_time = clock();
for (unsigned k = 1; k <= n; k++) {
std::cout << "Iteration = " << k << std::endl;
//uncomment for vortex test
mlSol.CopySolutionToOldSolution();
mlSol.UpdateSolution("U" , InitalValueU, pi * k / n);
mlSol.UpdateSolution("V" , InitalValueV, pi * k / n);
if (dim == 3) mlSol.UpdateSolution("W" , InitalValueW, pi * k / n);
linea.AdvectionParallel(mlSol.GetLevel(numberOfUniformLevels - 1), 40, T / n, 4);
linea.GetLine(line[0]);
PrintLine(DEFAULT_OUTPUTDIR, line, false, k);
}
std::cout << std::endl << " advection in: " << std::setw(11) << std::setprecision(6) << std::fixed
<< static_cast<double>((clock() - advection_time)) / CLOCKS_PER_SEC << " s" << std::endl;
std::cout << std::endl << " RANNA in: " << std::setw(11) << std::setprecision(6) << std::fixed
<< static_cast<double>((clock() - start_time)) / CLOCKS_PER_SEC << " s" << std::endl;
//computing the geometric error
double error = 0.;
for (unsigned j = 0; j < size + 1; j++) {
double tempError = 0.;
for (unsigned i = 0; i < dim; i++) {
tempError += (line0[0][j][i] - line[0][j][i]) * (line0[0][j][i] - line[0][j][i]);
}
error += sqrt(tempError);
}
error = error / size;
std::cout << " ERROR = " << std::setprecision(15) << error << std::endl;
// for(unsigned j = 0; j < size; j++) {
// std::vector <double> trial(dim);
// trial = linea._particles[linea._printList[j]]->GetIprocMarkerCoordinates();
// for(unsigned i=0; i<dim; i++){
// std::cout << " x[" << j << "][" << i << "]=" << trial[i] << std::endl;
// }
// }
return 0;
}
<commit_msg>commit to pull<commit_after>// tests the inclusion algorithm for all 2D and 3D elements
#include "FemusInit.hpp"
#include "Marker.hpp"
#include "Line.hpp"
#include "MultiLevelMesh.hpp"
#include "VTKWriter.hpp"
#include "NonLinearImplicitSystem.hpp"
#include "MyVector.hpp"
using namespace femus;
// 2D CASE rigid rotation
// double InitalValueU(const std::vector < double >& x) {
// return -x[1];
// }
//
// double InitalValueV(const std::vector < double >& x) {
// return x[0];
// }
//
// double InitalValueW(const std::vector < double >& x) {
// return 0.;
// }
//3D CASE rotation
double InitalValueU(const std::vector < double >& x)
{
return (-x[1] + x[2]) / sqrt(3);
}
double InitalValueV(const std::vector < double >& x)
{
return (x[0] - x[2]) / sqrt(3);
}
double InitalValueW(const std::vector < double >& x)
{
return (x[1] - x[0]) / sqrt(3);
}
// //2D CASE with vorticity
// double pi = acos(-1.);
//
// double InitalValueU(const std::vector < double >& x) {
// double time = (x.size() == 4) ? x[3] : 0.;
// return 2. * sin(pi * (x[0] + 0.5)) * sin(pi * (x[0] + 0.5)) * sin(pi * (x[1] + 0.5)) * cos(pi * (x[1] + 0.5)) * cos(time);
// }
//
// double InitalValueV(const std::vector < double >& x) {
// double time = (x.size() == 4) ? x[3] : 0.;
// return -2. * sin(pi * (x[1] + 0.5)) * sin(pi * (x[1] + 0.5)) * sin(pi * (x[0] + 0.5)) * cos(pi * (x[0] + 0.5)) * cos(time);
// }
//
// double InitalValueW(const std::vector < double >& x) {
// double time = (x.size() == 4) ? x[3] : 0.;
// return 0.;
// }
// 3D CASE with vorticity
// double pi = acos(-1.);
//
// double InitalValueU(const std::vector < double >& x) {
// double time = (x.size() == 4) ? x[3] : 0.;
// return
// 2.*(sin(pi * (x[0] + 0.5)) * sin(pi * (x[0] + 0.5)) *
// ( sin(pi * (x[1] + 0.5)) * cos(pi * (x[1] + 0.5)) - sin(pi * (x[2] + 0.5)) * cos(pi * (x[2] + 0.5)) )
// )* cos(time);
// }
//
// double InitalValueV(const std::vector < double >& x) {
// double time = (x.size() == 4) ? x[3] : 0.;
// return
// 2.*(sin(pi * (x[1] + 0.5)) * sin(pi * (x[1] + 0.5)) *
// ( sin(pi * (x[2] + 0.5)) * cos(pi * (x[2] + 0.5)) - sin(pi * (x[0] + 0.5)) * cos(pi * (x[0] + 0.5)) )
// )* cos(time);
// }
//
// double InitalValueW(const std::vector < double >& x) {
// double time = (x.size() == 4) ? x[3] : 0.;
// return
// 2.*( sin(pi * (x[2] + 0.5)) * sin(pi * (x[2] + 0.5)) *
// ( sin(pi * (x[0] + 0.5)) * cos(pi * (x[0] + 0.5)) - sin(pi * (x[1] + 0.5)) * cos(pi * (x[1] + 0.5)) )
// )* cos(time);
//
// return 0.;
// }
bool SetRefinementFlag(const std::vector < double >& x, const int& elemgroupnumber, const int& level)
{
bool refine = 0;
if (elemgroupnumber == 6 && level < 4) refine = 1;
if (elemgroupnumber == 7 && level < 5) refine = 1;
if (elemgroupnumber == 8 && level < 6) refine = 1;
return refine;
}
int main(int argc, char** args)
{
// init Petsc-MPI communicator
FemusInit mpinit(argc, args, MPI_COMM_WORLD);
MultiLevelMesh mlMsh;
double scalingFactor = 1.;
unsigned numberOfUniformLevels = 3; //for refinement in 3D
//unsigned numberOfUniformLevels = 1;
unsigned numberOfSelectiveLevels = 0;
std::vector < std::string > variablesToBePrinted;
/* element types
0 = HEX
1 = TET
2 = WEDGE
3 = QUAD
4 = TRI
*/
unsigned solType = 2;
std::cout << " -------------------------------------------------- TEST --------------------------------------------------" << std::endl;
//mlMsh.ReadCoarseMesh("./input/prism3D.neu", "seventh", scalingFactor);
//mlMsh.ReadCoarseMesh("./input/square.neu", "seventh", scalingFactor);
//mlMsh.ReadCoarseMesh("./input/tri2.neu", "seventh", scalingFactor);
//mlMsh.ReadCoarseMesh("./input/cubeMixed.neu", "seventh", scalingFactor);
mlMsh.ReadCoarseMesh("./input/test3Dbis.neu", "seventh", scalingFactor);
//mlMsh.ReadCoarseMesh("./input/test2Dbis.neu", "seventh", scalingFactor);
//mlMsh.ReadCoarseMesh("./input/test2D.neu", "seventh", scalingFactor);
//mlMsh.ReadCoarseMesh("./input/cubeTet.neu", "seventh", scalingFactor);
mlMsh.RefineMesh(numberOfUniformLevels + numberOfSelectiveLevels, numberOfUniformLevels , SetRefinementFlag);
unsigned dim = mlMsh.GetDimension();
// unsigned size = 100;
// std::vector < std::vector < double > > x; // marker
// std::vector < MarkerType > markerType;
//
// x.resize(size);
// markerType.resize(size);
//
// for(unsigned j = 0; j < size; j++) {
// x[j].assign(dim, 0);
// markerType[j] = VOLUME;
// }
//
// double pi = acos(-1.);
// for(unsigned j = 0; j < size; j++) {
// x[j][0] = 0. + 0.125 * cos(2.*pi / size * j);
// x[j][1] = .25 + 0.125 * sin(2.*pi / size * j);
// // x[j][2] = 0.;
// }
//
// Line linea(x, markerType, mlMsh.GetLevel(numberOfUniformLevels - 1), solType);
//BEGIN TEST FOR UPDATE LINE: to use it, make _particles public and initialize as the identity printList in UpdateLine
// std::vector <Marker* > particles(size);
//
// for(unsigned j = 0; j < size; j++) {
// std::vector <double> y(dim);
// y[0] = -0.15 + 0.2 * cos(2.*pi / size * j);
// y[1] = 0. + 0.2 * sin(2.*pi / size * j);
// particles[j] = new Marker(y, VOLUME, mlMsh.GetLevel(numberOfUniformLevels - 1), solType, true);
// }
//
// for(unsigned i=0; i<size; i++){
// linea._particles[i] = particles[i];
// }
//
// linea.UpdateLine();
//END
// PrintLine(DEFAULT_OUTPUTDIR, linea.GetLine(), false, 0);
MultiLevelSolution mlSol(&mlMsh);
// add variables to mlSol
mlSol.AddSolution("U", LAGRANGE, SECOND, 2);
mlSol.AddSolution("V", LAGRANGE, SECOND, 2);
if (dim == 3) mlSol.AddSolution("W", LAGRANGE, SECOND, 2);
mlSol.Initialize("U" , InitalValueU);
mlSol.Initialize("V" , InitalValueV);
if (dim == 3) mlSol.Initialize("W", InitalValueW);
std::cout << " --------------------------------------------------------------------------------------------- " << std::endl;
// Marker a1Quad(x, VOLUME, mlMsh.GetLevel(0), solType, true);
//Marker a( x, VOLUME, mlMsh.GetLevel(numberOfUniformLevels + numberOfSelectiveLevels -1) );
//std::cout << " The coordinates of the marker are " << x[0] << " ," << x[1] << " ," << x[2] << std::endl;
//std::cout << " The marker type is " << a1Quad.GetMarkerType() << std::endl;
variablesToBePrinted.push_back("All");
VTKWriter vtkIO(&mlSol);
vtkIO.SetDebugOutput(true);
vtkIO.Write(DEFAULT_OUTPUTDIR, "biquadratic", variablesToBePrinted);
clock_t start_time = clock();
clock_t init_time = clock();
unsigned size = 100;
std::vector < std::vector < double > > x; // marker
std::vector < MarkerType > markerType;
x.resize(size);
markerType.resize(size);
std::vector < std::vector < std::vector < double > > > line(1);
std::vector < std::vector < std::vector < double > > > line0(1);
for (unsigned j = 0; j < size; j++) {
x[j].assign(dim, 0.);
markerType[j] = VOLUME;
}
// srand(2); //TODO 3D n=10, problem at iteration 6 with seed srand(1);
double pi = acos(-1.);
for (unsigned j = 0; j < size; j++) {
//BEGIN random initialization
// double r_rad = static_cast <double> (rand()) / RAND_MAX;
// r_rad = 0.4 * (1. - r_rad * r_rad * r_rad);
// double r_theta = static_cast <double> (rand()) / RAND_MAX * 2 * pi;
// double r_phi = static_cast <double> (rand()) / RAND_MAX * pi;
//
// x[j][0] = r_rad * sin(r_phi) * cos(r_theta);
// x[j][1] = r_rad * sin(r_phi) * sin(r_theta);
// if (dim == 3) {
// x[j][2] = r_rad * cos(r_phi);
// }
//END
x[j][0] = 0. + 0.125 * cos(2.*pi / size * j);
x[j][1] = .25 + 0.125 * sin(2.*pi / size * j);
if (dim == 3) {
x[j][2] = 0.;
}
}
Line linea(x, markerType, mlMsh.GetLevel(numberOfUniformLevels - 1), solType);
linea.GetLine(line0[0]);
PrintLine(DEFAULT_OUTPUTDIR, line0, false, 0);
double T = 2 * acos(-1.);
unsigned n = 100;
std::cout << std::endl << " init in " << std::setw(11) << std::setprecision(6) << std::fixed
<< static_cast<double>((clock() - init_time)) / CLOCKS_PER_SEC << " s" << std::endl;
clock_t advection_time = clock();
for (unsigned k = 1; k <= n; k++) {
std::cout << "Iteration = " << k << std::endl;
//uncomment for vortex test
mlSol.CopySolutionToOldSolution();
mlSol.UpdateSolution("U" , InitalValueU, pi * k / n);
mlSol.UpdateSolution("V" , InitalValueV, pi * k / n);
if (dim == 3) mlSol.UpdateSolution("W" , InitalValueW, pi * k / n);
linea.AdvectionParallel(mlSol.GetLevel(numberOfUniformLevels - 1), 40, T / n, 4);
linea.GetLine(line[0]);
PrintLine(DEFAULT_OUTPUTDIR, line, false, k);
}
std::cout << std::endl << " advection in: " << std::setw(11) << std::setprecision(6) << std::fixed
<< static_cast<double>((clock() - advection_time)) / CLOCKS_PER_SEC << " s" << std::endl;
std::cout << std::endl << " RANNA in: " << std::setw(11) << std::setprecision(6) << std::fixed
<< static_cast<double>((clock() - start_time)) / CLOCKS_PER_SEC << " s" << std::endl;
//computing the geometric error
double error = 0.;
for (unsigned j = 0; j < size + 1; j++) {
double tempError = 0.;
for (unsigned i = 0; i < dim; i++) {
tempError += (line0[0][j][i] - line[0][j][i]) * (line0[0][j][i] - line[0][j][i]);
}
error += sqrt(tempError);
}
error = error / size;
std::cout << " ERROR = " << std::setprecision(15) << error << std::endl;
// for(unsigned j = 0; j < size; j++) {
// std::vector <double> trial(dim);
// trial = linea._particles[linea._printList[j]]->GetIprocMarkerCoordinates();
// for(unsigned i=0; i<dim; i++){
// std::cout << " x[" << j << "][" << i << "]=" << trial[i] << std::endl;
// }
// }
return 0;
}
<|endoftext|> |
<commit_before>/*!
\copyright (c) RDO-Team, 2011
\file rdo_resource.inl
\author (dluschan@rk9.bmstu.ru)
\date 15.06.2011
\brief RDOResource inline implementation
\indent 4T
*/
// ----------------------------------------------------------------------- INCLUDES
// ----------------------------------------------------------------------- SYNOPSIS
#include "utils/rdomacros.h"
#include "simulator/runtime/namespace.h"
// --------------------------------------------------------------------------------
OPEN_RDO_RUNTIME_NAMESPACE
// --------------------------------------------------------------------------------
// -------------------- RDOResource
// --------------------------------------------------------------------------------
inline void RDOResource::setRuntime(CREF(LPRDORuntime) pRuntime)
{
UNUSED(pRuntime);
/// @todo
NEVER_REACH_HERE;
}
inline tstring RDOResource::whoAreYou()
{
return _T("rdoRes");
}
inline void RDOResource::makeTemporary(rbool value)
{
m_temporary = value;
}
inline RDOResource::ConvertStatus RDOResource::getState() const
{
return m_state;
}
inline void RDOResource::setState(RDOResource::ConvertStatus value)
{
m_state = value;
}
inline rbool RDOResource::checkType(ruint type) const
{
return m_type == type;
}
inline CREF(LPIResourceType) RDOResource::getResType() const
{
return m_resType;
}
inline ruint RDOResource::getType() const
{
return m_type;
}
inline CREF(RDOResource::ParamList) RDOResource::getParamList() const
{
return m_paramList;
}
inline CREF(RDOValue) RDOResource::getParam(ruint index) const
{
ASSERT(index < m_paramList.size());
return m_paramList[index];
}
inline REF(RDOValue) RDOResource::getParamRaw(ruint index)
{
ASSERT(index < m_paramList.size());
setState(CS_Keep);
return m_paramList[index];
}
inline void RDOResource::setParam(ruint index, CREF(RDOValue) value)
{
ASSERT(index < m_paramList.size());
setState(CS_Keep);
m_paramList[index] = value;
}
inline ruint RDOResource::paramsCount() const
{
return m_paramList.size();
}
inline void RDOResource::appendParams(CREF(ParamCIt) from_begin, CREF(ParamCIt) from_end)
{
m_paramList.insert(m_paramList.end(), from_begin, from_end);
}
inline rbool RDOResource::canFree() const
{
return m_referenceCount == 0;
}
inline void RDOResource::incRef()
{
++m_referenceCount;
}
inline void RDOResource::decRef()
{
--m_referenceCount;
}
inline tstring RDOResource::traceTypeId()
{
return m_typeId.empty() ? (m_typeId = getTypeId()) : m_typeId;
}
CLOSE_RDO_RUNTIME_NAMESPACE
<commit_msg> - оптимизация кода<commit_after>/*!
\copyright (c) RDO-Team, 2011
\file rdo_resource.inl
\author (dluschan@rk9.bmstu.ru)
\date 15.06.2011
\brief RDOResource inline implementation
\indent 4T
*/
// ----------------------------------------------------------------------- INCLUDES
// ----------------------------------------------------------------------- SYNOPSIS
#include "utils/rdomacros.h"
#include "simulator/runtime/namespace.h"
// --------------------------------------------------------------------------------
OPEN_RDO_RUNTIME_NAMESPACE
// --------------------------------------------------------------------------------
// -------------------- RDOResource
// --------------------------------------------------------------------------------
inline void RDOResource::setRuntime(CREF(LPRDORuntime) pRuntime)
{
UNUSED(pRuntime);
/// @todo
NEVER_REACH_HERE;
}
inline tstring RDOResource::whoAreYou()
{
return _T("rdoRes");
}
inline void RDOResource::makeTemporary(rbool value)
{
m_temporary = value;
}
inline RDOResource::ConvertStatus RDOResource::getState() const
{
return m_state;
}
inline void RDOResource::setState(RDOResource::ConvertStatus value)
{
m_state = value;
}
inline rbool RDOResource::checkType(ruint type) const
{
return m_type == type;
}
inline CREF(LPIResourceType) RDOResource::getResType() const
{
return m_resType;
}
inline ruint RDOResource::getType() const
{
return m_type;
}
inline CREF(RDOResource::ParamList) RDOResource::getParamList() const
{
return m_paramList;
}
inline CREF(RDOValue) RDOResource::getParam(ruint index) const
{
ASSERT(index < m_paramList.size());
return m_paramList[index];
}
inline REF(RDOValue) RDOResource::getParamRaw(ruint index)
{
setState(CS_Keep);
return getParam(index);
}
inline void RDOResource::setParam(ruint index, CREF(RDOValue) value)
{
ASSERT(index < m_paramList.size());
setState(CS_Keep);
m_paramList[index] = value;
}
inline ruint RDOResource::paramsCount() const
{
return m_paramList.size();
}
inline void RDOResource::appendParams(CREF(ParamCIt) from_begin, CREF(ParamCIt) from_end)
{
m_paramList.insert(m_paramList.end(), from_begin, from_end);
}
inline rbool RDOResource::canFree() const
{
return m_referenceCount == 0;
}
inline void RDOResource::incRef()
{
++m_referenceCount;
}
inline void RDOResource::decRef()
{
--m_referenceCount;
}
inline tstring RDOResource::traceTypeId()
{
return m_typeId.empty() ? (m_typeId = getTypeId()) : m_typeId;
}
CLOSE_RDO_RUNTIME_NAMESPACE
<|endoftext|> |
<commit_before>#include "include/redis_admin.h"
//TO-DO: When an operation fails, it should automatically detect whether there are
//Sentinels available and, if so, try to failover to another Redis Node.
void RedisAdmin::init(std::string hostname, int port, int timeout_seconds, int timeout_microseconds)
{
struct timeval timeout = {timeout_seconds, timeout_microseconds};
c = redisConnectWithTimeout(hostname.c_str(), port, timeout);
if (c == NULL || c->err) {
if (c == NULL)
{
throw RedisConnectionException( "Error: Cannot Allocate Redis Instance" );
}
else if (c->err)
{
std::string err_msg (c->errstr);
err_msg = "Error:" + err_msg;
throw RedisConnectionException( err_msg );
}
exit(1);
}
}
bool RedisAdmin::process_std_string_reply(redisReply *reply)
{
bool ret_val = false;
if ( strcmp(reply->str, "OK") == 0 ) {
ret_val = true;
}
freeReplyObject(reply);
reply = NULL;
return ret_val;
}
bool RedisAdmin::process_std_int_reply(redisReply *reply)
{
int reply_code = reply->integer;
freeReplyObject(reply);
reply = NULL;
if (reply_code == 1) {
return true;
}
return false;
}
int RedisAdmin::return_int_reply(redisReply *reply)
{
int reply_code = reply->integer;
freeReplyObject(reply);
reply = NULL;
return reply_code;
}
std::string RedisAdmin::return_string_reply(redisReply *reply)
{
std::string reply_str (reply->str);
freeReplyObject(reply);
reply = NULL;
return reply_str;
}
RedisAdmin::RedisAdmin(std::string hostname, int port)
{
init(hostname, port, 5, 0);
}
RedisAdmin::RedisAdmin(std::string hostname, int port, int timeout_seconds, int timeout_microseconds)
{
init(hostname, port, timeout_seconds, timeout_microseconds);
}
RedisAdmin::RedisAdmin(RedisConnChain current_connection)
{
//Connect to the DB
init(current_connection.ip, current_connection.port, current_connection.timeout, 0);
//Authenticate with the DB
std::string key_str = "AUTH " + current_connection.password;
reply = (redisReply *) redisCommand(c, key_str.c_str());
if ( !(strcmp(reply->str, "OK") == 0) ) {
std::string err_msg = "Error: Authentication Failed";
throw RedisConnectionException( err_msg );
}
freeReplyObject(reply);
}
RedisAdmin::~RedisAdmin()
{
if (c)
{
redisFree(c);
}
if (reply)
{
freeReplyObject(reply);
}
}
//! Load a value from Redis
std::string RedisAdmin::load ( std::string key )
{
std::string key_str = "GET " + key;
reply = (redisReply *) redisCommand(c, key_str.c_str());
return return_string_reply(reply);
}
//! Save a value to Redis
bool RedisAdmin::save ( std::string key, std::string msg )
{
reply = (redisReply *) redisCommand( c, "SET %s %s", key.c_str(), msg.c_str() );
return process_std_string_reply(reply);
}
//! Does a key exist in Redis?
bool RedisAdmin::exists ( std::string key )
{
std::string key_str = "EXISTS " + key;
reply = (redisReply *) redisCommand(c, key_str.c_str());
return process_std_int_reply(reply);
}
//! Delete a value from Redis
bool RedisAdmin::del ( std::string key )
{
std::string key_str = "DEL " + key;
reply = (redisReply *) redisCommand( c, key_str.c_str() );
return process_std_int_reply(reply);
}
//! Expire a value in Redis after a specified number of seconds
bool RedisAdmin::expire ( std::string key, unsigned int second)
{
std::string length_key = std::to_string(second);
reply = (redisReply *) redisCommand( c, "EXPIRE %s %s", key.c_str(), length_key.c_str() );
return process_std_int_reply(reply);
}
bool RedisAdmin::persist ( std::string key )
{
std::string key_str = "PERSIST " + key;
reply = (redisReply *) redisCommand( c, key_str.c_str() );
return process_std_int_reply(reply);
}
int RedisAdmin::incr ( std::string key )
{
std::string key_str = "INCR " + key;
reply = (redisReply *) redisCommand( c, key_str.c_str() );
return return_int_reply(reply);
}
int RedisAdmin::incr ( std::string key, int incr_amt )
{
std::string key_str = "INCRBY " + key + " " + std::to_string(incr_amt);
reply = (redisReply *) redisCommand( c, key_str.c_str() );
return return_int_reply(reply);
}
int RedisAdmin::decr ( std::string key )
{
std::string key_str = "DECR " + key;
reply = (redisReply *) redisCommand( c, key_str.c_str() );
return return_int_reply(reply);
}
int RedisAdmin::decr ( std::string key, int decr_amt )
{
std::string key_str = "DECRBY " + key + " " + std::to_string(decr_amt);
reply = (redisReply *) redisCommand( c, key_str.c_str() );
return return_int_reply(reply);
}
bool RedisAdmin::setex ( std::string key, std::string val, unsigned int second)
{
std::string length_key = std::to_string(second);
reply = (redisReply *) redisCommand( c, "SETEX %s \"%s\" %s", key.c_str(), val.c_str(), length_key.c_str() );
return process_std_string_reply(reply);
}
bool RedisAdmin::append ( std::string key, std::string val )
{
reply = (redisReply *) redisCommand( c, "APPEND %s \"%s\"", key.c_str(), val.c_str() );
return process_std_string_reply(reply);
}
int RedisAdmin::len ( std::string key )
{
std::string key_str = "STRLEN " + key;
reply = (redisReply *) redisCommand( c, key_str.c_str() );
return return_int_reply(reply);
}
int RedisAdmin::lpush ( std::string key, std::string val )
{
reply = (redisReply *) redisCommand( c, "LPUSH %s \"%s\"", key.c_str(), val.c_str() );
return return_int_reply(reply);
}
int RedisAdmin::rpush ( std::string key, std::string val )
{
reply = (redisReply *) redisCommand( c, "RPUSH %s \"%s\"", key.c_str(), val.c_str() );
return return_int_reply(reply);
}
//! Pop a value from a Redis list on the given key
std::string RedisAdmin::lpop ( std::string key )
{
std::string key_str = "LPOP " + key;
reply = (redisReply *) redisCommand(c, key_str.c_str());
return return_string_reply(reply);
}
//! Pop a value from a Redis list on the given key
std::string RedisAdmin::rpop ( std::string key )
{
std::string key_str = "RPOP " + key;
reply = (redisReply *) redisCommand(c, key_str.c_str());
return return_string_reply(reply);
}
//! Set the value stored in the list at key and the index at index
bool RedisAdmin::lset ( std::string key, std::string val, int index)
{
std::string index_str = std::to_string(index);
reply = (redisReply *) redisCommand( c, "APPEND %s %s \"%s\"", key.c_str(), index_str.c_str(), val.c_str() );
return process_std_string_reply(reply);
}
//! Insert a value into the list at key and before/after the pivot value
int RedisAdmin::linsert ( std::string key, std::string val, std::string pivot, bool before_pivot=true)
{
std::string ba_str;
if (before_pivot) {ba_str = "BEFORE";}
else {ba_str = "AFTER";}
std::string key_str = "LINSERT " + key;
reply = (redisReply *) redisCommand(c, "LINSERT %s \"%s\" \"%s\"", key_str.c_str(), pivot.c_str(), val.c_str());
return return_int_reply(reply);
}
//! Get the value stored in the list at key and the index at index
std::string RedisAdmin::lindex ( std::string key, int index)
{
std::string length_key = std::to_string(index);
reply = (redisReply *) redisCommand( c, "LINDEX %s %s", key.c_str(), length_key.c_str() );
return return_string_reply(reply);
}
//! Get the length of a list stored in Redis
int RedisAdmin::llen ( std::string key )
{
std::string key_str = "LLEN " + key;
reply = (redisReply *) redisCommand( c, key_str.c_str() );
return return_int_reply(reply);
}
//! Trim a list to the specified start and end index
bool RedisAdmin::ltrim ( std::string key, int start_index, int end_index)
{
std::string start = std::to_string(start_index);
std::string end = std::to_string(end_index);
reply = (redisReply *) redisCommand( c, "LTRIM %s %s %s", key.c_str(), start.c_str(), end.c_str() );
return process_std_string_reply(reply);
}
bool RedisAdmin::mset ( std::vector<RedisKvPair> save_sets )
{
std::string cmd_str = "MSET ";
for (int i=0; i<save_sets.size(); ++i)
{
cmd_str = cmd_str + save_sets[i].key + " \"" + save_sets[i].val + "\" ";
}
reply = (redisReply *) redisCommand( c, cmd_str.c_str() );
return process_std_string_reply(reply);
}
std::vector<std::string> RedisAdmin::mget ( std::vector<std::string> keys )
{
std::string cmd_str = "MGET ";
for (int i=0; i<keys.size(); ++i)
{
cmd_str = cmd_str + keys[i] + " ";
}
reply = (redisReply *) redisCommand( c, cmd_str.c_str() );
std::vector<std::string> reply_string;
for (int j=0;j<reply->elements; ++j)
{
std::string new_element (reply->element[j]->str);
reply_string.push_back(new_element);
}
return reply_string;
}
bool RedisAdmin::msetnx ( std::vector<RedisKvPair> save_sets )
{
std::string cmd_str = "MSETNX ";
for (int i=0; i<save_sets.size(); ++i)
{
cmd_str = cmd_str + save_sets[i].key + " \"" + save_sets[i].val + "\" ";
}
reply = (redisReply *) redisCommand( c, cmd_str.c_str() );
return process_std_int_reply(reply);
}
bool RedisAdmin::setnx ( std::string key, std::string msg )
{
reply = (redisReply *) redisCommand( c, "SETNX %s %s", key.c_str(), msg.c_str() );
return process_std_int_reply(reply);
}
<commit_msg>New Redis Methods Added<commit_after>#include "include/redis_admin.h"
//TO-DO: When an operation fails, it should automatically detect whether there are
//Sentinels available and, if so, try to failover to another Redis Node.
void RedisAdmin::init(std::string hostname, int port, int timeout_seconds, int timeout_microseconds)
{
struct timeval timeout = {timeout_seconds, timeout_microseconds};
c = redisConnectWithTimeout(hostname.c_str(), port, timeout);
if (c == NULL || c->err) {
if (c == NULL)
{
throw RedisConnectionException( "Error: Cannot Allocate Redis Instance" );
}
else if (c->err)
{
std::string err_msg (c->errstr);
err_msg = "Error:" + err_msg;
throw RedisConnectionException( err_msg );
}
exit(1);
}
}
bool RedisAdmin::process_std_string_reply(redisReply *reply)
{
bool ret_val = false;
if ( strcmp(reply->str, "OK") == 0 ) {
ret_val = true;
}
freeReplyObject(reply);
reply = NULL;
return ret_val;
}
bool RedisAdmin::process_std_int_reply(redisReply *reply)
{
int reply_code = reply->integer;
freeReplyObject(reply);
reply = NULL;
if (reply_code == 1) {
return true;
}
return false;
}
int RedisAdmin::return_int_reply(redisReply *reply)
{
int reply_code = reply->integer;
freeReplyObject(reply);
reply = NULL;
return reply_code;
}
std::string RedisAdmin::return_string_reply(redisReply *reply)
{
std::string reply_str (reply->str);
freeReplyObject(reply);
reply = NULL;
return reply_str;
}
RedisAdmin::RedisAdmin(std::string hostname, int port)
{
init(hostname, port, 5, 0);
}
RedisAdmin::RedisAdmin(std::string hostname, int port, int timeout_seconds, int timeout_microseconds)
{
init(hostname, port, timeout_seconds, timeout_microseconds);
}
RedisAdmin::RedisAdmin(RedisConnChain current_connection)
{
//Connect to the DB
init(current_connection.ip, current_connection.port, current_connection.timeout, 0);
//Authenticate with the DB
std::string key_str = "AUTH " + current_connection.password;
reply = (redisReply *) redisCommand(c, key_str.c_str());
if ( !(strcmp(reply->str, "OK") == 0) ) {
std::string err_msg = "Error: Authentication Failed";
throw RedisConnectionException( err_msg );
}
freeReplyObject(reply);
}
RedisAdmin::~RedisAdmin()
{
if (c)
{
redisFree(c);
}
if (reply)
{
freeReplyObject(reply);
}
}
//! Load a value from Redis
std::string RedisAdmin::load ( std::string key )
{
std::string key_str = "GET " + key;
reply = (redisReply *) redisCommand(c, key_str.c_str());
return return_string_reply(reply);
}
//! Save a value to Redis
bool RedisAdmin::save ( std::string key, std::string msg )
{
reply = (redisReply *) redisCommand( c, "SET %s %s", key.c_str(), msg.c_str() );
return process_std_string_reply(reply);
}
//! Does a key exist in Redis?
bool RedisAdmin::exists ( std::string key )
{
std::string key_str = "EXISTS " + key;
reply = (redisReply *) redisCommand(c, key_str.c_str());
return process_std_int_reply(reply);
}
//! Delete a value from Redis
bool RedisAdmin::del ( std::string key )
{
std::string key_str = "DEL " + key;
reply = (redisReply *) redisCommand( c, key_str.c_str() );
return process_std_int_reply(reply);
}
//! Expire a value in Redis after a specified number of seconds
bool RedisAdmin::expire ( std::string key, unsigned int second)
{
std::string length_key = std::to_string(second);
reply = (redisReply *) redisCommand( c, "EXPIRE %s %s", key.c_str(), length_key.c_str() );
return process_std_int_reply(reply);
}
bool RedisAdmin::persist ( std::string key )
{
std::string key_str = "PERSIST " + key;
reply = (redisReply *) redisCommand( c, key_str.c_str() );
return process_std_int_reply(reply);
}
int RedisAdmin::incr ( std::string key )
{
std::string key_str = "INCR " + key;
reply = (redisReply *) redisCommand( c, key_str.c_str() );
return return_int_reply(reply);
}
int RedisAdmin::incr ( std::string key, int incr_amt )
{
std::string key_str = "INCRBY " + key + " " + std::to_string(incr_amt);
reply = (redisReply *) redisCommand( c, key_str.c_str() );
return return_int_reply(reply);
}
int RedisAdmin::decr ( std::string key )
{
std::string key_str = "DECR " + key;
reply = (redisReply *) redisCommand( c, key_str.c_str() );
return return_int_reply(reply);
}
int RedisAdmin::decr ( std::string key, int decr_amt )
{
std::string key_str = "DECRBY " + key + " " + std::to_string(decr_amt);
reply = (redisReply *) redisCommand( c, key_str.c_str() );
return return_int_reply(reply);
}
bool RedisAdmin::setex ( std::string key, std::string val, unsigned int second)
{
std::string length_key = std::to_string(second);
reply = (redisReply *) redisCommand( c, "SETEX %s \"%s\" %s", key.c_str(), val.c_str(), length_key.c_str() );
return process_std_string_reply(reply);
}
bool RedisAdmin::append ( std::string key, std::string val )
{
reply = (redisReply *) redisCommand( c, "APPEND %s \"%s\"", key.c_str(), val.c_str() );
return process_std_string_reply(reply);
}
int RedisAdmin::len ( std::string key )
{
std::string key_str = "STRLEN " + key;
reply = (redisReply *) redisCommand( c, key_str.c_str() );
return return_int_reply(reply);
}
int RedisAdmin::lpush ( std::string key, std::string val )
{
reply = (redisReply *) redisCommand( c, "LPUSH %s \"%s\"", key.c_str(), val.c_str() );
return return_int_reply(reply);
}
int RedisAdmin::rpush ( std::string key, std::string val )
{
reply = (redisReply *) redisCommand( c, "RPUSH %s \"%s\"", key.c_str(), val.c_str() );
return return_int_reply(reply);
}
//! Pop a value from a Redis list on the given key
std::string RedisAdmin::lpop ( std::string key )
{
std::string key_str = "LPOP " + key;
reply = (redisReply *) redisCommand(c, key_str.c_str());
return return_string_reply(reply);
}
//! Pop a value from a Redis list on the given key
std::string RedisAdmin::rpop ( std::string key )
{
std::string key_str = "RPOP " + key;
reply = (redisReply *) redisCommand(c, key_str.c_str());
return return_string_reply(reply);
}
//! Set the value stored in the list at key and the index at index
bool RedisAdmin::lset ( std::string key, std::string val, int index)
{
std::string index_str = std::to_string(index);
reply = (redisReply *) redisCommand( c, "APPEND %s %s \"%s\"", key.c_str(), index_str.c_str(), val.c_str() );
return process_std_string_reply(reply);
}
//! Insert a value into the list at key and before/after the pivot value
int RedisAdmin::linsert ( std::string key, std::string val, std::string pivot, bool before_pivot=true)
{
std::string ba_str;
if (before_pivot) {ba_str = "BEFORE";}
else {ba_str = "AFTER";}
std::string key_str = "LINSERT " + key;
reply = (redisReply *) redisCommand(c, "LINSERT %s \"%s\" \"%s\"", key_str.c_str(), pivot.c_str(), val.c_str());
return return_int_reply(reply);
}
//! Get the value stored in the list at key and the index at index
std::string RedisAdmin::lindex ( std::string key, int index)
{
std::string length_key = std::to_string(index);
reply = (redisReply *) redisCommand( c, "LINDEX %s %s", key.c_str(), length_key.c_str() );
return return_string_reply(reply);
}
//! Get the length of a list stored in Redis
int RedisAdmin::llen ( std::string key )
{
std::string key_str = "LLEN " + key;
reply = (redisReply *) redisCommand( c, key_str.c_str() );
return return_int_reply(reply);
}
//! Trim a list to the specified start and end index
bool RedisAdmin::ltrim ( std::string key, int start_index, int end_index)
{
std::string start = std::to_string(start_index);
std::string end = std::to_string(end_index);
reply = (redisReply *) redisCommand( c, "LTRIM %s %s %s", key.c_str(), start.c_str(), end.c_str() );
return process_std_string_reply(reply);
}
bool RedisAdmin::mset ( std::vector<RedisKvPair> save_sets )
{
std::string cmd_str = "MSET ";
for (std::size_t i=0; i<save_sets.size(); ++i)
{
cmd_str = cmd_str + save_sets[i].key + " \"" + save_sets[i].val + "\" ";
}
reply = (redisReply *) redisCommand( c, cmd_str.c_str() );
return process_std_string_reply(reply);
}
std::vector<std::string> RedisAdmin::mget ( std::vector<std::string> keys )
{
std::string cmd_str = "MGET ";
for (std::size_t i=0; i<keys.size(); ++i)
{
cmd_str = cmd_str + keys[i] + " ";
}
reply = (redisReply *) redisCommand( c, cmd_str.c_str() );
std::vector<std::string> reply_string;
for (std::size_t j=0;j<reply->elements; ++j)
{
std::string new_element (reply->element[j]->str);
reply_string.push_back(new_element);
}
return reply_string;
}
bool RedisAdmin::msetnx ( std::vector<RedisKvPair> save_sets )
{
std::string cmd_str = "MSETNX ";
for (std::size_t i=0; i<save_sets.size(); ++i)
{
cmd_str = cmd_str + save_sets[i].key + " \"" + save_sets[i].val + "\" ";
}
reply = (redisReply *) redisCommand( c, cmd_str.c_str() );
return process_std_int_reply(reply);
}
bool RedisAdmin::setnx ( std::string key, std::string msg )
{
reply = (redisReply *) redisCommand( c, "SETNX %s %s", key.c_str(), msg.c_str() );
return process_std_int_reply(reply);
}
<|endoftext|> |
<commit_before>/****************************************************************/
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* All contents are licensed under LGPL V2.1 */
/* See LICENSE for full restrictions */
/****************************************************************/
#include "Advection.h"
#include "Function.h"
template <>
InputParameters
validParams<Advection>()
{
InputParameters params = validParams<INSBase>();
params.addClassDescription("This class solves the scalar advection equation, $\\vec{a}\\cdot\\nabla u = f$ with SUPG stabilization.");
params.addParam<FunctionName>("forcing_func", 0, "The forcing function, typically used for MMS.");
MooseEnum tau_type("opt mod");
params.addRequiredParam<MooseEnum>(
"tau_type", tau_type, "The type of stabilization parameter to use.");
return params;
}
Advection::Advection(const InputParameters & parameters)
: INSBase(parameters),
_ffn(getFunction("forcing_func")),
_tau_type(getParam<MooseEnum>("tau_type"))
{}
Real
Advection::computeQpResidual()
{
Real tau_val = (_tau_type == "opt" ? tauNodal() : tau());
RealVectorValue U(_u_vel[_qp], _v_vel[_qp], _w_vel[_qp]);
return (_test[_i][_qp] + tau_val * (U * _grad_test[_i][_qp])) * (U * _grad_u[_qp] - _ffn.value(_t, _q_point[_qp]));
}
Real
Advection::computeQpJacobian()
{
Real tau_val = (_tau_type == "opt" ? tauNodal() : tau());
RealVectorValue U(_u_vel[_qp], _v_vel[_qp], _w_vel[_qp]);
return (_test[_i][_qp] + tau_val * (U * _grad_test[_i][_qp])) * (U * _grad_phi[_j][_qp]);
}
<commit_msg>Run clang-format on files.<commit_after>/****************************************************************/
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* All contents are licensed under LGPL V2.1 */
/* See LICENSE for full restrictions */
/****************************************************************/
#include "Advection.h"
#include "Function.h"
template <>
InputParameters
validParams<Advection>()
{
InputParameters params = validParams<INSBase>();
params.addClassDescription("This class solves the scalar advection equation, "
"$\\vec{a}\\cdot\\nabla u = f$ with SUPG stabilization.");
params.addParam<FunctionName>("forcing_func", 0, "The forcing function, typically used for MMS.");
MooseEnum tau_type("opt mod");
params.addRequiredParam<MooseEnum>(
"tau_type", tau_type, "The type of stabilization parameter to use.");
return params;
}
Advection::Advection(const InputParameters & parameters)
: INSBase(parameters),
_ffn(getFunction("forcing_func")),
_tau_type(getParam<MooseEnum>("tau_type"))
{
}
Real
Advection::computeQpResidual()
{
Real tau_val = (_tau_type == "opt" ? tauNodal() : tau());
RealVectorValue U(_u_vel[_qp], _v_vel[_qp], _w_vel[_qp]);
return (_test[_i][_qp] + tau_val * (U * _grad_test[_i][_qp])) *
(U * _grad_u[_qp] - _ffn.value(_t, _q_point[_qp]));
}
Real
Advection::computeQpJacobian()
{
Real tau_val = (_tau_type == "opt" ? tauNodal() : tau());
RealVectorValue U(_u_vel[_qp], _v_vel[_qp], _w_vel[_qp]);
return (_test[_i][_qp] + tau_val * (U * _grad_test[_i][_qp])) * (U * _grad_phi[_j][_qp]);
}
<|endoftext|> |
<commit_before>/**
* This file is part of the CernVM File System.
*/
#include <poll.h>
#include <pthread.h>
#include <unistd.h>
#include <cstdio>
#include <cstring>
#include <map>
#include <string>
#include <vector>
#include "download.h"
#include "json.h"
#include "letter.h"
#include "logging.h"
#include "mongoose.h"
#include "options.h"
#include "platform.h"
#include "signature.h"
#include "stratum_agent/uri_map.h"
#include "util/pointer.h"
#include "util/posix.h"
#include "util/string.h"
#include "uuid.h"
#include "whitelist.h"
using namespace std;
/**
* Everything that's needed to verify requests for a single repository
*/
struct RepositoryConfig : SingleCopy {
RepositoryConfig()
: download_mgr(NULL), signature_mgr(NULL), options_mgr(NULL) { }
~RepositoryConfig() {
delete download_mgr;
delete signature_mgr;
delete options_mgr;
delete statistics;
}
string alias;
string fqrn;
string stratum0_url;
download::DownloadManager *download_mgr;
signature::SignatureManager *signature_mgr;
OptionsManager *options_mgr;
perf::Statistics *statistics;
};
struct Job : SingleCopy {
Job() : fd_stdin(-1), fd_stdout(-1), fd_stderr(-1),
status(kStatusLimbo), exit_code(-1),
birth(platform_monotonic_time()), death(0), pid(0) { }
enum Status {
kStatusLimbo,
kStatusRunning,
kStatusDone
};
int fd_stdin;
int fd_stdout;
int fd_stderr;
string stdout;
string stderr;
Status status;
int exit_code;
pthread_t thread_job;
uint64_t birth;
uint64_t death;
pid_t pid;
};
map<string, RepositoryConfig *> g_repositories;
map<string, Job *> g_jobs;
UriMap g_uri_map;
/**
* Parse /etc/cvmfs/repositories.d/<fqrn>/.conf and search for stratum 1s
*/
static void ReadConfiguration() {
vector<string> repo_config_dirs =
FindDirectories("/etc/cvmfs/repositories.d");
for (unsigned i = 0; i < repo_config_dirs.size(); ++i) {
string name = GetFileName(repo_config_dirs[i]);
string optarg;
UniquePtr<OptionsManager> options_mgr(new BashOptionsManager());
options_mgr->set_taint_environment(false);
options_mgr->ParsePath(repo_config_dirs[i] + "/server.conf", false);
if (!options_mgr->GetValue("CVMFS_REPOSITORY_TYPE", &optarg) ||
(optarg != "stratum1"))
{
continue;
}
options_mgr->ParsePath(repo_config_dirs[i] + "/replica.conf", false);
UniquePtr<signature::SignatureManager>
signature_mgr(new signature::SignatureManager());
signature_mgr->Init();
options_mgr->GetValue("CVMFS_PUBLIC_KEY", &optarg);
if (!signature_mgr->LoadPublicRsaKeys(optarg)) {
LogCvmfs(kLogCvmfs, kLogStderr | kLogSyslogErr,
"(%s) could not load public key %s",
name.c_str(), optarg.c_str());
continue;
}
UniquePtr<perf::Statistics> statistics(new perf::Statistics());
UniquePtr<download::DownloadManager>
download_mgr(new download::DownloadManager());
download_mgr->Init(4, false, statistics);
if (options_mgr->GetValue("CVMFS_HTTP_TIMEOUT", &optarg))
download_mgr->SetTimeout(String2Uint64(optarg), String2Uint64(optarg));
if (options_mgr->GetValue("CVMFS_HTTP_RETRIES", &optarg))
download_mgr->SetRetryParameters(String2Uint64(optarg), 1000, 2000);
RepositoryConfig *config = new RepositoryConfig();
config->alias = name;
options_mgr->GetValue("CVMFS_REPOSITORY_NAME", &(config->fqrn));
options_mgr->GetValue("CVMFS_STRATUM0", &(config->stratum0_url));
config->signature_mgr = signature_mgr.Release();
config->download_mgr = download_mgr.Release();
config->options_mgr = options_mgr.Release();
config->statistics = statistics.Release();
g_repositories[name] = config;
LogCvmfs(kLogCvmfs, kLogStdout | kLogSyslog,
"watching %s (fqrn: %s)", name.c_str(), config->fqrn.c_str());
}
if (g_repositories.empty()) {
LogCvmfs(kLogCvmfs, kLogStdout | kLogSyslogWarn,
"Warning: no stratum 1 repositories found");
}
}
/**
* New replication job
*/
class UriHandlerReplicate : public UriHandler {
public:
explicit UriHandlerReplicate(RepositoryConfig *config) : config_(config) { }
virtual void OnRequest(const struct mg_request_info *req_info,
struct mg_connection *conn)
{
char post_data[kMaxPostData]; post_data[0] = '\0';
unsigned post_data_len = mg_read(conn, post_data, sizeof(post_data) - 1);
post_data[post_data_len] = '\0';
// Trim trailing newline
if (post_data_len && (post_data[post_data_len - 1] == '\n'))
post_data[post_data_len - 1] = '\0';
// Verify letter
string message;
string cert;
letter::Letter letter(config_->fqrn, post_data, config_->signature_mgr);
letter::Failures retval_lt = letter.Verify(kTimeoutLetter, &message, &cert);
if (retval_lt != letter::kFailOk) {
WebReply::Send(WebReply::k400, MkJsonError(letter::Code2Ascii(retval_lt)),
conn);
return;
}
whitelist::Whitelist whitelist(config_->fqrn, config_->download_mgr,
config_->signature_mgr);
whitelist::Failures retval_wl = whitelist.Load(config_->stratum0_url);
if (retval_wl == whitelist::kFailOk)
retval_wl = whitelist.VerifyLoadedCertificate();
if (retval_wl != whitelist::kFailOk) {
WebReply::Send(WebReply::k400,
MkJsonError(whitelist::Code2Ascii(retval_wl)), conn);
return;
}
UniquePtr<Job> job(new Job());
string exe = "/usr/bin/cvmfs_server";
vector<string> argv;
argv.push_back("snapshot");
argv.push_back(config_->alias);
bool retval_b = ExecuteBinary(
&job->fd_stdin, &job->fd_stdout, &job->fd_stderr,
exe, argv, false, &job->pid);
if (!retval_b) {
WebReply::Send(WebReply::k500,
MkJsonError("could not spawn snapshot process"), conn);
return;
}
int retval_i = pthread_create(&job->thread_job, NULL, MainJobMgr, job);
if (retval_i == 0) {
job->status = Job::kStatusRunning;
} else {
close(job->fd_stdin);
close(job->fd_stdout);
close(job->fd_stderr);
}
string uuid = cvmfs::Uuid::CreateOneTime();
g_jobs[uuid] = job.Release();
WebReply::Send(WebReply::k200, "{\"job_id\":\"" + uuid + "\"}", conn);
}
private:
static const unsigned kMaxPostData = 32 * 1024; // 32kB
static const unsigned kTimeoutLetter = 180; // 3 minutes
static void *MainJobMgr(void *data) {
Job *job = reinterpret_cast<Job *>(data);
Block2Nonblock(job->fd_stdout);
Block2Nonblock(job->fd_stderr);
char buf_stdout[kPageSize];
char buf_stderr[kPageSize];
struct pollfd watch_fds[2];
watch_fds[0].fd = job->fd_stdout;
watch_fds[1].fd = job->fd_stderr;
watch_fds[0].events = watch_fds[1].events = POLLIN | POLLPRI | POLLHUP;
watch_fds[0].revents = watch_fds[1].revents = 0;
bool terminate = false;
while (!terminate) {
int retval = poll(watch_fds, 2, -1);
if (retval < 0)
continue;
if (watch_fds[0].revents) {
watch_fds[0].revents = 0;
int nbytes = read(watch_fds[0].fd, buf_stdout, kPageSize);
if ((nbytes <= 0) && (errno != EINTR))
terminate = true;
if (nbytes > 0)
job->stdout += string(buf_stdout, nbytes);
}
if (watch_fds[1].revents) {
watch_fds[1].revents = 0;
int nbytes = read(watch_fds[1].fd, buf_stderr, kPageSize);
if ((nbytes <= 0) && (errno != EINTR))
terminate = true;
if (nbytes > 0)
job->stderr += string(buf_stderr, nbytes);
}
}
close(job->fd_stdin);
close(job->fd_stdout);
close(job->fd_stderr);
job->exit_code = WaitForChild(job->pid);
job->death = platform_monotonic_time();
job->status = Job::kStatusDone;
return NULL;
}
string MkJsonError(const string &msg) {
return "{\"error\": \"" + msg + "\"}";
}
RepositoryConfig *config_;
};
class UriHandlerJob : public UriHandler {
public:
virtual void OnRequest(const struct mg_request_info *req_info,
struct mg_connection *conn)
{
string what = GetFileName(req_info->uri);
string job_id = GetFileName(GetParentPath(req_info->uri));
map<string, Job *>::const_iterator iter = g_jobs.find(job_id);
if (iter == g_jobs.end()) {
WebReply::Send(WebReply::k404, "{\"error\":\"no such job\"}", conn);
return;
}
Job *job = iter->second;
if (what == "stdout") {
WebReply::Send(WebReply::k200, job->stdout, conn);
} else if (what == "stderr") {
WebReply::Send(WebReply::k200, job->stderr, conn);
} else if (what == "status") {
string reply = "{\"status\":";
switch (job->status) {
case Job::kStatusLimbo: reply += "\"limbo\""; break;
case Job::kStatusRunning: reply += "\"running\""; break;
case Job::kStatusDone: reply += "\"done\""; break;
default: assert(false);
}
if (job->status == Job::kStatusDone) {
reply += ",\"exit_code\":" + StringifyInt(job->exit_code);
reply += ",\"duration\":" + StringifyInt(job->death - job->birth);
}
reply += "}";
WebReply::Send(WebReply::k200, reply, conn);
} else {
WebReply::Send(WebReply::k404, "{\"error\":\"internal error\"}", conn);
}
}
};
// This function will be called by mongoose on every new request.
static int begin_request_handler(struct mg_connection *conn) {
const struct mg_request_info *request_info = mg_get_request_info(conn);
WebRequest request(request_info);
UriHandler *handler = g_uri_map.Route(request);
if (handler == NULL) {
if (g_uri_map.IsKnownUri(request.uri()))
WebReply::Send(WebReply::k405, "", conn);
else
WebReply::Send(WebReply::k404, "", conn);
return 1;
}
handler->OnRequest(request_info, conn);
return 1;
}
int main(int argc, char **argv) {
ReadConfiguration();
for (map<string, RepositoryConfig *>::const_iterator i =
g_repositories.begin(), i_end = g_repositories.end(); i != i_end; ++i)
{
string fqrn = i->second->fqrn;
g_uri_map.Register(WebRequest(
"/cvmfs/" + fqrn + "/api/v1/replicate/*/stdout", WebRequest::kGet),
new UriHandlerJob());
g_uri_map.Register(WebRequest(
"/cvmfs/" + fqrn + "/api/v1/replicate/*/stderr", WebRequest::kGet),
new UriHandlerJob());
g_uri_map.Register(WebRequest(
"/cvmfs/" + fqrn + "/api/v1/replicate/*/status", WebRequest::kGet),
new UriHandlerJob());
g_uri_map.Register(WebRequest("/cvmfs/" + fqrn + "/api/v1/replicate/new",
WebRequest::kPost),
new UriHandlerReplicate(i->second));
}
struct mg_context *ctx;
struct mg_callbacks callbacks;
// List of options. Last element must be NULL.
const char *options[] = {"num_threads", "2", "listening_ports", "8080", NULL};
// Prepare callbacks structure. We have only one callback, the rest are NULL.
memset(&callbacks, 0, sizeof(callbacks));
callbacks.begin_request = begin_request_handler;
// Start the web server.
ctx = mg_start(&callbacks, NULL, options);
// That's safe, our mongoose webserver doesn't spawn anything
// There is a race here, TODO: patch in mongoose source code
signal(SIGCHLD, SIG_DFL);
// Wait until user hits "enter". Server is running in separate thread.
// Navigating to http://localhost:8080 will invoke begin_request_handler().
while (true)
getchar();
// Stop the server.
mg_stop(ctx);
return 0;
}
<commit_msg>basic signal handling<commit_after>/**
* This file is part of the CernVM File System.
*/
#include <poll.h>
#include <pthread.h>
#include <unistd.h>
#include <cstdio>
#include <cstring>
#include <map>
#include <string>
#include <vector>
#include "download.h"
#include "json.h"
#include "letter.h"
#include "logging.h"
#include "mongoose.h"
#include "options.h"
#include "platform.h"
#include "signature.h"
#include "stratum_agent/uri_map.h"
#include "util/pointer.h"
#include "util/posix.h"
#include "util/string.h"
#include "uuid.h"
#include "whitelist.h"
using namespace std;
// Keep finished jobs for 3 hours
const unsigned kJobRetentionDuration = 3 * 3600;
const unsigned kCleanupInterval = 60; // Scan job table every minute
/**
* Everything that's needed to verify requests for a single repository
*/
struct RepositoryConfig : SingleCopy {
RepositoryConfig()
: download_mgr(NULL), signature_mgr(NULL), options_mgr(NULL) { }
~RepositoryConfig() {
delete download_mgr;
delete signature_mgr;
delete options_mgr;
delete statistics;
}
string alias;
string fqrn;
string stratum0_url;
download::DownloadManager *download_mgr;
signature::SignatureManager *signature_mgr;
OptionsManager *options_mgr;
perf::Statistics *statistics;
};
struct Job : SingleCopy {
Job() : fd_stdin(-1), fd_stdout(-1), fd_stderr(-1),
status(kStatusLimbo), exit_code(-1),
birth(platform_monotonic_time()), death(0), pid(0) { }
enum Status {
kStatusLimbo,
kStatusRunning,
kStatusDone
};
int fd_stdin;
int fd_stdout;
int fd_stderr;
string stdout;
string stderr;
Status status;
int exit_code;
pthread_t thread_job;
uint64_t birth;
uint64_t death;
pid_t pid;
};
map<string, RepositoryConfig *> g_repositories;
map<string, Job *> g_jobs;
UriMap g_uri_map;
/**
* Used to control the main thread from signals
*/
int g_pipe_ctrl[2];
/**
* Parse /etc/cvmfs/repositories.d/<fqrn>/.conf and search for stratum 1s
*/
static void ReadConfiguration() {
vector<string> repo_config_dirs =
FindDirectories("/etc/cvmfs/repositories.d");
for (unsigned i = 0; i < repo_config_dirs.size(); ++i) {
string name = GetFileName(repo_config_dirs[i]);
string optarg;
UniquePtr<OptionsManager> options_mgr(new BashOptionsManager());
options_mgr->set_taint_environment(false);
options_mgr->ParsePath(repo_config_dirs[i] + "/server.conf", false);
if (!options_mgr->GetValue("CVMFS_REPOSITORY_TYPE", &optarg) ||
(optarg != "stratum1"))
{
continue;
}
options_mgr->ParsePath(repo_config_dirs[i] + "/replica.conf", false);
UniquePtr<signature::SignatureManager>
signature_mgr(new signature::SignatureManager());
signature_mgr->Init();
options_mgr->GetValue("CVMFS_PUBLIC_KEY", &optarg);
if (!signature_mgr->LoadPublicRsaKeys(optarg)) {
LogCvmfs(kLogCvmfs, kLogStderr | kLogSyslogErr,
"(%s) could not load public key %s",
name.c_str(), optarg.c_str());
continue;
}
UniquePtr<perf::Statistics> statistics(new perf::Statistics());
UniquePtr<download::DownloadManager>
download_mgr(new download::DownloadManager());
download_mgr->Init(4, false, statistics);
if (options_mgr->GetValue("CVMFS_HTTP_TIMEOUT", &optarg))
download_mgr->SetTimeout(String2Uint64(optarg), String2Uint64(optarg));
if (options_mgr->GetValue("CVMFS_HTTP_RETRIES", &optarg))
download_mgr->SetRetryParameters(String2Uint64(optarg), 1000, 2000);
RepositoryConfig *config = new RepositoryConfig();
config->alias = name;
options_mgr->GetValue("CVMFS_REPOSITORY_NAME", &(config->fqrn));
options_mgr->GetValue("CVMFS_STRATUM0", &(config->stratum0_url));
config->signature_mgr = signature_mgr.Release();
config->download_mgr = download_mgr.Release();
config->options_mgr = options_mgr.Release();
config->statistics = statistics.Release();
g_repositories[name] = config;
LogCvmfs(kLogCvmfs, kLogStdout | kLogSyslog,
"watching %s (fqrn: %s)", name.c_str(), config->fqrn.c_str());
}
if (g_repositories.empty()) {
LogCvmfs(kLogCvmfs, kLogStdout | kLogSyslogWarn,
"Warning: no stratum 1 repositories found");
}
}
/**
* New replication job
*/
class UriHandlerReplicate : public UriHandler {
public:
explicit UriHandlerReplicate(RepositoryConfig *config) : config_(config) { }
virtual void OnRequest(const struct mg_request_info *req_info,
struct mg_connection *conn)
{
char post_data[kMaxPostData]; post_data[0] = '\0';
unsigned post_data_len = mg_read(conn, post_data, sizeof(post_data) - 1);
post_data[post_data_len] = '\0';
// Trim trailing newline
if (post_data_len && (post_data[post_data_len - 1] == '\n'))
post_data[post_data_len - 1] = '\0';
// Verify letter
string message;
string cert;
letter::Letter letter(config_->fqrn, post_data, config_->signature_mgr);
letter::Failures retval_lt = letter.Verify(kTimeoutLetter, &message, &cert);
if (retval_lt != letter::kFailOk) {
WebReply::Send(WebReply::k400, MkJsonError(letter::Code2Ascii(retval_lt)),
conn);
return;
}
whitelist::Whitelist whitelist(config_->fqrn, config_->download_mgr,
config_->signature_mgr);
whitelist::Failures retval_wl = whitelist.Load(config_->stratum0_url);
if (retval_wl == whitelist::kFailOk)
retval_wl = whitelist.VerifyLoadedCertificate();
if (retval_wl != whitelist::kFailOk) {
WebReply::Send(WebReply::k400,
MkJsonError(whitelist::Code2Ascii(retval_wl)), conn);
return;
}
UniquePtr<Job> job(new Job());
string exe = "/usr/bin/cvmfs_server";
vector<string> argv;
argv.push_back("snapshot");
argv.push_back(config_->alias);
bool retval_b = ExecuteBinary(
&job->fd_stdin, &job->fd_stdout, &job->fd_stderr,
exe, argv, false, &job->pid);
if (!retval_b) {
WebReply::Send(WebReply::k500,
MkJsonError("could not spawn snapshot process"), conn);
return;
}
int retval_i = pthread_create(&job->thread_job, NULL, MainJobMgr, job);
if (retval_i == 0) {
job->status = Job::kStatusRunning;
} else {
close(job->fd_stdin);
close(job->fd_stdout);
close(job->fd_stderr);
}
string uuid = cvmfs::Uuid::CreateOneTime();
g_jobs[uuid] = job.Release();
WebReply::Send(WebReply::k200, "{\"job_id\":\"" + uuid + "\"}", conn);
}
private:
static const unsigned kMaxPostData = 32 * 1024; // 32kB
static const unsigned kTimeoutLetter = 180; // 3 minutes
static void *MainJobMgr(void *data) {
Job *job = reinterpret_cast<Job *>(data);
Block2Nonblock(job->fd_stdout);
Block2Nonblock(job->fd_stderr);
char buf_stdout[kPageSize];
char buf_stderr[kPageSize];
struct pollfd watch_fds[2];
watch_fds[0].fd = job->fd_stdout;
watch_fds[1].fd = job->fd_stderr;
watch_fds[0].events = watch_fds[1].events = POLLIN | POLLPRI | POLLHUP;
watch_fds[0].revents = watch_fds[1].revents = 0;
bool terminate = false;
while (!terminate) {
int retval = poll(watch_fds, 2, -1);
if (retval < 0)
continue;
if (watch_fds[0].revents) {
watch_fds[0].revents = 0;
int nbytes = read(watch_fds[0].fd, buf_stdout, kPageSize);
if ((nbytes <= 0) && (errno != EINTR))
terminate = true;
if (nbytes > 0)
job->stdout += string(buf_stdout, nbytes);
}
if (watch_fds[1].revents) {
watch_fds[1].revents = 0;
int nbytes = read(watch_fds[1].fd, buf_stderr, kPageSize);
if ((nbytes <= 0) && (errno != EINTR))
terminate = true;
if (nbytes > 0)
job->stderr += string(buf_stderr, nbytes);
}
}
close(job->fd_stdin);
close(job->fd_stdout);
close(job->fd_stderr);
job->exit_code = WaitForChild(job->pid);
job->death = platform_monotonic_time();
job->status = Job::kStatusDone;
return NULL;
}
string MkJsonError(const string &msg) {
return "{\"error\": \"" + msg + "\"}";
}
RepositoryConfig *config_;
};
class UriHandlerJob : public UriHandler {
public:
virtual void OnRequest(const struct mg_request_info *req_info,
struct mg_connection *conn)
{
string what = GetFileName(req_info->uri);
string job_id = GetFileName(GetParentPath(req_info->uri));
map<string, Job *>::const_iterator iter = g_jobs.find(job_id);
if (iter == g_jobs.end()) {
WebReply::Send(WebReply::k404, "{\"error\":\"no such job\"}", conn);
return;
}
Job *job = iter->second;
if (what == "stdout") {
WebReply::Send(WebReply::k200, job->stdout, conn);
} else if (what == "stderr") {
WebReply::Send(WebReply::k200, job->stderr, conn);
} else if (what == "tail") {
WebReply::Send(WebReply::k200, Tail(job->stdout, 4), conn);
} else if (what == "status") {
string reply = "{\"status\":";
switch (job->status) {
case Job::kStatusLimbo: reply += "\"limbo\""; break;
case Job::kStatusRunning: reply += "\"running\""; break;
case Job::kStatusDone: reply += "\"done\""; break;
default: assert(false);
}
if (job->status == Job::kStatusDone) {
reply += ",\"exit_code\":" + StringifyInt(job->exit_code);
reply += ",\"duration\":" + StringifyInt(job->death - job->birth);
}
reply += "}";
WebReply::Send(WebReply::k200, reply, conn);
} else {
WebReply::Send(WebReply::k404, "{\"error\":\"internal error\"}", conn);
}
}
};
// This function will be called by mongoose on every new request.
static int begin_request_handler(struct mg_connection *conn) {
const struct mg_request_info *request_info = mg_get_request_info(conn);
WebRequest request(request_info);
UriHandler *handler = g_uri_map.Route(request);
if (handler == NULL) {
if (g_uri_map.IsKnownUri(request.uri()))
WebReply::Send(WebReply::k405, "", conn);
else
WebReply::Send(WebReply::k404, "", conn);
return 1;
}
handler->OnRequest(request_info, conn);
return 1;
}
void SignalCleanup(int signal) {
char c = 'C';
WritePipe(g_pipe_ctrl[1], &c, 1);
}
void SignalExit(int signal) {
char c = 'T';
WritePipe(g_pipe_ctrl[1], &c, 1);
}
void SignalReload(int signal) {
char c = 'R';
WritePipe(g_pipe_ctrl[1], &c, 1);
}
int main(int argc, char **argv) {
ReadConfiguration();
for (map<string, RepositoryConfig *>::const_iterator i =
g_repositories.begin(), i_end = g_repositories.end(); i != i_end; ++i)
{
string fqrn = i->second->fqrn;
g_uri_map.Register(WebRequest(
"/cvmfs/" + fqrn + "/api/v1/replicate/*/stdout", WebRequest::kGet),
new UriHandlerJob());
g_uri_map.Register(WebRequest(
"/cvmfs/" + fqrn + "/api/v1/replicate/*/stderr", WebRequest::kGet),
new UriHandlerJob());
g_uri_map.Register(WebRequest(
"/cvmfs/" + fqrn + "/api/v1/replicate/*/tail", WebRequest::kGet),
new UriHandlerJob());
g_uri_map.Register(WebRequest(
"/cvmfs/" + fqrn + "/api/v1/replicate/*/status", WebRequest::kGet),
new UriHandlerJob());
g_uri_map.Register(WebRequest("/cvmfs/" + fqrn + "/api/v1/replicate/new",
WebRequest::kPost),
new UriHandlerReplicate(i->second));
}
struct mg_context *ctx;
struct mg_callbacks callbacks;
// List of options. Last element must be NULL.
const char *options[] = {"num_threads", "2", "listening_ports", "8080", NULL};
// Prepare callbacks structure. We have only one callback, the rest are NULL.
memset(&callbacks, 0, sizeof(callbacks));
callbacks.begin_request = begin_request_handler;
// Start the web server.
ctx = mg_start(&callbacks, NULL, options);
// That's safe, our mongoose webserver doesn't spawn anything
// There is a race here, TODO: patch in mongoose source code
signal(SIGCHLD, SIG_DFL);
MakePipe(g_pipe_ctrl);
signal(SIGHUP, SignalReload);
signal(SIGTERM, SignalExit);
signal(SIGINT, SignalExit);
signal(SIGALRM, SignalCleanup);
alarm(kCleanupInterval);
char ctrl;
do {
ReadPipe(g_pipe_ctrl[0], &ctrl, 1);
if (ctrl == 'C') {
// Cleanup job table
for (map<string, Job *>::iterator i = g_jobs.begin(),
i_end = g_jobs.end(); i != i_end; )
{
if ( (i->second->status == Job::kStatusDone) &&
((platform_monotonic_time() - i->second->death) >
kJobRetentionDuration) )
{
map<string, Job *>::iterator delete_me = i++;
pthread_join(delete_me->second->thread_job, NULL);
delete delete_me->second;
g_jobs.erase(delete_me);
} else {
++i;
}
}
alarm(kCleanupInterval);
}
if (ctrl == 'R') {
LogCvmfs(kLogCvmfs, kLogStdout | kLogSyslog, "reloading configuration");
}
} while (ctrl != 'T');
LogCvmfs(kLogCvmfs, kLogStdout | kLogSyslog, "stopping stratum agent");
// Stop the server.
mg_stop(ctx);
return 0;
}
<|endoftext|> |
<commit_before>#include "audio_postprocess.h"
Audio::Audio()
{
internal_memory = std::make_unique<u8[]>(BUFFER_SIZE * 4);
for (u32 i = 0; i < 4; ++i)
buffers[i] = &internal_memory[BUFFER_SIZE * i];
SDL_AudioSpec opt = {}, tmp = {};
opt.freq = 44100;
opt.channels = 2;
opt.format = AUDIO_F32SYS;
opt.samples = 1024;
SDL_OpenAudio(&opt, &tmp);
SDL_PauseAudio(0);
}
Audio::~Audio()
{
SDL_CloseAudio();
}
u8** Audio::swap_buffers(u8** buffs, u32 count)
{
if (buffs == nullptr)
return buffers;
float buf[2048];
const u32 sample_count = (count + offset) / 48;
for (size_t i = 0; i < sample_count; i++)
{
const u32 index = i * 48 + offset;
u8 total = buffers[0][index] + buffers[1][index] + buffers[2][index] + buffers[3][index];
buf[i * 2] = total * 0.05f;
buf[i * 2 + 1] = total * 0.05f;
}
offset = (count + offset) % 48;
SDL_QueueAudio(1, buf, sample_count * 2 * sizeof(float));
while (SDL_GetQueuedAudioSize(1) > SAMPLE_COUNT * 2 * sizeof(float))
SDL_Delay(1);
return buffs;
}
<commit_msg>fix in audio "quality"<commit_after>#include "audio_postprocess.h"
Audio::Audio()
{
internal_memory = std::make_unique<u8[]>(BUFFER_SIZE * 4);
for (u32 i = 0; i < 4; ++i)
buffers[i] = &internal_memory[BUFFER_SIZE * i];
SDL_AudioSpec opt = {}, tmp = {};
opt.freq = 44100;
opt.channels = 2;
opt.format = AUDIO_F32SYS;
opt.samples = 1024;
SDL_OpenAudio(&opt, &tmp);
SDL_PauseAudio(0);
}
Audio::~Audio()
{
SDL_CloseAudio();
}
u8** Audio::swap_buffers(u8** buffs, u32 count)
{
if (buffs == nullptr)
return buffers;
float buf[2048];
const u32 sample_count = (count + offset) / 48;
for (size_t i = 0; i < sample_count; i++)
{
const u32 index = i * 48 + offset;
u8 total = buffers[0][index] + buffers[1][index] + buffers[2][index] + buffers[3][index];
buf[i * 2] = total * 0.025f;
buf[i * 2 + 1] = total * 0.025f;
}
offset = (count + offset) % 48;
SDL_QueueAudio(1, buf, sample_count * 2 * sizeof(float));
while (SDL_GetQueuedAudioSize(1) > SAMPLE_COUNT * 2 * sizeof(float))
SDL_Delay(1);
return buffs;
}
<|endoftext|> |
<commit_before>/**
* @file
* @brief Implementation of PulseTransfer module
* @copyright Copyright (c) 2017 CERN and the Allpix Squared authors.
* This software is distributed under the terms of the MIT License, copied verbatim in the file "LICENSE.md".
* In applying this license, CERN does not waive the privileges and immunities granted to it by virtue of its status as an
* Intergovernmental Organization or submit itself to any jurisdiction.
*/
#include "PulseTransferModule.hpp"
#include "objects/PixelCharge.hpp"
#include <string>
#include <utility>
#include <TAxis.h>
#include <TGraph.h>
#include "core/utils/log.h"
using namespace allpix;
PulseTransferModule::PulseTransferModule(Configuration& config,
Messenger* messenger,
const std::shared_ptr<Detector>& detector)
: Module(config, detector), detector_(detector), messenger_(messenger) {
config_.setDefault<bool>("output_pulsegraphs", false);
config_.setDefault<bool>("output_plots", config_.get<bool>("output_pulsegraphs"));
output_plots_ = config_.get<bool>("output_plots");
output_pulsegraphs_ = config_.get<bool>("output_pulsegraphs");
messenger_->bindSingle(this, &PulseTransferModule::message_, MsgFlags::REQUIRED);
}
void PulseTransferModule::run(unsigned int event_num) {
// Create map for all pixels
std::map<Pixel::Index, Pulse> pixel_map;
Pulse total_pulse;
// Accumulate all pulses from input message data:
for(const auto& prop : message_->getData()) {
auto pulses = prop.getPulses();
pixel_map =
std::accumulate(pulses.begin(), pulses.end(), pixel_map, [](std::map<Pixel::Index, Pulse>& m, const auto& p) {
return (m[p.first] += p.second, m);
});
}
// Create vector of pixel pulses to return for this detector
std::vector<PixelCharge> pixel_charges;
for(auto& pixel_index_pulse : pixel_map) {
// Store the pulse:
pixel_charges.emplace_back(detector_->getPixel(pixel_index_pulse.first), std::move(pixel_index_pulse.second));
// Sum all pulses for informational output:
total_pulse += pixel_index_pulse.second;
// Fill a graphs with the individual pixel pulses:
if(output_pulsegraphs_) {
auto index = pixel_index_pulse.first;
auto pulse = pixel_index_pulse.second.getPulse();
auto step = pixel_index_pulse.second.getBinning();
std::string name =
"pulse_px" + std::to_string(index.x()) + "-" + std::to_string(index.y()) + "_" + std::to_string(event_num);
// Generate x-axis:
std::vector<double> time(pulse.size());
std::generate(time.begin(), time.end(), [ n = 0.0, step ]() mutable { return n += step; });
auto pulse_graph = new TGraph(static_cast<int>(pulse.size()), &time[0], &pulse[0]);
pulse_graph->GetXaxis()->SetTitle("t [ns]");
pulse_graph->GetYaxis()->SetTitle("Q_{ind} [e]");
pulse_graph->SetTitle(("Induced charge in pixel (" + std::to_string(index.x()) + "," +
std::to_string(index.y()) +
"), Q_{tot} = " + std::to_string(pixel_index_pulse.second.getCharge()) + " e")
.c_str());
pulse_graph->Write(name.c_str());
}
}
// Create a new message with pixel pulses and dispatch:
auto pixel_charge_message = std::make_shared<PixelChargeMessage>(std::move(pixel_charges), detector_);
messenger_->dispatchMessage(this, pixel_charge_message);
LOG(INFO) << "Total charge induced on all pixels: " << Units::display(total_pulse.getCharge(), "e");
}
<commit_msg>PulseTransfer: preserve history<commit_after>/**
* @file
* @brief Implementation of PulseTransfer module
* @copyright Copyright (c) 2017 CERN and the Allpix Squared authors.
* This software is distributed under the terms of the MIT License, copied verbatim in the file "LICENSE.md".
* In applying this license, CERN does not waive the privileges and immunities granted to it by virtue of its status as an
* Intergovernmental Organization or submit itself to any jurisdiction.
*/
#include "PulseTransferModule.hpp"
#include "core/utils/log.h"
#include "objects/PixelCharge.hpp"
#include <string>
#include <utility>
#include <TAxis.h>
#include <TGraph.h>
using namespace allpix;
PulseTransferModule::PulseTransferModule(Configuration& config,
Messenger* messenger,
const std::shared_ptr<Detector>& detector)
: Module(config, detector), detector_(detector), messenger_(messenger) {
config_.setDefault<bool>("output_pulsegraphs", false);
config_.setDefault<bool>("output_plots", config_.get<bool>("output_pulsegraphs"));
output_plots_ = config_.get<bool>("output_plots");
output_pulsegraphs_ = config_.get<bool>("output_pulsegraphs");
messenger_->bindSingle(this, &PulseTransferModule::message_, MsgFlags::REQUIRED);
}
void PulseTransferModule::run(unsigned int event_num) {
// Create map for all pixels: pulse and propagated charges
std::map<Pixel::Index, Pulse> pixel_pulse_map;
std::map<Pixel::Index, std::vector<const PropagatedCharge*>> pixel_charge_map;
LOG(DEBUG) << "Received " << message_->getData().size() << " propagated charge objects.";
for(const auto& propagated_charge : message_->getData()) {
for(auto& pulse : propagated_charge.getPulses()) {
auto pixel_index = pulse.first;
// Accumulate all pulses from input message data:
pixel_pulse_map[pixel_index] += pulse.second;
auto px = pixel_charge_map[pixel_index];
// For each pulse, store the corresponding propagated charges to preserve history:
if(std::find(px.begin(), px.end(), &propagated_charge) == px.end()) {
pixel_charge_map[pixel_index].emplace_back(&propagated_charge);
}
}
}
// Create vector of pixel pulses to return for this detector
std::vector<PixelCharge> pixel_charges;
Pulse total_pulse;
for(auto& pixel_index_pulse : pixel_pulse_map) {
auto index = pixel_index_pulse.first;
auto pulse = pixel_index_pulse.second;
// Sum all pulses for informational output:
total_pulse += pulse;
// Fill a graphs with the individual pixel pulses:
if(output_pulsegraphs_) {
auto step = pulse.getBinning();
auto pulse_vec = pulse.getPulse();
std::string name =
"pulse_px" + std::to_string(index.x()) + "-" + std::to_string(index.y()) + "_" + std::to_string(event_num);
// Generate x-axis:
std::vector<double> time(pulse_vec.size());
std::generate(time.begin(), time.end(), [ n = 0.0, step ]() mutable { return n += step; });
auto pulse_graph = new TGraph(static_cast<int>(pulse_vec.size()), &time[0], &pulse_vec[0]);
pulse_graph->GetXaxis()->SetTitle("t [ns]");
pulse_graph->GetYaxis()->SetTitle("Q_{ind} [e]");
pulse_graph->SetTitle(("Induced charge in pixel (" + std::to_string(index.x()) + "," +
std::to_string(index.y()) +
"), Q_{tot} = " + std::to_string(pixel_index_pulse.second.getCharge()) + " e")
.c_str());
pulse_graph->Write(name.c_str());
}
LOG(DEBUG) << "Index " << index << " has " << pixel_charge_map[index].size() << " ancestors";
// Store the pulse:
pixel_charges.emplace_back(detector_->getPixel(index), std::move(pulse), pixel_charge_map[index]);
}
// Create a new message with pixel pulses and dispatch:
auto pixel_charge_message = std::make_shared<PixelChargeMessage>(std::move(pixel_charges), detector_);
messenger_->dispatchMessage(this, pixel_charge_message);
LOG(INFO) << "Total charge induced on all pixels: " << Units::display(total_pulse.getCharge(), "e");
}
<|endoftext|> |
<commit_before>#pragma once
#include <tudocomp/Compressor.hpp>
#include <sdsl/cst_fully.hpp>
#include <sdsl/cst_sada.hpp>
#include <tudocomp/Range.hpp>
#include <tudocomp/ds/TextDS.hpp>
#include <tudocomp/ds/st.hpp>
#include <tudocomp/ds/st_util.hpp>
namespace tdc {
class LZ78UCompressor: public Compressor {
private:
using node_type = SuffixTree::node_type;
public:
inline LZ78UCompressor(Env&& env):
Compressor(std::move(env))
{}
inline static Meta meta() {
Meta m("compressor", "lz78u", "Lempel-Ziv 78 U\n\n" );
// m.option("dict_size").dynamic("inf");
m.needs_sentinel_terminator();
return m;
}
virtual void compress(Input& input, Output& out) override {
env().begin_stat_phase("lz78u");
auto iview = input.as_view();
View T = iview;
SuffixTree::cst_t backing_cst;
{
env().begin_stat_phase("construct suffix tree");
// TODO: Specialize sdsl template for less alloc here
std::string bad_copy_1 = T.substr(0, T.size() - 1);
std::cout << vec_to_debug_string(bad_copy_1) << "\n";
construct_im(backing_cst, bad_copy_1, 1);
env().end_stat_phase();
}
SuffixTree ST(backing_cst);
const size_t max_z = T.size() * bits_for(ST.cst.csa.sigma) / bits_for(T.size());
env().log_stat("max z", max_z);
sdsl::int_vector<> R(ST.internal_nodes,0,bits_for(max_z));
len_t pos = 0;
len_t z = 0;
typedef SuffixTree::node_type node_t;
// tx: a a a b a b a a a b a a b a b a $
// sn: 5 10 15 16
while(pos < T.size()) {
const node_t l = ST.select_leaf(ST.cst.csa.isa[pos]);
const len_t leaflabel = pos;
std::cout << "Selecting leaf " << l << " with label " << leaflabel << std::endl;
std::cout << "Checking parent " << ST.parent(l) << " with R[parent] = " << R[ST.nid(ST.parent(l))] << std::endl;
if(ST.parent(l) == ST.root || R[ST.nid(ST.parent(l))] != 0) {
// DCHECK_EQ(T[pos + ST.str_depth(ST.parent(l))], lambda(ST.parent(l), l)[0]);
std::cout << "out l c: " << int(T[pos + ST.str_depth(ST.parent(l))]) << "\n";
std::cout << "out l r: " << int(0) << "\n";
++pos;
++z;
continue;
}
len_t d = 1;
node_t parent = ST.root;
node_t node = ST.level_anc(l, d);
while(R[ST.nid(node)] != 0) {
// DCHECK_EQ(lambda(parent, node).size(), ST.str_depth(node) - ST.str_depth(parent));
// pos += lambda(parent, node).size();
pos += ST.str_depth(node) - ST.str_depth(parent);
parent = node;
node = ST.level_anc(l, ++d);
std::cout << "pos : " << pos << std::endl;
}
R[ST.nid(node)] = ++z;
std::cout << "Setting R[" << node << "] to " << z << std::endl;
std::cout << "Extracting substring for nodes (" << parent << ", " << node << ") " << std::endl;
const auto& str = T.substr(leaflabel + ST.str_depth(parent), leaflabel + ST.str_depth(node));
std::cout << "extracted T[" << (leaflabel + ST.str_depth(parent)) << ", " << (leaflabel + ST.str_depth(node)) << "]: " << str << " of size " << str.size() << "\n";
std::cout << "out m s: " << vec_to_debug_string(str) << "\n";
std::cout << "out m r: " << int(R[ST.nid(ST.parent(node))]) << "\n";
pos += str.size();
}
env().end_stat_phase();
}
virtual void decompress(Input& input, Output& output) override final {
}
};
}//ns
<commit_msg>small bug fixed<commit_after>#pragma once
#include <tudocomp/Compressor.hpp>
#include <sdsl/cst_fully.hpp>
#include <sdsl/cst_sada.hpp>
#include <tudocomp/Range.hpp>
#include <tudocomp/ds/TextDS.hpp>
#include <tudocomp/ds/st.hpp>
#include <tudocomp/ds/st_util.hpp>
namespace tdc {
class LZ78UCompressor: public Compressor {
private:
using node_type = SuffixTree::node_type;
public:
inline LZ78UCompressor(Env&& env):
Compressor(std::move(env))
{}
inline static Meta meta() {
Meta m("compressor", "lz78u", "Lempel-Ziv 78 U\n\n" );
// m.option("dict_size").dynamic("inf");
m.needs_sentinel_terminator();
return m;
}
virtual void compress(Input& input, Output& out) override {
env().begin_stat_phase("lz78u");
auto iview = input.as_view();
View T = iview;
SuffixTree::cst_t backing_cst;
{
env().begin_stat_phase("construct suffix tree");
// TODO: Specialize sdsl template for less alloc here
std::string bad_copy_1 = T.substr(0, T.size() - 1);
std::cout << vec_to_debug_string(bad_copy_1) << "\n";
construct_im(backing_cst, bad_copy_1, 1);
env().end_stat_phase();
}
SuffixTree ST(backing_cst);
const size_t max_z = T.size() * bits_for(ST.cst.csa.sigma) / bits_for(T.size());
env().log_stat("max z", max_z);
sdsl::int_vector<> R(ST.internal_nodes,0,bits_for(max_z));
len_t pos = 0;
len_t z = 0;
typedef SuffixTree::node_type node_t;
// tx: a a a b a b a a a b a a b a b a $
// sn: 5 10 15 16
while(pos < T.size()) {
const node_t l = ST.select_leaf(ST.cst.csa.isa[pos]);
const len_t leaflabel = pos;
std::cout << "Selecting leaf " << l << " with label " << leaflabel << std::endl;
std::cout << "Checking parent " << ST.parent(l) << " with R[parent] = " << R[ST.nid(ST.parent(l))] << std::endl;
if(ST.parent(l) == ST.root || R[ST.nid(ST.parent(l))] != 0) {
// DCHECK_EQ(T[pos + ST.str_depth(ST.parent(l))], lambda(ST.parent(l), l)[0]);
std::cout << "out l c: " << int(T[pos + ST.str_depth(ST.parent(l))]) << "\n";
std::cout << "out l r: " << int(R[ST.nid(ST.parent(l))]) << "\n";
++pos;
++z;
continue;
}
len_t d = 1;
node_t parent = ST.root;
node_t node = ST.level_anc(l, d);
while(R[ST.nid(node)] != 0) {
// DCHECK_EQ(lambda(parent, node).size(), ST.str_depth(node) - ST.str_depth(parent));
// pos += lambda(parent, node).size();
pos += ST.str_depth(node) - ST.str_depth(parent);
parent = node;
node = ST.level_anc(l, ++d);
std::cout << "pos : " << pos << std::endl;
}
R[ST.nid(node)] = ++z;
std::cout << "Setting R[" << node << "] to " << z << std::endl;
std::cout << "Extracting substring for nodes (" << parent << ", " << node << ") " << std::endl;
const auto& str = T.substr(leaflabel + ST.str_depth(parent), leaflabel + ST.str_depth(node));
std::cout << "extracted T[" << (leaflabel + ST.str_depth(parent)) << ", " << (leaflabel + ST.str_depth(node)) << "]: " << str << " of size " << str.size() << "\n";
std::cout << "out m s: " << vec_to_debug_string(str) << "\n";
std::cout << "out m r: " << int(R[ST.nid(ST.parent(node))]) << "\n";
pos += str.size();
}
env().end_stat_phase();
}
virtual void decompress(Input& input, Output& output) override final {
}
};
}//ns
<|endoftext|> |
<commit_before>#pragma once
#include "pch.h"
#include "MatOps.h"
/**
*sum of squard difference (distance metric)
*starting from ax,ay in image a and bx,by in image b, with a width and height given
*indicies out of bounds results in MAX_DOUBLE
*/
double Matops::ssd(Mat& a, Mat& b, int x, int y) {
return 0;
}
/**
*singlular vaue decomposition, results are returned in destU, destS, and destV
*may pass in nil to disregaurd certian results
*/
void Matops::svd(Mat& a, Mat*destU, Mat*destS, Mat*destV) {
}
//TODO::add any conversion frunctions from Mat to other useful formats<commit_msg>merging estebans ssd<commit_after>#pragma once
#include "pch.h"
#include "MatOps.h"
#include <cfloat>
/**
*sum of squard difference (distance metric)
*starting from ax,ay in image a and bx,by in image b, with a width and height given
*indicies out of bounds results in MAX_DOUBLE
*/
double Matops::ssd(Mat& a, Mat& b, int x, int y) {
if ( x < 0 || y < 0 || x + b.cols() > a.cols()|| y + b.rows() > a.rows())
return DBL_MAX;
/* Declaring iterators for SDD */
int rb, cb;
double distance = 0.0;
for (rb = 0 ; rb < b.rows() ; rb++) {
for (cb = 0 ; cb < b.cols() ; cb++) {
distance += a[y+rb][x+cb] * b[rb][cb];
}
}
return distance;
}
/**
*singlular vaue decomposition, results are returned in destU, destS, and destV
*may pass in nil to disregaurd certian results
*/
void Matops::svd(Mat& a, Mat*destU, Mat*destS, Mat*destV) {
}
//TODO::add any conversion frunctions from Mat to other useful formats<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkProjectedTexture.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkProjectedTexture.h"
#include "vtkDataSet.h"
#include "vtkFloatArray.h"
#include "vtkMath.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
vtkCxxRevisionMacro(vtkProjectedTexture, "1.28");
vtkStandardNewMacro(vtkProjectedTexture);
// Description:
// Initialize the projected texture filter with a position of (0, 0, 1),
// a focal point of (0, 0, 0), an up vector on the +y axis,
// an aspect ratio of the projection frustum of equal width, height, and focal
// length, an S range of (0, 1) and a T range of (0, 1).
vtkProjectedTexture::vtkProjectedTexture()
{
this->Position[0] = 0.0;
this->Position[1] = 0.0;
this->Position[2] = 1.0;
this->Orientation[0] = this->Orientation[1] = this->Orientation[2] = 0.0;
this->SetFocalPoint(0.0, 0.0, 0.0);
this->Up[0] = 0.0;
this->Up[1] = 1.0;
this->Up[2] = 0.0;
this->AspectRatio[0] = 1.0;
this->AspectRatio[1] = 1.0;
this->AspectRatio[2] = 1.0;
this->MirrorSeparation = 1.0;
this->CameraMode = VTK_PROJECTED_TEXTURE_USE_PINHOLE;
this->SRange[0] = 0.0;
this->SRange[1] = 1.0;
this->TRange[0] = 0.0;
this->TRange[1] = 1.0;
}
void vtkProjectedTexture::SetFocalPoint(double fp[3])
{
this->SetFocalPoint(fp[0], fp[1], fp[2]);
}
void vtkProjectedTexture::SetFocalPoint(double x, double y, double z)
{
double orientation[3];
orientation[0] = x - this->Position[0];
orientation[1] = y - this->Position[1];
orientation[2] = z - this->Position[2];
vtkMath::Normalize(orientation);
if (this->Orientation[0] != orientation[0] ||
this->Orientation[1] != orientation[1] ||
this->Orientation[2] != orientation[2])
{
this->Orientation[0] = orientation[0];
this->Orientation[1] = orientation[1];
this->Orientation[2] = orientation[2];
this->Modified();
}
this->FocalPoint[0] = x;
this->FocalPoint[1] = y;
this->FocalPoint[2] = z;
}
void vtkProjectedTexture::Execute()
{
double tcoords[2];
vtkIdType numPts;
vtkFloatArray *newTCoords;
vtkIdType i;
int j;
double proj;
double rightv[3], upv[3], diff[3];
double sScale, tScale, sOffset, tOffset, sSize, tSize, s, t;
vtkDataSet *input = this->GetInput();
double p[3];
vtkDataSet *output = this->GetOutput();
vtkDebugMacro(<<"Generating texture coordinates!");
// First, copy the input to the output as a starting point
output->CopyStructure( input );
numPts=input->GetNumberOfPoints();
//
// Allocate texture data
//
newTCoords = vtkFloatArray::New();
newTCoords->SetNumberOfComponents(2);
newTCoords->SetNumberOfTuples(numPts);
vtkMath::Normalize (this->Orientation);
vtkMath::Cross (this->Orientation, this->Up, rightv);
vtkMath::Normalize (rightv);
vtkMath::Cross (rightv, this->Orientation, upv);
vtkMath::Normalize (upv);
sSize = this->AspectRatio[0] / this->AspectRatio[2];
tSize = this->AspectRatio[1] / this->AspectRatio[2];
sScale = (this->SRange[1] - this->SRange[0])/sSize;
tScale = (this->TRange[1] - this->TRange[0])/tSize;
sOffset = (this->SRange[1] - this->SRange[0])/2.0 + this->SRange[0];
tOffset = (this->TRange[1] - this->TRange[0])/2.0 + this->TRange[0];
// compute s-t coordinates
for (i = 0; i < numPts; i++)
{
output->GetPoint(i, p);
for (j = 0; j < 3; j++)
{
diff[j] = p[j] - this->Position[j];
}
proj = vtkMath::Dot(diff, this->Orientation);
// New mode to handle a two mirror camera with separation of
// MirrorSeparation -- In this case, we assume that the first mirror
// controls the elevation and the second controls the azimuth. Texture
// coordinates for the elevation are handled as normal, while those for
// the azimuth must be calculated based on a new baseline difference to
// include the mirror separation.
if (this->CameraMode == VTK_PROJECTED_TEXTURE_USE_TWO_MIRRORS)
{
// First calculate elevation coordinate t.
if(proj < 1.0e-10 && proj > -1.0e-10)
{
vtkWarningMacro(<<"Singularity: point located at elevation frustum Position");
tcoords[1] = tOffset;
}
else
{
for (j = 0; j < 3; j++)
{
diff[j] = diff[j]/proj - this->Orientation[j];
}
t = vtkMath::Dot(diff, upv);
tcoords[1] = t * tScale + tOffset;
}
// Now with t complete, continue on to calculate coordinate s
// by offsetting the center of the lens back by MirrorSeparation
// in direction opposite to the orientation.
for (j = 0; j < 3; j++)
{
diff[j] = p[j] - this->Position[j] + (this->MirrorSeparation*this->Orientation[j]);
}
proj = vtkMath::Dot(diff, this->Orientation);
if(proj < 1.0e-10 && proj > -1.0e-10)
{
vtkWarningMacro(<<"Singularity: point located at azimuth frustum Position");
tcoords[0] = sOffset;
}
else
{
for (j = 0; j < 3; j++)
{
diff[j] = diff[j]/proj - this->Orientation[j];
}
s = vtkMath::Dot(diff, rightv);
sSize = this->AspectRatio[0] / (this->AspectRatio[2] + this->MirrorSeparation);
sScale = (this->SRange[1] - this->SRange[0])/sSize;
sOffset = (this->SRange[1] - this->SRange[0])/2.0 + this->SRange[0];
tcoords[0] = s * sScale + sOffset;
}
}
else
{
if(proj < 1.0e-10 && proj > -1.0e-10)
{
vtkWarningMacro(<<"Singularity: point located at frustum Position");
tcoords[0] = sOffset;
tcoords[1] = tOffset;
}
else
{
for (j = 0; j < 3; j++)
{
diff[j] = diff[j]/proj - this->Orientation[j];
}
s = vtkMath::Dot(diff, rightv);
t = vtkMath::Dot(diff, upv);
tcoords[0] = s * sScale + sOffset;
tcoords[1] = t * tScale + tOffset;
}
}
newTCoords->SetTuple(i,tcoords);
}
//
// Update ourselves
//
output->GetPointData()->CopyTCoordsOff();
output->GetPointData()->PassData(input->GetPointData());
output->GetPointData()->SetTCoords(newTCoords);
newTCoords->Delete();
}
void vtkProjectedTexture::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "S Range: (" << this->SRange[0] << ", "
<< this->SRange[1] << ")\n";
os << indent << "T Range: (" << this->TRange[0] << ", "
<< this->TRange[1] << ")\n";
os << indent << "Position: (" << this->Position[0] << ", "
<< this->Position[1] << ", "
<< this->Position[2] << ")\n";
os << indent << "Orientation: (" << this->Orientation[0] << ", "
<< this->Orientation[1] << ", "
<< this->Orientation[2] << ")\n";
os << indent << "Focal Point: (" << this->FocalPoint[0] << ", "
<< this->FocalPoint[1] << ", "
<< this->FocalPoint[2] << ")\n";
os << indent << "Up: (" << this->Up[0] << ", "
<< this->Up[1] << ", "
<< this->Up[2] << ")\n";
os << indent << "AspectRatio: (" << this->AspectRatio[0] << ", "
<< this->AspectRatio[1] << ", "
<< this->AspectRatio[2] << ")\n";
os << indent << "CameraMode: ";
if (this->CameraMode == VTK_PROJECTED_TEXTURE_USE_PINHOLE)
{
os << "Pinhole\n";
}
else if (this->CameraMode == VTK_PROJECTED_TEXTURE_USE_TWO_MIRRORS)
{
os << "Two Mirror\n";
}
else
{
os << "Illegal Mode\n";
}
os << indent << "MirrorSeparation: " << this->MirrorSeparation << "\n";
}
<commit_msg>ENH: Adding name to array.<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkProjectedTexture.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkProjectedTexture.h"
#include "vtkDataSet.h"
#include "vtkFloatArray.h"
#include "vtkMath.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
vtkCxxRevisionMacro(vtkProjectedTexture, "1.29");
vtkStandardNewMacro(vtkProjectedTexture);
// Description:
// Initialize the projected texture filter with a position of (0, 0, 1),
// a focal point of (0, 0, 0), an up vector on the +y axis,
// an aspect ratio of the projection frustum of equal width, height, and focal
// length, an S range of (0, 1) and a T range of (0, 1).
vtkProjectedTexture::vtkProjectedTexture()
{
this->Position[0] = 0.0;
this->Position[1] = 0.0;
this->Position[2] = 1.0;
this->Orientation[0] = this->Orientation[1] = this->Orientation[2] = 0.0;
this->SetFocalPoint(0.0, 0.0, 0.0);
this->Up[0] = 0.0;
this->Up[1] = 1.0;
this->Up[2] = 0.0;
this->AspectRatio[0] = 1.0;
this->AspectRatio[1] = 1.0;
this->AspectRatio[2] = 1.0;
this->MirrorSeparation = 1.0;
this->CameraMode = VTK_PROJECTED_TEXTURE_USE_PINHOLE;
this->SRange[0] = 0.0;
this->SRange[1] = 1.0;
this->TRange[0] = 0.0;
this->TRange[1] = 1.0;
}
void vtkProjectedTexture::SetFocalPoint(double fp[3])
{
this->SetFocalPoint(fp[0], fp[1], fp[2]);
}
void vtkProjectedTexture::SetFocalPoint(double x, double y, double z)
{
double orientation[3];
orientation[0] = x - this->Position[0];
orientation[1] = y - this->Position[1];
orientation[2] = z - this->Position[2];
vtkMath::Normalize(orientation);
if (this->Orientation[0] != orientation[0] ||
this->Orientation[1] != orientation[1] ||
this->Orientation[2] != orientation[2])
{
this->Orientation[0] = orientation[0];
this->Orientation[1] = orientation[1];
this->Orientation[2] = orientation[2];
this->Modified();
}
this->FocalPoint[0] = x;
this->FocalPoint[1] = y;
this->FocalPoint[2] = z;
}
void vtkProjectedTexture::Execute()
{
double tcoords[2];
vtkIdType numPts;
vtkFloatArray *newTCoords;
vtkIdType i;
int j;
double proj;
double rightv[3], upv[3], diff[3];
double sScale, tScale, sOffset, tOffset, sSize, tSize, s, t;
vtkDataSet *input = this->GetInput();
double p[3];
vtkDataSet *output = this->GetOutput();
vtkDebugMacro(<<"Generating texture coordinates!");
// First, copy the input to the output as a starting point
output->CopyStructure( input );
numPts=input->GetNumberOfPoints();
//
// Allocate texture data
//
newTCoords = vtkFloatArray::New();
newTCoords->SetName("ProjectedTextureCoordinates");
newTCoords->SetNumberOfComponents(2);
newTCoords->SetNumberOfTuples(numPts);
vtkMath::Normalize (this->Orientation);
vtkMath::Cross (this->Orientation, this->Up, rightv);
vtkMath::Normalize (rightv);
vtkMath::Cross (rightv, this->Orientation, upv);
vtkMath::Normalize (upv);
sSize = this->AspectRatio[0] / this->AspectRatio[2];
tSize = this->AspectRatio[1] / this->AspectRatio[2];
sScale = (this->SRange[1] - this->SRange[0])/sSize;
tScale = (this->TRange[1] - this->TRange[0])/tSize;
sOffset = (this->SRange[1] - this->SRange[0])/2.0 + this->SRange[0];
tOffset = (this->TRange[1] - this->TRange[0])/2.0 + this->TRange[0];
// compute s-t coordinates
for (i = 0; i < numPts; i++)
{
output->GetPoint(i, p);
for (j = 0; j < 3; j++)
{
diff[j] = p[j] - this->Position[j];
}
proj = vtkMath::Dot(diff, this->Orientation);
// New mode to handle a two mirror camera with separation of
// MirrorSeparation -- In this case, we assume that the first mirror
// controls the elevation and the second controls the azimuth. Texture
// coordinates for the elevation are handled as normal, while those for
// the azimuth must be calculated based on a new baseline difference to
// include the mirror separation.
if (this->CameraMode == VTK_PROJECTED_TEXTURE_USE_TWO_MIRRORS)
{
// First calculate elevation coordinate t.
if(proj < 1.0e-10 && proj > -1.0e-10)
{
vtkWarningMacro(<<"Singularity: point located at elevation frustum Position");
tcoords[1] = tOffset;
}
else
{
for (j = 0; j < 3; j++)
{
diff[j] = diff[j]/proj - this->Orientation[j];
}
t = vtkMath::Dot(diff, upv);
tcoords[1] = t * tScale + tOffset;
}
// Now with t complete, continue on to calculate coordinate s
// by offsetting the center of the lens back by MirrorSeparation
// in direction opposite to the orientation.
for (j = 0; j < 3; j++)
{
diff[j] = p[j] - this->Position[j] + (this->MirrorSeparation*this->Orientation[j]);
}
proj = vtkMath::Dot(diff, this->Orientation);
if(proj < 1.0e-10 && proj > -1.0e-10)
{
vtkWarningMacro(<<"Singularity: point located at azimuth frustum Position");
tcoords[0] = sOffset;
}
else
{
for (j = 0; j < 3; j++)
{
diff[j] = diff[j]/proj - this->Orientation[j];
}
s = vtkMath::Dot(diff, rightv);
sSize = this->AspectRatio[0] / (this->AspectRatio[2] + this->MirrorSeparation);
sScale = (this->SRange[1] - this->SRange[0])/sSize;
sOffset = (this->SRange[1] - this->SRange[0])/2.0 + this->SRange[0];
tcoords[0] = s * sScale + sOffset;
}
}
else
{
if(proj < 1.0e-10 && proj > -1.0e-10)
{
vtkWarningMacro(<<"Singularity: point located at frustum Position");
tcoords[0] = sOffset;
tcoords[1] = tOffset;
}
else
{
for (j = 0; j < 3; j++)
{
diff[j] = diff[j]/proj - this->Orientation[j];
}
s = vtkMath::Dot(diff, rightv);
t = vtkMath::Dot(diff, upv);
tcoords[0] = s * sScale + sOffset;
tcoords[1] = t * tScale + tOffset;
}
}
newTCoords->SetTuple(i,tcoords);
}
//
// Update ourselves
//
output->GetPointData()->CopyTCoordsOff();
output->GetPointData()->PassData(input->GetPointData());
output->GetPointData()->SetTCoords(newTCoords);
newTCoords->Delete();
}
void vtkProjectedTexture::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "S Range: (" << this->SRange[0] << ", "
<< this->SRange[1] << ")\n";
os << indent << "T Range: (" << this->TRange[0] << ", "
<< this->TRange[1] << ")\n";
os << indent << "Position: (" << this->Position[0] << ", "
<< this->Position[1] << ", "
<< this->Position[2] << ")\n";
os << indent << "Orientation: (" << this->Orientation[0] << ", "
<< this->Orientation[1] << ", "
<< this->Orientation[2] << ")\n";
os << indent << "Focal Point: (" << this->FocalPoint[0] << ", "
<< this->FocalPoint[1] << ", "
<< this->FocalPoint[2] << ")\n";
os << indent << "Up: (" << this->Up[0] << ", "
<< this->Up[1] << ", "
<< this->Up[2] << ")\n";
os << indent << "AspectRatio: (" << this->AspectRatio[0] << ", "
<< this->AspectRatio[1] << ", "
<< this->AspectRatio[2] << ")\n";
os << indent << "CameraMode: ";
if (this->CameraMode == VTK_PROJECTED_TEXTURE_USE_PINHOLE)
{
os << "Pinhole\n";
}
else if (this->CameraMode == VTK_PROJECTED_TEXTURE_USE_TWO_MIRRORS)
{
os << "Two Mirror\n";
}
else
{
os << "Illegal Mode\n";
}
os << indent << "MirrorSeparation: " << this->MirrorSeparation << "\n";
}
<|endoftext|> |
<commit_before>#include <cstdlib>
#include <cmath>
#include <fstream>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <algorithm>
#include <exception>
#include <sys/time.h>
#include "modules/htmTree.h"
#include "modules/kdTree.h"
#include "misc.h"
#include "feat.h"
#include "structs.h"
#include "collision.h"
#include "global.h"
//reduce redistributes, updates 07/02/15 rnc
int main(int argc, char **argv) {
//// Initializations ---------------------------------------------
srand48(1234); // Make sure we have reproducability
check_args(argc);
Time t, time; // t for global, time for local
init_time(t);
Feat F;
MTL M;
// Read parameters file //
F.readInputFile(argv[1]);
printFile(argv[1]);
init_time_at(time,"# read target, SS, SF files",t);
MTL Targ=read_MTLfile(F.Targfile,F,0,0);
MTL SStars=read_MTLfile(F.SStarsfile,F,1,0);
MTL SkyF=read_MTLfile(F.SkyFfile,F,0,1);
print_time(time,"# ... took :");
//combine the three input files
M=Targ;
printf(" Target size %d \n",M.size());
M.insert(M.end(),SStars.begin(),SStars.end());
printf(" Standard Star size %d \n",M.size());
M.insert(M.end(),SkyF.begin(),SkyF.end());
printf(" Sky Fiber size %d \n",M.size());
F.Ngal = M.size();
assign_priority_class(M);
std::vector <int> count_class(M.priority_list.size(),0);
for(int i;i<M.size();++i){
if(!M[i].SS&&!M[i].SF){
count_class[M[i].priority_class]+=1;
}
}
for(int i;i<M.priority_list.size();++i){
printf(" class %d number %d\n",i,count_class[i]);
}
print_time(time,"# ... took :");
// fiber positioners
PP pp;
pp.read_fiber_positions(F);
F.Nfiber = pp.fp.size()/2;
F.Npetal = max(pp.spectrom)+1;
F.Nfbp = (int) (F.Nfiber/F.Npetal);// fibers per petal = 500
pp.get_neighbors(F);
pp.compute_fibsofsp(F);
//P is original list of plates
Plates P = read_plate_centers(F);
F.Nplate=P.size();
printf("# Read %s plate centers from %s and %d fibers from %s\n",f(F.Nplate).c_str(),F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str());
// Computes geometries of cb and fh: pieces of positioner - used to determine possible collisions
F.cb = create_cb(); // cb=central body
F.fh = create_fh(); // fh=fiber holder
//// Collect available galaxies <-> tilefibers --------------------
// HTM Tree of galaxies
const double MinTreeSize = 0.01;
init_time_at(time,"# Start building HTM tree",t);
htmTree<struct target> T(M,MinTreeSize);
print_time(time,"# ... took :");//T.stats();
init_time_at(time,"# collect galaxies at ",t);
// For plates/fibers, collect available galaxies; done in parallel P[plate j].av_gal[k]=[g1,g2,..]
collect_galaxies_for_all(M,T,P,pp,F);
print_time(time,"# ... took :");//T.stats();
init_time_at(time,"# collect available tile-fibers at",t);
// For each galaxy, computes available tilefibers G[i].av_tfs = [(j1,k1),(j2,k2),..]
collect_available_tilefibers(M,P,F);
//results_on_inputs("doc/figs/",G,P,F,true);
//// Assignment |||||||||||||||||||||||||||||||||||||||||||||||||||
printf(" Nplate %d Ngal %d Nfiber %d \n", F.Nplate, F.Ngal, F.Nfiber);
Assignment A(M,F);
// Make a plan ----------------------------------------------------
print_time(t,"# Start assignment at : ");
simple_assign(M,P,pp,F,A);
//check to see if there are tiles with no galaxies
//need to keep mapping of old tile list to new tile list
//and inverse map
A.inv_order=initList(F.Nplate,-1);
int inv_count=0;
for (int j=0;j<F.Nplate ;++j){
bool not_done=true;
for(int k=0;k<F.Nfiber && not_done;++k){
if(A.TF[j][k]!=-1){
A.suborder.push_back(j);//suborder[jused] is jused-th used plate
not_done=false;
A.inv_order[j]=inv_count;//inv_order[j] is -1 unless used
inv_count++;
}
}
}
F.NUsedplate=A.suborder.size();
printf(" Plates actually used %d \n",F.NUsedplate);
for(int i=0;i<F.NUsedplate;i++)printf(" jused %d j %d\n",i,A.suborder[i]);
print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Hist of unused fibs
// Smooth out distribution of free fibers, and increase the number of assignments
for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A,0);// more iterations will improve performance slightly
for (int i=0; i<3; i++) {
improve(M,P,pp,F,A,0);
redistribute_tf(M,P,pp,F,A,0);
}
print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false);
//try assigning SF and SS before real time assignment
for (int jused=0;jused<F.NUsedplate;++jused){
int j=A.suborder[jused];
assign_sf_ss(j,M,P,pp,F,A); // Assign SS and SF for each tile
assign_unused(j,M,P,pp,F,A);
}
// Results -------------------------------------------------------*/
std::vector <int> total_used_by_class(M.priority_list.size(),0);
int total_used_SS=0;
int total_used_SF=0;
for (int jused=0;jused<F.NUsedplate;++jused){
std::vector <int> used_by_class(M.priority_list.size(),0);
int used_SS=0;
int used_SF=0;
int j=A.suborder[jused];
for(int k=0;k<F.Nfiber;++k){
int g=A.TF[j][k];
if(g!=-1){
if(M[g].SS){
total_used_SS++;
used_SS++;
}
else if(M[g].SF){
used_SF++;
total_used_SF++;
}
else{
used_by_class[M[g].priority_class]++;
total_used_by_class[M[g].priority_class]++;
}
}
}
printf(" plate jused %5d j %5d SS %4d SF %4d",jused,j,used_SS,used_SF);
for (int pr=0;pr<M.priority_list.size();++pr){
printf(" class %2d %5d",pr,used_by_class[pr]);
}
printf("\n");
}
printf(" Totals SS %4d SF %4d",total_used_SS,total_used_SF);
for (int pr=0;pr<M.priority_list.size();++pr){
printf(" class %2d %5d",pr,total_used_by_class[pr]);
}
printf("\n");
if (F.PrintAscii) for (int jused=0; jused<F.NUsedplate; jused++){
int j=A.suborder[jused];
write_FAtile_ascii(j,F.outDir,M,P,pp,F,A);
}
if (F.PrintFits) for (int jused=0; jused<F.NUsedplate; jused++){
int j=A.suborder[jused];
fa_write(j,F.outDir,M,P,pp,F,A); // Write output
}
/*
display_results("doc/figs/",G,M,P,pp,F,A,true);
if (F.Verif) A.verif(P,M,pp,F); // Verification that the assignment is sane
*/
print_time(t,"# Finished !... in");
return(0);
}
<commit_msg>suppress lots of printing<commit_after>#include <cstdlib>
#include <cmath>
#include <fstream>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <algorithm>
#include <exception>
#include <sys/time.h>
#include "modules/htmTree.h"
#include "modules/kdTree.h"
#include "misc.h"
#include "feat.h"
#include "structs.h"
#include "collision.h"
#include "global.h"
//reduce redistributes, updates 07/02/15 rnc
int main(int argc, char **argv) {
//// Initializations ---------------------------------------------
srand48(1234); // Make sure we have reproducability
check_args(argc);
Time t, time; // t for global, time for local
init_time(t);
Feat F;
MTL M;
// Read parameters file //
F.readInputFile(argv[1]);
printFile(argv[1]);
init_time_at(time,"# read target, SS, SF files",t);
MTL Targ=read_MTLfile(F.Targfile,F,0,0);
MTL SStars=read_MTLfile(F.SStarsfile,F,1,0);
MTL SkyF=read_MTLfile(F.SkyFfile,F,0,1);
print_time(time,"# ... took :");
//combine the three input files
M=Targ;
printf(" Target size %d \n",M.size());
M.insert(M.end(),SStars.begin(),SStars.end());
printf(" Standard Star size %d \n",M.size());
M.insert(M.end(),SkyF.begin(),SkyF.end());
printf(" Sky Fiber size %d \n",M.size());
F.Ngal = M.size();
assign_priority_class(M);
std::vector <int> count_class(M.priority_list.size(),0);
for(int i;i<M.size();++i){
if(!M[i].SS&&!M[i].SF){
count_class[M[i].priority_class]+=1;
}
}
for(int i;i<M.priority_list.size();++i){
printf(" class %d number %d\n",i,count_class[i]);
}
print_time(time,"# ... took :");
// fiber positioners
PP pp;
pp.read_fiber_positions(F);
F.Nfiber = pp.fp.size()/2;
F.Npetal = max(pp.spectrom)+1;
F.Nfbp = (int) (F.Nfiber/F.Npetal);// fibers per petal = 500
pp.get_neighbors(F);
pp.compute_fibsofsp(F);
//P is original list of plates
Plates P = read_plate_centers(F);
F.Nplate=P.size();
printf("# Read %s plate centers from %s and %d fibers from %s\n",f(F.Nplate).c_str(),F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str());
// Computes geometries of cb and fh: pieces of positioner - used to determine possible collisions
F.cb = create_cb(); // cb=central body
F.fh = create_fh(); // fh=fiber holder
//// Collect available galaxies <-> tilefibers --------------------
// HTM Tree of galaxies
const double MinTreeSize = 0.01;
init_time_at(time,"# Start building HTM tree",t);
htmTree<struct target> T(M,MinTreeSize);
print_time(time,"# ... took :");//T.stats();
init_time_at(time,"# collect galaxies at ",t);
// For plates/fibers, collect available galaxies; done in parallel P[plate j].av_gal[k]=[g1,g2,..]
collect_galaxies_for_all(M,T,P,pp,F);
print_time(time,"# ... took :");//T.stats();
init_time_at(time,"# collect available tile-fibers at",t);
// For each galaxy, computes available tilefibers G[i].av_tfs = [(j1,k1),(j2,k2),..]
collect_available_tilefibers(M,P,F);
//results_on_inputs("doc/figs/",G,P,F,true);
//// Assignment |||||||||||||||||||||||||||||||||||||||||||||||||||
printf(" Nplate %d Ngal %d Nfiber %d \n", F.Nplate, F.Ngal, F.Nfiber);
Assignment A(M,F);
// Make a plan ----------------------------------------------------
print_time(t,"# Start assignment at : ");
simple_assign(M,P,pp,F,A);
//check to see if there are tiles with no galaxies
//need to keep mapping of old tile list to new tile list
//and inverse map
A.inv_order=initList(F.Nplate,-1);
int inv_count=0;
for (int j=0;j<F.Nplate ;++j){
bool not_done=true;
for(int k=0;k<F.Nfiber && not_done;++k){
if(A.TF[j][k]!=-1){
A.suborder.push_back(j);//suborder[jused] is jused-th used plate
not_done=false;
A.inv_order[j]=inv_count;//inv_order[j] is -1 unless used
inv_count++;
}
}
}
F.NUsedplate=A.suborder.size();
printf(" Plates actually used %d \n",F.NUsedplate);
//for(int i=0;i<F.NUsedplate;i++)printf(" jused %d j %d\n",i,A.suborder[i]);
print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Hist of unused fibs
// Smooth out distribution of free fibers, and increase the number of assignments
for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A,0);// more iterations will improve performance slightly
for (int i=0; i<3; i++) {
improve(M,P,pp,F,A,0);
redistribute_tf(M,P,pp,F,A,0);
}
print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false);
//try assigning SF and SS before real time assignment
for (int jused=0;jused<F.NUsedplate;++jused){
int j=A.suborder[jused];
assign_sf_ss(j,M,P,pp,F,A); // Assign SS and SF for each tile
assign_unused(j,M,P,pp,F,A);
}
// Results -------------------------------------------------------*/
std::vector <int> total_used_by_class(M.priority_list.size(),0);
int total_used_SS=0;
int total_used_SF=0;
for (int jused=0;jused<F.NUsedplate;++jused){
std::vector <int> used_by_class(M.priority_list.size(),0);
int used_SS=0;
int used_SF=0;
int j=A.suborder[jused];
for(int k=0;k<F.Nfiber;++k){
int g=A.TF[j][k];
if(g!=-1){
if(M[g].SS){
total_used_SS++;
used_SS++;
}
else if(M[g].SF){
used_SF++;
total_used_SF++;
}
else{
used_by_class[M[g].priority_class]++;
total_used_by_class[M[g].priority_class]++;
}
}
}
/* printf(" plate jused %5d j %5d SS %4d SF %4d",jused,j,used_SS,used_SF);
for (int pr=0;pr<M.priority_list.size();++pr){
printf(" class %2d %5d",pr,used_by_class[pr]);
}
printf("\n");
*/
}
printf(" Totals SS %4d SF %4d",total_used_SS,total_used_SF);
for (int pr=0;pr<M.priority_list.size();++pr){
printf(" class %2d %5d",pr,total_used_by_class[pr]);
}
printf("\n");
if (F.PrintAscii) for (int jused=0; jused<F.NUsedplate; jused++){
int j=A.suborder[jused];
write_FAtile_ascii(j,F.outDir,M,P,pp,F,A);
}
if (F.PrintFits) for (int jused=0; jused<F.NUsedplate; jused++){
int j=A.suborder[jused];
fa_write(j,F.outDir,M,P,pp,F,A); // Write output
}
/*
display_results("doc/figs/",G,M,P,pp,F,A,true);
if (F.Verif) A.verif(P,M,pp,F); // Verification that the assignment is sane
*/
print_time(t,"# Finished !... in");
return(0);
}
<|endoftext|> |
<commit_before>/* The Next Great Finite Element Library. */
/* Copyright (C) 2003 Benjamin S. Kirk */
/* 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 */
// <h1>Miscellaneous Example 6 - Meshing with LibMesh's TetGen and Triangle Interfaces</h1>
//
// LibMesh provides interfaces to both Triangle and TetGen for generating
// Delaunay triangulations and tetrahedralizations in two and three dimensions
// (respectively).
// Local header files
#include "elem.h"
#include "face_tri3.h"
#include "mesh.h"
#include "mesh_generation.h"
#include "mesh_tetgen_interface.h"
#include "mesh_triangle_holes.h"
#include "mesh_triangle_interface.h"
#include "node.h"
#include "serial_mesh.h"
// Bring in everything from the libMesh namespace
using namespace libMesh;
// Major functions called by main
void triangulate_domain();
void tetrahedralize_domain();
// Helper routine for tetrahedralize_domain(). Adds the points and elements
// of a convex hull generated by TetGen to the input mesh
void add_cube_convex_hull_to_mesh(MeshBase& mesh, Point lower_limit, Point upper_limit);
// Begin the main program.
int main (int argc, char** argv)
{
// Initialize libMesh and any dependent libaries, like in example 2.
LibMeshInit init (argc, argv);
libmesh_example_assert(2 <= LIBMESH_DIM, "2D support");
std::cout << "Triangulating an L-shaped domain with holes" << std::endl;
// 1.) 2D triangulation of L-shaped domain with three holes of different shape
triangulate_domain();
libmesh_example_assert(3 <= LIBMESH_DIM, "3D support");
std::cout << "Tetrahedralizing a prismatic domain with a hole" << std::endl;
// 2.) 3D tetrahedralization of rectangular domain with hole.
tetrahedralize_domain();
return 0;
}
void triangulate_domain()
{
#ifdef LIBMESH_HAVE_TRIANGLE
// Use typedefs for slightly less typing.
typedef TriangleInterface::Hole Hole;
typedef TriangleInterface::PolygonHole PolygonHole;
typedef TriangleInterface::ArbitraryHole ArbitraryHole;
// Libmesh mesh that will eventually be created.
Mesh mesh(2);
// The points which make up the L-shape:
mesh.add_point(Point( 0. , 0.));
mesh.add_point(Point( 0. , -1.));
mesh.add_point(Point(-1. , -1.));
mesh.add_point(Point(-1. , 1.));
mesh.add_point(Point( 1. , 1.));
mesh.add_point(Point( 1. , 0.));
// Declare the TriangleInterface object. This is where
// we can set parameters of the triangulation and where the
// actual triangulate function lives.
TriangleInterface t(mesh);
// Customize the variables for the triangulation
t.desired_area() = .01;
// A Planar Straight Line Graph (PSLG) is essentially a list
// of segments which have to exist in the final triangulation.
// For an L-shaped domain, Triangle will compute the convex
// hull of boundary points if we do not specify the PSLG.
// The PSLG algorithm is also required for triangulating domains
// containing holes
t.triangulation_type() = TriangleInterface::PSLG;
// Turn on/off Laplacian mesh smoothing after generation.
// By default this is on.
t.smooth_after_generating() = true;
// Define holes...
// hole_1 is a circle (discretized by 50 points)
PolygonHole hole_1(Point(-0.5, 0.5), // center
0.25, // radius
50); // n. points
// hole_2 is itself a triangle
PolygonHole hole_2(Point(0.5, 0.5), // center
0.1, // radius
3); // n. points
// hole_3 is an ellipse of 100 points which we define here
Point ellipse_center(-0.5, -0.5);
const unsigned int n_ellipse_points=100;
std::vector<Point> ellipse_points(n_ellipse_points);
const Real
dtheta = 2*libMesh::pi / static_cast<Real>(n_ellipse_points),
a = .1,
b = .2;
for (unsigned int i=0; i<n_ellipse_points; ++i)
ellipse_points[i]= Point(ellipse_center(0)+a*cos(i*dtheta),
ellipse_center(1)+b*sin(i*dtheta));
ArbitraryHole hole_3(ellipse_center, ellipse_points);
// Create the vector of Hole*'s ...
std::vector<Hole*> holes;
holes.push_back(&hole_1);
holes.push_back(&hole_2);
holes.push_back(&hole_3);
// ... and attach it to the triangulator object
t.attach_hole_list(&holes);
// Triangulate!
t.triangulate();
// Write the result to file
mesh.write("delaunay_l_shaped_hole.e");
#endif // LIBMESH_HAVE_TRIANGLE
}
void tetrahedralize_domain()
{
#ifdef LIBMESH_HAVE_TETGEN
// The algorithm is broken up into several steps:
// 1.) A convex hull is constructed for a rectangular hole.
// 2.) A convex hull is constructed for the domain exterior.
// 3.) Neighbor information is updated so TetGen knows there is a convex hull
// 4.) A vector of hole points is created.
// 5.) The domain is tetrahedralized, the mesh is written out, etc.
// The mesh we will eventually generate
SerialMesh mesh(3);
// Lower and Upper bounding box limits for a rectangular hole within the unit cube.
Point hole_lower_limit(0.2, 0.2, 0.4);
Point hole_upper_limit(0.8, 0.8, 0.6);
// 1.) Construct a convex hull for the hole
add_cube_convex_hull_to_mesh(mesh, hole_lower_limit, hole_upper_limit);
// 2.) Generate elements comprising the outer boundary of the domain.
add_cube_convex_hull_to_mesh(mesh, Point(0.,0.,0.), Point(1., 1., 1.));
// 3.) Update neighbor information so that TetGen can verify there is a convex hull.
mesh.find_neighbors();
// 4.) Set up vector of hole points
std::vector<Point> hole(1);
hole[0] = Point( 0.5*(hole_lower_limit + hole_upper_limit) );
// 5.) Set parameters and tetrahedralize the domain
// 0 means "use TetGen default value"
Real quality_constraint = 2.0;
// The volume constraint determines the max-allowed tetrahedral
// volume in the Mesh. TetGen will split cells which are larger than
// this size
Real volume_constraint = 0.001;
// Construct the Delaunay tetrahedralization
TetGenMeshInterface t(mesh);
t.triangulate_conformingDelaunayMesh_carvehole(hole,
quality_constraint,
volume_constraint);
// Find neighbors, etc in preparation for writing out the Mesh
mesh.prepare_for_use();
// Finally, write out the result
mesh.write("hole_3D.e");
#endif // LIBMESH_HAVE_TETGEN
}
void add_cube_convex_hull_to_mesh(MeshBase& mesh, Point lower_limit, Point upper_limit)
{
#ifdef LIBMESH_HAVE_TETGEN
Mesh cube_mesh(3);
unsigned n_elem = 1;
MeshTools::Generation::build_cube(cube_mesh,
n_elem,n_elem,n_elem, // n. elements in each direction
lower_limit(0), upper_limit(0),
lower_limit(1), upper_limit(1),
lower_limit(2), upper_limit(2),
HEX8);
// The pointset_convexhull() algorithm will ignore the Hex8s
// in the Mesh, and just construct the triangulation
// of the convex hull.
TetGenMeshInterface t(cube_mesh);
t.pointset_convexhull();
// Now add all nodes from the boundary of the cube_mesh to the input mesh.
// Map from "node id in cube_mesh" -> "node id in mesh". Initially inserted
// with a dummy value, later to be assigned a value by the input mesh.
std::map<unsigned,unsigned> node_id_map;
typedef std::map<unsigned,unsigned>::iterator iterator;
{
MeshBase::element_iterator it = cube_mesh.elements_begin();
const MeshBase::element_iterator end = cube_mesh.elements_end();
for ( ; it != end; ++it)
{
Elem* elem = *it;
for (unsigned s=0; s<elem->n_sides(); ++s)
if (elem->neighbor(s) == NULL)
{
// Add the node IDs of this side to the set
AutoPtr<Elem> side = elem->side(s);
for (unsigned n=0; n<side->n_nodes(); ++n)
node_id_map.insert( std::make_pair(side->node(n), /*dummy_value=*/0) );
}
}
}
// For each node in the map, insert it into the input mesh and keep
// track of the ID assigned.
for (iterator it=node_id_map.begin(); it != node_id_map.end(); ++it)
{
// Id of the node in the cube mesh
unsigned id = (*it).first;
// Pointer to node in the cube mesh
Node* old_node = cube_mesh.node_ptr(id);
// Add geometric point to input mesh
Node* new_node = mesh.add_point ( *old_node );
// Track ID value of new_node in map
(*it).second = new_node->id();
}
// With the points added and the map data structure in place, we are
// ready to add each TRI3 element of the cube_mesh to the input Mesh
// with proper node assignments
{
MeshBase::element_iterator el = cube_mesh.elements_begin();
const MeshBase::element_iterator end_el = cube_mesh.elements_end();
for (; el != end_el; ++el)
{
Elem* old_elem = *el;
if (old_elem->type() == TRI3)
{
Elem* new_elem = mesh.add_elem(new Tri3);
// Assign nodes in new elements. Since this is an example,
// we'll do it in several steps.
for (unsigned i=0; i<old_elem->n_nodes(); ++i)
{
// Locate old node ID in the map
iterator it = node_id_map.find(old_elem->node(i));
// Check for not found
if (it == node_id_map.end())
{
libMesh::err << "Node id " << old_elem->node(i) << " not found in map!" << std::endl;
libmesh_error();
}
// Mapping to node ID in input mesh
unsigned new_node_id = (*it).second;
// Node pointer assigned from input mesh
new_elem->set_node(i) = mesh.node_ptr(new_node_id);
}
}
}
}
#endif // LIBMESH_HAVE_TETGEN
}
<commit_msg>Using SerialMesh with TetGen for now<commit_after>/* The Next Great Finite Element Library. */
/* Copyright (C) 2003 Benjamin S. Kirk */
/* 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 */
// <h1>Miscellaneous Example 6 - Meshing with LibMesh's TetGen and Triangle Interfaces</h1>
//
// LibMesh provides interfaces to both Triangle and TetGen for generating
// Delaunay triangulations and tetrahedralizations in two and three dimensions
// (respectively).
// Local header files
#include "elem.h"
#include "face_tri3.h"
#include "mesh.h"
#include "mesh_generation.h"
#include "mesh_tetgen_interface.h"
#include "mesh_triangle_holes.h"
#include "mesh_triangle_interface.h"
#include "node.h"
#include "serial_mesh.h"
// Bring in everything from the libMesh namespace
using namespace libMesh;
// Major functions called by main
void triangulate_domain();
void tetrahedralize_domain();
// Helper routine for tetrahedralize_domain(). Adds the points and elements
// of a convex hull generated by TetGen to the input mesh
void add_cube_convex_hull_to_mesh(MeshBase& mesh, Point lower_limit, Point upper_limit);
// Begin the main program.
int main (int argc, char** argv)
{
// Initialize libMesh and any dependent libaries, like in example 2.
LibMeshInit init (argc, argv);
libmesh_example_assert(2 <= LIBMESH_DIM, "2D support");
std::cout << "Triangulating an L-shaped domain with holes" << std::endl;
// 1.) 2D triangulation of L-shaped domain with three holes of different shape
triangulate_domain();
libmesh_example_assert(3 <= LIBMESH_DIM, "3D support");
std::cout << "Tetrahedralizing a prismatic domain with a hole" << std::endl;
// 2.) 3D tetrahedralization of rectangular domain with hole.
tetrahedralize_domain();
return 0;
}
void triangulate_domain()
{
#ifdef LIBMESH_HAVE_TRIANGLE
// Use typedefs for slightly less typing.
typedef TriangleInterface::Hole Hole;
typedef TriangleInterface::PolygonHole PolygonHole;
typedef TriangleInterface::ArbitraryHole ArbitraryHole;
// Libmesh mesh that will eventually be created.
Mesh mesh(2);
// The points which make up the L-shape:
mesh.add_point(Point( 0. , 0.));
mesh.add_point(Point( 0. , -1.));
mesh.add_point(Point(-1. , -1.));
mesh.add_point(Point(-1. , 1.));
mesh.add_point(Point( 1. , 1.));
mesh.add_point(Point( 1. , 0.));
// Declare the TriangleInterface object. This is where
// we can set parameters of the triangulation and where the
// actual triangulate function lives.
TriangleInterface t(mesh);
// Customize the variables for the triangulation
t.desired_area() = .01;
// A Planar Straight Line Graph (PSLG) is essentially a list
// of segments which have to exist in the final triangulation.
// For an L-shaped domain, Triangle will compute the convex
// hull of boundary points if we do not specify the PSLG.
// The PSLG algorithm is also required for triangulating domains
// containing holes
t.triangulation_type() = TriangleInterface::PSLG;
// Turn on/off Laplacian mesh smoothing after generation.
// By default this is on.
t.smooth_after_generating() = true;
// Define holes...
// hole_1 is a circle (discretized by 50 points)
PolygonHole hole_1(Point(-0.5, 0.5), // center
0.25, // radius
50); // n. points
// hole_2 is itself a triangle
PolygonHole hole_2(Point(0.5, 0.5), // center
0.1, // radius
3); // n. points
// hole_3 is an ellipse of 100 points which we define here
Point ellipse_center(-0.5, -0.5);
const unsigned int n_ellipse_points=100;
std::vector<Point> ellipse_points(n_ellipse_points);
const Real
dtheta = 2*libMesh::pi / static_cast<Real>(n_ellipse_points),
a = .1,
b = .2;
for (unsigned int i=0; i<n_ellipse_points; ++i)
ellipse_points[i]= Point(ellipse_center(0)+a*cos(i*dtheta),
ellipse_center(1)+b*sin(i*dtheta));
ArbitraryHole hole_3(ellipse_center, ellipse_points);
// Create the vector of Hole*'s ...
std::vector<Hole*> holes;
holes.push_back(&hole_1);
holes.push_back(&hole_2);
holes.push_back(&hole_3);
// ... and attach it to the triangulator object
t.attach_hole_list(&holes);
// Triangulate!
t.triangulate();
// Write the result to file
mesh.write("delaunay_l_shaped_hole.e");
#endif // LIBMESH_HAVE_TRIANGLE
}
void tetrahedralize_domain()
{
#ifdef LIBMESH_HAVE_TETGEN
// The algorithm is broken up into several steps:
// 1.) A convex hull is constructed for a rectangular hole.
// 2.) A convex hull is constructed for the domain exterior.
// 3.) Neighbor information is updated so TetGen knows there is a convex hull
// 4.) A vector of hole points is created.
// 5.) The domain is tetrahedralized, the mesh is written out, etc.
// The mesh we will eventually generate
SerialMesh mesh(3);
// Lower and Upper bounding box limits for a rectangular hole within the unit cube.
Point hole_lower_limit(0.2, 0.2, 0.4);
Point hole_upper_limit(0.8, 0.8, 0.6);
// 1.) Construct a convex hull for the hole
add_cube_convex_hull_to_mesh(mesh, hole_lower_limit, hole_upper_limit);
// 2.) Generate elements comprising the outer boundary of the domain.
add_cube_convex_hull_to_mesh(mesh, Point(0.,0.,0.), Point(1., 1., 1.));
// 3.) Update neighbor information so that TetGen can verify there is a convex hull.
mesh.find_neighbors();
// 4.) Set up vector of hole points
std::vector<Point> hole(1);
hole[0] = Point( 0.5*(hole_lower_limit + hole_upper_limit) );
// 5.) Set parameters and tetrahedralize the domain
// 0 means "use TetGen default value"
Real quality_constraint = 2.0;
// The volume constraint determines the max-allowed tetrahedral
// volume in the Mesh. TetGen will split cells which are larger than
// this size
Real volume_constraint = 0.001;
// Construct the Delaunay tetrahedralization
TetGenMeshInterface t(mesh);
t.triangulate_conformingDelaunayMesh_carvehole(hole,
quality_constraint,
volume_constraint);
// Find neighbors, etc in preparation for writing out the Mesh
mesh.prepare_for_use();
// Finally, write out the result
mesh.write("hole_3D.e");
#endif // LIBMESH_HAVE_TETGEN
}
void add_cube_convex_hull_to_mesh(MeshBase& mesh, Point lower_limit, Point upper_limit)
{
#ifdef LIBMESH_HAVE_TETGEN
SerialMesh cube_mesh(3);
unsigned n_elem = 1;
MeshTools::Generation::build_cube(cube_mesh,
n_elem,n_elem,n_elem, // n. elements in each direction
lower_limit(0), upper_limit(0),
lower_limit(1), upper_limit(1),
lower_limit(2), upper_limit(2),
HEX8);
// The pointset_convexhull() algorithm will ignore the Hex8s
// in the Mesh, and just construct the triangulation
// of the convex hull.
TetGenMeshInterface t(cube_mesh);
t.pointset_convexhull();
// Now add all nodes from the boundary of the cube_mesh to the input mesh.
// Map from "node id in cube_mesh" -> "node id in mesh". Initially inserted
// with a dummy value, later to be assigned a value by the input mesh.
std::map<unsigned,unsigned> node_id_map;
typedef std::map<unsigned,unsigned>::iterator iterator;
{
MeshBase::element_iterator it = cube_mesh.elements_begin();
const MeshBase::element_iterator end = cube_mesh.elements_end();
for ( ; it != end; ++it)
{
Elem* elem = *it;
for (unsigned s=0; s<elem->n_sides(); ++s)
if (elem->neighbor(s) == NULL)
{
// Add the node IDs of this side to the set
AutoPtr<Elem> side = elem->side(s);
for (unsigned n=0; n<side->n_nodes(); ++n)
node_id_map.insert( std::make_pair(side->node(n), /*dummy_value=*/0) );
}
}
}
// For each node in the map, insert it into the input mesh and keep
// track of the ID assigned.
for (iterator it=node_id_map.begin(); it != node_id_map.end(); ++it)
{
// Id of the node in the cube mesh
unsigned id = (*it).first;
// Pointer to node in the cube mesh
Node* old_node = cube_mesh.node_ptr(id);
// Add geometric point to input mesh
Node* new_node = mesh.add_point ( *old_node );
// Track ID value of new_node in map
(*it).second = new_node->id();
}
// With the points added and the map data structure in place, we are
// ready to add each TRI3 element of the cube_mesh to the input Mesh
// with proper node assignments
{
MeshBase::element_iterator el = cube_mesh.elements_begin();
const MeshBase::element_iterator end_el = cube_mesh.elements_end();
for (; el != end_el; ++el)
{
Elem* old_elem = *el;
if (old_elem->type() == TRI3)
{
Elem* new_elem = mesh.add_elem(new Tri3);
// Assign nodes in new elements. Since this is an example,
// we'll do it in several steps.
for (unsigned i=0; i<old_elem->n_nodes(); ++i)
{
// Locate old node ID in the map
iterator it = node_id_map.find(old_elem->node(i));
// Check for not found
if (it == node_id_map.end())
{
libMesh::err << "Node id " << old_elem->node(i) << " not found in map!" << std::endl;
libmesh_error();
}
// Mapping to node ID in input mesh
unsigned new_node_id = (*it).second;
// Node pointer assigned from input mesh
new_elem->set_node(i) = mesh.node_ptr(new_node_id);
}
}
}
}
#endif // LIBMESH_HAVE_TETGEN
}
<|endoftext|> |
<commit_before>/*
* The MIT License (MIT)
*
* Copyright (c) 2014 Pavel Strakhov
*
* 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 "ToolWindowManagerArea.h"
#include "ToolWindowManagerTabBar.h"
#include "ToolWindowManagerWrapper.h"
#include "ToolWindowManager.h"
#include <QApplication>
#include <QMouseEvent>
#include <algorithm>
static void showCloseButton(QTabBar *bar, int index, bool show) {
QWidget *button = bar->tabButton(index, QTabBar::RightSide);
if(button == NULL)
button = bar->tabButton(index, QTabBar::LeftSide);
if(button)
button->resize(show ? QSize(16, 16) : QSize(0, 0));
}
ToolWindowManagerArea::ToolWindowManagerArea(ToolWindowManager *manager, QWidget *parent) :
QTabWidget(parent)
, m_manager(manager)
{
m_tabBar = new ToolWindowManagerTabBar(this);
setTabBar(m_tabBar);
m_tabBar->setTabsClosable(true);
m_dragCanStart = false;
m_tabDragCanStart = false;
m_inTabMoved = false;
m_userCanDrop = true;
setMovable(true);
setDocumentMode(true);
tabBar()->installEventFilter(this);
m_manager->m_areas << this;
QObject::connect(tabBar(), &QTabBar::tabMoved, this, &ToolWindowManagerArea::tabMoved);
QObject::connect(tabBar(), &QTabBar::tabCloseRequested, this, &ToolWindowManagerArea::tabClosing);
QObject::connect(tabBar(), &QTabBar::tabCloseRequested, this, &QTabWidget::tabCloseRequested);
QObject::connect(this, &QTabWidget::currentChanged, this, &ToolWindowManagerArea::tabSelected);
}
ToolWindowManagerArea::~ToolWindowManagerArea() {
m_manager->m_areas.removeOne(this);
}
void ToolWindowManagerArea::addToolWindow(QWidget *toolWindow, int insertIndex) {
addToolWindows(QList<QWidget*>() << toolWindow, insertIndex);
}
void ToolWindowManagerArea::addToolWindows(const QList<QWidget *> &toolWindows, int insertIndex) {
int index = 0;
foreach(QWidget* toolWindow, toolWindows) {
index = insertTab(insertIndex, toolWindow, toolWindow->windowIcon(), toolWindow->windowTitle());
insertIndex = index+1;
if(m_manager->toolWindowProperties(toolWindow) & ToolWindowManager::HideCloseButton) {
showCloseButton(tabBar(), index, false);
}
}
setCurrentIndex(index);
m_manager->m_lastUsedArea = this;
}
QList<QWidget *> ToolWindowManagerArea::toolWindows() {
QList<QWidget *> result;
for(int i = 0; i < count(); i++) {
result << widget(i);
}
return result;
}
void ToolWindowManagerArea::updateToolWindow(QWidget* toolWindow) {
int index = indexOf(toolWindow);
if(index >= 0) {
if(m_manager->toolWindowProperties(toolWindow) & ToolWindowManager::HideCloseButton) {
showCloseButton(tabBar(), index, false);
} else {
showCloseButton(tabBar(), index, true);
}
tabBar()->setTabText(index, toolWindow->windowTitle());
}
}
void ToolWindowManagerArea::mouseMoveEvent(QMouseEvent *) {
check_mouse_move();
}
bool ToolWindowManagerArea::eventFilter(QObject *object, QEvent *event) {
if (object == tabBar()) {
if (event->type() == QEvent::MouseButtonPress &&
qApp->mouseButtons() == Qt::LeftButton) {
QPoint pos = static_cast<QMouseEvent*>(event)->pos();
int tabIndex = tabBar()->tabAt(pos);
// can start tab drag only if mouse is at some tab, not at empty tabbar space
if (tabIndex >= 0) {
m_tabDragCanStart = true;
if (m_manager->toolWindowProperties(widget(tabIndex)) & ToolWindowManager::DisableDraggableTab) {
setMovable(false);
} else {
setMovable(true);
}
} else if (m_tabBar == NULL || !m_tabBar->inButton(pos)) {
m_dragCanStart = true;
m_dragCanStartPos = QCursor::pos();
}
} else if (event->type() == QEvent::MouseButtonPress &&
qApp->mouseButtons() == Qt::MiddleButton) {
int tabIndex = tabBar()->tabAt(static_cast<QMouseEvent*>(event)->pos());
if(tabIndex >= 0) {
QWidget *w = widget(tabIndex);
if(!(m_manager->toolWindowProperties(w) & ToolWindowManager::HideCloseButton)) {
m_manager->removeToolWindow(w);
}
}
} else if (event->type() == QEvent::MouseButtonRelease) {
m_tabDragCanStart = false;
m_dragCanStart = false;
m_manager->updateDragPosition();
} else if (event->type() == QEvent::MouseMove) {
m_manager->updateDragPosition();
if (m_tabDragCanStart) {
if (tabBar()->rect().contains(static_cast<QMouseEvent*>(event)->pos())) {
return false;
}
if (qApp->mouseButtons() != Qt::LeftButton) {
return false;
}
QWidget* toolWindow = currentWidget();
if (!toolWindow || !m_manager->m_toolWindows.contains(toolWindow)) {
return false;
}
m_tabDragCanStart = false;
//stop internal tab drag in QTabBar
QMouseEvent* releaseEvent = new QMouseEvent(QEvent::MouseButtonRelease,
static_cast<QMouseEvent*>(event)->pos(),
Qt::LeftButton, Qt::LeftButton, 0);
qApp->sendEvent(tabBar(), releaseEvent);
m_manager->startDrag(QList<QWidget*>() << toolWindow, NULL);
} else if (m_dragCanStart) {
check_mouse_move();
}
}
}
return QTabWidget::eventFilter(object, event);
}
void ToolWindowManagerArea::tabInserted(int index) {
// update the select order. Increment any existing index after the insertion point to keep the
// indices in the list up to date.
for (int &idx : m_tabSelectOrder) {
if (idx >= index)
idx++;
}
// if the tab inserted is the current index (most likely) then add it at the end, otherwise
// add it next-to-end (to keep the most recent tab the same).
if (currentIndex() == index || m_tabSelectOrder.isEmpty())
m_tabSelectOrder.append(index);
else
m_tabSelectOrder.insert(m_tabSelectOrder.count()-1, index);
QTabWidget::tabInserted(index);
}
void ToolWindowManagerArea::tabRemoved(int index) {
// update the select order. Remove the index that just got deleted, and decrement any index
// greater than it to remap to their new indices
m_tabSelectOrder.removeOne(index);
for (int &idx : m_tabSelectOrder) {
if (idx > index)
idx--;
}
QTabWidget::tabRemoved(index);
}
void ToolWindowManagerArea::tabSelected(int index) {
// move this tab to the end of the select order, as long as we have it - if it's a new index then
// ignore and leave it to be handled in tabInserted()
if (m_tabSelectOrder.contains(index)) {
m_tabSelectOrder.removeOne(index);
m_tabSelectOrder.append(index);
}
ToolWindowManagerWrapper* wrapper = m_manager->wrapperOf(this);
if (wrapper)
wrapper->updateTitle();
}
void ToolWindowManagerArea::tabClosing(int index) {
// before closing this index, switch the current index to the next tab in succession.
// should never get here but let's check this
if (m_tabSelectOrder.isEmpty())
return;
// when closing the last tab there's nothing to do
if (m_tabSelectOrder.count() == 1)
return;
// if the last in the select order is being closed, switch to the next most selected tab
if (m_tabSelectOrder.last() == index)
setCurrentIndex(m_tabSelectOrder.at(m_tabSelectOrder.count()-2));
}
QVariantMap ToolWindowManagerArea::saveState() {
QVariantMap result;
result[QStringLiteral("type")] = QStringLiteral("area");
result[QStringLiteral("currentIndex")] = currentIndex();
QVariantList objects;
objects.reserve(count());
for(int i = 0; i < count(); i++) {
QWidget *w = widget(i);
QString name = w->objectName();
if (name.isEmpty()) {
qWarning("cannot save state of tool window without object name");
} else {
QVariantMap objectData;
objectData[QStringLiteral("name")] = name;
objectData[QStringLiteral("data")] = w->property("persistData");
objects.push_back(objectData);
}
}
result[QStringLiteral("objects")] = objects;
return result;
}
void ToolWindowManagerArea::restoreState(const QVariantMap &savedData) {
for(QVariant object : savedData[QStringLiteral("objects")].toList()) {
QVariantMap objectData = object.toMap();
if (objectData.isEmpty()) { continue; }
QString objectName = objectData[QStringLiteral("name")].toString();
if (objectName.isEmpty()) { continue; }
QWidget *t = NULL;
for(QWidget* toolWindow : m_manager->m_toolWindows) {
if (toolWindow->objectName() == objectName) {
t = toolWindow;
break;
}
}
if (t == NULL) t = m_manager->createToolWindow(objectName);
if (t) {
t->setProperty("persistData", objectData[QStringLiteral("data")]);
addToolWindow(t);
} else {
qWarning("tool window with name '%s' not found or created", objectName.toLocal8Bit().constData());
}
}
setCurrentIndex(savedData[QStringLiteral("currentIndex")].toInt());
}
void ToolWindowManagerArea::check_mouse_move() {
if (qApp->mouseButtons() == Qt::LeftButton && m_dragCanStart) {
m_dragCanStart = false;
}
m_manager->updateDragPosition();
if (m_dragCanStart &&
(QCursor::pos() - m_dragCanStartPos).manhattanLength() > 10) {
m_dragCanStart = false;
QList<QWidget*> toolWindows;
for(int i = 0; i < count(); i++) {
QWidget* toolWindow = widget(i);
if (!m_manager->m_toolWindows.contains(toolWindow)) {
qWarning("tab widget contains unmanaged widget");
} else {
toolWindows << toolWindow;
}
}
m_manager->startDrag(toolWindows, NULL);
}
}
bool ToolWindowManagerArea::useMinimalTabBar() {
QWidget *w = widget(0);
if (w == NULL)
return false;
return (m_manager->toolWindowProperties(w) & ToolWindowManager::AlwaysDisplayFullTabs) == 0;
}
void ToolWindowManagerArea::tabMoved(int from, int to) {
if(m_inTabMoved) return;
// update the select order.
// This amounts to just a swap - any indices other than the pair in question are unaffected since
// one tab is removed (above/below) and added (below/above) so the indices themselves remain the
// same.
for (int &idx : m_tabSelectOrder) {
if (idx == from)
idx = to;
else if (idx == to)
idx = from;
}
QWidget *a = widget(from);
QWidget *b = widget(to);
if(!a || !b) return;
if(m_manager->toolWindowProperties(a) & ToolWindowManager::DisableDraggableTab ||
m_manager->toolWindowProperties(b) & ToolWindowManager::DisableDraggableTab)
{
m_inTabMoved = true;
tabBar()->moveTab(to, from);
m_inTabMoved = false;
}
}
<commit_msg>Get fix for toolwindowmanager - 3a02944<commit_after>/*
* The MIT License (MIT)
*
* Copyright (c) 2014 Pavel Strakhov
*
* 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 "ToolWindowManagerArea.h"
#include "ToolWindowManagerTabBar.h"
#include "ToolWindowManagerWrapper.h"
#include "ToolWindowManager.h"
#include <QApplication>
#include <QMouseEvent>
#include <algorithm>
static void showCloseButton(QTabBar *bar, int index, bool show) {
QWidget *button = bar->tabButton(index, QTabBar::RightSide);
if(button == NULL)
button = bar->tabButton(index, QTabBar::LeftSide);
if(button)
button->resize(show ? QSize(16, 16) : QSize(0, 0));
}
ToolWindowManagerArea::ToolWindowManagerArea(ToolWindowManager *manager, QWidget *parent) :
QTabWidget(parent)
, m_manager(manager)
{
m_tabBar = new ToolWindowManagerTabBar(this);
setTabBar(m_tabBar);
m_tabBar->setTabsClosable(true);
m_dragCanStart = false;
m_tabDragCanStart = false;
m_inTabMoved = false;
m_userCanDrop = true;
setMovable(true);
setDocumentMode(true);
tabBar()->installEventFilter(this);
m_manager->m_areas << this;
QObject::connect(tabBar(), &QTabBar::tabMoved, this, &ToolWindowManagerArea::tabMoved);
QObject::connect(tabBar(), &QTabBar::tabCloseRequested, this, &ToolWindowManagerArea::tabClosing);
QObject::connect(tabBar(), &QTabBar::tabCloseRequested, this, &QTabWidget::tabCloseRequested);
QObject::connect(this, &QTabWidget::currentChanged, this, &ToolWindowManagerArea::tabSelected);
}
ToolWindowManagerArea::~ToolWindowManagerArea() {
m_manager->m_areas.removeOne(this);
}
void ToolWindowManagerArea::addToolWindow(QWidget *toolWindow, int insertIndex) {
addToolWindows(QList<QWidget*>() << toolWindow, insertIndex);
}
void ToolWindowManagerArea::addToolWindows(const QList<QWidget *> &toolWindows, int insertIndex) {
int index = 0;
foreach(QWidget* toolWindow, toolWindows) {
index = insertTab(insertIndex, toolWindow, toolWindow->windowIcon(), toolWindow->windowTitle());
insertIndex = index+1;
if(m_manager->toolWindowProperties(toolWindow) & ToolWindowManager::HideCloseButton) {
showCloseButton(tabBar(), index, false);
}
}
setCurrentIndex(index);
m_manager->m_lastUsedArea = this;
}
QList<QWidget *> ToolWindowManagerArea::toolWindows() {
QList<QWidget *> result;
for(int i = 0; i < count(); i++) {
result << widget(i);
}
return result;
}
void ToolWindowManagerArea::updateToolWindow(QWidget* toolWindow) {
int index = indexOf(toolWindow);
if(index >= 0) {
if(m_manager->toolWindowProperties(toolWindow) & ToolWindowManager::HideCloseButton) {
showCloseButton(tabBar(), index, false);
} else {
showCloseButton(tabBar(), index, true);
}
tabBar()->setTabText(index, toolWindow->windowTitle());
}
}
void ToolWindowManagerArea::mouseMoveEvent(QMouseEvent *) {
check_mouse_move();
}
bool ToolWindowManagerArea::eventFilter(QObject *object, QEvent *event) {
if (object == tabBar()) {
if (event->type() == QEvent::MouseButtonPress &&
qApp->mouseButtons() == Qt::LeftButton) {
QPoint pos = static_cast<QMouseEvent*>(event)->pos();
int tabIndex = tabBar()->tabAt(pos);
// can start tab drag only if mouse is at some tab, not at empty tabbar space
if (tabIndex >= 0) {
m_tabDragCanStart = true;
if (m_manager->toolWindowProperties(widget(tabIndex)) & ToolWindowManager::DisableDraggableTab) {
setMovable(false);
} else {
setMovable(true);
}
} else if (m_tabBar == NULL || !m_tabBar->inButton(pos)) {
m_dragCanStart = true;
m_dragCanStartPos = QCursor::pos();
}
} else if (event->type() == QEvent::MouseButtonPress &&
qApp->mouseButtons() == Qt::MiddleButton) {
int tabIndex = tabBar()->tabAt(static_cast<QMouseEvent*>(event)->pos());
if(tabIndex >= 0) {
QWidget *w = widget(tabIndex);
if(!(m_manager->toolWindowProperties(w) & ToolWindowManager::HideCloseButton)) {
m_manager->removeToolWindow(w);
}
}
} else if (event->type() == QEvent::MouseButtonRelease) {
m_tabDragCanStart = false;
m_dragCanStart = false;
m_manager->updateDragPosition();
} else if (event->type() == QEvent::MouseMove) {
m_manager->updateDragPosition();
if (m_tabDragCanStart) {
if (tabBar()->rect().contains(static_cast<QMouseEvent*>(event)->pos())) {
return false;
}
if (qApp->mouseButtons() != Qt::LeftButton) {
return false;
}
QWidget* toolWindow = currentWidget();
if (!toolWindow || !m_manager->m_toolWindows.contains(toolWindow)) {
return false;
}
m_tabDragCanStart = false;
//stop internal tab drag in QTabBar
QMouseEvent* releaseEvent = new QMouseEvent(QEvent::MouseButtonRelease,
static_cast<QMouseEvent*>(event)->pos(),
Qt::LeftButton, Qt::LeftButton, 0);
qApp->sendEvent(tabBar(), releaseEvent);
m_manager->startDrag(QList<QWidget*>() << toolWindow, NULL);
} else if (m_dragCanStart) {
check_mouse_move();
}
}
}
return QTabWidget::eventFilter(object, event);
}
void ToolWindowManagerArea::tabInserted(int index) {
// update the select order. Increment any existing index after the insertion point to keep the
// indices in the list up to date.
for (int &idx : m_tabSelectOrder) {
if (idx >= index)
idx++;
}
// if the tab inserted is the current index (most likely) then add it at the end, otherwise
// add it next-to-end (to keep the most recent tab the same).
if (currentIndex() == index || m_tabSelectOrder.isEmpty())
m_tabSelectOrder.append(index);
else
m_tabSelectOrder.insert(m_tabSelectOrder.count()-1, index);
QTabWidget::tabInserted(index);
}
void ToolWindowManagerArea::tabRemoved(int index) {
// update the select order. Remove the index that just got deleted, and decrement any index
// greater than it to remap to their new indices
m_tabSelectOrder.removeOne(index);
for (int &idx : m_tabSelectOrder) {
if (idx > index)
idx--;
}
QTabWidget::tabRemoved(index);
}
void ToolWindowManagerArea::tabSelected(int index) {
// move this tab to the end of the select order, as long as we have it - if it's a new index then
// ignore and leave it to be handled in tabInserted()
if (m_tabSelectOrder.contains(index)) {
m_tabSelectOrder.removeOne(index);
m_tabSelectOrder.append(index);
}
ToolWindowManagerWrapper* wrapper = m_manager->wrapperOf(this);
if (wrapper)
wrapper->updateTitle();
}
void ToolWindowManagerArea::tabClosing(int index) {
// before closing this index, switch the current index to the next tab in succession.
// should never get here but let's check this
if (m_tabSelectOrder.isEmpty())
return;
// when closing the last tab there's nothing to do
if (m_tabSelectOrder.count() == 1)
return;
// if the last in the select order is being closed, switch to the next most selected tab
if (m_tabSelectOrder.last() == index)
setCurrentIndex(m_tabSelectOrder.at(m_tabSelectOrder.count()-2));
}
QVariantMap ToolWindowManagerArea::saveState() {
QVariantMap result;
result[QStringLiteral("type")] = QStringLiteral("area");
result[QStringLiteral("currentIndex")] = currentIndex();
QVariantList objects;
objects.reserve(count());
for(int i = 0; i < count(); i++) {
QWidget *w = widget(i);
QString name = w->objectName();
if (name.isEmpty()) {
qWarning("cannot save state of tool window without object name");
} else {
QVariantMap objectData;
objectData[QStringLiteral("name")] = name;
objectData[QStringLiteral("data")] = w->property("persistData");
objects.push_back(objectData);
}
}
result[QStringLiteral("objects")] = objects;
return result;
}
void ToolWindowManagerArea::restoreState(const QVariantMap &savedData) {
for(QVariant object : savedData[QStringLiteral("objects")].toList()) {
QVariantMap objectData = object.toMap();
if (objectData.isEmpty()) { continue; }
QString objectName = objectData[QStringLiteral("name")].toString();
if (objectName.isEmpty()) { continue; }
QWidget *t = NULL;
for(QWidget* toolWindow : m_manager->m_toolWindows) {
if (toolWindow->objectName() == objectName) {
t = toolWindow;
break;
}
}
if (t == NULL) t = m_manager->createToolWindow(objectName);
if (t) {
t->setProperty("persistData", objectData[QStringLiteral("data")]);
addToolWindow(t);
} else {
qWarning("tool window with name '%s' not found or created", objectName.toLocal8Bit().constData());
}
}
setCurrentIndex(savedData[QStringLiteral("currentIndex")].toInt());
}
void ToolWindowManagerArea::check_mouse_move() {
if (qApp->mouseButtons() != Qt::LeftButton && m_dragCanStart) {
m_dragCanStart = false;
}
m_manager->updateDragPosition();
if (m_dragCanStart &&
(QCursor::pos() - m_dragCanStartPos).manhattanLength() > 10) {
m_dragCanStart = false;
QList<QWidget*> toolWindows;
for(int i = 0; i < count(); i++) {
QWidget* toolWindow = widget(i);
if (!m_manager->m_toolWindows.contains(toolWindow)) {
qWarning("tab widget contains unmanaged widget");
} else {
toolWindows << toolWindow;
}
}
m_manager->startDrag(toolWindows, NULL);
}
}
bool ToolWindowManagerArea::useMinimalTabBar() {
QWidget *w = widget(0);
if (w == NULL)
return false;
return (m_manager->toolWindowProperties(w) & ToolWindowManager::AlwaysDisplayFullTabs) == 0;
}
void ToolWindowManagerArea::tabMoved(int from, int to) {
if(m_inTabMoved) return;
// update the select order.
// This amounts to just a swap - any indices other than the pair in question are unaffected since
// one tab is removed (above/below) and added (below/above) so the indices themselves remain the
// same.
for (int &idx : m_tabSelectOrder) {
if (idx == from)
idx = to;
else if (idx == to)
idx = from;
}
QWidget *a = widget(from);
QWidget *b = widget(to);
if(!a || !b) return;
if(m_manager->toolWindowProperties(a) & ToolWindowManager::DisableDraggableTab ||
m_manager->toolWindowProperties(b) & ToolWindowManager::DisableDraggableTab)
{
m_inTabMoved = true;
tabBar()->moveTab(to, from);
m_inTabMoved = false;
}
}
<|endoftext|> |
<commit_before>/******************************************************************************
Copyright (c) 2015, Geoffrey TOURON
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 dusty nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
#include "new.hpp"
#include "configmanager.hpp"
#include "graphicengine.hpp"
Graphicengine::Graphicengine() : _animations_size(4096), _animations_count(0), _animations(0),
_lights_size(4096), _lights_count(0), _lights(0), _lights_links(0),
_materials_size(0), _materials_count(0), _materials(0),
_renderer(1440, 900)
{
camera.resolution[0] = 1440;
camera.resolution[1] = 900;
camera.spherical_coord[0] = -2.2f;
camera.spherical_coord[1] = -0.7f;
camera.fov = 1.9198621771f;
_animations = new Animation*[_animations_size];
_lights = new Light[_lights_size];
_lights_links = new Light**[_lights_size];
_load_materials("materials.df");
}
Graphicengine::~Graphicengine()
{
delete [] _animations;
delete [] _lights;
delete [] _lights_links;
delete [] _materials;
}
void Graphicengine::set_resolution(unsigned int const width, unsigned int const height)
{
camera.resolution[0] = width;
camera.resolution[1] = height;
_renderer.set_resolution(width, height);
}
void Graphicengine::tick(float const delta)
{
for (unsigned int i = 0; i < _animations_count; ++i)
_animations[i]->tick(delta);
int x;
int y;
SDL_GetRelativeMouseState(&x, &y);
camera.spherical_coord[0] -= x / 200.0f;
camera.spherical_coord[1] -= y / 200.0f;
_renderer.render(this);
}
void Graphicengine::add_animation(Animation *animation)
{
if (_animations_count >= _animations_size)
{
_animations_size <<= 1;
_animations = resize(_animations, _animations_count, _animations_size);
}
_animations[_animations_count++] = animation;
}
void Graphicengine::remove_animation(Animation *animation)
{
int index;
for (index = _animations_count - 1; index >= 0 && _animations[index] != animation; --index)
;
if (index >= 0)
_animations[index] = _animations[--_animations_count];
}
void Graphicengine::new_light(Light **link)
{
if (_lights_count >= _lights_size)
{
_lights_size <<= 1;
_lights = resize(_lights, _lights_count, _lights_size);
_lights_links = resize(_lights_links, _lights_count, _lights_size);
for (unsigned int i = 0; i < _lights_count; ++i)
*_lights_links[i] = _lights + i;
}
_lights_links[_lights_count] = link;
*link = _lights + _lights_count++;
}
void Graphicengine::delete_light(Light *light)
{
int index;
index = light - _lights;
_lights[index] = _lights[--_lights_count];
_lights_links[index] = _lights_links[_lights_count];
}
void Graphicengine::_load_materials(char const *filename)
{
Df_node const *nd = Configmanager::get_instance().get(filename);
_materials_count = nd->data_size;
_materials_size = nd->data_size;
_materials = new Material[_materials_size];
memcpy(_materials, nd->data_storage, nd->data_size);
}
<commit_msg>64bits fix<commit_after>/******************************************************************************
Copyright (c) 2015, Geoffrey TOURON
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 dusty nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
#include "new.hpp"
#include "configmanager.hpp"
#include "graphicengine.hpp"
Graphicengine::Graphicengine() : _animations_size(4096), _animations_count(0), _animations(0),
_lights_size(4096), _lights_count(0), _lights(0), _lights_links(0),
_materials_size(0), _materials_count(0), _materials(0),
_renderer(1440, 900)
{
camera.resolution[0] = 1440;
camera.resolution[1] = 900;
camera.spherical_coord[0] = -2.2f;
camera.spherical_coord[1] = -0.7f;
camera.fov = 1.9198621771f;
_animations = new Animation*[_animations_size];
_lights = new Light[_lights_size];
_lights_links = new Light**[_lights_size];
_load_materials("materials.df");
}
Graphicengine::~Graphicengine()
{
delete [] _animations;
delete [] _lights;
delete [] _lights_links;
delete [] _materials;
}
void Graphicengine::set_resolution(unsigned int const width, unsigned int const height)
{
camera.resolution[0] = width;
camera.resolution[1] = height;
_renderer.set_resolution(width, height);
}
void Graphicengine::tick(float const delta)
{
for (unsigned int i = 0; i < _animations_count; ++i)
_animations[i]->tick(delta);
int x;
int y;
SDL_GetRelativeMouseState(&x, &y);
camera.spherical_coord[0] -= x / 200.0f;
camera.spherical_coord[1] -= y / 200.0f;
_renderer.render(this);
}
void Graphicengine::add_animation(Animation *animation)
{
if (_animations_count >= _animations_size)
{
_animations_size <<= 1;
_animations = resize(_animations, _animations_count, _animations_size);
}
_animations[_animations_count++] = animation;
}
void Graphicengine::remove_animation(Animation *animation)
{
int index;
for (index = _animations_count - 1; index >= 0 && _animations[index] != animation; --index)
;
if (index >= 0)
_animations[index] = _animations[--_animations_count];
}
void Graphicengine::new_light(Light **link)
{
if (_lights_count >= _lights_size)
{
_lights_size <<= 1;
_lights = resize(_lights, _lights_count, _lights_size);
_lights_links = resize(_lights_links, _lights_count, _lights_size);
for (unsigned int i = 0; i < _lights_count; ++i)
*_lights_links[i] = _lights + i;
}
_lights_links[_lights_count] = link;
*link = _lights + _lights_count++;
}
void Graphicengine::delete_light(Light *light)
{
int index;
index = (int)(light - _lights);
_lights[index] = _lights[--_lights_count];
_lights_links[index] = _lights_links[_lights_count];
}
void Graphicengine::_load_materials(char const *filename)
{
Df_node const *nd = Configmanager::get_instance().get(filename);
_materials_count = nd->data_size;
_materials_size = nd->data_size;
_materials = new Material[_materials_size];
memcpy(_materials, nd->data_storage, nd->data_size);
}
<|endoftext|> |
<commit_before>/*
* Author: Landon Fuller <landon@landonf.org>
*
* Copyright (c) 2015 Landon Fuller <landon@landonf.org>.
* All rights reserved.
*
* 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.
*/
#pragma once
#include "PMLog.h"
#include <mach-o/loader.h>
#include <mach-o/dyld.h>
#include <assert.h>
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
#include <dlfcn.h>
#include <vector>
#include <map>
#include <string>
#include "SymbolName.hpp"
namespace patchmaster {
/* Architecture-specific Mach-O types and constants */
#ifdef __LP64__
typedef struct mach_header_64 pl_mach_header_t;
typedef struct segment_command_64 pl_segment_command_t;
typedef struct section_64 pl_section_t;
typedef struct nlist_64 pl_nlist_t;
static constexpr uint32_t PL_LC_SEGMENT = LC_SEGMENT_64;
#else
typedef struct mach_header pl_mach_header_t;
typedef struct segment_command pl_segment_command_t;
typedef struct section pl_section_t;
typedef struct nlist pl_nlist_t;
static constexpr uint32_t PL_LC_SEGMENT = LC_SEGMENT;
#endif
uint64_t read_uleb128 (const void *location, std::size_t *size);
int64_t read_sleb128 (const void *location, std::size_t *size);
/* Forward declaration */
class LocalImage;
/**
* A simple byte-based opcode stream reader.
*
* This was adapted from our DWARF opcode evaluation code in PLCrashReporter.
*/
class bind_opstream {
public:
class symbol_proc;
private:
/** Current position within the op stream */
const uint8_t *_p;
/** Starting address. */
const uint8_t *_instr;
/** Ending address. */
const uint8_t *_instr_max;
/** Current immediate value */
uint8_t _immd = 0;
/**
* If true, this is a lazy opcode section; BIND_OPCODE_DONE is automatically skipped at the end of
* each entry (the lazy section is written to terminate evaluation after each entry, as each symbol within
* the lazy section is by dyld on-demand, and is supposed to terminate after resolving one symbol).
*/
bool _isLazy;
/**
* Opcode evaluation state.
*/
struct evaluation_state {
/* dylib path from which the symbol will be resolved, or an empty string if unspecified or flat binding. */
std::string sym_image = "";
/* bind type (one of BIND_TYPE_POINTER, BIND_TYPE_TEXT_ABSOLUTE32, or BIND_TYPE_TEXT_PCREL32) */
uint8_t bind_type = BIND_TYPE_POINTER;
/* symbol name */
const char *sym_name = "";
/* symbol flags (one of BIND_SYMBOL_FLAGS_WEAK_IMPORT, BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) */
uint8_t sym_flags = 0;
/* A value to be added to the resolved symbol's address before binding. */
int64_t addend = 0;
/* The actual in-memory bind target address. */
uintptr_t bind_address = 0;
/**
* Return symbol_proc representation of the current evaluation state.
*/
symbol_proc symbol_proc () {
return symbol_proc::symbol_proc(
SymbolName(sym_image, sym_name),
bind_type,
sym_flags,
addend,
bind_address
);
}
};
/** The current evaluation state. */
evaluation_state _eval_state;
public:
bind_opstream (const uint8_t *opcodes, const size_t opcodes_len, bool isLazy) : _p(opcodes), _instr(_p), _instr_max(_p + opcodes_len), _isLazy(isLazy) {}
bind_opstream (const bind_opstream &other) : _p(other._p), _instr(other._instr), _instr_max(other._instr_max), _isLazy(other._isLazy), _eval_state(other._eval_state) {}
/**
* The parsed bind procedure for a single symbol.
*/
class symbol_proc {
public:
/**
* Construct a new symbol procedure record.
*
* @param name The two-level symbol name bound by this procedure.
* @param type The bind type for this symbol.
* @param flags The bind flags for this symbol.
* @param addend A value to be added to the resolved symbol's address before binding.
* @param bind_address The actual in-memory bind target address.
*/
symbol_proc (const SymbolName &name, uint8_t type, uint8_t flags, int64_t addend, uintptr_t bind_address) :
_name(name), _type(type), _flags(flags), _addend(addend), _bind_address(bind_address) {}
symbol_proc (SymbolName &&name, uint8_t type, uint8_t flags, int64_t addend, uintptr_t bind_address) :
_name(std::move(name)), _type(type), _flags(flags), _addend(addend), _bind_address(bind_address) {}
/** The two-level symbol name bound by this procedure. */
const SymbolName &name () const { return _name; }
/* The bind type for this symbol (one of BIND_TYPE_POINTER, BIND_TYPE_TEXT_ABSOLUTE32, or BIND_TYPE_TEXT_PCREL32) */
uint8_t type () const { return _type; }
/* The bind flags for this symbol (one of BIND_SYMBOL_FLAGS_WEAK_IMPORT, BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) */
uint8_t flags () const { return _flags; }
/* A value to be added to the resolved symbol's address before binding. */
int64_t addend () const { return _addend; }
/* The actual in-memory bind target address. */
uintptr_t bind_address () const { return _bind_address; }
private:
/** The two-level symbol name bound by this procedure. */
SymbolName _name;
/* The bind type for this symbol (one of BIND_TYPE_POINTER, BIND_TYPE_TEXT_ABSOLUTE32, or BIND_TYPE_TEXT_PCREL32) */
uint8_t _type;
/* The bind flags for this symbol (one of BIND_SYMBOL_FLAGS_WEAK_IMPORT, BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) */
uint8_t _flags = 0;
/* A value to be added to the resolved symbol's address before binding. */
int64_t _addend = 0;
/* The actual in-memory bind target address. */
uintptr_t _bind_address = 0;
};
void evaluate (const LocalImage &image, const std::function<void(const symbol_proc &)> &bind);
uint8_t step (const LocalImage &image, const std::function<void(const symbol_proc &)> &bind);
/** Read a ULEB128 value and advance the stream */
inline uint64_t uleb128 () {
size_t len;
uint64_t result = read_uleb128(_p, &len);
_p += len;
assert(_p <= _instr_max);
return result;
}
/** Read a SLEB128 value and advance the stream */
inline int64_t sleb128 () {
size_t len;
int64_t result = read_sleb128(_p, &len);
_p += len;
assert(_p <= _instr_max);
return result;
}
/** Skip @a offset bytes. */
inline void skip (size_t offset) {
_p += offset;
assert(_p <= _instr_max);
}
/** Read a single opcode from the stream. */
inline uint8_t opcode () {
assert(_p < _instr_max);
uint8_t op = (*_p) & BIND_OPCODE_MASK;
_immd = (*_p) & BIND_IMMEDIATE_MASK;
_p++;
/* Skip BIND_OPCODE_DONE if it occurs within a lazy binding opcode stream */
if (_isLazy && op == BIND_OPCODE_DONE && !isEmpty())
skip(1);
return op;
};
/** Return the current stream position. */
inline const uint8_t *position () { return _p; };
/** Return true if there are no additional opcodes to be read. */
inline bool isEmpty () { return _p >= _instr_max; }
/** Return true if this is a lazy opcode stream. */
inline bool isLazy () { return _isLazy; }
/** Read a NUL-terminated C string from the stream, advancing the current position past the string. */
inline const char *cstring () {
const char *result = (const char *) _p;
skip(strlen(result) + 1);
return result;
}
/** Return the immediate value from the last opcode */
inline uint8_t immd () { return _immd; }
/** Return the signed representation of immd */
inline int8_t signed_immd () {
/* All other constants are negative */
if (immd() == 0)
return 0;
/* Sign-extend the immediate value */
return (~BIND_IMMEDIATE_MASK) | (immd() & BIND_IMMEDIATE_MASK);
}
};
/**
* An in-memory Mach-O image.
*/
class LocalImage {
private:
friend class bind_opstream;
/**
* Construct a new local image.
*/
LocalImage (
const std::string &path,
const pl_mach_header_t *header,
const intptr_t vmaddr_slide,
std::shared_ptr<std::vector<const std::string>> &libraries,
std::shared_ptr<std::vector<const pl_segment_command_t *>> &segments,
std::shared_ptr<std::vector<const bind_opstream>> &bindings
) : _header(header), _vmaddr_slide(vmaddr_slide), _libraries(libraries), _segments(segments), _bindOpcodes(bindings), _path(path) {}
public:
static const std::string &MainExecutablePath ();
static LocalImage Analyze (const std::string &path, const pl_mach_header_t *header);
void rebind_symbols (const std::function<void(const bind_opstream::symbol_proc &)> &bind);
/**
* Return a borrowed reference to the image's path.
*/
const std::string &path () const { return _path; }
/**
* Return the image's vm_slide.
*/
intptr_t vmaddr_slide () const { return _vmaddr_slide; }
/**
* Return the image's symbol binding opcode streams.
*/
std::shared_ptr<std::vector<const bind_opstream>> bindOpcodes () const { return _bindOpcodes; }
/**
* Return the image's defined segments.
*/
std::shared_ptr<std::vector<const pl_segment_command_t *>> segments () const { return _segments; }
private:
/** Mach-O image header */
const pl_mach_header_t *_header;
/** Offset applied when the image was loaded; required to compute in-memory addresses from on-disk VM addresses.. */
const intptr_t _vmaddr_slide;
/** Linked libraries, indexed by reference order. */
std::shared_ptr<std::vector<const std::string>> _libraries;
/** Segment commands, indexed by declaration order. */
std::shared_ptr<std::vector<const pl_segment_command_t *>> _segments;
/** All symbol binding opcodes. */
std::shared_ptr<std::vector<const bind_opstream>> _bindOpcodes;
/** Image path */
const std::string _path;
};
} /* namespace patchmaster */<commit_msg>Revert "Fix a off-by-one bug in BIND_OPCODE_DONE handling."<commit_after>/*
* Author: Landon Fuller <landon@landonf.org>
*
* Copyright (c) 2015 Landon Fuller <landon@landonf.org>.
* All rights reserved.
*
* 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.
*/
#pragma once
#include "PMLog.h"
#include <mach-o/loader.h>
#include <mach-o/dyld.h>
#include <assert.h>
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
#include <dlfcn.h>
#include <vector>
#include <map>
#include <string>
#include "SymbolName.hpp"
namespace patchmaster {
/* Architecture-specific Mach-O types and constants */
#ifdef __LP64__
typedef struct mach_header_64 pl_mach_header_t;
typedef struct segment_command_64 pl_segment_command_t;
typedef struct section_64 pl_section_t;
typedef struct nlist_64 pl_nlist_t;
static constexpr uint32_t PL_LC_SEGMENT = LC_SEGMENT_64;
#else
typedef struct mach_header pl_mach_header_t;
typedef struct segment_command pl_segment_command_t;
typedef struct section pl_section_t;
typedef struct nlist pl_nlist_t;
static constexpr uint32_t PL_LC_SEGMENT = LC_SEGMENT;
#endif
uint64_t read_uleb128 (const void *location, std::size_t *size);
int64_t read_sleb128 (const void *location, std::size_t *size);
/* Forward declaration */
class LocalImage;
/**
* A simple byte-based opcode stream reader.
*
* This was adapted from our DWARF opcode evaluation code in PLCrashReporter.
*/
class bind_opstream {
public:
class symbol_proc;
private:
/** Current position within the op stream */
const uint8_t *_p;
/** Starting address. */
const uint8_t *_instr;
/** Ending address. */
const uint8_t *_instr_max;
/** Current immediate value */
uint8_t _immd = 0;
/**
* If true, this is a lazy opcode section; BIND_OPCODE_DONE is automatically skipped at the end of
* each entry (the lazy section is written to terminate evaluation after each entry, as each symbol within
* the lazy section is by dyld on-demand, and is supposed to terminate after resolving one symbol).
*/
bool _isLazy;
/**
* Opcode evaluation state.
*/
struct evaluation_state {
/* dylib path from which the symbol will be resolved, or an empty string if unspecified or flat binding. */
std::string sym_image = "";
/* bind type (one of BIND_TYPE_POINTER, BIND_TYPE_TEXT_ABSOLUTE32, or BIND_TYPE_TEXT_PCREL32) */
uint8_t bind_type = BIND_TYPE_POINTER;
/* symbol name */
const char *sym_name = "";
/* symbol flags (one of BIND_SYMBOL_FLAGS_WEAK_IMPORT, BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) */
uint8_t sym_flags = 0;
/* A value to be added to the resolved symbol's address before binding. */
int64_t addend = 0;
/* The actual in-memory bind target address. */
uintptr_t bind_address = 0;
/**
* Return symbol_proc representation of the current evaluation state.
*/
symbol_proc symbol_proc () {
return symbol_proc::symbol_proc(
SymbolName(sym_image, sym_name),
bind_type,
sym_flags,
addend,
bind_address
);
}
};
/** The current evaluation state. */
evaluation_state _eval_state;
public:
bind_opstream (const uint8_t *opcodes, const size_t opcodes_len, bool isLazy) : _p(opcodes), _instr(_p), _instr_max(_p + opcodes_len), _isLazy(isLazy) {}
bind_opstream (const bind_opstream &other) : _p(other._p), _instr(other._instr), _instr_max(other._instr_max), _isLazy(other._isLazy), _eval_state(other._eval_state) {}
/**
* The parsed bind procedure for a single symbol.
*/
class symbol_proc {
public:
/**
* Construct a new symbol procedure record.
*
* @param name The two-level symbol name bound by this procedure.
* @param type The bind type for this symbol.
* @param flags The bind flags for this symbol.
* @param addend A value to be added to the resolved symbol's address before binding.
* @param bind_address The actual in-memory bind target address.
*/
symbol_proc (const SymbolName &name, uint8_t type, uint8_t flags, int64_t addend, uintptr_t bind_address) :
_name(name), _type(type), _flags(flags), _addend(addend), _bind_address(bind_address) {}
symbol_proc (SymbolName &&name, uint8_t type, uint8_t flags, int64_t addend, uintptr_t bind_address) :
_name(std::move(name)), _type(type), _flags(flags), _addend(addend), _bind_address(bind_address) {}
/** The two-level symbol name bound by this procedure. */
const SymbolName &name () const { return _name; }
/* The bind type for this symbol (one of BIND_TYPE_POINTER, BIND_TYPE_TEXT_ABSOLUTE32, or BIND_TYPE_TEXT_PCREL32) */
uint8_t type () const { return _type; }
/* The bind flags for this symbol (one of BIND_SYMBOL_FLAGS_WEAK_IMPORT, BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) */
uint8_t flags () const { return _flags; }
/* A value to be added to the resolved symbol's address before binding. */
int64_t addend () const { return _addend; }
/* The actual in-memory bind target address. */
uintptr_t bind_address () const { return _bind_address; }
private:
/** The two-level symbol name bound by this procedure. */
SymbolName _name;
/* The bind type for this symbol (one of BIND_TYPE_POINTER, BIND_TYPE_TEXT_ABSOLUTE32, or BIND_TYPE_TEXT_PCREL32) */
uint8_t _type;
/* The bind flags for this symbol (one of BIND_SYMBOL_FLAGS_WEAK_IMPORT, BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) */
uint8_t _flags = 0;
/* A value to be added to the resolved symbol's address before binding. */
int64_t _addend = 0;
/* The actual in-memory bind target address. */
uintptr_t _bind_address = 0;
};
void evaluate (const LocalImage &image, const std::function<void(const symbol_proc &)> &bind);
uint8_t step (const LocalImage &image, const std::function<void(const symbol_proc &)> &bind);
/** Read a ULEB128 value and advance the stream */
inline uint64_t uleb128 () {
size_t len;
uint64_t result = read_uleb128(_p, &len);
_p += len;
assert(_p <= _instr_max);
return result;
}
/** Read a SLEB128 value and advance the stream */
inline int64_t sleb128 () {
size_t len;
int64_t result = read_sleb128(_p, &len);
_p += len;
assert(_p <= _instr_max);
return result;
}
/** Skip @a offset bytes. */
inline void skip (size_t offset) {
_p += offset;
assert(_p <= _instr_max);
}
/** Read a single opcode from the stream. */
inline uint8_t opcode () {
assert(_p < _instr_max);
uint8_t value = (*_p) & BIND_OPCODE_MASK;
_immd = (*_p) & BIND_IMMEDIATE_MASK;
_p++;
/* Skip BIND_OPCODE_DONE if it occurs within a lazy binding opcode stream */
if (_isLazy && *_p == BIND_OPCODE_DONE && !isEmpty())
skip(1);
return value;
};
/** Return the current stream position. */
inline const uint8_t *position () { return _p; };
/** Return true if there are no additional opcodes to be read. */
inline bool isEmpty () { return _p >= _instr_max; }
/** Return true if this is a lazy opcode stream. */
inline bool isLazy () { return _isLazy; }
/** Read a NUL-terminated C string from the stream, advancing the current position past the string. */
inline const char *cstring () {
const char *result = (const char *) _p;
skip(strlen(result) + 1);
return result;
}
/** Return the immediate value from the last opcode */
inline uint8_t immd () { return _immd; }
/** Return the signed representation of immd */
inline int8_t signed_immd () {
/* All other constants are negative */
if (immd() == 0)
return 0;
/* Sign-extend the immediate value */
return (~BIND_IMMEDIATE_MASK) | (immd() & BIND_IMMEDIATE_MASK);
}
};
/**
* An in-memory Mach-O image.
*/
class LocalImage {
private:
friend class bind_opstream;
/**
* Construct a new local image.
*/
LocalImage (
const std::string &path,
const pl_mach_header_t *header,
const intptr_t vmaddr_slide,
std::shared_ptr<std::vector<const std::string>> &libraries,
std::shared_ptr<std::vector<const pl_segment_command_t *>> &segments,
std::shared_ptr<std::vector<const bind_opstream>> &bindings
) : _header(header), _vmaddr_slide(vmaddr_slide), _libraries(libraries), _segments(segments), _bindOpcodes(bindings), _path(path) {}
public:
static const std::string &MainExecutablePath ();
static LocalImage Analyze (const std::string &path, const pl_mach_header_t *header);
void rebind_symbols (const std::function<void(const bind_opstream::symbol_proc &)> &bind);
/**
* Return a borrowed reference to the image's path.
*/
const std::string &path () const { return _path; }
/**
* Return the image's vm_slide.
*/
intptr_t vmaddr_slide () const { return _vmaddr_slide; }
/**
* Return the image's symbol binding opcode streams.
*/
std::shared_ptr<std::vector<const bind_opstream>> bindOpcodes () const { return _bindOpcodes; }
/**
* Return the image's defined segments.
*/
std::shared_ptr<std::vector<const pl_segment_command_t *>> segments () const { return _segments; }
private:
/** Mach-O image header */
const pl_mach_header_t *_header;
/** Offset applied when the image was loaded; required to compute in-memory addresses from on-disk VM addresses.. */
const intptr_t _vmaddr_slide;
/** Linked libraries, indexed by reference order. */
std::shared_ptr<std::vector<const std::string>> _libraries;
/** Segment commands, indexed by declaration order. */
std::shared_ptr<std::vector<const pl_segment_command_t *>> _segments;
/** All symbol binding opcodes. */
std::shared_ptr<std::vector<const bind_opstream>> _bindOpcodes;
/** Image path */
const std::string _path;
};
} /* namespace patchmaster */<|endoftext|> |
<commit_before>/*****************************************************************************
* MindTheGap: Integrated detection and assembly of insertion variants
* A tool from the GATB (Genome Assembly Tool Box)
* Copyright (C) 2014 INRIA
* Authors: C.Lemaitre, G.Rizk
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*****************************************************************************/
#ifndef _TOOL_Filler_HPP_
#define _TOOL_Filler_HPP_
/********************************************************************************/
#include <gatb/gatb_core.hpp>
#include <GraphOutputDot.hpp>
#include <Utils.hpp>
using namespace std;
/********************************************************************************/
static const char* STR_URI_CONTIG = "-contig";
static const char* STR_CONTIG_OVERLAP = "-overlap";
static const char* STR_URI_BKPT = "-bkpt";
static const char* STR_MAX_DEPTH = "-max-length";
static const char* STR_MAX_NODES = "-max-nodes";
class info_node_t
{
public:
int node_id;
int pos; // pos of beginning of right anchor
int nb_errors;
//bool anchor_is_repeated;
bkpt_t targetId;
//required to be inserted in std::set
bool operator< (const info_node_t & other) const
{
return ( (node_id < other.node_id) || ((node_id == other.node_id) && (pos < other.pos)) );
}
bool operator> (const info_node_t & other) const
{
return ( (node_id > other.node_id) || ((node_id == other.node_id) && (pos > other.pos)) );
}
//required to be used in unordered_map
bool operator==(const info_node_t & other) const
{
return(node_id == other.node_id
&& pos == other.pos
&& nb_errors == other.nb_errors
&& targetId == other.targetId);
}
};
struct nodeHasher
{
std::size_t operator()(const info_node_t& k) const
{
using std::size_t;
using std::hash;
using std::string;
return ((std::hash<int>()(k.node_id)
^ (hash<int>()(k.pos) << 1)) >> 1)
^ (hash<int>()(k.nb_errors) << 1);
}
};
class Filler : public Tool
{
public:
// Constructor
Filler ();
void FillerHelp();
const char* _mtg_version;
size_t _kmerSize;
Graph _graph;
int _nbCores;
BankFasta* _breakpointBank;
bool _breakpointMode; //true if insertion breakpoints, false if gap-filling between contigs
//to print some statistics at the end
int _nb_breakpoints; //nb seeds in contig mode
int _nb_filled_breakpoints;
int _nb_multiple_fill;
int _nb_contigs;
int _nb_used_contigs;
//useful to compute average abundance of each filled sequence
Storage* _storage;
//output file with filled sequences
string _insert_file_name;
FILE * _insert_file;
//output file in GFA format (fot -contig)
string _gfa_file_name;
FILE * _gfa_file;
//output file with statistics about each attempt of gap-filling
string _insert_info_file_name;
FILE * _insert_info_file;
//parameters for dbg traversal (stop criteria)
int _max_depth;
int _max_nodes;
//parameters for looking for the target sequence in the contig graph, with some mismatches and/or gaps
int _nb_mis_allowed;
int _nb_gap_allowed;
//parameter for gap-filling between contigs
int _contig_trim_size;
string _vcf_file_name;
FILE * _vcf_file;
// Actual job done by the tool is here
void execute ();
//these two func moved to public because need access from functors breakpointFunctor and contigFunctor
/** writes a given breakpoint in the output file
*/
void writeFilledBreakpoint(std::vector<filled_insertion_t>& filledSequences, string breakpointName, std::string infostring);
void writeToGFA(std::vector<filled_insertion_t>& filledSequences, string sourceSequence, string SeedName, bool isRc);
/** writes a given variant in the output vcf file
*/
void writeVcf(std::vector<filled_insertion_t>& filledSequences, string breakpointName, string seedk);
/** Fill one gap
*/
/*template<size_t span>
void gapFill(std::string & infostring,int tid,string sourceSequence, string targetSequence, set<filled_insertion_t>& filledSequences, bool begin_kmer_repeated, bool end_kmer_repeated
,bool reversed =false);*/
template<size_t span>
void gapFillFromSource(std::string & infostring, int tid, string sourceSequence, string targetSequence, std::vector<filled_insertion_t>& filledSequences, bkpt_dict_t targetDictionary,bool is_anchor_repeated, bool reverse );
gatb::core::tools::dp::IteratorListener* _progress;
private:
/** fills getInfo() with parameters informations
*/
void resumeParameters();
/** fills getInfo() with results informations
*/
void resumeResults(double seconds);
/** Main function to fill the gaps of all breakpoints
*/
template<size_t span>
struct fillBreakpoints { void operator () (Filler* object); };
template<size_t span>
struct fillContig { void operator () (Filler* object); };
template<size_t span>
struct fillAny { void operator () (Filler* object); };
/** writes the header of the vcf file
*/
void writeVcfHeader();
/**
* returns the nodes containing the targetSequence (can be an approximate match)
*/
set< info_node_t > find_nodes_containing_R(string targetSequence, string linear_seqs_name, int nb_mis_allowed, int nb_gaps_allowed, bool anchor_is_repeated);
set< info_node_t> find_nodes_containing_multiple_R(bkpt_dict_t targetDictionary, string linear_seqs_name, int nb_mis_allowed, int nb_gaps_allowed);
/** Handle on the progress information. */
void setProgress (gatb::core::tools::dp::IteratorListener* progress) { SP_SETATTR(progress); }
//tiens, on a pas encore de destructeur pour cette classe?
};
/********************************************************************************/
#endif /* _TOOL_Filler_HPP_ */
<commit_msg>follow-up preceding commit : adding a novel parameter to filter out low quality insertions (multiple sequences)<commit_after>/*****************************************************************************
* MindTheGap: Integrated detection and assembly of insertion variants
* A tool from the GATB (Genome Assembly Tool Box)
* Copyright (C) 2014 INRIA
* Authors: C.Lemaitre, G.Rizk
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*****************************************************************************/
#ifndef _TOOL_Filler_HPP_
#define _TOOL_Filler_HPP_
/********************************************************************************/
#include <gatb/gatb_core.hpp>
#include <GraphOutputDot.hpp>
#include <Utils.hpp>
using namespace std;
/********************************************************************************/
static const char* STR_URI_CONTIG = "-contig";
static const char* STR_CONTIG_OVERLAP = "-overlap";
static const char* STR_URI_BKPT = "-bkpt";
static const char* STR_MAX_DEPTH = "-max-length";
static const char* STR_MAX_NODES = "-max-nodes";
static const char* STR_FILTER = "-filter";
class info_node_t
{
public:
int node_id;
int pos; // pos of beginning of right anchor
int nb_errors;
//bool anchor_is_repeated;
bkpt_t targetId;
//required to be inserted in std::set
bool operator< (const info_node_t & other) const
{
return ( (node_id < other.node_id) || ((node_id == other.node_id) && (pos < other.pos)) );
}
bool operator> (const info_node_t & other) const
{
return ( (node_id > other.node_id) || ((node_id == other.node_id) && (pos > other.pos)) );
}
//required to be used in unordered_map
bool operator==(const info_node_t & other) const
{
return(node_id == other.node_id
&& pos == other.pos
&& nb_errors == other.nb_errors
&& targetId == other.targetId);
}
};
struct nodeHasher
{
std::size_t operator()(const info_node_t& k) const
{
using std::size_t;
using std::hash;
using std::string;
return ((std::hash<int>()(k.node_id)
^ (hash<int>()(k.pos) << 1)) >> 1)
^ (hash<int>()(k.nb_errors) << 1);
}
};
class Filler : public Tool
{
public:
// Constructor
Filler ();
void FillerHelp();
const char* _mtg_version;
size_t _kmerSize;
Graph _graph;
int _nbCores;
BankFasta* _breakpointBank;
bool _breakpointMode; //true if insertion breakpoints, false if gap-filling between contigs
//to print some statistics at the end
int _nb_breakpoints; //nb seeds in contig mode
int _nb_filled_breakpoints;
int _nb_multiple_fill;
int _nb_contigs;
int _nb_used_contigs;
//useful to compute average abundance of each filled sequence
Storage* _storage;
//output file with filled sequences
string _insert_file_name;
FILE * _insert_file;
//output file in GFA format (fot -contig)
string _gfa_file_name;
FILE * _gfa_file;
//output file with statistics about each attempt of gap-filling
string _insert_info_file_name;
FILE * _insert_info_file;
//parameters for dbg traversal (stop criteria)
int _max_depth;
int _max_nodes;
//parameters for looking for the target sequence in the contig graph, with some mismatches and/or gaps
int _nb_mis_allowed;
int _nb_gap_allowed;
//parameter for gap-filling between contigs
int _contig_trim_size;
//parameter for filtering out low quality insertions
bool _filter;
string _vcf_file_name;
FILE * _vcf_file;
// Actual job done by the tool is here
void execute ();
//these two func moved to public because need access from functors breakpointFunctor and contigFunctor
/** writes a given breakpoint in the output file
*/
void writeFilledBreakpoint(std::vector<filled_insertion_t>& filledSequences, string breakpointName, std::string infostring);
void writeToGFA(std::vector<filled_insertion_t>& filledSequences, string sourceSequence, string SeedName, bool isRc);
/** writes a given variant in the output vcf file
*/
void writeVcf(std::vector<filled_insertion_t>& filledSequences, string breakpointName, string seedk);
/** Fill one gap
*/
/*template<size_t span>
void gapFill(std::string & infostring,int tid,string sourceSequence, string targetSequence, set<filled_insertion_t>& filledSequences, bool begin_kmer_repeated, bool end_kmer_repeated
,bool reversed =false);*/
template<size_t span>
void gapFillFromSource(std::string & infostring, int tid, string sourceSequence, string targetSequence, std::vector<filled_insertion_t>& filledSequences, bkpt_dict_t targetDictionary,bool is_anchor_repeated, bool reverse );
gatb::core::tools::dp::IteratorListener* _progress;
private:
/** fills getInfo() with parameters informations
*/
void resumeParameters();
/** fills getInfo() with results informations
*/
void resumeResults(double seconds);
/** Main function to fill the gaps of all breakpoints
*/
template<size_t span>
struct fillBreakpoints { void operator () (Filler* object); };
template<size_t span>
struct fillContig { void operator () (Filler* object); };
template<size_t span>
struct fillAny { void operator () (Filler* object); };
/** writes the header of the vcf file
*/
void writeVcfHeader();
/**
* returns the nodes containing the targetSequence (can be an approximate match)
*/
set< info_node_t > find_nodes_containing_R(string targetSequence, string linear_seqs_name, int nb_mis_allowed, int nb_gaps_allowed, bool anchor_is_repeated);
set< info_node_t> find_nodes_containing_multiple_R(bkpt_dict_t targetDictionary, string linear_seqs_name, int nb_mis_allowed, int nb_gaps_allowed);
/** Handle on the progress information. */
void setProgress (gatb::core::tools::dp::IteratorListener* progress) { SP_SETATTR(progress); }
//tiens, on a pas encore de destructeur pour cette classe?
};
/********************************************************************************/
#endif /* _TOOL_Filler_HPP_ */
<|endoftext|> |
<commit_before>/*
Copyright (c) 2009 Volker Krause <vkrause@kde.org>
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at your
option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public
License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
*/
#include "itemretrievalmanager.h"
#include "itemretrievalrequest.h"
#include "itemretrievaljob.h"
#include "resourceinterface.h"
#include "akdebug.h"
#include <QCoreApplication>
#include <QReadWriteLock>
#include <QWaitCondition>
#include <QDBusConnection>
#include <QDBusConnectionInterface>
using namespace Akonadi;
ItemRetrievalManager* ItemRetrievalManager::sInstance = 0;
ItemRetrievalManager::ItemRetrievalManager( QObject *parent ) :
QObject( parent ),
mDBusConnection(
QDBusConnection::connectToBus(
QDBusConnection::SessionBus,
QString::fromLatin1("AkonadiServerItemRetrievalManager") ) )
{
// make sure we are created from the retrieval thread and only once
Q_ASSERT( QThread::currentThread() != QCoreApplication::instance()->thread() );
Q_ASSERT( sInstance == 0 );
sInstance = this;
mLock = new QReadWriteLock();
mWaitCondition = new QWaitCondition();
connect( mDBusConnection.interface(), SIGNAL(serviceOwnerChanged(QString,QString,QString)),
this, SLOT(serviceOwnerChanged(QString,QString,QString)) );
connect( this, SIGNAL(requestAdded()), this, SLOT(processRequest()), Qt::QueuedConnection );
}
ItemRetrievalManager::~ItemRetrievalManager()
{
delete mWaitCondition;
delete mLock;
}
ItemRetrievalManager* ItemRetrievalManager::instance()
{
Q_ASSERT( sInstance );
return sInstance;
}
// called within the retrieval thread
void ItemRetrievalManager::serviceOwnerChanged(const QString& serviceName, const QString& oldOwner, const QString& newOwner)
{
Q_UNUSED( newOwner );
if ( oldOwner.isEmpty() )
return;
if ( !serviceName.startsWith( QLatin1String("org.freedesktop.Akonadi.Resource.") ) )
return;
const QString resourceId = serviceName.mid( 33 );
qDebug() << "Lost connection to resource" << serviceName << ", discarding cached interface";
mResourceInterfaces.remove( resourceId );
}
// called within the retrieval thread
OrgFreedesktopAkonadiResourceInterface* ItemRetrievalManager::resourceInterface(const QString& id)
{
if ( id.isEmpty() )
return 0;
OrgFreedesktopAkonadiResourceInterface *iface = 0;
if ( mResourceInterfaces.contains( id ) )
iface = mResourceInterfaces.value( id );
if ( iface && iface->isValid() )
return iface;
delete iface;
iface = new OrgFreedesktopAkonadiResourceInterface( QLatin1String("org.freedesktop.Akonadi.Resource.") + id,
QLatin1String("/"), mDBusConnection, this );
if ( !iface || !iface->isValid() ) {
qDebug() << QString::fromLatin1( "Cannot connect to agent instance with identifier '%1', error message: '%2'" )
.arg( id, iface ? iface->lastError().message() : QString() );
delete iface;
return 0;
}
mResourceInterfaces.insert( id, iface );
return iface;
}
// called from any thread
void ItemRetrievalManager::requestItemDelivery( qint64 uid, const QByteArray& remoteId, const QByteArray& mimeType,
const QString& resource, const QStringList& parts )
{
ItemRetrievalRequest *req = new ItemRetrievalRequest();
req->id = uid;
req->remoteId = remoteId;
req->mimeType = mimeType;
req->resourceId = resource;
req->parts = parts;
requestItemDelivery( req );
}
void ItemRetrievalManager::requestItemDelivery( ItemRetrievalRequest *req )
{
mLock->lockForWrite();
qDebug() << "posting retrieval request for item" << req->id << " there are " << mPendingRequests.size() << " queues and " << mPendingRequests[ req->resourceId ].size() << " items in mine";
mPendingRequests[ req->resourceId ].append( req );
mLock->unlock();
emit requestAdded();
mLock->lockForRead();
forever {
qDebug() << "checking if request for item" << req->id << "has been processed...";
if ( req->processed ) {
Q_ASSERT( !mPendingRequests[ req->resourceId ].contains( req ) );
const QString errorMsg = req->errorMsg;
mLock->unlock();
qDebug() << "request for item" << req->id << "processed, error:" << errorMsg;
delete req;
if ( errorMsg.isEmpty() )
return;
else
throw ItemRetrieverException( errorMsg );
} else {
qDebug() << "request for item" << req->id << "still pending - waiting";
mWaitCondition->wait( mLock );
qDebug() << "continuing";
}
}
throw ItemRetrieverException( "WTF?" );
}
// called within the retrieval thread
void ItemRetrievalManager::processRequest()
{
QVector<QPair<ItemRetrievalJob*, QString> > newJobs;
mLock->lockForWrite();
// look for idle resources
for ( QHash< QString, QList< ItemRetrievalRequest* > >::iterator it = mPendingRequests.begin(); it != mPendingRequests.end(); ) {
if ( it.value().isEmpty() ) {
it = mPendingRequests.erase( it );
continue;
}
if ( !mCurrentJobs.contains( it.key() ) || mCurrentJobs.value( it.key() ) == 0 ) {
// TODO: check if there is another one for the same uid with more parts requested
ItemRetrievalRequest* req = it.value().takeFirst();
Q_ASSERT( req->resourceId == it.key() );
ItemRetrievalJob *job = new ItemRetrievalJob( req, this );
connect( job, SIGNAL(requestCompleted(ItemRetrievalRequest*,QString)), SLOT(retrievalJobFinished(ItemRetrievalRequest*,QString)) );
mCurrentJobs.insert( req->resourceId, job );
// delay job execution until after we unlocked the mutex, since the job can emit the finished signal immediately in some cases
newJobs.append( qMakePair( job, req->resourceId ) );
}
++it;
}
bool nothingGoingOn = mPendingRequests.isEmpty() && mCurrentJobs.isEmpty() && newJobs.isEmpty();
mLock->unlock();
if ( nothingGoingOn ) { // someone asked as to process requests although everything is done already, he might still be waiting
mWaitCondition->wakeAll();
return;
}
for ( QVector< QPair< ItemRetrievalJob*, QString > >::const_iterator it = newJobs.constBegin(); it != newJobs.constEnd(); ++it )
(*it).first->start( resourceInterface( (*it).second ) );
}
void ItemRetrievalManager::retrievalJobFinished(ItemRetrievalRequest* request, const QString& errorMsg)
{
mLock->lockForWrite();
request->errorMsg = errorMsg;
request->processed = true;
Q_ASSERT( mCurrentJobs.contains( request->resourceId ) );
mCurrentJobs.remove( request->resourceId );
// TODO check if (*it)->parts is a subset of currentRequest->parts
for ( QList<ItemRetrievalRequest*>::Iterator it = mPendingRequests[ request->resourceId ].begin(); it != mPendingRequests[ request->resourceId ].end(); ) {
if ( (*it)->id == request->id ) {
qDebug() << "someone else requested item" << request->id << "as well, marking as processed";
(*it)->errorMsg = errorMsg;
(*it)->processed = true;
it = mPendingRequests[ request->resourceId ].erase( it );
} else {
++it;
}
}
mWaitCondition->wakeAll();
mLock->unlock();
emit requestAdded(); // trigger processRequest() again, in case there is more in the queues
}
void ItemRetrievalManager::triggerCollectionSync(const QString& resource, qint64 colId)
{
OrgFreedesktopAkonadiResourceInterface *interface = resourceInterface( resource );
if ( interface )
interface->synchronizeCollection( colId );
}
void ItemRetrievalManager::triggerCollectionTreeSync( const QString& resource )
{
OrgFreedesktopAkonadiResourceInterface *interface = resourceInterface( resource );
if ( interface )
interface->synchronizeCollectionTree();
}
#include "itemretrievalmanager.moc"
<commit_msg>I'm not the only one who gets confused with "request for item processed, error:" when there's no error -> clarify the debug output.<commit_after>/*
Copyright (c) 2009 Volker Krause <vkrause@kde.org>
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at your
option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public
License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
*/
#include "itemretrievalmanager.h"
#include "itemretrievalrequest.h"
#include "itemretrievaljob.h"
#include "resourceinterface.h"
#include "akdebug.h"
#include <QCoreApplication>
#include <QReadWriteLock>
#include <QWaitCondition>
#include <QDBusConnection>
#include <QDBusConnectionInterface>
using namespace Akonadi;
ItemRetrievalManager* ItemRetrievalManager::sInstance = 0;
ItemRetrievalManager::ItemRetrievalManager( QObject *parent ) :
QObject( parent ),
mDBusConnection(
QDBusConnection::connectToBus(
QDBusConnection::SessionBus,
QString::fromLatin1("AkonadiServerItemRetrievalManager") ) )
{
// make sure we are created from the retrieval thread and only once
Q_ASSERT( QThread::currentThread() != QCoreApplication::instance()->thread() );
Q_ASSERT( sInstance == 0 );
sInstance = this;
mLock = new QReadWriteLock();
mWaitCondition = new QWaitCondition();
connect( mDBusConnection.interface(), SIGNAL(serviceOwnerChanged(QString,QString,QString)),
this, SLOT(serviceOwnerChanged(QString,QString,QString)) );
connect( this, SIGNAL(requestAdded()), this, SLOT(processRequest()), Qt::QueuedConnection );
}
ItemRetrievalManager::~ItemRetrievalManager()
{
delete mWaitCondition;
delete mLock;
}
ItemRetrievalManager* ItemRetrievalManager::instance()
{
Q_ASSERT( sInstance );
return sInstance;
}
// called within the retrieval thread
void ItemRetrievalManager::serviceOwnerChanged(const QString& serviceName, const QString& oldOwner, const QString& newOwner)
{
Q_UNUSED( newOwner );
if ( oldOwner.isEmpty() )
return;
if ( !serviceName.startsWith( QLatin1String("org.freedesktop.Akonadi.Resource.") ) )
return;
const QString resourceId = serviceName.mid( 33 );
qDebug() << "Lost connection to resource" << serviceName << ", discarding cached interface";
mResourceInterfaces.remove( resourceId );
}
// called within the retrieval thread
OrgFreedesktopAkonadiResourceInterface* ItemRetrievalManager::resourceInterface(const QString& id)
{
if ( id.isEmpty() )
return 0;
OrgFreedesktopAkonadiResourceInterface *iface = mResourceInterfaces.value( id );
if ( iface && iface->isValid() )
return iface;
delete iface;
iface = new OrgFreedesktopAkonadiResourceInterface( QLatin1String("org.freedesktop.Akonadi.Resource.") + id,
QLatin1String("/"), mDBusConnection, this );
if ( !iface || !iface->isValid() ) {
qDebug() << QString::fromLatin1( "Cannot connect to agent instance with identifier '%1', error message: '%2'" )
.arg( id, iface ? iface->lastError().message() : QString() );
delete iface;
return 0;
}
mResourceInterfaces.insert( id, iface );
return iface;
}
// called from any thread
void ItemRetrievalManager::requestItemDelivery( qint64 uid, const QByteArray& remoteId, const QByteArray& mimeType,
const QString& resource, const QStringList& parts )
{
ItemRetrievalRequest *req = new ItemRetrievalRequest();
req->id = uid;
req->remoteId = remoteId;
req->mimeType = mimeType;
req->resourceId = resource;
req->parts = parts;
requestItemDelivery( req );
}
void ItemRetrievalManager::requestItemDelivery( ItemRetrievalRequest *req )
{
mLock->lockForWrite();
qDebug() << "posting retrieval request for item" << req->id << " there are " << mPendingRequests.size() << " queues and " << mPendingRequests[ req->resourceId ].size() << " items in mine";
mPendingRequests[ req->resourceId ].append( req );
mLock->unlock();
emit requestAdded();
mLock->lockForRead();
forever {
//qDebug() << "checking if request for item" << req->id << "has been processed...";
if ( req->processed ) {
Q_ASSERT( !mPendingRequests[ req->resourceId ].contains( req ) );
const QString errorMsg = req->errorMsg;
mLock->unlock();
delete req;
if ( errorMsg.isEmpty() ) {
qDebug() << "request for item" << req->id << "succeeded";
return;
} else {
qDebug() << "request for item" << req->id << req->remoteId << "failed:" << errorMsg;
throw ItemRetrieverException( errorMsg );
}
} else {
qDebug() << "request for item" << req->id << "still pending - waiting";
mWaitCondition->wait( mLock );
qDebug() << "continuing";
}
}
throw ItemRetrieverException( "WTF?" );
}
// called within the retrieval thread
void ItemRetrievalManager::processRequest()
{
QVector<QPair<ItemRetrievalJob*, QString> > newJobs;
mLock->lockForWrite();
// look for idle resources
for ( QHash< QString, QList< ItemRetrievalRequest* > >::iterator it = mPendingRequests.begin(); it != mPendingRequests.end(); ) {
if ( it.value().isEmpty() ) {
it = mPendingRequests.erase( it );
continue;
}
if ( !mCurrentJobs.contains( it.key() ) || mCurrentJobs.value( it.key() ) == 0 ) {
// TODO: check if there is another one for the same uid with more parts requested
ItemRetrievalRequest* req = it.value().takeFirst();
Q_ASSERT( req->resourceId == it.key() );
ItemRetrievalJob *job = new ItemRetrievalJob( req, this );
connect( job, SIGNAL(requestCompleted(ItemRetrievalRequest*,QString)), SLOT(retrievalJobFinished(ItemRetrievalRequest*,QString)) );
mCurrentJobs.insert( req->resourceId, job );
// delay job execution until after we unlocked the mutex, since the job can emit the finished signal immediately in some cases
newJobs.append( qMakePair( job, req->resourceId ) );
}
++it;
}
bool nothingGoingOn = mPendingRequests.isEmpty() && mCurrentJobs.isEmpty() && newJobs.isEmpty();
mLock->unlock();
if ( nothingGoingOn ) { // someone asked as to process requests although everything is done already, he might still be waiting
mWaitCondition->wakeAll();
return;
}
for ( QVector< QPair< ItemRetrievalJob*, QString > >::const_iterator it = newJobs.constBegin(); it != newJobs.constEnd(); ++it )
(*it).first->start( resourceInterface( (*it).second ) );
}
void ItemRetrievalManager::retrievalJobFinished(ItemRetrievalRequest* request, const QString& errorMsg)
{
mLock->lockForWrite();
request->errorMsg = errorMsg;
request->processed = true;
Q_ASSERT( mCurrentJobs.contains( request->resourceId ) );
mCurrentJobs.remove( request->resourceId );
// TODO check if (*it)->parts is a subset of currentRequest->parts
for ( QList<ItemRetrievalRequest*>::Iterator it = mPendingRequests[ request->resourceId ].begin(); it != mPendingRequests[ request->resourceId ].end(); ) {
if ( (*it)->id == request->id ) {
qDebug() << "someone else requested item" << request->id << "as well, marking as processed";
(*it)->errorMsg = errorMsg;
(*it)->processed = true;
it = mPendingRequests[ request->resourceId ].erase( it );
} else {
++it;
}
}
mWaitCondition->wakeAll();
mLock->unlock();
emit requestAdded(); // trigger processRequest() again, in case there is more in the queues
}
void ItemRetrievalManager::triggerCollectionSync(const QString& resource, qint64 colId)
{
OrgFreedesktopAkonadiResourceInterface *interface = resourceInterface( resource );
if ( interface )
interface->synchronizeCollection( colId );
}
void ItemRetrievalManager::triggerCollectionTreeSync( const QString& resource )
{
OrgFreedesktopAkonadiResourceInterface *interface = resourceInterface( resource );
if ( interface )
interface->synchronizeCollectionTree();
}
#include "itemretrievalmanager.moc"
<|endoftext|> |
<commit_before>/**
* @file HoughCircle_Demo.cpp
* @brief Demo code for Hough Transform
* @author OpenCV team
*/
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
using namespace cv;
namespace
{
// windows and trackbars name
const std::string windowName = "Hough Circle Detection Demo";
const std::string cannyThresholdTrackbarName = "Canny threshold";
const std::string accumulatorThresholdTrackbarName = "Accumulator Threshold";
// initial and max values of the parameters of interests.
const int cannyThresholdInitialValue = 200;
const int accumulatorThresholdInitialValue = 50;
const int maxAccumulatorThreshold = 200;
const int maxCannyThreshold = 255;
void HoughDetection(const Mat& src_gray, const Mat& src_display, int cannyThreshold, int accumulatorThreshold)
{
// will hold the results of the detection
std::vector<Vec3f> circles;
// runs the actual detection
HoughCircles( src_gray, circles, HOUGH_GRADIENT, 1, src_gray.rows/8, cannyThreshold, accumulatorThreshold, 0, 0 );
// clone the colour, input image for displaying purposes
Mat display = src_display.clone();
for( size_t i = 0; i < circles.size(); i++ )
{
Point center(cvRound(circles[i][0]), cvRound(circles[i][1]));
int radius = cvRound(circles[i][2]);
// circle center
circle( display, center, 3, Scalar(0,255,0), -1, 8, 0 );
// circle outline
circle( display, center, radius, Scalar(0,0,255), 3, 8, 0 );
}
// shows the results
imshow( windowName, display);
}
}
int main(int, char** argv)
{
Mat src, src_gray;
// Read the image
src = imread( argv[1], 1 );
if( !src.data )
{
std::cerr<<"Invalid input image\n";
std::cout<<"Usage : tutorial_HoughCircle_Demo <path_to_input_image>\n";
return -1;
}
// Convert it to gray
cvtColor( src, src_gray, COLOR_BGR2GRAY );
// Reduce the noise so we avoid false circle detection
GaussianBlur( src_gray, src_gray, Size(9, 9), 2, 2 );
//declare and initialize both parameters that are subjects to change
int cannyThreshold = cannyThresholdInitialValue;
int accumulatorThreshold = accumulatorThresholdInitialValue;
// create the main window, and attach the trackbars
namedWindow( windowName, WINDOW_AUTOSIZE );
createTrackbar(cannyThresholdTrackbarName, windowName, &cannyThreshold,maxCannyThreshold);
createTrackbar(accumulatorThresholdTrackbarName, windowName, &accumulatorThreshold, maxAccumulatorThreshold);
// inifinite loop to display
// and refresh the content of the output image
// unti the user presses q or Q
int key = 0;
while(key != 'q' && key != 'Q')
{
// those paramaters cannot be =0
// so we must check here
cannyThreshold = std::max(cannyThreshold, 1);
accumulatorThreshold = std::max(accumulatorThreshold, 1);
//runs the detection, and update the display
HoughDetection(src_gray, src, cannyThreshold, accumulatorThreshold);
// get user key
key = waitKey(10);
}
return 0;
}
<commit_msg>fix typos<commit_after>/**
* @file HoughCircle_Demo.cpp
* @brief Demo code for Hough Transform
* @author OpenCV team
*/
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
using namespace cv;
namespace
{
// windows and trackbars name
const std::string windowName = "Hough Circle Detection Demo";
const std::string cannyThresholdTrackbarName = "Canny threshold";
const std::string accumulatorThresholdTrackbarName = "Accumulator Threshold";
// initial and max values of the parameters of interests.
const int cannyThresholdInitialValue = 200;
const int accumulatorThresholdInitialValue = 50;
const int maxAccumulatorThreshold = 200;
const int maxCannyThreshold = 255;
void HoughDetection(const Mat& src_gray, const Mat& src_display, int cannyThreshold, int accumulatorThreshold)
{
// will hold the results of the detection
std::vector<Vec3f> circles;
// runs the actual detection
HoughCircles( src_gray, circles, HOUGH_GRADIENT, 1, src_gray.rows/8, cannyThreshold, accumulatorThreshold, 0, 0 );
// clone the colour, input image for displaying purposes
Mat display = src_display.clone();
for( size_t i = 0; i < circles.size(); i++ )
{
Point center(cvRound(circles[i][0]), cvRound(circles[i][1]));
int radius = cvRound(circles[i][2]);
// circle center
circle( display, center, 3, Scalar(0,255,0), -1, 8, 0 );
// circle outline
circle( display, center, radius, Scalar(0,0,255), 3, 8, 0 );
}
// shows the results
imshow( windowName, display);
}
}
int main(int, char** argv)
{
Mat src, src_gray;
// Read the image
src = imread( argv[1], 1 );
if( !src.data )
{
std::cerr<<"Invalid input image\n";
std::cout<<"Usage : tutorial_HoughCircle_Demo <path_to_input_image>\n";
return -1;
}
// Convert it to gray
cvtColor( src, src_gray, COLOR_BGR2GRAY );
// Reduce the noise so we avoid false circle detection
GaussianBlur( src_gray, src_gray, Size(9, 9), 2, 2 );
//declare and initialize both parameters that are subjects to change
int cannyThreshold = cannyThresholdInitialValue;
int accumulatorThreshold = accumulatorThresholdInitialValue;
// create the main window, and attach the trackbars
namedWindow( windowName, WINDOW_AUTOSIZE );
createTrackbar(cannyThresholdTrackbarName, windowName, &cannyThreshold,maxCannyThreshold);
createTrackbar(accumulatorThresholdTrackbarName, windowName, &accumulatorThreshold, maxAccumulatorThreshold);
// infinite loop to display
// and refresh the content of the output image
// until the user presses q or Q
int key = 0;
while(key != 'q' && key != 'Q')
{
// those paramaters cannot be =0
// so we must check here
cannyThreshold = std::max(cannyThreshold, 1);
accumulatorThreshold = std::max(accumulatorThreshold, 1);
//runs the detection, and update the display
HoughDetection(src_gray, src, cannyThreshold, accumulatorThreshold);
// get user key
key = waitKey(10);
}
return 0;
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.