text
stringlengths
54
60.6k
<commit_before>/**************************************************************************** ** ** Copyright (C) 2012 Denis Shienkov <denis.shienkov@gmail.com> ** Copyright (C) 2012 Laszlo Papp <lpapp@kde.org> ** Contact: http://www.qt-project.org/legal ** ** This file is part of the QtSerialPort module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "console.h" #include <QScrollBar> #include <QtCore/QDebug> Console::Console(QWidget *parent) : QPlainTextEdit(parent) , localEchoEnabled(false) { document()->setMaximumBlockCount(100); QPalette p = palette(); p.setColor(QPalette::Base, Qt::black); p.setColor(QPalette::Text, Qt::green); setPalette(p); } void Console::putData(const QByteArray &data) { insertPlainText(QString(data)); QScrollBar *bar = verticalScrollBar(); bar->setValue(bar->maximum()); } void Console::setLocalEchoEnabled(bool set) { localEchoEnabled = set; } void Console::keyPressEvent(QKeyEvent *e) { switch (e->key()) { case Qt::Key_Backspace: case Qt::Key_Left: case Qt::Key_Right: case Qt::Key_Up: case Qt::Key_Down: // skip processing break; default: if (localEchoEnabled) QPlainTextEdit::keyPressEvent(e); emit getData(e->text().toLocal8Bit()); } } void Console::mousePressEvent(QMouseEvent *e) { Q_UNUSED(e) setFocus(); } void Console::mouseDoubleClickEvent(QMouseEvent *e) { Q_UNUSED(e) } void Console::contextMenuEvent(QContextMenuEvent *e) { Q_UNUSED(e) } <commit_msg>force terminal font to be fixed<commit_after>/**************************************************************************** ** ** Copyright (C) 2012 Denis Shienkov <denis.shienkov@gmail.com> ** Copyright (C) 2012 Laszlo Papp <lpapp@kde.org> ** Contact: http://www.qt-project.org/legal ** ** This file is part of the QtSerialPort module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "console.h" #include <QScrollBar> #include <QtCore/QDebug> Console::Console(QWidget *parent) : QPlainTextEdit(parent) , localEchoEnabled(false) { document()->setMaximumBlockCount(100); QPalette p = palette(); p.setColor(QPalette::Base, Qt::black); p.setColor(QPalette::Text, Qt::green); setPalette(p); setFont(QFont("Courier", 15)); } void Console::putData(const QByteArray &data) { insertPlainText(QString(data)); QScrollBar *bar = verticalScrollBar(); bar->setValue(bar->maximum()); } void Console::setLocalEchoEnabled(bool set) { localEchoEnabled = set; } void Console::keyPressEvent(QKeyEvent *e) { switch (e->key()) { case Qt::Key_Backspace: case Qt::Key_Left: case Qt::Key_Right: case Qt::Key_Up: case Qt::Key_Down: // skip processing break; default: if (localEchoEnabled) QPlainTextEdit::keyPressEvent(e); emit getData(e->text().toLocal8Bit()); } } void Console::mousePressEvent(QMouseEvent *e) { Q_UNUSED(e) setFocus(); } void Console::mouseDoubleClickEvent(QMouseEvent *e) { Q_UNUSED(e) } void Console::contextMenuEvent(QContextMenuEvent *e) { Q_UNUSED(e) } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: outdev5.cxx,v $ * * $Revision: 1.9 $ * * last change: $Author: obo $ $Date: 2006-09-17 12:07:28 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_vcl.hxx" #include <tools/ref.hxx> #ifndef _SV_SVSYS_HXX #include <svsys.h> #endif #ifndef _SV_SALGDI_HXX #include <salgdi.hxx> #endif #ifndef _DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef _SV_SVDATA_HXX #include <svdata.hxx> #endif #ifndef _TL_POLY_HXX #include <tools/poly.hxx> #endif #ifndef _SV_METAACT_HXX #include <metaact.hxx> #endif #ifndef _SV_GDIMTF_HXX #include <gdimtf.hxx> #endif #ifndef _SV_OUTDATA_HXX #include <outdata.hxx> #endif #ifndef _SV_OUTDEV_H #include <outdev.h> #endif #ifndef _SV_OUTDEV_HXX #include <outdev.hxx> #endif #ifndef _SV_VIRDEV_HXX #include <virdev.hxx> #endif // ======================================================================= DBG_NAMEEX( OutputDevice ) // ======================================================================= void OutputDevice::DrawRect( const Rectangle& rRect, ULONG nHorzRound, ULONG nVertRound ) { DBG_TRACE( "OutputDevice::DrawRoundRect()" ); DBG_CHKTHIS( OutputDevice, ImplDbgCheckOutputDevice ); if ( mpMetaFile ) mpMetaFile->AddAction( new MetaRoundRectAction( rRect, nHorzRound, nVertRound ) ); if ( !IsDeviceOutputNecessary() || (!mbLineColor && !mbFillColor) || ImplIsRecordLayout() ) return; const Rectangle aRect( ImplLogicToDevicePixel( rRect ) ); if ( aRect.IsEmpty() ) return; nHorzRound = ImplLogicWidthToDevicePixel( nHorzRound ); nVertRound = ImplLogicHeightToDevicePixel( nVertRound ); // we need a graphics if ( !mpGraphics ) { if ( !ImplGetGraphics() ) return; } if ( mbInitClipRegion ) ImplInitClipRegion(); if ( mbOutputClipped ) return; if ( mbInitLineColor ) ImplInitLineColor(); if ( mbInitFillColor ) ImplInitFillColor(); if ( !nHorzRound && !nVertRound ) mpGraphics->DrawRect( aRect.Left(), aRect.Top(), aRect.GetWidth(), aRect.GetHeight(), this ); else { const Polygon aRoundRectPoly( aRect, nHorzRound, nVertRound ); if ( aRoundRectPoly.GetSize() >= 2 ) { const SalPoint* pPtAry = (const SalPoint*) aRoundRectPoly.GetConstPointAry(); if ( !mbFillColor ) mpGraphics->DrawPolyLine( aRoundRectPoly.GetSize(), pPtAry, this ); else mpGraphics->DrawPolygon( aRoundRectPoly.GetSize(), pPtAry, this ); } } if( mpAlphaVDev ) mpAlphaVDev->DrawRect( rRect, nHorzRound, nVertRound ); } // ----------------------------------------------------------------------- void OutputDevice::DrawEllipse( const Rectangle& rRect ) { DBG_TRACE( "OutputDevice::DrawEllipse()" ); DBG_CHKTHIS( OutputDevice, ImplDbgCheckOutputDevice ); if ( mpMetaFile ) mpMetaFile->AddAction( new MetaEllipseAction( rRect ) ); if ( !IsDeviceOutputNecessary() || (!mbLineColor && !mbFillColor) || ImplIsRecordLayout() ) return; Rectangle aRect( ImplLogicToDevicePixel( rRect ) ); if ( aRect.IsEmpty() ) return; // we need a graphics if ( !mpGraphics ) { if ( !ImplGetGraphics() ) return; } if ( mbInitClipRegion ) ImplInitClipRegion(); if ( mbOutputClipped ) return; if ( mbInitLineColor ) ImplInitLineColor(); Polygon aRectPoly( aRect.Center(), aRect.GetWidth() >> 1, aRect.GetHeight() >> 1 ); if ( aRectPoly.GetSize() >= 2 ) { const SalPoint* pPtAry = (const SalPoint*)aRectPoly.GetConstPointAry(); if ( !mbFillColor ) mpGraphics->DrawPolyLine( aRectPoly.GetSize(), pPtAry, this ); else { if ( mbInitFillColor ) ImplInitFillColor(); mpGraphics->DrawPolygon( aRectPoly.GetSize(), pPtAry, this ); } } if( mpAlphaVDev ) mpAlphaVDev->DrawEllipse( rRect ); } // ----------------------------------------------------------------------- void OutputDevice::DrawArc( const Rectangle& rRect, const Point& rStartPt, const Point& rEndPt ) { DBG_TRACE( "OutputDevice::DrawArc()" ); DBG_CHKTHIS( OutputDevice, ImplDbgCheckOutputDevice ); if ( mpMetaFile ) mpMetaFile->AddAction( new MetaArcAction( rRect, rStartPt, rEndPt ) ); if ( !IsDeviceOutputNecessary() || !mbLineColor || ImplIsRecordLayout() ) return; Rectangle aRect( ImplLogicToDevicePixel( rRect ) ); if ( aRect.IsEmpty() ) return; // we need a graphics if ( !mpGraphics ) { if ( !ImplGetGraphics() ) return; } if ( mbInitClipRegion ) ImplInitClipRegion(); if ( mbOutputClipped ) return; if ( mbInitLineColor ) ImplInitLineColor(); const Point aStart( ImplLogicToDevicePixel( rStartPt ) ); const Point aEnd( ImplLogicToDevicePixel( rEndPt ) ); Polygon aArcPoly( aRect, aStart, aEnd, POLY_ARC ); if ( aArcPoly.GetSize() >= 2 ) { const SalPoint* pPtAry = (const SalPoint*)aArcPoly.GetConstPointAry(); mpGraphics->DrawPolyLine( aArcPoly.GetSize(), pPtAry, this ); } if( mpAlphaVDev ) mpAlphaVDev->DrawArc( rRect, rStartPt, rEndPt ); } // ----------------------------------------------------------------------- void OutputDevice::DrawPie( const Rectangle& rRect, const Point& rStartPt, const Point& rEndPt ) { DBG_TRACE( "OutputDevice::DrawPie()" ); DBG_CHKTHIS( OutputDevice, ImplDbgCheckOutputDevice ); if ( mpMetaFile ) mpMetaFile->AddAction( new MetaPieAction( rRect, rStartPt, rEndPt ) ); if ( !IsDeviceOutputNecessary() || (!mbLineColor && !mbFillColor) || ImplIsRecordLayout() ) return; Rectangle aRect( ImplLogicToDevicePixel( rRect ) ); if ( aRect.IsEmpty() ) return; // we need a graphics if ( !mpGraphics ) { if ( !ImplGetGraphics() ) return; } if ( mbInitClipRegion ) ImplInitClipRegion(); if ( mbOutputClipped ) return; if ( mbInitLineColor ) ImplInitLineColor(); const Point aStart( ImplLogicToDevicePixel( rStartPt ) ); const Point aEnd( ImplLogicToDevicePixel( rEndPt ) ); Polygon aPiePoly( aRect, aStart, aEnd, POLY_PIE ); if ( aPiePoly.GetSize() >= 2 ) { const SalPoint* pPtAry = (const SalPoint*)aPiePoly.GetConstPointAry(); if ( !mbFillColor ) mpGraphics->DrawPolyLine( aPiePoly.GetSize(), pPtAry, this ); else { if ( mbInitFillColor ) ImplInitFillColor(); mpGraphics->DrawPolygon( aPiePoly.GetSize(), pPtAry, this ); } } if( mpAlphaVDev ) mpAlphaVDev->DrawPie( rRect, rStartPt, rEndPt ); } // ----------------------------------------------------------------------- void OutputDevice::DrawChord( const Rectangle& rRect, const Point& rStartPt, const Point& rEndPt ) { DBG_TRACE( "OutputDevice::DrawChord()" ); DBG_CHKTHIS( OutputDevice, ImplDbgCheckOutputDevice ); if ( mpMetaFile ) mpMetaFile->AddAction( new MetaChordAction( rRect, rStartPt, rEndPt ) ); if ( !IsDeviceOutputNecessary() || (!mbLineColor && !mbFillColor) || ImplIsRecordLayout() ) return; Rectangle aRect( ImplLogicToDevicePixel( rRect ) ); if ( aRect.IsEmpty() ) return; // we need a graphics if ( !mpGraphics ) { if ( !ImplGetGraphics() ) return; } if ( mbInitClipRegion ) ImplInitClipRegion(); if ( mbOutputClipped ) return; if ( mbInitLineColor ) ImplInitLineColor(); const Point aStart( ImplLogicToDevicePixel( rStartPt ) ); const Point aEnd( ImplLogicToDevicePixel( rEndPt ) ); Polygon aChordPoly( aRect, aStart, aEnd, POLY_CHORD ); if ( aChordPoly.GetSize() >= 2 ) { const SalPoint* pPtAry = (const SalPoint*)aChordPoly.GetConstPointAry(); if ( !mbFillColor ) mpGraphics->DrawPolyLine( aChordPoly.GetSize(), pPtAry, this ); else { if ( mbInitFillColor ) ImplInitFillColor(); mpGraphics->DrawPolygon( aChordPoly.GetSize(), pPtAry, this ); } } if( mpAlphaVDev ) mpAlphaVDev->DrawChord( rRect, rStartPt, rEndPt ); } <commit_msg>INTEGRATION: CWS vgbugs07 (1.9.240); FILE MERGED 2007/06/04 13:29:37 vg 1.9.240.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: outdev5.cxx,v $ * * $Revision: 1.10 $ * * last change: $Author: hr $ $Date: 2007-06-27 20:19:52 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_vcl.hxx" #include <tools/ref.hxx> #ifndef _SV_SVSYS_HXX #include <svsys.h> #endif #ifndef _SV_SALGDI_HXX #include <vcl/salgdi.hxx> #endif #ifndef _DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef _SV_SVDATA_HXX #include <vcl/svdata.hxx> #endif #ifndef _TL_POLY_HXX #include <tools/poly.hxx> #endif #ifndef _SV_METAACT_HXX #include <vcl/metaact.hxx> #endif #ifndef _SV_GDIMTF_HXX #include <vcl/gdimtf.hxx> #endif #ifndef _SV_OUTDATA_HXX #include <outdata.hxx> #endif #ifndef _SV_OUTDEV_H #include <outdev.h> #endif #ifndef _SV_OUTDEV_HXX #include <vcl/outdev.hxx> #endif #ifndef _SV_VIRDEV_HXX #include <vcl/virdev.hxx> #endif // ======================================================================= DBG_NAMEEX( OutputDevice ) // ======================================================================= void OutputDevice::DrawRect( const Rectangle& rRect, ULONG nHorzRound, ULONG nVertRound ) { DBG_TRACE( "OutputDevice::DrawRoundRect()" ); DBG_CHKTHIS( OutputDevice, ImplDbgCheckOutputDevice ); if ( mpMetaFile ) mpMetaFile->AddAction( new MetaRoundRectAction( rRect, nHorzRound, nVertRound ) ); if ( !IsDeviceOutputNecessary() || (!mbLineColor && !mbFillColor) || ImplIsRecordLayout() ) return; const Rectangle aRect( ImplLogicToDevicePixel( rRect ) ); if ( aRect.IsEmpty() ) return; nHorzRound = ImplLogicWidthToDevicePixel( nHorzRound ); nVertRound = ImplLogicHeightToDevicePixel( nVertRound ); // we need a graphics if ( !mpGraphics ) { if ( !ImplGetGraphics() ) return; } if ( mbInitClipRegion ) ImplInitClipRegion(); if ( mbOutputClipped ) return; if ( mbInitLineColor ) ImplInitLineColor(); if ( mbInitFillColor ) ImplInitFillColor(); if ( !nHorzRound && !nVertRound ) mpGraphics->DrawRect( aRect.Left(), aRect.Top(), aRect.GetWidth(), aRect.GetHeight(), this ); else { const Polygon aRoundRectPoly( aRect, nHorzRound, nVertRound ); if ( aRoundRectPoly.GetSize() >= 2 ) { const SalPoint* pPtAry = (const SalPoint*) aRoundRectPoly.GetConstPointAry(); if ( !mbFillColor ) mpGraphics->DrawPolyLine( aRoundRectPoly.GetSize(), pPtAry, this ); else mpGraphics->DrawPolygon( aRoundRectPoly.GetSize(), pPtAry, this ); } } if( mpAlphaVDev ) mpAlphaVDev->DrawRect( rRect, nHorzRound, nVertRound ); } // ----------------------------------------------------------------------- void OutputDevice::DrawEllipse( const Rectangle& rRect ) { DBG_TRACE( "OutputDevice::DrawEllipse()" ); DBG_CHKTHIS( OutputDevice, ImplDbgCheckOutputDevice ); if ( mpMetaFile ) mpMetaFile->AddAction( new MetaEllipseAction( rRect ) ); if ( !IsDeviceOutputNecessary() || (!mbLineColor && !mbFillColor) || ImplIsRecordLayout() ) return; Rectangle aRect( ImplLogicToDevicePixel( rRect ) ); if ( aRect.IsEmpty() ) return; // we need a graphics if ( !mpGraphics ) { if ( !ImplGetGraphics() ) return; } if ( mbInitClipRegion ) ImplInitClipRegion(); if ( mbOutputClipped ) return; if ( mbInitLineColor ) ImplInitLineColor(); Polygon aRectPoly( aRect.Center(), aRect.GetWidth() >> 1, aRect.GetHeight() >> 1 ); if ( aRectPoly.GetSize() >= 2 ) { const SalPoint* pPtAry = (const SalPoint*)aRectPoly.GetConstPointAry(); if ( !mbFillColor ) mpGraphics->DrawPolyLine( aRectPoly.GetSize(), pPtAry, this ); else { if ( mbInitFillColor ) ImplInitFillColor(); mpGraphics->DrawPolygon( aRectPoly.GetSize(), pPtAry, this ); } } if( mpAlphaVDev ) mpAlphaVDev->DrawEllipse( rRect ); } // ----------------------------------------------------------------------- void OutputDevice::DrawArc( const Rectangle& rRect, const Point& rStartPt, const Point& rEndPt ) { DBG_TRACE( "OutputDevice::DrawArc()" ); DBG_CHKTHIS( OutputDevice, ImplDbgCheckOutputDevice ); if ( mpMetaFile ) mpMetaFile->AddAction( new MetaArcAction( rRect, rStartPt, rEndPt ) ); if ( !IsDeviceOutputNecessary() || !mbLineColor || ImplIsRecordLayout() ) return; Rectangle aRect( ImplLogicToDevicePixel( rRect ) ); if ( aRect.IsEmpty() ) return; // we need a graphics if ( !mpGraphics ) { if ( !ImplGetGraphics() ) return; } if ( mbInitClipRegion ) ImplInitClipRegion(); if ( mbOutputClipped ) return; if ( mbInitLineColor ) ImplInitLineColor(); const Point aStart( ImplLogicToDevicePixel( rStartPt ) ); const Point aEnd( ImplLogicToDevicePixel( rEndPt ) ); Polygon aArcPoly( aRect, aStart, aEnd, POLY_ARC ); if ( aArcPoly.GetSize() >= 2 ) { const SalPoint* pPtAry = (const SalPoint*)aArcPoly.GetConstPointAry(); mpGraphics->DrawPolyLine( aArcPoly.GetSize(), pPtAry, this ); } if( mpAlphaVDev ) mpAlphaVDev->DrawArc( rRect, rStartPt, rEndPt ); } // ----------------------------------------------------------------------- void OutputDevice::DrawPie( const Rectangle& rRect, const Point& rStartPt, const Point& rEndPt ) { DBG_TRACE( "OutputDevice::DrawPie()" ); DBG_CHKTHIS( OutputDevice, ImplDbgCheckOutputDevice ); if ( mpMetaFile ) mpMetaFile->AddAction( new MetaPieAction( rRect, rStartPt, rEndPt ) ); if ( !IsDeviceOutputNecessary() || (!mbLineColor && !mbFillColor) || ImplIsRecordLayout() ) return; Rectangle aRect( ImplLogicToDevicePixel( rRect ) ); if ( aRect.IsEmpty() ) return; // we need a graphics if ( !mpGraphics ) { if ( !ImplGetGraphics() ) return; } if ( mbInitClipRegion ) ImplInitClipRegion(); if ( mbOutputClipped ) return; if ( mbInitLineColor ) ImplInitLineColor(); const Point aStart( ImplLogicToDevicePixel( rStartPt ) ); const Point aEnd( ImplLogicToDevicePixel( rEndPt ) ); Polygon aPiePoly( aRect, aStart, aEnd, POLY_PIE ); if ( aPiePoly.GetSize() >= 2 ) { const SalPoint* pPtAry = (const SalPoint*)aPiePoly.GetConstPointAry(); if ( !mbFillColor ) mpGraphics->DrawPolyLine( aPiePoly.GetSize(), pPtAry, this ); else { if ( mbInitFillColor ) ImplInitFillColor(); mpGraphics->DrawPolygon( aPiePoly.GetSize(), pPtAry, this ); } } if( mpAlphaVDev ) mpAlphaVDev->DrawPie( rRect, rStartPt, rEndPt ); } // ----------------------------------------------------------------------- void OutputDevice::DrawChord( const Rectangle& rRect, const Point& rStartPt, const Point& rEndPt ) { DBG_TRACE( "OutputDevice::DrawChord()" ); DBG_CHKTHIS( OutputDevice, ImplDbgCheckOutputDevice ); if ( mpMetaFile ) mpMetaFile->AddAction( new MetaChordAction( rRect, rStartPt, rEndPt ) ); if ( !IsDeviceOutputNecessary() || (!mbLineColor && !mbFillColor) || ImplIsRecordLayout() ) return; Rectangle aRect( ImplLogicToDevicePixel( rRect ) ); if ( aRect.IsEmpty() ) return; // we need a graphics if ( !mpGraphics ) { if ( !ImplGetGraphics() ) return; } if ( mbInitClipRegion ) ImplInitClipRegion(); if ( mbOutputClipped ) return; if ( mbInitLineColor ) ImplInitLineColor(); const Point aStart( ImplLogicToDevicePixel( rStartPt ) ); const Point aEnd( ImplLogicToDevicePixel( rEndPt ) ); Polygon aChordPoly( aRect, aStart, aEnd, POLY_CHORD ); if ( aChordPoly.GetSize() >= 2 ) { const SalPoint* pPtAry = (const SalPoint*)aChordPoly.GetConstPointAry(); if ( !mbFillColor ) mpGraphics->DrawPolyLine( aChordPoly.GetSize(), pPtAry, this ); else { if ( mbInitFillColor ) ImplInitFillColor(); mpGraphics->DrawPolygon( aChordPoly.GetSize(), pPtAry, this ); } } if( mpAlphaVDev ) mpAlphaVDev->DrawChord( rRect, rStartPt, rEndPt ); } <|endoftext|>
<commit_before>/* Copyright 2008 Brain Research Institute, Melbourne, Australia Written by J-Donald Tournier, 27/06/08. This file is part of MRtrix. MRtrix is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. MRtrix is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with MRtrix. If not, see <http://www.gnu.org/licenses/>. */ #include "file/config.h" #include "file/ofstream.h" #include "file/path.h" #include "file/utils.h" #include "file/mmap.h" #include "image/utils.h" #include "image/format/list.h" #include "image/header.h" #include "image/handler/default.h" #include "get_set.h" /* MRI format: Magic number: MRI# (4 bytes) Byte order specifier: uint16_t = 1 (2 bytes) ... Elements: ID specifier: uint32_t (4 bytes) size: uint32_t (4 bytes) contents: unspecified ('size' bytes) ... */ #define MRI_DATA 0x01 #define MRI_DIMENSIONS 0x02 #define MRI_ORDER 0x03 #define MRI_VOXELSIZE 0x04 #define MRI_COMMENT 0x05 #define MRI_TRANSFORM 0x06 #define MRI_DWSCHEME 0x07 namespace MR { namespace Image { namespace Format { namespace { inline size_t char2order (char item, bool& forward) { switch (item) { case 'L': forward = true; return (0); case 'R': forward = false; return (0); case 'P': forward = true; return (1); case 'A': forward = false; return (1); case 'I': forward = true; return (2); case 'S': forward = false; return (2); case 'B': forward = true; return (3); case 'E': forward = false; return (3); } return (std::numeric_limits<size_t>::max()); } inline char order2char (size_t axis, bool forward) { switch (axis) { case 0: if (forward) return ('L'); else return ('R'); case 1: if (forward) return ('P'); else return ('A'); case 2: if (forward) return ('I'); else return ('S'); case 3: if (forward) return ('B'); else return ('E'); } return ('\0'); } inline size_t type (const uint8_t* pos, bool is_BE) { return (get<uint32_t> (pos, is_BE)); } inline size_t size (const uint8_t* pos, bool is_BE) { return (get<uint32_t> (pos + sizeof (uint32_t), is_BE)); } inline const uint8_t* data (const uint8_t* pos) { return (pos + 2*sizeof (uint32_t)); } inline const uint8_t* next (const uint8_t* current_pos, bool is_BE) { return (current_pos + 2*sizeof (uint32_t) + size (current_pos, is_BE)); } inline void write_tag (std::ostream& out, uint32_t Type, uint32_t Size, bool is_BE) { Type = ByteOrder::swap<uint32_t> (Type, is_BE); out.write ( (const char*) &Type, sizeof (uint32_t)); Size = ByteOrder::swap<uint32_t> (Size, is_BE); out.write ( (const char*) &Size, sizeof (uint32_t)); } template <typename T> inline void write (std::ostream& out, T val, bool is_BE) { val = ByteOrder::swap<T> (val, is_BE); out.write ( (const char*) &val, sizeof (T)); } } std::shared_ptr<Handler::Base> MRI::read (Header& H) const { if (!Path::has_suffix (H.name(), ".mri")) return std::shared_ptr<Handler::Base>(); File::MMap fmap (H.name()); if (memcmp (fmap.address(), "MRI#", 4)) throw Exception ("file \"" + H.name() + "\" is not in MRI format (unrecognised magic number)"); bool is_BE = false; if (get<uint16_t> (fmap.address() + sizeof (int32_t), is_BE) == 0x0100U) is_BE = true; else if (get<uint16_t> (fmap.address() + sizeof (uint32_t), is_BE) != 0x0001U) throw Exception ("MRI file \"" + H.name() + "\" is badly formed (invalid byte order specifier)"); H.set_ndim (4); size_t data_offset = 0; char* c; const uint8_t* current = fmap.address() + sizeof (int32_t) + sizeof (uint16_t); const uint8_t* last = fmap.address() + fmap.size() - 2*sizeof (uint32_t); while (current <= last) { switch (type (current, is_BE)) { case MRI_DATA: H.datatype() = (reinterpret_cast<const char*> (data (current))) [-4]; data_offset = current + 5 - (uint8_t*) fmap.address(); break; case MRI_DIMENSIONS: H.dim(0) = get<uint32_t> (data (current), is_BE); H.dim(1) = get<uint32_t> (data (current) + sizeof (uint32_t), is_BE); H.dim(2) = get<uint32_t> (data (current) + 2*sizeof (uint32_t), is_BE); H.dim(3) = get<uint32_t> (data (current) + 3*sizeof (uint32_t), is_BE); break; case MRI_ORDER: c = (char*) data (current); for (size_t n = 0; n < 4; n++) { bool forward = true; size_t ax = char2order (c[n], forward); if (ax == std::numeric_limits<size_t>::max()) throw Exception ("invalid order specifier in MRI image \"" + H.name() + "\""); H.stride(ax) = n+1; if (!forward) H.stride(ax) = -H.stride (ax); } break; case MRI_VOXELSIZE: H.vox(0) = get<float32> (data (current), is_BE); H.vox(1) = get<float32> (data (current) + sizeof (float32), is_BE); H.vox(2) = get<float32> (data (current) + 2*sizeof (float32), is_BE); break; case MRI_COMMENT: H.comments().push_back (std::string (reinterpret_cast<const char*> (data (current)), size (current, is_BE))); break; case MRI_TRANSFORM: H.transform().allocate (4,4); for (size_t i = 0; i < 4; ++i) for (size_t j = 0; j < 4; ++j) H.transform() (i,j) = get<float32> (data (current) + (i*4 + j) *sizeof (float32), is_BE); break; case MRI_DWSCHEME: H.DW_scheme().allocate (size (current, is_BE) / (4*sizeof (float32)), 4); for (size_t i = 0; i < H.DW_scheme().rows(); ++i) for (size_t j = 0; j < 4; ++j) H.DW_scheme() (i,j) = get<float32> (data (current) + (i*4 + j) *sizeof (float32), is_BE); break; default: WARN ("unknown header entity (" + str (type (current, is_BE)) + ", offset " + str (current - fmap.address()) + ") in image \"" + H.name() + "\" - ignored"); break; } if (data_offset) break; current = next (current, is_BE); } if (!data_offset) throw Exception ("no data field found in MRI image \"" + H.name() + "\""); std::shared_ptr<Handler::Base> handler (new Handler::Default (H)); handler->files.push_back (File::Entry (H.name(), data_offset)); return handler; } bool MRI::check (Header& H, size_t num_axes) const { if (!Path::has_suffix (H.name(), ".mri")) return false; if (H.ndim() > num_axes && num_axes != 4) throw Exception ("MRTools format can only support 4 dimensions"); H.set_ndim (num_axes); return true; } std::shared_ptr<Handler::Base> MRI::create (Header& H) const { File::OFStream out (H.name()); #ifdef MRTRIX_BYTE_ORDER_BIG_ENDIAN bool is_BE = true; #else bool is_BE = false; #endif out.write ("MRI#", 4); write<uint16_t> (out, 0x01U, is_BE); write_tag (out, MRI_DIMENSIONS, 4*sizeof (uint32_t), is_BE); write<uint32_t> (out, H.dim (0), is_BE); write<uint32_t> (out, (H.ndim() > 1 ? H.dim (1) : 1), is_BE); write<uint32_t> (out, (H.ndim() > 2 ? H.dim (2) : 1), is_BE); write<uint32_t> (out, (H.ndim() > 3 ? H.dim (3) : 1), is_BE); write_tag (out, MRI_ORDER, 4*sizeof (uint8_t), is_BE); size_t n; char order[4]; for (n = 0; n < H.ndim(); ++n) order[std::abs (H.stride (n))-1] = order2char (n, H.stride (n) >0); for (; n < 4; ++n) order[n] = order2char (n, true); out.write (order, 4); write_tag (out, MRI_VOXELSIZE, 3*sizeof (float32), is_BE); write<float> (out, H.vox (0), is_BE); write<float> (out, (H.ndim() > 1 ? H.vox (1) : 2.0f), is_BE); write<float> (out, (H.ndim() > 2 ? H.vox (2) : 2.0f), is_BE); for (size_t n = 0; n < H.comments().size(); n++) { size_t l = H.comments() [n].size(); if (l) { write_tag (out, MRI_COMMENT, l, is_BE); out.write (H.comments() [n].c_str(), l); } } if (H.transform().is_set()) { write_tag (out, MRI_TRANSFORM, 16*sizeof (float32), is_BE); for (size_t i = 0; i < 4; ++i) for (size_t j = 0; j < 4; ++j) write<float> (out, H.transform() (i,j), is_BE); } if (H.DW_scheme().is_set()) { write_tag (out, MRI_DWSCHEME, 4*H.DW_scheme().rows() *sizeof (float32), is_BE); for (size_t i = 0; i < H.DW_scheme().rows(); ++i) for (size_t j = 0; j < 4; ++j) write<float> (out, H.DW_scheme() (i,j), is_BE); } write_tag (out, MRI_DATA, 1, is_BE); out.write (reinterpret_cast<const char*> (&H.datatype()()), 1); size_t data_offset = out.tellp(); out.close(); std::shared_ptr<Handler::Base> handler (new Handler::Default (H)); File::resize (H.name(), data_offset + Image::footprint(H)); handler->files.push_back (File::Entry (H.name(), data_offset)); return handler; } } } } <commit_msg>fix bug in handling of (ancient and deprecated) MRI format<commit_after>/* Copyright 2008 Brain Research Institute, Melbourne, Australia Written by J-Donald Tournier, 27/06/08. This file is part of MRtrix. MRtrix is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. MRtrix is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with MRtrix. If not, see <http://www.gnu.org/licenses/>. */ #include "file/config.h" #include "file/ofstream.h" #include "file/path.h" #include "file/utils.h" #include "file/mmap.h" #include "image/utils.h" #include "image/format/list.h" #include "image/header.h" #include "image/handler/default.h" #include "get_set.h" /* MRI format: Magic number: MRI# (4 bytes) Byte order specifier: uint16_t = 1 (2 bytes) ... Elements: ID specifier: uint32_t (4 bytes) size: uint32_t (4 bytes) contents: unspecified ('size' bytes) ... */ #define MRI_DATA 0x01 #define MRI_DIMENSIONS 0x02 #define MRI_ORDER 0x03 #define MRI_VOXELSIZE 0x04 #define MRI_COMMENT 0x05 #define MRI_TRANSFORM 0x06 #define MRI_DWSCHEME 0x07 namespace MR { namespace Image { namespace Format { namespace { inline size_t char2order (char item, bool& forward) { switch (item) { case 'L': forward = true; return (0); case 'R': forward = false; return (0); case 'P': forward = true; return (1); case 'A': forward = false; return (1); case 'I': forward = true; return (2); case 'S': forward = false; return (2); case 'B': forward = true; return (3); case 'E': forward = false; return (3); } return (std::numeric_limits<size_t>::max()); } inline char order2char (size_t axis, bool forward) { switch (axis) { case 0: if (forward) return ('L'); else return ('R'); case 1: if (forward) return ('P'); else return ('A'); case 2: if (forward) return ('I'); else return ('S'); case 3: if (forward) return ('B'); else return ('E'); } return ('\0'); } inline size_t type (const uint8_t* pos, bool is_BE) { return (get<uint32_t> (pos, is_BE)); } inline size_t size (const uint8_t* pos, bool is_BE) { return (get<uint32_t> (pos + sizeof (uint32_t), is_BE)); } inline const uint8_t* data (const uint8_t* pos) { return (pos + 2*sizeof (uint32_t)); } inline const uint8_t* next (const uint8_t* current_pos, bool is_BE) { return (current_pos + 2*sizeof (uint32_t) + size (current_pos, is_BE)); } inline void write_tag (std::ostream& out, uint32_t Type, uint32_t Size, bool is_BE) { Type = ByteOrder::swap<uint32_t> (Type, is_BE); out.write ( (const char*) &Type, sizeof (uint32_t)); Size = ByteOrder::swap<uint32_t> (Size, is_BE); out.write ( (const char*) &Size, sizeof (uint32_t)); } template <typename T> inline void write (std::ostream& out, T val, bool is_BE) { val = ByteOrder::swap<T> (val, is_BE); out.write ( (const char*) &val, sizeof (T)); } // needed to get around changes in hard-coded enum types in datatype.h: DataType fetch_datatype (uint8_t c) { uint8_t d = c & 0x07U; uint8_t t = c & ~(0x07U); if (d >= 0x05U) ++d; return { uint8_t (d | t) }; } uint8_t store_datatype (DataType& dt) { uint8_t d = dt() & 0x07U; uint8_t t = dt() & ~(0x07U); if (d >= 0x05U) --d; return (d | t); } } std::shared_ptr<Handler::Base> MRI::read (Header& H) const { if (!Path::has_suffix (H.name(), ".mri")) return std::shared_ptr<Handler::Base>(); File::MMap fmap (H.name()); if (memcmp (fmap.address(), "MRI#", 4)) throw Exception ("file \"" + H.name() + "\" is not in MRI format (unrecognised magic number)"); bool is_BE = false; if (get<uint16_t> (fmap.address() + sizeof (int32_t), is_BE) == 0x0100U) is_BE = true; else if (get<uint16_t> (fmap.address() + sizeof (uint32_t), is_BE) != 0x0001U) throw Exception ("MRI file \"" + H.name() + "\" is badly formed (invalid byte order specifier)"); H.set_ndim (4); size_t data_offset = 0; char* c; const uint8_t* current = fmap.address() + sizeof (int32_t) + sizeof (uint16_t); const uint8_t* last = fmap.address() + fmap.size() - 2*sizeof (uint32_t); while (current <= last) { switch (type (current, is_BE)) { case MRI_DATA: H.datatype() = fetch_datatype (data(current)[-4]); data_offset = current + 5 - (uint8_t*) fmap.address(); break; case MRI_DIMENSIONS: H.dim(0) = get<uint32_t> (data (current), is_BE); H.dim(1) = get<uint32_t> (data (current) + sizeof (uint32_t), is_BE); H.dim(2) = get<uint32_t> (data (current) + 2*sizeof (uint32_t), is_BE); H.dim(3) = get<uint32_t> (data (current) + 3*sizeof (uint32_t), is_BE); break; case MRI_ORDER: c = (char*) data (current); for (size_t n = 0; n < 4; n++) { bool forward = true; size_t ax = char2order (c[n], forward); if (ax == std::numeric_limits<size_t>::max()) throw Exception ("invalid order specifier in MRI image \"" + H.name() + "\""); H.stride(ax) = n+1; if (!forward) H.stride(ax) = -H.stride (ax); } break; case MRI_VOXELSIZE: H.vox(0) = get<float32> (data (current), is_BE); H.vox(1) = get<float32> (data (current) + sizeof (float32), is_BE); H.vox(2) = get<float32> (data (current) + 2*sizeof (float32), is_BE); break; case MRI_COMMENT: H.comments().push_back (std::string (reinterpret_cast<const char*> (data (current)), size (current, is_BE))); break; case MRI_TRANSFORM: H.transform().allocate (4,4); for (size_t i = 0; i < 4; ++i) for (size_t j = 0; j < 4; ++j) H.transform() (i,j) = get<float32> (data (current) + (i*4 + j) *sizeof (float32), is_BE); break; case MRI_DWSCHEME: H.DW_scheme().allocate (size (current, is_BE) / (4*sizeof (float32)), 4); for (size_t i = 0; i < H.DW_scheme().rows(); ++i) for (size_t j = 0; j < 4; ++j) H.DW_scheme() (i,j) = get<float32> (data (current) + (i*4 + j) *sizeof (float32), is_BE); break; default: WARN ("unknown header entity (" + str (type (current, is_BE)) + ", offset " + str (current - fmap.address()) + ") in image \"" + H.name() + "\" - ignored"); break; } if (data_offset) break; current = next (current, is_BE); } if (!data_offset) throw Exception ("no data field found in MRI image \"" + H.name() + "\""); std::shared_ptr<Handler::Base> handler (new Handler::Default (H)); handler->files.push_back (File::Entry (H.name(), data_offset)); return handler; } bool MRI::check (Header& H, size_t num_axes) const { if (!Path::has_suffix (H.name(), ".mri")) return false; if (H.ndim() > num_axes && num_axes != 4) throw Exception ("MRTools format can only support 4 dimensions"); H.set_ndim (num_axes); return true; } std::shared_ptr<Handler::Base> MRI::create (Header& H) const { File::OFStream out (H.name()); #ifdef MRTRIX_BYTE_ORDER_BIG_ENDIAN bool is_BE = true; #else bool is_BE = false; #endif out.write ("MRI#", 4); write<uint16_t> (out, 0x01U, is_BE); write_tag (out, MRI_DIMENSIONS, 4*sizeof (uint32_t), is_BE); write<uint32_t> (out, H.dim (0), is_BE); write<uint32_t> (out, (H.ndim() > 1 ? H.dim (1) : 1), is_BE); write<uint32_t> (out, (H.ndim() > 2 ? H.dim (2) : 1), is_BE); write<uint32_t> (out, (H.ndim() > 3 ? H.dim (3) : 1), is_BE); write_tag (out, MRI_ORDER, 4*sizeof (uint8_t), is_BE); size_t n; char order[4]; for (n = 0; n < H.ndim(); ++n) order[std::abs (H.stride (n))-1] = order2char (n, H.stride (n) >0); for (; n < 4; ++n) order[n] = order2char (n, true); out.write (order, 4); write_tag (out, MRI_VOXELSIZE, 3*sizeof (float32), is_BE); write<float> (out, H.vox (0), is_BE); write<float> (out, (H.ndim() > 1 ? H.vox (1) : 2.0f), is_BE); write<float> (out, (H.ndim() > 2 ? H.vox (2) : 2.0f), is_BE); for (size_t n = 0; n < H.comments().size(); n++) { size_t l = H.comments() [n].size(); if (l) { write_tag (out, MRI_COMMENT, l, is_BE); out.write (H.comments() [n].c_str(), l); } } if (H.transform().is_set()) { write_tag (out, MRI_TRANSFORM, 16*sizeof (float32), is_BE); for (size_t i = 0; i < 4; ++i) for (size_t j = 0; j < 4; ++j) write<float> (out, H.transform() (i,j), is_BE); } if (H.DW_scheme().is_set()) { write_tag (out, MRI_DWSCHEME, 4*H.DW_scheme().rows() *sizeof (float32), is_BE); for (size_t i = 0; i < H.DW_scheme().rows(); ++i) for (size_t j = 0; j < 4; ++j) write<float> (out, H.DW_scheme() (i,j), is_BE); } write_tag (out, MRI_DATA, 1, is_BE); out.put (store_datatype (H.datatype())); size_t data_offset = out.tellp(); out.close(); std::shared_ptr<Handler::Base> handler (new Handler::Default (H)); File::resize (H.name(), data_offset + Image::footprint(H)); handler->files.push_back (File::Entry (H.name(), data_offset)); return handler; } } } } <|endoftext|>
<commit_before>#include <btBulletDynamicsCommon.h> #include "../Physics/GlmConversion.hpp" #include "RigidBody.hpp" namespace Component { RigidBody::~RigidBody() { Destroy(); } Json::Value RigidBody::Save() const { Json::Value component; component["mass"] = mass; component["friction"] = friction; component["rollingFriction"] = rollingFriction; component["spinningFriction"] = spinningFriction; component["cor"] = restitution; component["kinematic"] = kinematic; return component; } bool RigidBody::IsKinematic() const { return kinematic; } float RigidBody::GetFriction() const { return friction; } float RigidBody::GetRollingFriction() const { return rollingFriction; } float RigidBody::GetSpinningFriction() const { return spinningFriction; } float RigidBody::GetRestitution() const { return restitution; } float RigidBody::GetLinearDamping() const { return linearDamping; } btRigidBody* RigidBody::GetBulletRigidBody() { return rigidBody; } void RigidBody::NewBulletRigidBody(float mass) { Destroy(); this->mass = mass; // Motion states inform us of movement caused by physics so that we can // deal with those changes as needed. btDefaultMotionState* motionState = new btDefaultMotionState(btTransform(btQuaternion(0, 0, 0, 1), btVector3(0, 0, 0))); // Bullet treats zero mass as infinite, resulting in immovable objects. btRigidBody::btRigidBodyConstructionInfo constructionInfo(mass, motionState, nullptr, btVector3(0, 0, 0)); rigidBody = new btRigidBody(constructionInfo); rigidBody->setUserPointer(this); } void RigidBody::Destroy() { if (rigidBody) { delete rigidBody->getMotionState(); delete rigidBody; } } glm::vec3 RigidBody::GetPosition() const { btTransform trans; if (IsKinematic()) rigidBody->getMotionState()->getWorldTransform(trans); else trans = rigidBody->getWorldTransform(); return Physics::btToGlm(trans.getOrigin()); } void RigidBody::SetPosition(const glm::vec3& pos) { if (IsKinematic()) { btTransform trans; rigidBody->getMotionState()->getWorldTransform(trans); trans.setOrigin(Physics::glmToBt(pos)); rigidBody->getMotionState()->setWorldTransform(trans); } else { btTransform trans = rigidBody->getWorldTransform(); trans.setOrigin(Physics::glmToBt(pos)); rigidBody->setWorldTransform(trans); } } glm::quat RigidBody::GetOrientation() const { btTransform trans; if (IsKinematic()) rigidBody->getMotionState()->getWorldTransform(trans); else trans = rigidBody->getWorldTransform(); return Physics::btToGlm(trans.getRotation()); } void RigidBody::SetOrientation(const glm::quat& rotation) { if (IsKinematic()) { btTransform trans; rigidBody->getMotionState()->getWorldTransform(trans); trans.setRotation(Physics::glmToBt(rotation)); rigidBody->getMotionState()->setWorldTransform(trans); } else { btTransform trans = rigidBody->getWorldTransform(); trans.setRotation(Physics::glmToBt(rotation)); rigidBody->setWorldTransform(trans); } } float RigidBody::GetMass() { return mass; } void RigidBody::SetMass(float mass) { // Bullet provides a method on the shape that we can use to calculate // inertia. btVector3 inertia; rigidBody->getCollisionShape()->calculateLocalInertia(mass, inertia); rigidBody->setMassProps(mass, inertia); this->mass = mass; } void RigidBody::SetFriction(float friction) { rigidBody->setFriction(friction); this->friction = friction; } void RigidBody::SetRollingFriction(float friction) { rigidBody->setRollingFriction(friction); this->rollingFriction = friction; } void RigidBody::SetSpinningFriction(float friction) { rigidBody->setSpinningFriction(friction); this->spinningFriction = friction; } void RigidBody::SetRestitution(float cor) { rigidBody->setRestitution(cor); this->restitution = cor; } void RigidBody::SetLinearDamping(float damping) { rigidBody->setDamping(linearDamping, 0.0f); this->linearDamping = damping; } void RigidBody::MakeKinematic() { rigidBody->setCollisionFlags(rigidBody->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT); kinematic = true; } void RigidBody::MakeDynamic() { rigidBody->setCollisionFlags(rigidBody->getCollisionFlags() & ~btCollisionObject::CF_KINEMATIC_OBJECT); kinematic = false; } bool RigidBody::GetForceTransformSync() const { return forceTransformSync; } void RigidBody::SetForceTransformSync(bool sync) { forceTransformSync = sync; } } <commit_msg>Save linear damping to JSON.<commit_after>#include <btBulletDynamicsCommon.h> #include "../Physics/GlmConversion.hpp" #include "RigidBody.hpp" namespace Component { RigidBody::~RigidBody() { Destroy(); } Json::Value RigidBody::Save() const { Json::Value component; component["mass"] = mass; component["friction"] = friction; component["rollingFriction"] = rollingFriction; component["spinningFriction"] = spinningFriction; component["cor"] = restitution; component["linearDamping"] = linearDamping; component["kinematic"] = kinematic; return component; } bool RigidBody::IsKinematic() const { return kinematic; } float RigidBody::GetFriction() const { return friction; } float RigidBody::GetRollingFriction() const { return rollingFriction; } float RigidBody::GetSpinningFriction() const { return spinningFriction; } float RigidBody::GetRestitution() const { return restitution; } float RigidBody::GetLinearDamping() const { return linearDamping; } btRigidBody* RigidBody::GetBulletRigidBody() { return rigidBody; } void RigidBody::NewBulletRigidBody(float mass) { Destroy(); this->mass = mass; // Motion states inform us of movement caused by physics so that we can // deal with those changes as needed. btDefaultMotionState* motionState = new btDefaultMotionState(btTransform(btQuaternion(0, 0, 0, 1), btVector3(0, 0, 0))); // Bullet treats zero mass as infinite, resulting in immovable objects. btRigidBody::btRigidBodyConstructionInfo constructionInfo(mass, motionState, nullptr, btVector3(0, 0, 0)); rigidBody = new btRigidBody(constructionInfo); rigidBody->setUserPointer(this); } void RigidBody::Destroy() { if (rigidBody) { delete rigidBody->getMotionState(); delete rigidBody; } } glm::vec3 RigidBody::GetPosition() const { btTransform trans; if (IsKinematic()) rigidBody->getMotionState()->getWorldTransform(trans); else trans = rigidBody->getWorldTransform(); return Physics::btToGlm(trans.getOrigin()); } void RigidBody::SetPosition(const glm::vec3& pos) { if (IsKinematic()) { btTransform trans; rigidBody->getMotionState()->getWorldTransform(trans); trans.setOrigin(Physics::glmToBt(pos)); rigidBody->getMotionState()->setWorldTransform(trans); } else { btTransform trans = rigidBody->getWorldTransform(); trans.setOrigin(Physics::glmToBt(pos)); rigidBody->setWorldTransform(trans); } } glm::quat RigidBody::GetOrientation() const { btTransform trans; if (IsKinematic()) rigidBody->getMotionState()->getWorldTransform(trans); else trans = rigidBody->getWorldTransform(); return Physics::btToGlm(trans.getRotation()); } void RigidBody::SetOrientation(const glm::quat& rotation) { if (IsKinematic()) { btTransform trans; rigidBody->getMotionState()->getWorldTransform(trans); trans.setRotation(Physics::glmToBt(rotation)); rigidBody->getMotionState()->setWorldTransform(trans); } else { btTransform trans = rigidBody->getWorldTransform(); trans.setRotation(Physics::glmToBt(rotation)); rigidBody->setWorldTransform(trans); } } float RigidBody::GetMass() { return mass; } void RigidBody::SetMass(float mass) { // Bullet provides a method on the shape that we can use to calculate // inertia. btVector3 inertia; rigidBody->getCollisionShape()->calculateLocalInertia(mass, inertia); rigidBody->setMassProps(mass, inertia); this->mass = mass; } void RigidBody::SetFriction(float friction) { rigidBody->setFriction(friction); this->friction = friction; } void RigidBody::SetRollingFriction(float friction) { rigidBody->setRollingFriction(friction); this->rollingFriction = friction; } void RigidBody::SetSpinningFriction(float friction) { rigidBody->setSpinningFriction(friction); this->spinningFriction = friction; } void RigidBody::SetRestitution(float cor) { rigidBody->setRestitution(cor); this->restitution = cor; } void RigidBody::SetLinearDamping(float damping) { rigidBody->setDamping(linearDamping, 0.0f); this->linearDamping = damping; } void RigidBody::MakeKinematic() { rigidBody->setCollisionFlags(rigidBody->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT); kinematic = true; } void RigidBody::MakeDynamic() { rigidBody->setCollisionFlags(rigidBody->getCollisionFlags() & ~btCollisionObject::CF_KINEMATIC_OBJECT); kinematic = false; } bool RigidBody::GetForceTransformSync() const { return forceTransformSync; } void RigidBody::SetForceTransformSync(bool sync) { forceTransformSync = sync; } } <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <cstdlib> #include <math.h> using namespace std; int main(int argc, char *argv[]) { ofstream outfile; outfile.open("config"); bool cont = true; int prefix = atoi(argv[1]); if (prefix < 9) { int a = 0; while(cont) { outfile << a << ".0.0.0/" << prefix << "\t" << argv[2] << endl; a = a + pow(2, (8 - prefix)); if (a == 256) cont = false; } } else if (prefix < 17) { int a = 0; int b = 0; while(cont) { outfile << a << "." << b << ".0.0/" << prefix << "\t" << argv[2] << endl; b = b + pow(2, (16 - prefix)); if (b == 256) { b = 0; a++; if (a == 256) cont = false; } } } else if (prefix < 25) { int a = 0; int b = 0; int c = 0; while(cont) { outfile << a << "." << b << "." << c << ".0/" << prefix << "\t" << argv[2] << endl; c = c + pow(2, (24 - prefix)); if (c == 256) { c = 0; b++; if (b == 256) { b = 0; a++; if (a == 256) cont = false; } } } } else { int a = 0; int b = 0; int c = 0; int d = 0; while(cont) { outfile << a << "." << b << "." << c << "." << d << "/" << prefix << "\t" << argv[2] << endl; d = d + pow(2, (32 - prefix)); if (d == 256) { d = 0; c++; if (c == 256) { c = 0; b++; if (b == 256) { b = 0; a++; if (a == 256) cont = false; } } } } } outfile.close(); return 0; } <commit_msg>update configgen.cpp<commit_after>#include <iostream> #include <fstream> #include <cstdlib> #include <math.h> using namespace std; int main(int argc, char *argv[]) { ofstream outfile; outfile.open("config"); bool cont = true; int prefix = atoi(argv[1]); if (prefix < 9) { int a = 0; while(cont) { outfile << a << ".0.0.0/" << prefix << "\t" << argv[2] << endl; a = a + pow(2, (8 - prefix)); if (a == 256) cont = false; } } else if (prefix < 17) { int a = 0; int b = 0; while(cont) { outfile << a << "." << b << ".0.0/" << prefix << "\t" << argv[2] << endl; b = b + pow(2, (16 - prefix)); if (b == 256) { b = 0; a++; if (a == 256) cont = false; } } } else if (prefix < 25) { int a = 0; int b = 0; int c = 0; while(cont) { outfile << a << "." << b << "." << c << ".0/" << prefix << "\t" << argv[2] << endl; c = c + pow(2, (24 - prefix)); if (c == 256) { c = 0; b++; if (b == 256) { b = 0; a++; if (a == 256) cont = false; } } } } else { int a = 0; int b = 0; int c = 0; int d = 0; while(cont) { outfile << a << "." << b << "." << c << "." << d << "/" << prefix << "\t" << argv[2] << endl; d = d + pow(2, (32 - prefix)); if (d == 256) { d = 0; c++; if (c == 256) { c = 0; b++; if (b == 256) { b = 0; a++; if (a == 256) cont = false; } } } } } outfile.close(); return 0; } <|endoftext|>
<commit_before>// Time: O(n) // Space: O(1) class Solution { public: bool isValidSerialization(string preorder) { if (preorder.empty()) { return false; } Tokenizer tokens(preorder); int depth = 0; int i = 0; for (; i < tokens.size(); ++i) { if (tokens.get_next() == "#") { --depth; if (depth < 0) { break; } } else { ++depth; } } return i == tokens.size() - 1; } class Tokenizer { public: Tokenizer(const string& str) : str_(str), i_(0), cnt_(0) { size_ = count(str_.cbegin(), str_.cend(), ',') + 1; } string get_next() { string next; if (cnt_ < size_) { size_t j = str_.find(",", i_); next = str_.substr(i_, j - i_); i_ = j + 1; ++cnt_; } return next; } size_t size() { return size_; } private: const string& str_; size_t size_; size_t cnt_; size_t i_; }; }; <commit_msg>Update verify-preorder-serialization-of-a-binary-tree.cpp<commit_after>// Time: O(n) // Space: O(1) class Solution { public: bool isValidSerialization(string preorder) { if (preorder.empty()) { return false; } Tokenizer tokens(preorder); int depth = 0; int i = 0; for (; i < tokens.size() && depth >= 0; ++i) { if (tokens.get_next() == "#") { --depth; } else { ++depth; } } return i == tokens.size() && depth < 0; } class Tokenizer { public: Tokenizer(const string& str) : str_(str), i_(0), cnt_(0) { size_ = count(str_.cbegin(), str_.cend(), ',') + 1; } string get_next() { string next; if (cnt_ < size_) { size_t j = str_.find(",", i_); next = str_.substr(i_, j - i_); i_ = j + 1; ++cnt_; } return next; } size_t size() { return size_; } private: const string& str_; size_t size_; size_t cnt_; size_t i_; }; }; <|endoftext|>
<commit_before><commit_msg>Deleting 'test.cpp'<commit_after><|endoftext|>
<commit_before>#include "mitkImageStatisticsHolder.h" #include "mitkHistogramGenerator.h" #include "mitkImageTimeSelector.h" mitk::ImageStatisticsHolder::ImageStatisticsHolder( mitk::Image::Pointer image) : m_Image(NULL), m_TimeSelectorForExtremaObject(NULL) { m_CountOfMinValuedVoxels.resize(1, 0); m_CountOfMaxValuedVoxels.resize(1, 0); m_ScalarMin.resize(1, itk::NumericTraits<ScalarType>::max()); m_ScalarMax.resize(1, itk::NumericTraits<ScalarType>::NonpositiveMin()); m_Scalar2ndMin.resize(1, itk::NumericTraits<ScalarType>::max()); m_Scalar2ndMax.resize(1, itk::NumericTraits<ScalarType>::NonpositiveMin()); mitk::HistogramGenerator::Pointer generator = mitk::HistogramGenerator::New(); m_HistogramGeneratorObject = generator; m_Image = image; // create time selector this->GetTimeSelector(); } mitk::ImageStatisticsHolder::~ImageStatisticsHolder() { m_HistogramGeneratorObject = NULL; m_TimeSelectorForExtremaObject = NULL; } const mitk::ImageStatisticsHolder::HistogramType* mitk::ImageStatisticsHolder::GetScalarHistogram(int t) { mitk::ImageTimeSelector* timeSelector = this->GetTimeSelector(); if(timeSelector!=NULL) { timeSelector->SetTimeNr(t); timeSelector->UpdateLargestPossibleRegion(); mitk::HistogramGenerator* generator = static_cast<mitk::HistogramGenerator*>(m_HistogramGeneratorObject.GetPointer()); generator->SetImage(timeSelector->GetOutput()); generator->ComputeHistogram(); return static_cast<const mitk::ImageStatisticsHolder::HistogramType*>(generator->GetHistogram()); } return NULL; } bool mitk::ImageStatisticsHolder::IsValidTimeStep( int t) const { return m_Image->IsValidTimeStep(t); } mitk::ImageTimeSelector* mitk::ImageStatisticsHolder::GetTimeSelector() { if(m_TimeSelectorForExtremaObject.IsNull()) { m_TimeSelectorForExtremaObject = ImageTimeSelector::New(); ImageTimeSelector* timeSelector = static_cast<mitk::ImageTimeSelector*>( m_TimeSelectorForExtremaObject.GetPointer() ); timeSelector->SetInput(m_Image); m_Image->UnRegister(); } return static_cast<ImageTimeSelector*>( m_TimeSelectorForExtremaObject.GetPointer() ); } void mitk::ImageStatisticsHolder::Expand( unsigned int timeSteps ) { if(! m_Image->IsValidTimeStep(timeSteps - 1) ) return; // The BaseData needs to be expanded, call the mitk::Image::Expand() method m_Image->Expand(timeSteps); if(timeSteps > m_ScalarMin.size() ) { m_ScalarMin.resize(timeSteps, itk::NumericTraits<ScalarType>::max()); m_ScalarMax.resize(timeSteps, itk::NumericTraits<ScalarType>::NonpositiveMin()); m_Scalar2ndMin.resize(timeSteps, itk::NumericTraits<ScalarType>::max()); m_Scalar2ndMax.resize(timeSteps, itk::NumericTraits<ScalarType>::NonpositiveMin()); m_CountOfMinValuedVoxels.resize(timeSteps, 0); m_CountOfMaxValuedVoxels.resize(timeSteps, 0); } } void mitk::ImageStatisticsHolder::ResetImageStatistics() { m_ScalarMin.assign(1, itk::NumericTraits<ScalarType>::max()); m_ScalarMax.assign(1, itk::NumericTraits<ScalarType>::NonpositiveMin()); m_Scalar2ndMin.assign(1, itk::NumericTraits<ScalarType>::max()); m_Scalar2ndMax.assign(1, itk::NumericTraits<ScalarType>::NonpositiveMin()); m_CountOfMinValuedVoxels.assign(1, 0); m_CountOfMaxValuedVoxels.assign(1, 0); } #include "mitkImageAccessByItk.h" //#define BOUNDINGOBJECT_IGNORE template < typename ItkImageType > void mitk::_ComputeExtremaInItkImage( const ItkImageType* itkImage, mitk::ImageStatisticsHolder* statisticsHolder, int t) { typename ItkImageType::RegionType region; region = itkImage->GetBufferedRegion(); if(region.Crop(itkImage->GetRequestedRegion()) == false) return; if(region != itkImage->GetRequestedRegion()) return; itk::ImageRegionConstIterator<ItkImageType> it(itkImage, region); typedef typename ItkImageType::PixelType TPixel; TPixel value = 0; if ( statisticsHolder == NULL || !statisticsHolder->IsValidTimeStep( t ) ) return; statisticsHolder->Expand(t+1); // make sure we have initialized all arrays statisticsHolder->m_CountOfMinValuedVoxels[t] = 0; statisticsHolder->m_CountOfMaxValuedVoxels[t] = 0; statisticsHolder->m_Scalar2ndMin[t]= statisticsHolder->m_ScalarMin[t] = itk::NumericTraits<ScalarType>::max(); statisticsHolder->m_Scalar2ndMax[t]= statisticsHolder->m_ScalarMax[t] = itk::NumericTraits<ScalarType>::NonpositiveMin(); while( !it.IsAtEnd() ) { value = it.Get(); // if ( (value > mitkImage->m_ScalarMin) && (value < mitkImage->m_Scalar2ndMin) ) mitkImage->m_Scalar2ndMin = value; // else if ( (value < mitkImage->m_ScalarMax) && (value > mitkImage->m_Scalar2ndMax) ) mitkImage->m_Scalar2ndMax = value; // else if (value > mitkImage->m_ScalarMax) mitkImage->m_ScalarMax = value; // else if (value < mitkImage->m_ScalarMin) mitkImage->m_ScalarMin = value; // if numbers start with 2ndMin or 2ndMax and never have that value again, the previous above logic failed #ifdef BOUNDINGOBJECT_IGNORE if( value > -32765) { #endif // update min if ( value < statisticsHolder->m_ScalarMin[t] ) { statisticsHolder->m_Scalar2ndMin[t] = statisticsHolder->m_ScalarMin[t]; statisticsHolder->m_ScalarMin[t] = value; statisticsHolder->m_CountOfMinValuedVoxels[t] = 1; } else if ( value == statisticsHolder->m_ScalarMin[t] ) { ++statisticsHolder->m_CountOfMinValuedVoxels[t]; } else if ( value < statisticsHolder->m_Scalar2ndMin[t] ) { statisticsHolder->m_Scalar2ndMin[t] = value; } // update max if ( value > statisticsHolder->m_ScalarMax[t] ) { statisticsHolder->m_Scalar2ndMax[t] = statisticsHolder->m_ScalarMax[t]; statisticsHolder->m_ScalarMax[t] = value; statisticsHolder->m_CountOfMaxValuedVoxels[t] = 1; } else if ( value == statisticsHolder->m_ScalarMax[t] ) { ++statisticsHolder->m_CountOfMaxValuedVoxels[t]; } else if ( value > statisticsHolder->m_Scalar2ndMax[t] ) { statisticsHolder->m_Scalar2ndMax[t] = value; } #ifdef BOUNDINGOBJECT_IGNORE } #endif ++it; } //// guard for wrong 2dMin/Max on single constant value images if (statisticsHolder->m_ScalarMax[t] == statisticsHolder->m_ScalarMin[t]) { statisticsHolder->m_Scalar2ndMax[t] = statisticsHolder->m_Scalar2ndMin[t] = statisticsHolder->m_ScalarMax[t]; } statisticsHolder->m_LastRecomputeTimeStamp.Modified(); //MITK_DEBUG <<"extrema "<<itk::NumericTraits<TPixel>::NonpositiveMin()<<" "<<mitkImage->m_ScalarMin<<" "<<mitkImage->m_Scalar2ndMin<<" "<<mitkImage->m_Scalar2ndMax<<" "<<mitkImage->m_ScalarMax<<" "<<itk::NumericTraits<TPixel>::max(); } void mitk::ImageStatisticsHolder::ComputeImageStatistics(int t) { // timestep valid? if (!m_Image->IsValidTimeStep(t)) return; // image modified? if (this->m_Image->GetMTime() > m_LastRecomputeTimeStamp.GetMTime()) this->ResetImageStatistics(); Expand(t+1); // do we have valid information already? if( m_ScalarMin[t] != itk::NumericTraits<ScalarType>::max() || m_Scalar2ndMin[t] != itk::NumericTraits<ScalarType>::max() ) return; // Values already calculated before... const mitk::PixelType pType = m_Image->GetPixelType(0); if(pType.GetNumberOfComponents() == 1) { // recompute mitk::ImageTimeSelector* timeSelector = this->GetTimeSelector(); if(timeSelector!=NULL) { timeSelector->SetTimeNr(t); timeSelector->UpdateLargestPossibleRegion(); mitk::Image* image = timeSelector->GetOutput(); AccessByItk_2( image, _ComputeExtremaInItkImage, this, t ); } } else if(pType.GetNumberOfComponents() > 1) { m_ScalarMin[t] = 0; m_ScalarMax[t] = 255; } } mitk::ScalarType mitk::ImageStatisticsHolder::GetScalarValueMin(int t) { ComputeImageStatistics(t); return m_ScalarMin[t]; } mitk::ScalarType mitk::ImageStatisticsHolder::GetScalarValueMax(int t) { ComputeImageStatistics(t); return m_ScalarMax[t]; } mitk::ScalarType mitk::ImageStatisticsHolder::GetScalarValue2ndMin(int t) { ComputeImageStatistics(t); return m_Scalar2ndMin[t]; } mitk::ScalarType mitk::ImageStatisticsHolder::GetScalarValue2ndMax(int t) { ComputeImageStatistics(t); return m_Scalar2ndMax[t]; } mitk::ScalarType mitk::ImageStatisticsHolder::GetCountOfMinValuedVoxels(int t) { ComputeImageStatistics(t); return m_CountOfMinValuedVoxels[t]; } mitk::ScalarType mitk::ImageStatisticsHolder::GetCountOfMaxValuedVoxels(int t) { ComputeImageStatistics(t); return m_CountOfMaxValuedVoxels[t]; } <commit_msg>added default values for m_Scalar2ndMin and Max<commit_after>#include "mitkImageStatisticsHolder.h" #include "mitkHistogramGenerator.h" #include "mitkImageTimeSelector.h" mitk::ImageStatisticsHolder::ImageStatisticsHolder( mitk::Image::Pointer image) : m_Image(NULL), m_TimeSelectorForExtremaObject(NULL) { m_CountOfMinValuedVoxels.resize(1, 0); m_CountOfMaxValuedVoxels.resize(1, 0); m_ScalarMin.resize(1, itk::NumericTraits<ScalarType>::max()); m_ScalarMax.resize(1, itk::NumericTraits<ScalarType>::NonpositiveMin()); m_Scalar2ndMin.resize(1, itk::NumericTraits<ScalarType>::max()); m_Scalar2ndMax.resize(1, itk::NumericTraits<ScalarType>::NonpositiveMin()); mitk::HistogramGenerator::Pointer generator = mitk::HistogramGenerator::New(); m_HistogramGeneratorObject = generator; m_Image = image; // create time selector this->GetTimeSelector(); } mitk::ImageStatisticsHolder::~ImageStatisticsHolder() { m_HistogramGeneratorObject = NULL; m_TimeSelectorForExtremaObject = NULL; } const mitk::ImageStatisticsHolder::HistogramType* mitk::ImageStatisticsHolder::GetScalarHistogram(int t) { mitk::ImageTimeSelector* timeSelector = this->GetTimeSelector(); if(timeSelector!=NULL) { timeSelector->SetTimeNr(t); timeSelector->UpdateLargestPossibleRegion(); mitk::HistogramGenerator* generator = static_cast<mitk::HistogramGenerator*>(m_HistogramGeneratorObject.GetPointer()); generator->SetImage(timeSelector->GetOutput()); generator->ComputeHistogram(); return static_cast<const mitk::ImageStatisticsHolder::HistogramType*>(generator->GetHistogram()); } return NULL; } bool mitk::ImageStatisticsHolder::IsValidTimeStep( int t) const { return m_Image->IsValidTimeStep(t); } mitk::ImageTimeSelector* mitk::ImageStatisticsHolder::GetTimeSelector() { if(m_TimeSelectorForExtremaObject.IsNull()) { m_TimeSelectorForExtremaObject = ImageTimeSelector::New(); ImageTimeSelector* timeSelector = static_cast<mitk::ImageTimeSelector*>( m_TimeSelectorForExtremaObject.GetPointer() ); timeSelector->SetInput(m_Image); m_Image->UnRegister(); } return static_cast<ImageTimeSelector*>( m_TimeSelectorForExtremaObject.GetPointer() ); } void mitk::ImageStatisticsHolder::Expand( unsigned int timeSteps ) { if(! m_Image->IsValidTimeStep(timeSteps - 1) ) return; // The BaseData needs to be expanded, call the mitk::Image::Expand() method m_Image->Expand(timeSteps); if(timeSteps > m_ScalarMin.size() ) { m_ScalarMin.resize(timeSteps, itk::NumericTraits<ScalarType>::max()); m_ScalarMax.resize(timeSteps, itk::NumericTraits<ScalarType>::NonpositiveMin()); m_Scalar2ndMin.resize(timeSteps, itk::NumericTraits<ScalarType>::max()); m_Scalar2ndMax.resize(timeSteps, itk::NumericTraits<ScalarType>::NonpositiveMin()); m_CountOfMinValuedVoxels.resize(timeSteps, 0); m_CountOfMaxValuedVoxels.resize(timeSteps, 0); } } void mitk::ImageStatisticsHolder::ResetImageStatistics() { m_ScalarMin.assign(1, itk::NumericTraits<ScalarType>::max()); m_ScalarMax.assign(1, itk::NumericTraits<ScalarType>::NonpositiveMin()); m_Scalar2ndMin.assign(1, itk::NumericTraits<ScalarType>::max()); m_Scalar2ndMax.assign(1, itk::NumericTraits<ScalarType>::NonpositiveMin()); m_CountOfMinValuedVoxels.assign(1, 0); m_CountOfMaxValuedVoxels.assign(1, 0); } #include "mitkImageAccessByItk.h" //#define BOUNDINGOBJECT_IGNORE template < typename ItkImageType > void mitk::_ComputeExtremaInItkImage( const ItkImageType* itkImage, mitk::ImageStatisticsHolder* statisticsHolder, int t) { typename ItkImageType::RegionType region; region = itkImage->GetBufferedRegion(); if(region.Crop(itkImage->GetRequestedRegion()) == false) return; if(region != itkImage->GetRequestedRegion()) return; itk::ImageRegionConstIterator<ItkImageType> it(itkImage, region); typedef typename ItkImageType::PixelType TPixel; TPixel value = 0; if ( statisticsHolder == NULL || !statisticsHolder->IsValidTimeStep( t ) ) return; statisticsHolder->Expand(t+1); // make sure we have initialized all arrays statisticsHolder->m_CountOfMinValuedVoxels[t] = 0; statisticsHolder->m_CountOfMaxValuedVoxels[t] = 0; statisticsHolder->m_Scalar2ndMin[t]= statisticsHolder->m_ScalarMin[t] = itk::NumericTraits<ScalarType>::max(); statisticsHolder->m_Scalar2ndMax[t]= statisticsHolder->m_ScalarMax[t] = itk::NumericTraits<ScalarType>::NonpositiveMin(); while( !it.IsAtEnd() ) { value = it.Get(); // if ( (value > mitkImage->m_ScalarMin) && (value < mitkImage->m_Scalar2ndMin) ) mitkImage->m_Scalar2ndMin = value; // else if ( (value < mitkImage->m_ScalarMax) && (value > mitkImage->m_Scalar2ndMax) ) mitkImage->m_Scalar2ndMax = value; // else if (value > mitkImage->m_ScalarMax) mitkImage->m_ScalarMax = value; // else if (value < mitkImage->m_ScalarMin) mitkImage->m_ScalarMin = value; // if numbers start with 2ndMin or 2ndMax and never have that value again, the previous above logic failed #ifdef BOUNDINGOBJECT_IGNORE if( value > -32765) { #endif // update min if ( value < statisticsHolder->m_ScalarMin[t] ) { statisticsHolder->m_Scalar2ndMin[t] = statisticsHolder->m_ScalarMin[t]; statisticsHolder->m_ScalarMin[t] = value; statisticsHolder->m_CountOfMinValuedVoxels[t] = 1; } else if ( value == statisticsHolder->m_ScalarMin[t] ) { ++statisticsHolder->m_CountOfMinValuedVoxels[t]; } else if ( value < statisticsHolder->m_Scalar2ndMin[t] ) { statisticsHolder->m_Scalar2ndMin[t] = value; } // update max if ( value > statisticsHolder->m_ScalarMax[t] ) { statisticsHolder->m_Scalar2ndMax[t] = statisticsHolder->m_ScalarMax[t]; statisticsHolder->m_ScalarMax[t] = value; statisticsHolder->m_CountOfMaxValuedVoxels[t] = 1; } else if ( value == statisticsHolder->m_ScalarMax[t] ) { ++statisticsHolder->m_CountOfMaxValuedVoxels[t]; } else if ( value > statisticsHolder->m_Scalar2ndMax[t] ) { statisticsHolder->m_Scalar2ndMax[t] = value; } #ifdef BOUNDINGOBJECT_IGNORE } #endif ++it; } //// guard for wrong 2dMin/Max on single constant value images if (statisticsHolder->m_ScalarMax[t] == statisticsHolder->m_ScalarMin[t]) { statisticsHolder->m_Scalar2ndMax[t] = statisticsHolder->m_Scalar2ndMin[t] = statisticsHolder->m_ScalarMax[t]; } statisticsHolder->m_LastRecomputeTimeStamp.Modified(); //MITK_DEBUG <<"extrema "<<itk::NumericTraits<TPixel>::NonpositiveMin()<<" "<<mitkImage->m_ScalarMin<<" "<<mitkImage->m_Scalar2ndMin<<" "<<mitkImage->m_Scalar2ndMax<<" "<<mitkImage->m_ScalarMax<<" "<<itk::NumericTraits<TPixel>::max(); } void mitk::ImageStatisticsHolder::ComputeImageStatistics(int t) { // timestep valid? if (!m_Image->IsValidTimeStep(t)) return; // image modified? if (this->m_Image->GetMTime() > m_LastRecomputeTimeStamp.GetMTime()) this->ResetImageStatistics(); Expand(t+1); // do we have valid information already? if( m_ScalarMin[t] != itk::NumericTraits<ScalarType>::max() || m_Scalar2ndMin[t] != itk::NumericTraits<ScalarType>::max() ) return; // Values already calculated before... const mitk::PixelType pType = m_Image->GetPixelType(0); if(pType.GetNumberOfComponents() == 1) { // recompute mitk::ImageTimeSelector* timeSelector = this->GetTimeSelector(); if(timeSelector!=NULL) { timeSelector->SetTimeNr(t); timeSelector->UpdateLargestPossibleRegion(); mitk::Image* image = timeSelector->GetOutput(); AccessByItk_2( image, _ComputeExtremaInItkImage, this, t ); } } else if(pType.GetNumberOfComponents() > 1) { m_ScalarMin[t] = 0; m_ScalarMax[t] = 255; m_Scalar2ndMin[t] = 0; m_Scalar2ndMax[t] = 255; } } mitk::ScalarType mitk::ImageStatisticsHolder::GetScalarValueMin(int t) { ComputeImageStatistics(t); return m_ScalarMin[t]; } mitk::ScalarType mitk::ImageStatisticsHolder::GetScalarValueMax(int t) { ComputeImageStatistics(t); return m_ScalarMax[t]; } mitk::ScalarType mitk::ImageStatisticsHolder::GetScalarValue2ndMin(int t) { ComputeImageStatistics(t); return m_Scalar2ndMin[t]; } mitk::ScalarType mitk::ImageStatisticsHolder::GetScalarValue2ndMax(int t) { ComputeImageStatistics(t); return m_Scalar2ndMax[t]; } mitk::ScalarType mitk::ImageStatisticsHolder::GetCountOfMinValuedVoxels(int t) { ComputeImageStatistics(t); return m_CountOfMinValuedVoxels[t]; } mitk::ScalarType mitk::ImageStatisticsHolder::GetCountOfMaxValuedVoxels(int t) { ComputeImageStatistics(t); return m_CountOfMaxValuedVoxels[t]; } <|endoftext|>
<commit_before>#include "consoleui.h" using namespace std; ConsoleUI::ConsoleUI() { } void ConsoleUI::run() { bool run = true; while (run) { cout << " ================================" << endl; cout << " Press 1 to add" << endl; cout << " Press 2 to sort" << endl; cout << " Press 3 to list" << endl; cout << " Press 4 to search" << endl; cout << " Press 5 to remove scientist" << endl; cout << " Press 6 to exit" << endl; cout << " ================================" << endl; char input = '0'; cin >> input; cin.clear(); fflush(stdin); int choice = input - '0'; switch (choice) { case 1: addData(); break; case 2: sortData(); break; case 3: showData(); break; case 4: searchData(); break; case 5: removeData(); case 6: run = false; break; default: cout << "Error! Invalid Input" << endl; } } } void ConsoleUI::addData() { string name; char gender; int birthYear; int deathYear; cout << "Enter Name: "; cin >> ws; getline(cin,name); if(!isupper(name[0])) { name[0] = toupper(name[0]); } cout << "Enter gender (M/F): "; cin >> gender; cin.clear(); fflush(stdin); if(genderCheck(gender) == false) { if(check() == false) { return; } } cout << "Enter birth year: "; cin >> birthYear; cout << "Enter death year (0 for living person): "; cin >> deathYear; if(birthChecks(birthYear, deathYear) == false) { check(); // Checks if you want to try to input again. } else { Persons newPerson(name, gender, birthYear, deathYear); serve.add(newPerson); } } bool ConsoleUI::genderCheck(char& gender) { if(gender == 'm' || gender == 'M' || gender == 'f' || gender == 'F') { if(gender == 'm') { gender = 'M'; } if(gender == 'f') { gender = 'F'; } return true; } else { cout << "Wrong input for gender!" << endl; return false; } } bool ConsoleUI::check() { char continuel; cout << "Do you want to try again? (Y for yes and N for No)" ; cin >> continuel; if(continuel == 'Y' || continuel == 'y') { addData(); return true; } else { return false; } } bool ConsoleUI::birthChecks(int birthYear, int deathYear) { if(birthYear < 0 ) { cout << "You can not be born before the year zero." << endl; return false; } if(birthYear > 2016) { cout << "You can not be born after the year 2016" << endl; return false; } if(deathYear < birthYear && deathYear != 0) { cout << "You cannot die before you are born!" << endl; return false; } if(deathYear > 2016 ) { cout << "You are Still alive."; return false; } return true; } void ConsoleUI::showData() { cout << endl; printLine(); for(size_t i = 0; i < serve.list().size();i++) { cout << serve.list()[i]; } cout << "_____________________________________________________" << endl; } void ConsoleUI::searchData() { bool error = false; do { cout << "How would you like to search the data?" << endl; cout << " =====================================" << endl; cout << " Press 1 to search by name" << endl; cout << " Press 2 to search by birth year" << endl; cout << " Press 3 to search for gender" << endl; cout << " Press 4 to search by birth year range" << endl; cout << " Press 5 to cancel" << endl; cout << " ======================================" << endl; char input = '0'; cin >> input; int choice = input - '0'; switch(choice) { case 1: { string n = " "; cout << "Enter name: "; cin >> ws; getline(cin, n); vector<int> v_n = serve.searchByName(n); if (v_n.size() == 0) { cout << "No results found\n"; } else { printLine(); for (unsigned int i = 0; i < v_n.size(); i++) { cout << serve.list()[v_n[i]]; } } error = false; break; } case 2: { int y = 0; cout << "Enter year: "; cin >> y; vector<int> v_y = serve.searchByYear(y); if (v_y.size() == 0) { cout << "No results found\n"; } else { printLine(); for (unsigned int i = 0; i < v_y.size(); i++) { cout << serve.list()[v_y[i]]; } } error = false; break; } case 3: { char gender; cout << "Enter gender (M/F): "; cin >> gender; vector<int> v_g = serve.searchByGender(gender); if (v_g.size() == 0) { cout << "No results found" << endl; } else { printLine(); for (unsigned int i = 0; i < v_g.size(); i++) { cout << serve.list()[v_g[i]]; } } break; } case 4: { int f = 0, l = 0; cout << "Enter first year in range: "; cin >> f; cout << "Enter last yar in range: "; cin >> l; vector<int> v_r = serve.searchByRange(f,l); if (v_r.size() == 0) { cout << "No results found" << endl; } else { printLine(); for (unsigned int i = 0; i < v_r.size(); i++) { cout << serve.list()[v_r[i]]; } } break; } case 5: error = false; break; default: { cout << "Error! invalid input" << endl; error = true; } } } while (error); } void ConsoleUI::sortData() { char input = '0'; int choice = 0; int choice2 = 0; bool error = false; do { cout << "How would you like to sort the list?" << endl; cout << " ================================" << endl; cout << " Press 1 for Name" << endl; cout << " Press 2 for Birth Year" << endl; cout << " Press 3 for Death Year " << endl; cout << " Press 4 for Gender" << endl; cout << " Press 5 to cancel" << endl; cout << " ================================" << endl; cin >> input; choice = input - '0'; choice2 = 0; input = '1'; switch (choice) { case 1: do { if (input != '1' && input != '2' && input != '3') { cout << "Error! Invalid input" << endl; } cout << "Regular or Reversed sorting?" << endl; cout << " ================================" << endl; cout << "Press 1 for regular sorting" << endl; cout << "Press 2 for reversed sorting" << endl; cout << "Press 3 to cancel" << endl; cout << " ================================" << endl; cin >> input; } while (input != '1' && input != '2' && input != '3'); choice2 = input - '0'; if (choice2 == 1 || choice2 == 2) { serve.sorting(choice, choice2); error = false; } else { error = true; } break; case 2: do { if (input != '1' && input != '2' && input != '3') { cout << "Error! Invalid input" << endl; } cout << "Regular or Reversed sorting?" << endl; cout << " ================================" << endl; cout << "Press 1 for regular sorting" << endl; cout << "Press 2 for reversed sorting" << endl; cout << "Press 3 to cancel" << endl; cout << " ================================" << endl; cin >> input; } while (input != '1' && input != '2' && input != '3'); choice2 = input - '0'; if (choice2 == 1 || choice2 == 2) { serve.sorting(choice, choice2); error = false; } else { error = true; } break; case 3: do { if (input != '1' && input != '2' && input != '3') { cout << "Error! Invalid input" << endl; } cout << "Regular or Reversed sorting?" << endl; cout << " ================================" << endl; cout << "Press 1 for regular sorting" << endl; cout << "Press 2 for reversed sorting" << endl; cout << "Press 3 to cancel" << endl; cout << " ================================" << endl; cin >> input; } while (input != '1' && input != '2' && input != '3'); choice2 = input - '0'; if (choice2 == 1 || choice2 == 2) { serve.sorting(choice, choice2); error = false; } else { error = true; } break; case 4: do { if (input != '1' && input != '2' && input != '3') { cout << "Error! Invalid input" << endl; } cout << "Sort by Males or Females?" << endl; cout << " ================================" << endl; cout << "Press 1 for sorting by Females first" << endl; cout << "Press 2 for sorting by Males first" << endl; cout << "Press 3 to cancel" << endl; cout << " ================================" << endl; cin >> input; } while (input != '1' && input != '2' && input != '3'); choice2 = input - '0'; if (choice2 == 1 || choice2 == 2) { serve.sorting(choice, choice2); error = false; } else { error = true; } break; case 5: error = false; break; default: cout << "Error! Invalid input!" << endl; error = true; } } while (error); if (choice != 5) //if you press cancel, you don't want to see the list, do you? { showData(); } } void ConsoleUI::printLine() { cout.width(16); cout << left << "Name"; cout << "\tGender\tBorn\tDied" << endl; cout << "_____________________________________________________" << endl; } void ConsoleUI::removeData() { string str; cout << "Enter the name of the scientist you want to remove: " << endl; } <commit_msg> corrected search by gender<commit_after>#include "consoleui.h" using namespace std; ConsoleUI::ConsoleUI() { } void ConsoleUI::run() { bool run = true; while (run) { cout << " ================================" << endl; cout << " Press 1 to add" << endl; cout << " Press 2 to sort" << endl; cout << " Press 3 to list" << endl; cout << " Press 4 to search" << endl; cout << " Press 5 to remove scientist" << endl; cout << " Press 6 to exit" << endl; cout << " ================================" << endl; char input = '0'; cin >> input; cin.clear(); fflush(stdin); int choice = input - '0'; switch (choice) { case 1: addData(); break; case 2: sortData(); break; case 3: showData(); break; case 4: searchData(); break; case 5: removeData(); case 6: run = false; break; default: cout << "Error! Invalid Input" << endl; } } } void ConsoleUI::addData() { string name; char gender; int birthYear; int deathYear; cout << "Enter Name: "; cin >> ws; getline(cin,name); if(!isupper(name[0])) { name[0] = toupper(name[0]); } cout << "Enter gender (M/F): "; cin >> gender; cin.clear(); fflush(stdin); if(genderCheck(gender) == false) { if(check() == false) { return; } } cout << "Enter birth year: "; cin >> birthYear; cout << "Enter death year (0 for living person): "; cin >> deathYear; if(birthChecks(birthYear, deathYear) == false) { check(); // Checks if you want to try to input again. } else { Persons newPerson(name, gender, birthYear, deathYear); serve.add(newPerson); } } bool ConsoleUI::genderCheck(char& gender) { if(gender == 'm' || gender == 'M' || gender == 'f' || gender == 'F') { if(gender == 'm') { gender = 'M'; } if(gender == 'f') { gender = 'F'; } return true; } else { cout << "Wrong input for gender!" << endl; return false; } } bool ConsoleUI::check() { char continuel; cout << "Do you want to try again? (Y for yes and N for No)" ; cin >> continuel; if(continuel == 'Y' || continuel == 'y') { addData(); return true; } else { return false; } } bool ConsoleUI::birthChecks(int birthYear, int deathYear) { if(birthYear < 0 ) { cout << "You can not be born before the year zero." << endl; return false; } if(birthYear > 2016) { cout << "You can not be born after the year 2016" << endl; return false; } if(deathYear < birthYear && deathYear != 0) { cout << "You cannot die before you are born!" << endl; return false; } if(deathYear > 2016 ) { cout << "You are Still alive."; return false; } return true; } void ConsoleUI::showData() { cout << endl; printLine(); for(size_t i = 0; i < serve.list().size();i++) { cout << serve.list()[i]; } cout << "_____________________________________________________" << endl; } void ConsoleUI::searchData() { bool error = false; do { cout << "How would you like to search the data?" << endl; cout << " =====================================" << endl; cout << " Press 1 to search by name" << endl; cout << " Press 2 to search by birth year" << endl; cout << " Press 3 to search for gender" << endl; cout << " Press 4 to search by birth year range" << endl; cout << " Press 5 to cancel" << endl; cout << " ======================================" << endl; char input = '0'; cin >> input; int choice = input - '0'; switch(choice) { case 1: { string n = " "; cout << "Enter name: "; cin >> ws; getline(cin, n); vector<int> v_n = serve.searchByName(n); if (v_n.size() == 0) { cout << "No results found\n"; } else { printLine(); for (unsigned int i = 0; i < v_n.size(); i++) { cout << serve.list()[v_n[i]]; } } error = false; break; } case 2: { int y = 0; cout << "Enter year: "; cin >> y; vector<int> v_y = serve.searchByYear(y); if (v_y.size() == 0) { cout << "No results found\n"; } else { printLine(); for (unsigned int i = 0; i < v_y.size(); i++) { cout << serve.list()[v_y[i]]; } } error = false; break; } case 3: { char gender; cout << "Enter gender (M/F): "; cin >> gender; if(genderCheck(gender) == false) { searchData(); } vector<int> v_g = serve.searchByGender(gender); if (v_g.size() == 0) { cout << "No results found" << endl; } else { printLine(); for (unsigned int i = 0; i < v_g.size(); i++) { cout << serve.list()[v_g[i]]; } } break; } case 4: { int f = 0, l = 0; cout << "Enter first year in range: "; cin >> f; cout << "Enter last yar in range: "; cin >> l; vector<int> v_r = serve.searchByRange(f,l); if (v_r.size() == 0) { cout << "No results found" << endl; } else { printLine(); for (unsigned int i = 0; i < v_r.size(); i++) { cout << serve.list()[v_r[i]]; } } break; } case 5: error = false; break; default: { cout << "Error! invalid input" << endl; error = true; } } } while (error); } void ConsoleUI::sortData() { char input = '0'; int choice = 0; int choice2 = 0; bool error = false; do { cout << "How would you like to sort the list?" << endl; cout << " ================================" << endl; cout << " Press 1 for Name" << endl; cout << " Press 2 for Birth Year" << endl; cout << " Press 3 for Death Year " << endl; cout << " Press 4 for Gender" << endl; cout << " Press 5 to cancel" << endl; cout << " ================================" << endl; cin >> input; choice = input - '0'; choice2 = 0; input = '1'; switch (choice) { case 1: do { if (input != '1' && input != '2' && input != '3') { cout << "Error! Invalid input" << endl; } cout << "Regular or Reversed sorting?" << endl; cout << " ================================" << endl; cout << "Press 1 for regular sorting" << endl; cout << "Press 2 for reversed sorting" << endl; cout << "Press 3 to cancel" << endl; cout << " ================================" << endl; cin >> input; } while (input != '1' && input != '2' && input != '3'); choice2 = input - '0'; if (choice2 == 1 || choice2 == 2) { serve.sorting(choice, choice2); error = false; } else { error = true; } break; case 2: do { if (input != '1' && input != '2' && input != '3') { cout << "Error! Invalid input" << endl; } cout << "Regular or Reversed sorting?" << endl; cout << " ================================" << endl; cout << "Press 1 for regular sorting" << endl; cout << "Press 2 for reversed sorting" << endl; cout << "Press 3 to cancel" << endl; cout << " ================================" << endl; cin >> input; } while (input != '1' && input != '2' && input != '3'); choice2 = input - '0'; if (choice2 == 1 || choice2 == 2) { serve.sorting(choice, choice2); error = false; } else { error = true; } break; case 3: do { if (input != '1' && input != '2' && input != '3') { cout << "Error! Invalid input" << endl; } cout << "Regular or Reversed sorting?" << endl; cout << " ================================" << endl; cout << "Press 1 for regular sorting" << endl; cout << "Press 2 for reversed sorting" << endl; cout << "Press 3 to cancel" << endl; cout << " ================================" << endl; cin >> input; } while (input != '1' && input != '2' && input != '3'); choice2 = input - '0'; if (choice2 == 1 || choice2 == 2) { serve.sorting(choice, choice2); error = false; } else { error = true; } break; case 4: do { if (input != '1' && input != '2' && input != '3') { cout << "Error! Invalid input" << endl; } cout << "Sort by Males or Females?" << endl; cout << " ================================" << endl; cout << "Press 1 for sorting by Females first" << endl; cout << "Press 2 for sorting by Males first" << endl; cout << "Press 3 to cancel" << endl; cout << " ================================" << endl; cin >> input; } while (input != '1' && input != '2' && input != '3'); choice2 = input - '0'; if (choice2 == 1 || choice2 == 2) { serve.sorting(choice, choice2); error = false; } else { error = true; } break; case 5: error = false; break; default: cout << "Error! Invalid input!" << endl; error = true; } } while (error); if (choice != 5) //if you press cancel, you don't want to see the list, do you? { showData(); } } void ConsoleUI::printLine() { cout.width(16); cout << left << "Name"; cout << "\tGender\tBorn\tDied" << endl; cout << "_____________________________________________________" << endl; } void ConsoleUI::removeData() { string str; cout << "Enter the name of the scientist you want to remove: " << endl; } <|endoftext|>
<commit_before>#include "consoleui.h" #include "servicelayer.h" #include <fstream> #include <string> #include <iostream> using namespace std; ConsoleUI::ConsoleUI() { } void ConsoleUI::run() { bool run = true; while (run) { cout << " ================================" << endl; cout << " Press 1 to add" << endl; cout << " Press 2 to sort" << endl; cout << " Press 3 to list" << endl; cout << " Press 4 to search" << endl; cout << " Press 5 to exit" << endl; cout << " ================================" << endl; char input = '0'; cin >> input; int choice = input - '0'; switch (choice) { case 1: addData(); break; case 2: sortData(); break; case 3: showData(); break; case 4: searchData(); break; case 5: run = false; break; default: cout << "Error! Invalid Input" << endl; } } } void ConsoleUI::addData() { string name; char gender; int birthYear; int deathYear; cout << "Enter Name: "; cin >> ws; getline(cin,name); cout << "Enter gender (M/F): "; cin >> gender; cout << "Enter birth year: "; cin >> birthYear; cout << "Enter death year (0 for living person): "; cin >> deathYear; Persons newPerson(name, gender, birthYear, deathYear); serve.add(newPerson); } void ConsoleUI::showData() { printLine(); for(size_t i = 0; i < serve.list().size();i++) { cout << serve.list()[i].getName() << "\t " << serve.list()[i].getGender() << "\t" << serve.list()[i].getBirthYear() << "\t"; if (serve.list()[i].getAlive()) { cout << "Alive\n"; } else { cout << serve.list()[i].getDeathYear() << endl; } } } void ConsoleUI::searchData() { bool error = false; do { cout << "How would you like to search the data?" << endl; cout << " =====================================" << endl; cout << " Press 1 to search by name" << endl; cout << " Press 2 to search by birth year" << endl; cout << " Press 3 to cancel" << endl; cout << "======================================" << endl; char input = '0'; cin >> input; int choice = input - '0'; switch(choice) { case 1: { string n = " "; cout << "Enter name: "; cin >> n; vector<int> v_n = serve.searchByName(n); if (v_n.size() == 0) { cout << "No results found\n"; } else { printLine(); for (unsigned int i = 0; i < v_n.size(); i++) { cout << serve.list()[v_n[i]].getName() << "\t " << serve.list()[v_n[i]].getGender() << "\t" << serve.list()[v_n[i]].getBirthYear() << "\t"; if (serve.list()[v_n[i]].getAlive()) { cout << "Alive\n"; } else { cout << serve.list()[v_n[i]].getDeathYear() << endl; } } } error = false; break; } case 2: { int y = 0; cout << "Enter year: "; cin >> y; vector<int> v_y = serve.searchByYear(y); if (v_y.size() == 0) { cout << "No results found\n"; } else { printLine(); for (unsigned int i = 0; i < v_y.size(); i++) { cout << serve.list()[v_y[i]].getName() << "\t " << serve.list()[v_y[i]].getGender() << "\t" << serve.list()[v_y[i]].getBirthYear() << "\t"; if (serve.list()[v_y[i]].getAlive()) { cout << "Alive\n"; } else { cout << serve.list()[v_y[i]].getDeathYear() << endl; } } } error = false; break; } case 3: error = false; break; default: { cout << "Error! invalid input" << endl; error = true; } } } while (error); } void ConsoleUI::sortData() { bool error = false; do { cout << "How would you like to sort the list?" << endl; cout << " ================================" << endl; cout << "Press 1 for Name" << endl; cout << "Press 2 for Birth Year" << endl; cout << "Press 3 for Death Year " << endl; cout << "Press 4 for Gender" << endl; cout << "Press 5 to cancel" << endl; cout << " ================================" << endl; char input = '0'; cin >> input; int choice = input - '0'; switch (choice) { case 1: serve.sort(choice); error = false; break; case 2: serve.sort(choice); error = false; break; case 3: serve.sort(choice); error = false; break; case 4: serve.sort(choice); error = false; break; case 5: error = false; break; default: cout << "Error! Invalid input!" << endl; error = true; } } while (error); showData(); } void ConsoleUI::printLine() { cout.width(16); cout << left << "Name"; cout << "\tGender" << "\t" << "Born" << "\t" << "Died" << endl; cout << "_____________________________________________________" << endl; } <commit_msg>search fallið<commit_after>#include "consoleui.h" #include "servicelayer.h" #include <fstream> #include <string> #include <iostream> using namespace std; ConsoleUI::ConsoleUI() { } void ConsoleUI::run() { bool run = true; while (run) { cout << " ================================" << endl; cout << " Press 1 to add" << endl; cout << " Press 2 to sort" << endl; cout << " Press 3 to list" << endl; cout << " Press 4 to search" << endl; cout << " Press 5 to exit" << endl; cout << " ================================" << endl; char input = '0'; cin >> input; int choice = input - '0'; switch (choice) { case 1: addData(); break; case 2: sortData(); break; case 3: showData(); break; case 4: searchData(); break; case 5: run = false; break; default: cout << "Error! Invalid Input" << endl; } } } void ConsoleUI::addData() { string name; char gender; int birthYear; int deathYear; cout << "Enter Name: "; cin >> ws; getline(cin,name); cout << "Enter gender (M/F): "; cin >> gender; cout << "Enter birth year: "; cin >> birthYear; cout << "Enter death year (0 for living person): "; cin >> deathYear; Persons newPerson(name, gender, birthYear, deathYear); serve.add(newPerson); } void ConsoleUI::showData() { printLine(); for(size_t i = 0; i < serve.list().size();i++) { cout << serve.list()[i].getName() << "\t " << serve.list()[i].getGender() << "\t" << serve.list()[i].getBirthYear() << "\t"; if (serve.list()[i].getAlive()) { cout << "Alive\n"; } else { cout << serve.list()[i].getDeathYear() << endl; } } } void ConsoleUI::searchData() { bool error = false; do { cout << "How would you like to search the data?" << endl; cout << " =====================================" << endl; cout << " Press 1 to search by name" << endl; cout << " Press 2 to search by birth year" << endl; cout << " Press 3 to cancel" << endl; cout << "======================================" << endl; char input = '0'; cin >> input; int choice = input - '0'; switch(choice) { case 1: { string n = " "; cout << "Enter name: "; cin >> n; vector<int> v_n = serve.searchByName(n); if (v_n.size() == 0) { cout << "No results found\n"; } else { printLine(); for (unsigned int i = 0; i < v_n.size(); i++) { cout << serve.list()[v_n[i]].getName() << "\t " << serve.list()[v_n[i]].getGender() << "\t" << serve.list()[v_n[i]].getBirthYear() << "\t"; if (serve.list()[v_n[i]].getAlive()) { cout << "Alive\n"; } else { cout << serve.list()[v_n[i]].getDeathYear() << endl; } } } error = false; break; } case 2: { int y = 0; cout << "Enter year: "; cin >> y; vector<int> v_y = serve.searchByYear(y); if (v_y.size() == 0) { cout << "No results found\n"; } else { printLine(); for (unsigned int i = 0; i < v_y.size(); i++) { cout << serve.list()[v_y[i]].getName() << "\t " << serve.list()[v_y[i]].getGender() << "\t" << serve.list()[v_y[i]].getBirthYear() << "\t"; if (serve.list()[v_y[i]].getAlive()) { cout << "Alive\n"; } else { cout << serve.list()[v_y[i]].getDeathYear() << endl; } } } error = false; break; } case 3: error = false; break; default: { cout << "Error! invalid input" << endl; error = true; } } } while (error); } void ConsoleUI::sortData() { bool error = false; do { cout << "How would you like to sort the list?" << endl; cout << " ================================" << endl; cout << "Press 1 for Name" << endl; cout << "Press 2 for Birth Year" << endl; cout << "Press 3 for Death Year " << endl; cout << "Press 4 for Gender" << endl; cout << "Press 5 to cancel" << endl; cout << " ================================" << endl; char input = '0'; cin >> input; int choice = input - '0'; switch (choice) { case 1: serve.sort(choice); error = false; break; case 2: serve.sort(choice); error = false; break; case 3: serve.sort(choice); error = false; break; case 4: serve.sort(choice); error = false; break; case 5: error = false; break; default: cout << "Error! Invalid input!" << endl; error = true; } } while (error); showData(); } void ConsoleUI::printLine() { cout.width(16); cout << left << "Name\t"; cout << "\tGender" << "\t" << "Born" << "\t" << "Died" << endl; cout << "_____________________________________________________" << endl; } <|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt 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 notices for more information. =========================================================================*/ #include "otbTrainVectorBase.h" // Validation #include "otbConfusionMatrixCalculator.h" namespace otb { namespace Wrapper { class TrainVectorClassifier : public TrainVectorBase { public: typedef TrainVectorClassifier Self; typedef TrainVectorBase Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; itkNewMacro( Self ) itkTypeMacro( Self, Superclass ) typedef Superclass::SampleType SampleType; typedef Superclass::ListSampleType ListSampleType; typedef Superclass::TargetListSampleType TargetListSampleType; // Estimate performance on validation sample typedef otb::ConfusionMatrixCalculator<TargetListSampleType, TargetListSampleType> ConfusionMatrixCalculatorType; typedef ConfusionMatrixCalculatorType::ConfusionMatrixType ConfusionMatrixType; typedef ConfusionMatrixCalculatorType::MapOfIndicesType MapOfIndicesType; typedef ConfusionMatrixCalculatorType::ClassLabelType ClassLabelType; private: void DoTrainInit() { // Nothing to do here } void DoTrainUpdateParameters() { // Nothing to do here } void DoBeforeTrainExecute() { // Enforce the need of class field name in supervised mode if (GetClassifierCategory() == Supervised) { featuresInfo.SetClassFieldNames( GetChoiceNames( "cfield" ), GetSelectedItems( "cfield" ) ); if( featuresInfo.m_SelectedCFieldIdx.empty() ) { otbAppLogFATAL( << "No field has been selected for data labelling!" ); } } } void DoAfterTrainExecute() { if (GetClassifierCategory() == Supervised) { ConfusionMatrixCalculatorType::Pointer confMatCalc = ComputeConfusionMatrix( predictedList, classificationListSamples.labeledListSample ); WriteConfusionMatrix( confMatCalc ); } else { // TODO Compute Contingency Table } } ConfusionMatrixCalculatorType::Pointer ComputeConfusionMatrix(const TargetListSampleType::Pointer &predictedListSample, const TargetListSampleType::Pointer &performanceLabeledListSample) { ConfusionMatrixCalculatorType::Pointer confMatCalc = ConfusionMatrixCalculatorType::New(); otbAppLogINFO( "Predicted list size : " << predictedListSample->Size() ); otbAppLogINFO( "ValidationLabeledListSample size : " << performanceLabeledListSample->Size() ); confMatCalc->SetReferenceLabels( performanceLabeledListSample ); confMatCalc->SetProducedLabels( predictedListSample ); confMatCalc->Compute(); otbAppLogINFO( "training performances" ); LogConfusionMatrix( confMatCalc ); for( unsigned int itClasses = 0; itClasses < confMatCalc->GetNumberOfClasses(); itClasses++ ) { ConfusionMatrixCalculatorType::ClassLabelType classLabel = confMatCalc->GetMapOfIndices()[itClasses]; otbAppLogINFO( "Precision of class [" << classLabel << "] vs all: " << confMatCalc->GetPrecisions()[itClasses] ); otbAppLogINFO( "Recall of class [" << classLabel << "] vs all: " << confMatCalc->GetRecalls()[itClasses] ); otbAppLogINFO( "F-score of class [" << classLabel << "] vs all: " << confMatCalc->GetFScores()[itClasses] << "\n" ); } otbAppLogINFO( "Global performance, Kappa index: " << confMatCalc->GetKappaIndex() ); return confMatCalc; } /** * Write the confidence matrix into a file if output is provided. * \param confMatCalc the input matrix to write. */ void WriteConfusionMatrix(const ConfusionMatrixCalculatorType::Pointer &confMatCalc) { if( this->HasValue( "io.confmatout" ) ) { // Writing the confusion matrix in the output .CSV file MapOfIndicesType::iterator itMapOfIndicesValid, itMapOfIndicesPred; ClassLabelType labelValid = 0; ConfusionMatrixType confusionMatrix = confMatCalc->GetConfusionMatrix(); MapOfIndicesType mapOfIndicesValid = confMatCalc->GetMapOfIndices(); unsigned long nbClassesPred = mapOfIndicesValid.size(); ///////////////////////////////////////////// // Filling the 2 headers for the output file const std::string commentValidStr = "#Reference labels (rows):"; const std::string commentPredStr = "#Produced labels (columns):"; const char separatorChar = ','; std::ostringstream ossHeaderValidLabels, ossHeaderPredLabels; // Filling ossHeaderValidLabels and ossHeaderPredLabels for the output file ossHeaderValidLabels << commentValidStr; ossHeaderPredLabels << commentPredStr; itMapOfIndicesValid = mapOfIndicesValid.begin(); while( itMapOfIndicesValid != mapOfIndicesValid.end() ) { // labels labelValid of mapOfIndicesValid are already sorted in otbConfusionMatrixCalculator labelValid = itMapOfIndicesValid->second; otbAppLogINFO( "mapOfIndicesValid[" << itMapOfIndicesValid->first << "] = " << labelValid ); ossHeaderValidLabels << labelValid; ossHeaderPredLabels << labelValid; ++itMapOfIndicesValid; if( itMapOfIndicesValid != mapOfIndicesValid.end() ) { ossHeaderValidLabels << separatorChar; ossHeaderPredLabels << separatorChar; } else { ossHeaderValidLabels << std::endl; ossHeaderPredLabels << std::endl; } } std::ofstream outFile; outFile.open( this->GetParameterString( "io.confmatout" ).c_str() ); outFile << std::fixed; outFile.precision( 10 ); ///////////////////////////////////// // Writing the 2 headers outFile << ossHeaderValidLabels.str(); outFile << ossHeaderPredLabels.str(); ///////////////////////////////////// unsigned int indexLabelValid = 0, indexLabelPred = 0; for( itMapOfIndicesValid = mapOfIndicesValid.begin(); itMapOfIndicesValid != mapOfIndicesValid.end(); ++itMapOfIndicesValid ) { indexLabelPred = 0; for( itMapOfIndicesPred = mapOfIndicesValid.begin(); itMapOfIndicesPred != mapOfIndicesValid.end(); ++itMapOfIndicesPred ) { // Writing the confusion matrix (sorted in otbConfusionMatrixCalculator) in the output file outFile << confusionMatrix( indexLabelValid, indexLabelPred ); if( indexLabelPred < ( nbClassesPred - 1 ) ) { outFile << separatorChar; } else { outFile << std::endl; } ++indexLabelPred; } ++indexLabelValid; } outFile.close(); } } /** * Display the log of the confusion matrix computed with * \param confMatCalc the input confusion matrix to display */ void LogConfusionMatrix(ConfusionMatrixCalculatorType *confMatCalc) { ConfusionMatrixCalculatorType::ConfusionMatrixType matrix = confMatCalc->GetConfusionMatrix(); // Compute minimal width size_t minwidth = 0; for( unsigned int i = 0; i < matrix.Rows(); i++ ) { for( unsigned int j = 0; j < matrix.Cols(); j++ ) { std::ostringstream os; os << matrix( i, j ); size_t size = os.str().size(); if( size > minwidth ) { minwidth = size; } } } MapOfIndicesType mapOfIndices = confMatCalc->GetMapOfIndices(); MapOfIndicesType::const_iterator it = mapOfIndices.begin(); MapOfIndicesType::const_iterator end = mapOfIndices.end(); for( ; it != end; ++it ) { std::ostringstream os; os << "[" << it->second << "]"; size_t size = os.str().size(); if( size > minwidth ) { minwidth = size; } } // Generate matrix string, with 'minwidth' as size specifier std::ostringstream os; // Header line for( size_t i = 0; i < minwidth; ++i ) os << " "; os << " "; it = mapOfIndices.begin(); end = mapOfIndices.end(); for( ; it != end; ++it ) { os << "[" << it->second << "]" << " "; } os << std::endl; // Each line of confusion matrix for( unsigned int i = 0; i < matrix.Rows(); i++ ) { ConfusionMatrixCalculatorType::ClassLabelType label = mapOfIndices[i]; os << "[" << std::setw( minwidth - 2 ) << label << "]" << " "; for( unsigned int j = 0; j < matrix.Cols(); j++ ) { os << std::setw( minwidth ) << matrix( i, j ) << " "; } os << std::endl; } otbAppLogINFO( "Confusion matrix (rows = reference labels, columns = produced labels):\n" << os.str() ); } }; } } OTB_APPLICATION_EXPORT( otb::Wrapper::TrainVectorClassifier ) <commit_msg>ENH: Compute and write contingency table.<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt 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 notices for more information. =========================================================================*/ #include "otbTrainVectorBase.h" // Validation #include "otbConfusionMatrixCalculator.h" #include "otbContingencyTableCalculator.h" namespace otb { namespace Wrapper { class TrainVectorClassifier : public TrainVectorBase { public: typedef TrainVectorClassifier Self; typedef TrainVectorBase Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; itkNewMacro( Self ) itkTypeMacro( Self, Superclass ) typedef Superclass::SampleType SampleType; typedef Superclass::ListSampleType ListSampleType; typedef Superclass::TargetListSampleType TargetListSampleType; // Estimate performance on validation sample typedef otb::ConfusionMatrixCalculator<TargetListSampleType, TargetListSampleType> ConfusionMatrixCalculatorType; typedef ConfusionMatrixCalculatorType::ConfusionMatrixType ConfusionMatrixType; typedef ConfusionMatrixCalculatorType::MapOfIndicesType MapOfIndicesType; typedef ConfusionMatrixCalculatorType::ClassLabelType ClassLabelType; private: void DoTrainInit() { // Nothing to do here } void DoTrainUpdateParameters() { // Nothing to do here } void DoBeforeTrainExecute() { // Enforce the need of class field name in supervised mode if (GetClassifierCategory() == Supervised) { featuresInfo.SetClassFieldNames( GetChoiceNames( "cfield" ), GetSelectedItems( "cfield" ) ); if( featuresInfo.m_SelectedCFieldIdx.empty() ) { otbAppLogFATAL( << "No field has been selected for data labelling!" ); } } } void DoAfterTrainExecute() { if (GetClassifierCategory() == Supervised) { ConfusionMatrixCalculatorType::Pointer confMatCalc = ComputeConfusionMatrix( predictedList, classificationListSamples.labeledListSample ); WriteConfusionMatrix( confMatCalc ); } else { WriteContingencyTable(); } } void WriteContingencyTable() { // Compute contingency table typedef ContingencyTableCalculator<ClassLabelType> ContigencyTableCalcutaltorType; ContigencyTableCalcutaltorType::Pointer contingencyTableCalculator = ContigencyTableCalcutaltorType::New(); contingencyTableCalculator->Compute(predictedList->Begin(), predictedList->End(), classificationListSamples.labeledListSample->Begin(), classificationListSamples.labeledListSample->End()); ContingencyTable<ClassLabelType> contingencyTable = contingencyTableCalculator->GetContingencyTable(); // Write contingency table std::ofstream outFile; outFile.open( this->GetParameterString( "io.confmatout" ).c_str() ); outFile << contingencyTable.to_csv(); } ConfusionMatrixCalculatorType::Pointer ComputeConfusionMatrix(const TargetListSampleType::Pointer &predictedListSample, const TargetListSampleType::Pointer &performanceLabeledListSample) { ConfusionMatrixCalculatorType::Pointer confMatCalc = ConfusionMatrixCalculatorType::New(); otbAppLogINFO( "Predicted list size : " << predictedListSample->Size() ); otbAppLogINFO( "ValidationLabeledListSample size : " << performanceLabeledListSample->Size() ); confMatCalc->SetReferenceLabels( performanceLabeledListSample ); confMatCalc->SetProducedLabels( predictedListSample ); confMatCalc->Compute(); otbAppLogINFO( "training performances" ); LogConfusionMatrix( confMatCalc ); for( unsigned int itClasses = 0; itClasses < confMatCalc->GetNumberOfClasses(); itClasses++ ) { ConfusionMatrixCalculatorType::ClassLabelType classLabel = confMatCalc->GetMapOfIndices()[itClasses]; otbAppLogINFO( "Precision of class [" << classLabel << "] vs all: " << confMatCalc->GetPrecisions()[itClasses] ); otbAppLogINFO( "Recall of class [" << classLabel << "] vs all: " << confMatCalc->GetRecalls()[itClasses] ); otbAppLogINFO( "F-score of class [" << classLabel << "] vs all: " << confMatCalc->GetFScores()[itClasses] << "\n" ); } otbAppLogINFO( "Global performance, Kappa index: " << confMatCalc->GetKappaIndex() ); return confMatCalc; } /** * Write the confidence matrix into a file if output is provided. * \param confMatCalc the input matrix to write. */ void WriteConfusionMatrix(const ConfusionMatrixCalculatorType::Pointer &confMatCalc) { if( this->HasValue( "io.confmatout" ) ) { // Writing the confusion matrix in the output .CSV file MapOfIndicesType::iterator itMapOfIndicesValid, itMapOfIndicesPred; ClassLabelType labelValid = 0; ConfusionMatrixType confusionMatrix = confMatCalc->GetConfusionMatrix(); MapOfIndicesType mapOfIndicesValid = confMatCalc->GetMapOfIndices(); unsigned long nbClassesPred = mapOfIndicesValid.size(); ///////////////////////////////////////////// // Filling the 2 headers for the output file const std::string commentValidStr = "#Reference labels (rows):"; const std::string commentPredStr = "#Produced labels (columns):"; const char separatorChar = ','; std::ostringstream ossHeaderValidLabels, ossHeaderPredLabels; // Filling ossHeaderValidLabels and ossHeaderPredLabels for the output file ossHeaderValidLabels << commentValidStr; ossHeaderPredLabels << commentPredStr; itMapOfIndicesValid = mapOfIndicesValid.begin(); while( itMapOfIndicesValid != mapOfIndicesValid.end() ) { // labels labelValid of mapOfIndicesValid are already sorted in otbConfusionMatrixCalculator labelValid = itMapOfIndicesValid->second; otbAppLogINFO( "mapOfIndicesValid[" << itMapOfIndicesValid->first << "] = " << labelValid ); ossHeaderValidLabels << labelValid; ossHeaderPredLabels << labelValid; ++itMapOfIndicesValid; if( itMapOfIndicesValid != mapOfIndicesValid.end() ) { ossHeaderValidLabels << separatorChar; ossHeaderPredLabels << separatorChar; } else { ossHeaderValidLabels << std::endl; ossHeaderPredLabels << std::endl; } } std::ofstream outFile; outFile.open( this->GetParameterString( "io.confmatout" ).c_str() ); outFile << std::fixed; outFile.precision( 10 ); ///////////////////////////////////// // Writing the 2 headers outFile << ossHeaderValidLabels.str(); outFile << ossHeaderPredLabels.str(); ///////////////////////////////////// unsigned int indexLabelValid = 0, indexLabelPred = 0; for( itMapOfIndicesValid = mapOfIndicesValid.begin(); itMapOfIndicesValid != mapOfIndicesValid.end(); ++itMapOfIndicesValid ) { indexLabelPred = 0; for( itMapOfIndicesPred = mapOfIndicesValid.begin(); itMapOfIndicesPred != mapOfIndicesValid.end(); ++itMapOfIndicesPred ) { // Writing the confusion matrix (sorted in otbConfusionMatrixCalculator) in the output file outFile << confusionMatrix( indexLabelValid, indexLabelPred ); if( indexLabelPred < ( nbClassesPred - 1 ) ) { outFile << separatorChar; } else { outFile << std::endl; } ++indexLabelPred; } ++indexLabelValid; } outFile.close(); } } /** * Display the log of the confusion matrix computed with * \param confMatCalc the input confusion matrix to display */ void LogConfusionMatrix(ConfusionMatrixCalculatorType *confMatCalc) { ConfusionMatrixCalculatorType::ConfusionMatrixType matrix = confMatCalc->GetConfusionMatrix(); // Compute minimal width size_t minwidth = 0; for( unsigned int i = 0; i < matrix.Rows(); i++ ) { for( unsigned int j = 0; j < matrix.Cols(); j++ ) { std::ostringstream os; os << matrix( i, j ); size_t size = os.str().size(); if( size > minwidth ) { minwidth = size; } } } MapOfIndicesType mapOfIndices = confMatCalc->GetMapOfIndices(); MapOfIndicesType::const_iterator it = mapOfIndices.begin(); MapOfIndicesType::const_iterator end = mapOfIndices.end(); for( ; it != end; ++it ) { std::ostringstream os; os << "[" << it->second << "]"; size_t size = os.str().size(); if( size > minwidth ) { minwidth = size; } } // Generate matrix string, with 'minwidth' as size specifier std::ostringstream os; // Header line for( size_t i = 0; i < minwidth; ++i ) os << " "; os << " "; it = mapOfIndices.begin(); end = mapOfIndices.end(); for( ; it != end; ++it ) { os << "[" << it->second << "]" << " "; } os << std::endl; // Each line of confusion matrix for( unsigned int i = 0; i < matrix.Rows(); i++ ) { ConfusionMatrixCalculatorType::ClassLabelType label = mapOfIndices[i]; os << "[" << std::setw( minwidth - 2 ) << label << "]" << " "; for( unsigned int j = 0; j < matrix.Cols(); j++ ) { os << std::setw( minwidth ) << matrix( i, j ) << " "; } os << std::endl; } otbAppLogINFO( "Confusion matrix (rows = reference labels, columns = produced labels):\n" << os.str() ); } }; } } OTB_APPLICATION_EXPORT( otb::Wrapper::TrainVectorClassifier ) <|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt 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 notices for more information. =========================================================================*/ #include "otbImage.h" #include "otbImageToNoDataMaskFilter.h" #include "itkImageRegionIterator.h" int otbImageToNoDataMaskFilter(int itkNotUsed(argc),char * itkNotUsed(argv) []) { // Build an image typedef otb::Image<double> ImageType; ImageType::Pointer img = ImageType::New(); ImageType::SizeType size; size.Fill(20); ImageType::RegionType region; region.SetSize(size); // Fill it with a default value img->SetRegions(region); img->Allocate(); img->FillBuffer(10); // Write no-data flags to it std::vector<bool> flags(1,true); std::vector<double> values(1,-10.); otb::WriteNoDataFlags(flags,values,img->GetMetaDataDictionary()); // Fill half of the pixels with no-data values itk::ImageRegionIterator<ImageType> it(img,region); unsigned int count = 0; for(it.GoToBegin();!it.IsAtEnd();++it,++count) { if (count%2 == 0) it.Set(-10.); } // Instanciate filter typedef otb::ImageToNoDataMaskFilter<ImageType,ImageType> FilterType; FilterType::Pointer filter = FilterType::New(); filter->SetInput(img); filter->SetInsideValue(255); filter->SetOutsideValue(0); filter->Update(); // Check output it = itk::ImageRegionIterator<ImageType>(filter->GetOutput(),region); count = 0; bool failed = false; for(it.GoToBegin();!it.IsAtEnd();++it,++count) { if (count%2 == 0 and it.Get()!=0) { std::cerr<<"Pixel should be masked"<<std::endl; failed = true; } else if(count%2 == 1 and it.Get()!=255) { std::cerr<<"Pixel should not be masked"<<std::endl; failed = true; } } if(failed) return EXIT_FAILURE; return EXIT_SUCCESS; } <commit_msg>COMP: replace and by && for win32<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt 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 notices for more information. =========================================================================*/ #include "otbImage.h" #include "otbImageToNoDataMaskFilter.h" #include "itkImageRegionIterator.h" int otbImageToNoDataMaskFilter(int itkNotUsed(argc),char * itkNotUsed(argv) []) { // Build an image typedef otb::Image<double> ImageType; ImageType::Pointer img = ImageType::New(); ImageType::SizeType size; size.Fill(20); ImageType::RegionType region; region.SetSize(size); // Fill it with a default value img->SetRegions(region); img->Allocate(); img->FillBuffer(10); // Write no-data flags to it std::vector<bool> flags(1,true); std::vector<double> values(1,-10.); otb::WriteNoDataFlags(flags,values,img->GetMetaDataDictionary()); // Fill half of the pixels with no-data values itk::ImageRegionIterator<ImageType> it(img,region); unsigned int count = 0; for(it.GoToBegin();!it.IsAtEnd();++it,++count) { if (count%2 == 0) it.Set(-10.); } // Instanciate filter typedef otb::ImageToNoDataMaskFilter<ImageType,ImageType> FilterType; FilterType::Pointer filter = FilterType::New(); filter->SetInput(img); filter->SetInsideValue(255); filter->SetOutsideValue(0); filter->Update(); // Check output it = itk::ImageRegionIterator<ImageType>(filter->GetOutput(),region); count = 0; bool failed = false; for(it.GoToBegin();!it.IsAtEnd();++it,++count) { if (count%2 == 0 && it.Get()!=0) { std::cerr<<"Pixel should be masked"<<std::endl; failed = true; } else if(count%2 == 1 && it.Get()!=255) { std::cerr<<"Pixel should not be masked"<<std::endl; failed = true; } } if(failed) return EXIT_FAILURE; return EXIT_SUCCESS; } <|endoftext|>
<commit_before> #include "SchedulingManagerFactory.h" #include "TimeWarpEventSetFactory.h" #include "TimeWarpSimulationManager.h" #include "SimulationConfiguration.h" #include "SchedulingManager.h" #include "DefaultSchedulingManager.h" #include "TimeWarpMultiSetSchedulingManager.h" #include <WarpedDebug.h> /* #if USE_TIMEWARP #include "threadedtimewarp/ThreadedTimeWarpSimulationManager.h" #include "threadedtimewarp/ThreadedSchedulingManager.h" #endif */ #include "ThreadedTimeWarpSimulationManager.h" #include "ThreadedTimeWarpMultiSetSchedulingManager.h" using std::cerr; using std::endl; SchedulingManagerFactory::SchedulingManagerFactory(){} SchedulingManagerFactory::~SchedulingManagerFactory(){ // myScheduler will be deleted by the end user - the // TimeWarpSimulationManager } Configurable * SchedulingManagerFactory::allocate( SimulationConfiguration &configuration, Configurable *parent ) const { SchedulingManager *retval = 0; std::string simulationType = configuration.get_string({"Simulation"}, "Sequential"); std::string schedulerType = configuration.get_string({"TimeWarp", "Scheduler", "Type"}, "Default"); if(schedulerType == "MultiSet"){ TimeWarpSimulationManager *mySimulationManager = dynamic_cast<TimeWarpSimulationManager *>( parent ); ASSERT(mySimulationManager!=0); retval = new TimeWarpMultiSetSchedulingManager( mySimulationManager ); debug::debugout << " a TimeWarpMultiSetSchedulingManager." << endl; } else { dynamic_cast<TimeWarpSimulationManager *>(parent)->shutdown( "Unknown SCHEDULER choice \"" + schedulerType + "\"" ); } #if USE_TIMEWARP if (simulationType == "ThreadedTimeWarp") { if (schedulerType == "MultiSet") { ThreadedTimeWarpSimulationManager *mySimulationManager = dynamic_cast<ThreadedTimeWarpSimulationManager *> (parent); ASSERT(mySimulationManager!=0); retval = new ThreadedTimeWarpMultiSetSchedulingManager(mySimulationManager); debug::debugout << " a Threaded TimeWarpMultiSetSchedulingManager." << endl; } else { dynamic_cast<TimeWarpSimulationManager *> (parent)->shutdown( "Unknown SCHEDULER choice \"" + schedulerType + "\""); } } #endif return retval; } const SchedulingManagerFactory * SchedulingManagerFactory::instance(){ static SchedulingManagerFactory *singleton = new SchedulingManagerFactory(); return singleton; } <commit_msg>Removed USE_TIMEWARP macro usage<commit_after> #include "SchedulingManagerFactory.h" #include "TimeWarpEventSetFactory.h" #include "TimeWarpSimulationManager.h" #include "SimulationConfiguration.h" #include "SchedulingManager.h" #include "DefaultSchedulingManager.h" #include "TimeWarpMultiSetSchedulingManager.h" #include <WarpedDebug.h> #include "ThreadedTimeWarpSimulationManager.h" #include "ThreadedTimeWarpMultiSetSchedulingManager.h" using std::cerr; using std::endl; SchedulingManagerFactory::SchedulingManagerFactory(){} SchedulingManagerFactory::~SchedulingManagerFactory(){ // myScheduler will be deleted by the end user - the // TimeWarpSimulationManager } Configurable * SchedulingManagerFactory::allocate( SimulationConfiguration &configuration, Configurable *parent ) const { SchedulingManager *retval = 0; std::string simulationType = configuration.get_string({"Simulation"}, "Sequential"); std::string schedulerType = configuration.get_string({"TimeWarp", "Scheduler", "Type"}, "Default"); if(schedulerType == "MultiSet"){ TimeWarpSimulationManager *mySimulationManager = dynamic_cast<TimeWarpSimulationManager *>( parent ); ASSERT(mySimulationManager!=0); retval = new TimeWarpMultiSetSchedulingManager( mySimulationManager ); debug::debugout << " a TimeWarpMultiSetSchedulingManager." << endl; } else { dynamic_cast<TimeWarpSimulationManager *>(parent)->shutdown( "Unknown SCHEDULER choice \"" + schedulerType + "\"" ); } if (simulationType == "ThreadedTimeWarp") { if (schedulerType == "MultiSet") { ThreadedTimeWarpSimulationManager *mySimulationManager = dynamic_cast<ThreadedTimeWarpSimulationManager *> (parent); ASSERT(mySimulationManager!=0); retval = new ThreadedTimeWarpMultiSetSchedulingManager(mySimulationManager); debug::debugout << " a Threaded TimeWarpMultiSetSchedulingManager." << endl; } else { dynamic_cast<TimeWarpSimulationManager *> (parent)->shutdown( "Unknown SCHEDULER choice \"" + schedulerType + "\""); } } return retval; } const SchedulingManagerFactory * SchedulingManagerFactory::instance(){ static SchedulingManagerFactory *singleton = new SchedulingManagerFactory(); return singleton; } <|endoftext|>
<commit_before>#include "nxtKitInterpreterPlugin.h" #include <QtWidgets/QApplication> #include <twoDModel/engine/twoDModelEngineFacade.h> using namespace nxt; using namespace qReal; const Id robotDiagramType = Id("RobotsMetamodel", "RobotsDiagram", "RobotsDiagramNode"); const Id subprogramDiagramType = Id("RobotsMetamodel", "RobotsDiagram", "SubprogramDiagram"); NxtKitInterpreterPlugin::NxtKitInterpreterPlugin() : mUsbRealRobotModel(kitId(), "nxtKitUsbRobot") // todo: somewhere generate robotId for each robot , mBluetoothRealRobotModel(kitId(), "nxtKitBluetoothRobot") , mTwoDRobotModel(mUsbRealRobotModel) , mBlocksFactory(new blocks::NxtBlocksFactory) { mAdditionalPreferences = new NxtAdditionalPreferences(mBluetoothRealRobotModel.name()); auto modelEngine = new twoDModel::engine::TwoDModelEngineFacade(mTwoDRobotModel); mTwoDRobotModel.setEngine(modelEngine->engine()); mTwoDModel.reset(modelEngine); connect(mAdditionalPreferences, &NxtAdditionalPreferences::settingsChanged , &mUsbRealRobotModel, &robotModel::real::RealRobotModel::rereadSettings); connect(mAdditionalPreferences, &NxtAdditionalPreferences::settingsChanged , &mBluetoothRealRobotModel, &robotModel::real::RealRobotModel::rereadSettings); connect(mAdditionalPreferences, &NxtAdditionalPreferences::settingsChanged , &mTwoDRobotModel, &robotModel::twoD::TwoDRobotModel::rereadSettings); } NxtKitInterpreterPlugin::~NxtKitInterpreterPlugin() { if (mOwnsAdditionalPreferences) { delete mAdditionalPreferences; } if (mOwnsBlocksFactory) { delete mBlocksFactory; } } void NxtKitInterpreterPlugin::init(const kitBase::KitPluginConfigurator &configurator) { connect(&configurator.eventsForKitPlugin(), &kitBase::EventsForKitPluginInterface::robotModelChanged , [this](const QString &modelName) { mCurrentlySelectedModelName = modelName; }); connect(&configurator.qRealConfigurator().systemEvents(), &qReal::SystemEvents::activeTabChanged , this, &NxtKitInterpreterPlugin::onActiveTabChanged); qReal::gui::MainWindowInterpretersInterface &interpretersInterface = configurator.qRealConfigurator().mainWindowInterpretersInterface(); connect(&mUsbRealRobotModel, &robotModel::real::RealRobotModel::errorOccured , [&interpretersInterface](const QString &message) { interpretersInterface.errorReporter()->addError(message); }); connect(&mBluetoothRealRobotModel, &robotModel::real::RealRobotModel::errorOccured , [&interpretersInterface](const QString &message) { interpretersInterface.errorReporter()->addError(message); }); mUsbRealRobotModel.checkConnection(); mBluetoothRealRobotModel.checkConnection(); mTwoDModel->init(configurator.eventsForKitPlugin() , configurator.qRealConfigurator().systemEvents() , configurator.qRealConfigurator().graphicalModelApi() , configurator.qRealConfigurator().logicalModelApi() , interpretersInterface , configurator.interpreterControl()); } QString NxtKitInterpreterPlugin::kitId() const { return "nxtKit"; } QString NxtKitInterpreterPlugin::friendlyKitName() const { return tr("Lego NXT"); } QList<kitBase::robotModel::RobotModelInterface *> NxtKitInterpreterPlugin::robotModels() { return {&mUsbRealRobotModel, &mBluetoothRealRobotModel, &mTwoDRobotModel}; } kitBase::blocksBase::BlocksFactoryInterface *NxtKitInterpreterPlugin::blocksFactoryFor( const kitBase::robotModel::RobotModelInterface *model) { Q_UNUSED(model); mOwnsBlocksFactory = false; return mBlocksFactory; } kitBase::robotModel::RobotModelInterface *NxtKitInterpreterPlugin::defaultRobotModel() { return &mTwoDRobotModel; } QList<kitBase::AdditionalPreferences *> NxtKitInterpreterPlugin::settingsWidgets() { mOwnsAdditionalPreferences = false; return {mAdditionalPreferences}; } QList<qReal::ActionInfo> NxtKitInterpreterPlugin::customActions() { return { mTwoDModel->showTwoDModelWidgetActionInfo() }; } QList<HotKeyActionInfo> NxtKitInterpreterPlugin::hotKeyActions() { mTwoDModel->showTwoDModelWidgetActionInfo().action()->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_2)); HotKeyActionInfo d2ModelActionInfo("Interpreter.Show2dModelForNxt", tr("Show 2d model") , mTwoDModel->showTwoDModelWidgetActionInfo().action()); return { d2ModelActionInfo }; } QString NxtKitInterpreterPlugin::defaultSettingsFile() const { return ":/nxtDefaultSettings.ini"; } QIcon NxtKitInterpreterPlugin::iconForFastSelector( const kitBase::robotModel::RobotModelInterface &robotModel) const { return &robotModel == &mUsbRealRobotModel ? QIcon(":/icons/switch-real-nxt-usb.svg") : &robotModel == &mBluetoothRealRobotModel ? QIcon(":/icons/switch-real-nxt-bluetooth.svg") : QIcon(":/icons/switch-2d.svg"); } kitBase::DevicesConfigurationProvider * NxtKitInterpreterPlugin::devicesConfigurationProvider() { return &mTwoDModel->devicesConfigurationProvider(); } void NxtKitInterpreterPlugin::onActiveTabChanged(const TabInfo &info) { const Id type = info.rootDiagramId().type(); const bool enabled = type == robotDiagramType || type == subprogramDiagramType && mCurrentlySelectedModelName == mTwoDRobotModel.name(); mTwoDModel->showTwoDModelWidgetActionInfo().action()->setVisible(enabled); } <commit_msg>Fixed extra NXT 2D model action visible in all modes<commit_after>#include "nxtKitInterpreterPlugin.h" #include <QtWidgets/QApplication> #include <twoDModel/engine/twoDModelEngineFacade.h> using namespace nxt; using namespace qReal; const Id robotDiagramType = Id("RobotsMetamodel", "RobotsDiagram", "RobotsDiagramNode"); const Id subprogramDiagramType = Id("RobotsMetamodel", "RobotsDiagram", "SubprogramDiagram"); NxtKitInterpreterPlugin::NxtKitInterpreterPlugin() : mUsbRealRobotModel(kitId(), "nxtKitUsbRobot") // todo: somewhere generate robotId for each robot , mBluetoothRealRobotModel(kitId(), "nxtKitBluetoothRobot") , mTwoDRobotModel(mUsbRealRobotModel) , mBlocksFactory(new blocks::NxtBlocksFactory) { mAdditionalPreferences = new NxtAdditionalPreferences(mBluetoothRealRobotModel.name()); auto modelEngine = new twoDModel::engine::TwoDModelEngineFacade(mTwoDRobotModel); mTwoDRobotModel.setEngine(modelEngine->engine()); mTwoDModel.reset(modelEngine); connect(mAdditionalPreferences, &NxtAdditionalPreferences::settingsChanged , &mUsbRealRobotModel, &robotModel::real::RealRobotModel::rereadSettings); connect(mAdditionalPreferences, &NxtAdditionalPreferences::settingsChanged , &mBluetoothRealRobotModel, &robotModel::real::RealRobotModel::rereadSettings); connect(mAdditionalPreferences, &NxtAdditionalPreferences::settingsChanged , &mTwoDRobotModel, &robotModel::twoD::TwoDRobotModel::rereadSettings); } NxtKitInterpreterPlugin::~NxtKitInterpreterPlugin() { if (mOwnsAdditionalPreferences) { delete mAdditionalPreferences; } if (mOwnsBlocksFactory) { delete mBlocksFactory; } } void NxtKitInterpreterPlugin::init(const kitBase::KitPluginConfigurator &configurator) { connect(&configurator.eventsForKitPlugin(), &kitBase::EventsForKitPluginInterface::robotModelChanged , [this](const QString &modelName) { mCurrentlySelectedModelName = modelName; }); connect(&configurator.qRealConfigurator().systemEvents(), &qReal::SystemEvents::activeTabChanged , this, &NxtKitInterpreterPlugin::onActiveTabChanged); qReal::gui::MainWindowInterpretersInterface &interpretersInterface = configurator.qRealConfigurator().mainWindowInterpretersInterface(); connect(&mUsbRealRobotModel, &robotModel::real::RealRobotModel::errorOccured , [&interpretersInterface](const QString &message) { interpretersInterface.errorReporter()->addError(message); }); connect(&mBluetoothRealRobotModel, &robotModel::real::RealRobotModel::errorOccured , [&interpretersInterface](const QString &message) { interpretersInterface.errorReporter()->addError(message); }); mUsbRealRobotModel.checkConnection(); mBluetoothRealRobotModel.checkConnection(); mTwoDModel->init(configurator.eventsForKitPlugin() , configurator.qRealConfigurator().systemEvents() , configurator.qRealConfigurator().graphicalModelApi() , configurator.qRealConfigurator().logicalModelApi() , interpretersInterface , configurator.interpreterControl()); } QString NxtKitInterpreterPlugin::kitId() const { return "nxtKit"; } QString NxtKitInterpreterPlugin::friendlyKitName() const { return tr("Lego NXT"); } QList<kitBase::robotModel::RobotModelInterface *> NxtKitInterpreterPlugin::robotModels() { return {&mUsbRealRobotModel, &mBluetoothRealRobotModel, &mTwoDRobotModel}; } kitBase::blocksBase::BlocksFactoryInterface *NxtKitInterpreterPlugin::blocksFactoryFor( const kitBase::robotModel::RobotModelInterface *model) { Q_UNUSED(model); mOwnsBlocksFactory = false; return mBlocksFactory; } kitBase::robotModel::RobotModelInterface *NxtKitInterpreterPlugin::defaultRobotModel() { return &mTwoDRobotModel; } QList<kitBase::AdditionalPreferences *> NxtKitInterpreterPlugin::settingsWidgets() { mOwnsAdditionalPreferences = false; return {mAdditionalPreferences}; } QList<qReal::ActionInfo> NxtKitInterpreterPlugin::customActions() { return { mTwoDModel->showTwoDModelWidgetActionInfo() }; } QList<HotKeyActionInfo> NxtKitInterpreterPlugin::hotKeyActions() { mTwoDModel->showTwoDModelWidgetActionInfo().action()->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_2)); HotKeyActionInfo d2ModelActionInfo("Interpreter.Show2dModelForNxt", tr("Show 2d model") , mTwoDModel->showTwoDModelWidgetActionInfo().action()); return { d2ModelActionInfo }; } QString NxtKitInterpreterPlugin::defaultSettingsFile() const { return ":/nxtDefaultSettings.ini"; } QIcon NxtKitInterpreterPlugin::iconForFastSelector( const kitBase::robotModel::RobotModelInterface &robotModel) const { return &robotModel == &mUsbRealRobotModel ? QIcon(":/icons/switch-real-nxt-usb.svg") : &robotModel == &mBluetoothRealRobotModel ? QIcon(":/icons/switch-real-nxt-bluetooth.svg") : QIcon(":/icons/switch-2d.svg"); } kitBase::DevicesConfigurationProvider * NxtKitInterpreterPlugin::devicesConfigurationProvider() { return &mTwoDModel->devicesConfigurationProvider(); } void NxtKitInterpreterPlugin::onActiveTabChanged(const TabInfo &info) { const Id type = info.rootDiagramId().type(); const bool enabled = (type == robotDiagramType || type == subprogramDiagramType) && mCurrentlySelectedModelName == mTwoDRobotModel.name(); mTwoDModel->showTwoDModelWidgetActionInfo().action()->setVisible(enabled); } <|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkImageStatisticsWidget.h" #include "QmitkTableModelToStringConverter.h" #include "QmitkImageStatisticsTreeModel.h" #include <QSortFilterProxyModel> #include <QClipboard> QmitkImageStatisticsWidget::QmitkImageStatisticsWidget(QWidget* parent) : QWidget(parent) { m_Controls.setupUi(this); m_imageStatisticsModel = new QmitkImageStatisticsTreeModel(parent); CreateConnections(); m_ProxyModel = new QSortFilterProxyModel(this); m_Controls.treeViewStatistics->setEnabled(false); m_Controls.treeViewStatistics->setModel(m_ProxyModel); m_ProxyModel->setSourceModel(m_imageStatisticsModel); connect(m_imageStatisticsModel, &QmitkImageStatisticsTreeModel::dataAvailable, this, &QmitkImageStatisticsWidget::OnDataAvailable); } void QmitkImageStatisticsWidget::SetDataStorage(mitk::DataStorage* newDataStorage) { m_imageStatisticsModel->SetDataStorage(newDataStorage); } void QmitkImageStatisticsWidget::SetImageNodes(const std::vector<mitk::DataNode::ConstPointer>& nodes) { m_imageStatisticsModel->SetImageNodes(nodes); } void QmitkImageStatisticsWidget::SetMaskNodes(const std::vector<mitk::DataNode::ConstPointer>& nodes) { m_imageStatisticsModel->SetMaskNodes(nodes); } void QmitkImageStatisticsWidget::Reset() { m_imageStatisticsModel->Clear(); m_Controls.treeViewStatistics->setEnabled(false); m_Controls.buttonCopyImageStatisticsToClipboard->setEnabled(false); } void QmitkImageStatisticsWidget::CreateConnections() { connect(m_Controls.buttonCopyImageStatisticsToClipboard, &QPushButton::clicked, this, &QmitkImageStatisticsWidget::OnClipboardButtonClicked); } void QmitkImageStatisticsWidget::OnDataAvailable() { m_Controls.buttonCopyImageStatisticsToClipboard->setEnabled(true); m_Controls.treeViewStatistics->setEnabled(true); } void QmitkImageStatisticsWidget::OnClipboardButtonClicked() { QmitkTableModelToStringConverter converter; converter.SetTableModel(m_imageStatisticsModel); converter.SetIncludeHeaderData(true); converter.SetColumnDelimiter('\t'); QString clipboardAsString = converter.GetString(); QApplication::clipboard()->setText(clipboardAsString, QClipboard::Clipboard); } <commit_msg>auto expand by default after loading<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkImageStatisticsWidget.h" #include "QmitkTableModelToStringConverter.h" #include "QmitkImageStatisticsTreeModel.h" #include <QSortFilterProxyModel> #include <QClipboard> QmitkImageStatisticsWidget::QmitkImageStatisticsWidget(QWidget* parent) : QWidget(parent) { m_Controls.setupUi(this); m_imageStatisticsModel = new QmitkImageStatisticsTreeModel(parent); CreateConnections(); m_ProxyModel = new QSortFilterProxyModel(this); m_Controls.treeViewStatistics->setEnabled(false); m_Controls.treeViewStatistics->setModel(m_ProxyModel); m_ProxyModel->setSourceModel(m_imageStatisticsModel); connect(m_imageStatisticsModel, &QmitkImageStatisticsTreeModel::dataAvailable, this, &QmitkImageStatisticsWidget::OnDataAvailable); connect(m_imageStatisticsModel, &QmitkImageStatisticsTreeModel::modelChanged, m_Controls.treeViewStatistics, &QTreeView::expandAll); } void QmitkImageStatisticsWidget::SetDataStorage(mitk::DataStorage* newDataStorage) { m_imageStatisticsModel->SetDataStorage(newDataStorage); } void QmitkImageStatisticsWidget::SetImageNodes(const std::vector<mitk::DataNode::ConstPointer>& nodes) { m_imageStatisticsModel->SetImageNodes(nodes); } void QmitkImageStatisticsWidget::SetMaskNodes(const std::vector<mitk::DataNode::ConstPointer>& nodes) { m_imageStatisticsModel->SetMaskNodes(nodes); } void QmitkImageStatisticsWidget::Reset() { m_imageStatisticsModel->Clear(); m_Controls.treeViewStatistics->setEnabled(false); m_Controls.buttonCopyImageStatisticsToClipboard->setEnabled(false); } void QmitkImageStatisticsWidget::CreateConnections() { connect(m_Controls.buttonCopyImageStatisticsToClipboard, &QPushButton::clicked, this, &QmitkImageStatisticsWidget::OnClipboardButtonClicked); } void QmitkImageStatisticsWidget::OnDataAvailable() { m_Controls.buttonCopyImageStatisticsToClipboard->setEnabled(true); m_Controls.treeViewStatistics->setEnabled(true); } void QmitkImageStatisticsWidget::OnClipboardButtonClicked() { QmitkTableModelToStringConverter converter; converter.SetTableModel(m_imageStatisticsModel); converter.SetIncludeHeaderData(true); converter.SetColumnDelimiter('\t'); QString clipboardAsString = converter.GetString(); QApplication::clipboard()->setText(clipboardAsString, QClipboard::Clipboard); } <|endoftext|>
<commit_before>// faster alternative to PPTrajectory.eval() in Matlab // Michael Kaess, June 2013 #include <mex.h> #include <Eigen/Dense> #include <unsupported/Eigen/MatrixFunctions> #include <vector> #include <iostream> using namespace Eigen; using namespace std; // Initialization: // obj = PPTmex(breaks,coefs,order,dims) // Evaluation: // y = PPTmex(obj, 1, t) // // t: 1 single evaluation point // // breaks: n+1 // coefs: nxd1xd2 x p // order: 1 p // dims: 2 d1,d2 // // y: p class PPTrajectory { private: VectorXd m_breaks; MatrixXd m_coefs; const int m_d1, m_d2, m_order; int m_cached_idx; public: PPTrajectory(const VectorXd& breaks, const MatrixXd& coefs, int order, int d1, int d2) : m_breaks(breaks), m_coefs(coefs), m_order(order), m_d1(d1), m_d2(d2), m_cached_idx(-1) {} int d1() { return m_d1; } int d2() { return m_d2; } void eval(double t, Map<MatrixXd>& y) { if (t<m_breaks(0)) t=m_breaks(0); if (t>m_breaks(m_breaks.rows()-1)) t=m_breaks(m_breaks.rows()-1); Map<VectorXd> r(y.data(), m_d1*m_d2); // reshape // use cached index if possible int idx; if (m_cached_idx >= 0 && m_cached_idx < m_breaks.rows() // valid m_cached_idx? && t < m_breaks[m_cached_idx+1] // still in same interval? && ((m_cached_idx == 0) || (t >= m_breaks[m_cached_idx]))) { // left up to -infinity idx = m_cached_idx; } else { // search for the correct interval // todo: binary search for (int b=static_cast<int>(m_breaks.rows())-2; b>=1; b--) { // ignore first and last break if (t < m_breaks(b)) idx=b-1; } m_cached_idx = idx; } int base = idx*m_d1*m_d2; double local = t - m_breaks[idx]; r = m_coefs.block(base, 0, m_d1*m_d2, 1); for (int i=2; i<=m_order; i++) { r = local*r + m_coefs.block(base, i-1, m_d1*m_d2, 1); } } }; void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { if (nrhs == 4 && nlhs == 1) { // create object Map<VectorXd> breaks(mxGetPr(prhs[0]), mxGetNumberOfElements(prhs[0])); Map<MatrixXd> coefs(mxGetPr(prhs[1]), mxGetM(prhs[1]), mxGetN(prhs[1])); int order = static_cast<int>(mxGetScalar(prhs[2])); Map<VectorXd> dims(mxGetPr(prhs[3]), mxGetNumberOfElements(prhs[3])); int d1 = static_cast<int>(dims(0)); int d2 = 1; if (dims.rows() > 1) d2 = static_cast<int>(dims(1)); PPTrajectory *ppt = new PPTrajectory(breaks, coefs, order, d1, d2); mxClassID cid; if (sizeof(ppt)==4) cid = mxUINT32_CLASS; else if (sizeof(ppt)==8) cid = mxUINT64_CLASS; else mexErrMsgIdAndTxt("Drake:PPTmex:PointerSize","Are you on a 32-bit machine or 64-bit machine??"); plhs[0] = mxCreateNumericMatrix(1,1,cid,mxREAL); memcpy(mxGetData(plhs[0]),&ppt,sizeof(ppt)); } else { // retrieve object PPTrajectory *ppt = NULL; if (nrhs==0 || !mxIsNumeric(prhs[0]) || mxGetNumberOfElements(prhs[0])!=1) mexErrMsgIdAndTxt("Drake:PPTmex:BadInputs","the first argument should be the mex_ptr"); memcpy(&ppt,mxGetData(prhs[0]),sizeof(ppt)); if (nrhs == 1) { // delete object delete ppt; } else { // eval() function call if (nrhs < 2) { mexErrMsgIdAndTxt("Drake:PPTmex:WrongNumberOfInputs","Usage obj = PPTmex(breaks,coefs,order,dims) or y = PPTmex(obj,t)"); } double *command = mxGetPr(prhs[1]); switch ((int)(*command)) { case 1: { // eval double *t = mxGetPr(prhs[2]); int d1 = ppt->d1(); int d2 = ppt->d2(); plhs[0] = mxCreateDoubleMatrix(d1,d2,mxREAL); Map<MatrixXd> y(mxGetPr(plhs[0]),d1,d2); ppt->eval(*t, y); break; } default: mexErrMsgIdAndTxt("Drake:PPTmex:UnknownCommand","Check arguments"); } } } } <commit_msg>not sure how this line got zapped...<commit_after>// faster alternative to PPTrajectory.eval() in Matlab // Michael Kaess, June 2013 #include <mex.h> #include <Eigen/Dense> #include <unsupported/Eigen/MatrixFunctions> #include <vector> #include <iostream> using namespace Eigen; using namespace std; // Initialization: // obj = PPTmex(breaks,coefs,order,dims) // Evaluation: // y = PPTmex(obj, 1, t) // // t: 1 single evaluation point // // breaks: n+1 // coefs: nxd1xd2 x p // order: 1 p // dims: 2 d1,d2 // // y: p class PPTrajectory { private: VectorXd m_breaks; MatrixXd m_coefs; const int m_d1, m_d2, m_order; int m_cached_idx; public: PPTrajectory(const VectorXd& breaks, const MatrixXd& coefs, int order, int d1, int d2) : m_breaks(breaks), m_coefs(coefs), m_order(order), m_d1(d1), m_d2(d2), m_cached_idx(-1) {} int d1() { return m_d1; } int d2() { return m_d2; } void eval(double t, Map<MatrixXd>& y) { if (t<m_breaks(0)) t=m_breaks(0); if (t>m_breaks(m_breaks.rows()-1)) t=m_breaks(m_breaks.rows()-1); Map<VectorXd> r(y.data(), m_d1*m_d2); // reshape // use cached index if possible int idx; if (m_cached_idx >= 0 && m_cached_idx < m_breaks.rows() // valid m_cached_idx? && t < m_breaks[m_cached_idx+1] // still in same interval? && ((m_cached_idx == 0) || (t >= m_breaks[m_cached_idx]))) { // left up to -infinity idx = m_cached_idx; } else { // search for the correct interval idx = m_breaks.rows()-2; // todo: binary search for (int b=static_cast<int>(m_breaks.rows())-2; b>=1; b--) { // ignore first and last break if (t < m_breaks(b)) idx=b-1; } m_cached_idx = idx; } int base = idx*m_d1*m_d2; double local = t - m_breaks[idx]; r = m_coefs.block(base, 0, m_d1*m_d2, 1); for (int i=2; i<=m_order; i++) { r = local*r + m_coefs.block(base, i-1, m_d1*m_d2, 1); } } }; void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { if (nrhs == 4 && nlhs == 1) { // create object Map<VectorXd> breaks(mxGetPr(prhs[0]), mxGetNumberOfElements(prhs[0])); Map<MatrixXd> coefs(mxGetPr(prhs[1]), mxGetM(prhs[1]), mxGetN(prhs[1])); int order = static_cast<int>(mxGetScalar(prhs[2])); Map<VectorXd> dims(mxGetPr(prhs[3]), mxGetNumberOfElements(prhs[3])); int d1 = static_cast<int>(dims(0)); int d2 = 1; if (dims.rows() > 1) d2 = static_cast<int>(dims(1)); PPTrajectory *ppt = new PPTrajectory(breaks, coefs, order, d1, d2); mxClassID cid; if (sizeof(ppt)==4) cid = mxUINT32_CLASS; else if (sizeof(ppt)==8) cid = mxUINT64_CLASS; else mexErrMsgIdAndTxt("Drake:PPTmex:PointerSize","Are you on a 32-bit machine or 64-bit machine??"); plhs[0] = mxCreateNumericMatrix(1,1,cid,mxREAL); memcpy(mxGetData(plhs[0]),&ppt,sizeof(ppt)); } else { // retrieve object PPTrajectory *ppt = NULL; if (nrhs==0 || !mxIsNumeric(prhs[0]) || mxGetNumberOfElements(prhs[0])!=1) mexErrMsgIdAndTxt("Drake:PPTmex:BadInputs","the first argument should be the mex_ptr"); memcpy(&ppt,mxGetData(prhs[0]),sizeof(ppt)); if (nrhs == 1) { // delete object delete ppt; } else { // eval() function call if (nrhs < 2) { mexErrMsgIdAndTxt("Drake:PPTmex:WrongNumberOfInputs","Usage obj = PPTmex(breaks,coefs,order,dims) or y = PPTmex(obj,t)"); } double *command = mxGetPr(prhs[1]); switch ((int)(*command)) { case 1: { // eval double *t = mxGetPr(prhs[2]); int d1 = ppt->d1(); int d2 = ppt->d2(); plhs[0] = mxCreateDoubleMatrix(d1,d2,mxREAL); Map<MatrixXd> y(mxGetPr(plhs[0]),d1,d2); ppt->eval(*t, y); break; } default: mexErrMsgIdAndTxt("Drake:PPTmex:UnknownCommand","Check arguments"); } } } } <|endoftext|>
<commit_before>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Module: $RCSfile$ Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html 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 notices for more information. =========================================================================*/ #include "QmitkSimpleExampleFunctionality.h" #include "QmitkSimpleExampleControls.h" #include <qaction.h> #include "slicer.xpm" // for slice-navigation #include <mitkEventMapper.h> #include <mitkGlobalInteraction.h> #include <mitkBaseRenderer.h> #include "QmitkRenderWindow.h" #include "QmitkSelectableGLWidget.h" #include "QmitkStdMultiWidget.h" #include <QmitkStepperAdapter.h> #include <mitkMovieGenerator.h> #include <qpushbutton.h> #include <qfiledialog.h> // for stereo setting #include <mitkOpenGLRenderer.h> #include <mitkVtkRenderWindow.h> #include <vtkRenderWindow.h> // for zoom/pan #include <mitkDisplayCoordinateOperation.h> #include <mitkDisplayVectorInteractor.h> #include <mitkDisplayInteractor.h> #include <mitkInteractionConst.h> QmitkSimpleExampleFunctionality::QmitkSimpleExampleFunctionality(QObject *parent, const char *name, QmitkStdMultiWidget *mitkStdMultiWidget, mitk::DataTreeIteratorBase* it) : QmitkFunctionality(parent, name, it) , controls(NULL), multiWidget(mitkStdMultiWidget), m_NavigatorsInitialized(false) { SetAvailability(true); } QmitkSimpleExampleFunctionality::~QmitkSimpleExampleFunctionality() { // delete moveNzoom; } QWidget * QmitkSimpleExampleFunctionality::CreateMainWidget(QWidget *parent) { QWidget *result = NULL; if (multiWidget == NULL) { multiWidget = new QmitkStdMultiWidget(parent); result = multiWidget; } else { result = NULL; } return result; } QWidget * QmitkSimpleExampleFunctionality::CreateControlWidget(QWidget *parent) { if (controls == NULL) { controls = new QmitkSimpleExampleControls(parent); new QmitkStepperAdapter(controls->getSliceNavigatorTransversal(), multiWidget->mitkWidget1->GetSliceNavigationController()->GetSlice(), "sliceNavigatorTransversalFromSimpleExample"); new QmitkStepperAdapter(controls->getSliceNavigatorSagittal(), multiWidget->mitkWidget2->GetSliceNavigationController()->GetSlice(), "sliceNavigatorSagittalFromSimpleExample"); new QmitkStepperAdapter(controls->getSliceNavigatorFrontal(), multiWidget->mitkWidget3->GetSliceNavigationController()->GetSlice(), "sliceNavigatorFrontalFromSimpleExample"); new QmitkStepperAdapter(controls->getSliceNavigatorTime(), multiWidget->GetTimeNavigationController()->GetTime(), "sliceNavigatorTimeFromSimpleExample"); new QmitkStepperAdapter(controls->getMovieNavigatorTime(), multiWidget->GetTimeNavigationController()->GetTime(), "movieNavigatorTimeFromSimpleExample"); } return controls; } void QmitkSimpleExampleFunctionality::CreateConnections() { if ( controls ) { connect(controls->getStereoSelect(), SIGNAL(activated(int)), this, SLOT(stereoSelectionChanged(int)) ); connect(controls->getReInitializeNavigatorsButton(), SIGNAL(clicked()), this, SLOT(initNavigators()) ); connect(controls->getGenerateMovieButton(), SIGNAL(clicked()), this, SLOT(generateMovie()) ); } } QAction * QmitkSimpleExampleFunctionality::CreateAction(QActionGroup *parent) { QAction* action; action = new QAction( tr( "Simple Example" ), QPixmap((const char**)slicer_xpm), tr( "&Simple Example" ), CTRL + Key_L, parent, "simple example" ); return action; } void QmitkSimpleExampleFunctionality::initNavigators() { m_NavigatorsInitialized = multiWidget->InitializeStandardViews(m_DataTreeIterator.GetPointer()); } void QmitkSimpleExampleFunctionality::generateMovie() { mitk::Stepper::Pointer stepper = multiWidget->mitkWidget1->GetSliceNavigationController()->GetSlice(); mitk::MovieGenerator::Pointer movieGenerator = mitk::MovieGenerator::New(); if (movieGenerator.IsNotNull()) { movieGenerator->SetStepper( stepper ); movieGenerator->SetRenderer( multiWidget->mitkWidget1->GetRenderer() ); QString movieFileName = QFileDialog::getSaveFileName( QString::null, "Movie (*.avi)", 0, "movie file dialog", "Choose a file name" ); movieGenerator->SetFileName( movieFileName.ascii() ); movieGenerator->WriteMovie(); } } void QmitkSimpleExampleFunctionality::TreeChanged() { } void QmitkSimpleExampleFunctionality::Activated() { QmitkFunctionality::Activated(); assert( multiWidget != NULL ); // init widget 4 as a 3D widget multiWidget->mitkWidget4->GetRenderer()->SetMapperID(2); if(m_NavigatorsInitialized) { multiWidget->ReInitializeStandardViews(); } } void QmitkSimpleExampleFunctionality::stereoSelectionChanged( int id ) { vtkRenderWindow * vtkrenderwindow = ((mitk::OpenGLRenderer*)(multiWidget->mitkWidget4->GetRenderer()))->GetVtkRenderWindow(); switch(id) { case 0: vtkrenderwindow->StereoRenderOff(); break; case 1: vtkrenderwindow->SetStereoTypeToRedBlue(); vtkrenderwindow->StereoRenderOn(); break; case 2: vtkrenderwindow->SetStereoTypeToDresden(); vtkrenderwindow->StereoRenderOn(); break; } multiWidget->mitkWidget4->GetRenderer()->SetMapperID(2); multiWidget->mitkWidget4->GetRenderer()->GetRenderWindow()->RequestUpdate(); } <commit_msg>FIX: Crash when canceling movie recording in SimpleFunctionality<commit_after>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Module: $RCSfile$ Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html 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 notices for more information. =========================================================================*/ #include "QmitkSimpleExampleFunctionality.h" #include "QmitkSimpleExampleControls.h" #include <qaction.h> #include "slicer.xpm" // for slice-navigation #include <mitkEventMapper.h> #include <mitkGlobalInteraction.h> #include <mitkBaseRenderer.h> #include "QmitkRenderWindow.h" #include "QmitkSelectableGLWidget.h" #include "QmitkStdMultiWidget.h" #include <QmitkStepperAdapter.h> #include <mitkMovieGenerator.h> #include <qpushbutton.h> #include <qfiledialog.h> // for stereo setting #include <mitkOpenGLRenderer.h> #include <mitkVtkRenderWindow.h> #include <vtkRenderWindow.h> // for zoom/pan #include <mitkDisplayCoordinateOperation.h> #include <mitkDisplayVectorInteractor.h> #include <mitkDisplayInteractor.h> #include <mitkInteractionConst.h> QmitkSimpleExampleFunctionality::QmitkSimpleExampleFunctionality(QObject *parent, const char *name, QmitkStdMultiWidget *mitkStdMultiWidget, mitk::DataTreeIteratorBase* it) : QmitkFunctionality(parent, name, it) , controls(NULL), multiWidget(mitkStdMultiWidget), m_NavigatorsInitialized(false) { SetAvailability(true); } QmitkSimpleExampleFunctionality::~QmitkSimpleExampleFunctionality() { // delete moveNzoom; } QWidget * QmitkSimpleExampleFunctionality::CreateMainWidget(QWidget *parent) { QWidget *result = NULL; if (multiWidget == NULL) { multiWidget = new QmitkStdMultiWidget(parent); result = multiWidget; } else { result = NULL; } return result; } QWidget * QmitkSimpleExampleFunctionality::CreateControlWidget(QWidget *parent) { if (controls == NULL) { controls = new QmitkSimpleExampleControls(parent); new QmitkStepperAdapter(controls->getSliceNavigatorTransversal(), multiWidget->mitkWidget1->GetSliceNavigationController()->GetSlice(), "sliceNavigatorTransversalFromSimpleExample"); new QmitkStepperAdapter(controls->getSliceNavigatorSagittal(), multiWidget->mitkWidget2->GetSliceNavigationController()->GetSlice(), "sliceNavigatorSagittalFromSimpleExample"); new QmitkStepperAdapter(controls->getSliceNavigatorFrontal(), multiWidget->mitkWidget3->GetSliceNavigationController()->GetSlice(), "sliceNavigatorFrontalFromSimpleExample"); new QmitkStepperAdapter(controls->getSliceNavigatorTime(), multiWidget->GetTimeNavigationController()->GetTime(), "sliceNavigatorTimeFromSimpleExample"); new QmitkStepperAdapter(controls->getMovieNavigatorTime(), multiWidget->GetTimeNavigationController()->GetTime(), "movieNavigatorTimeFromSimpleExample"); } return controls; } void QmitkSimpleExampleFunctionality::CreateConnections() { if ( controls ) { connect(controls->getStereoSelect(), SIGNAL(activated(int)), this, SLOT(stereoSelectionChanged(int)) ); connect(controls->getReInitializeNavigatorsButton(), SIGNAL(clicked()), this, SLOT(initNavigators()) ); connect(controls->getGenerateMovieButton(), SIGNAL(clicked()), this, SLOT(generateMovie()) ); } } QAction * QmitkSimpleExampleFunctionality::CreateAction(QActionGroup *parent) { QAction* action; action = new QAction( tr( "Simple Example" ), QPixmap((const char**)slicer_xpm), tr( "&Simple Example" ), CTRL + Key_L, parent, "simple example" ); return action; } void QmitkSimpleExampleFunctionality::initNavigators() { m_NavigatorsInitialized = multiWidget->InitializeStandardViews(m_DataTreeIterator.GetPointer()); } void QmitkSimpleExampleFunctionality::generateMovie() { mitk::Stepper::Pointer stepper = multiWidget->mitkWidget1->GetSliceNavigationController()->GetSlice(); mitk::MovieGenerator::Pointer movieGenerator = mitk::MovieGenerator::New(); if (movieGenerator.IsNotNull()) { movieGenerator->SetStepper( stepper ); movieGenerator->SetRenderer( multiWidget->mitkWidget1->GetRenderer() ); QString movieFileName = QFileDialog::getSaveFileName( QString::null, "Movie (*.avi)", 0, "movie file dialog", "Choose a file name" ); if (!movieFileName.isEmpty()) { movieGenerator->SetFileName( movieFileName.ascii() ); movieGenerator->WriteMovie(); } } } void QmitkSimpleExampleFunctionality::TreeChanged() { } void QmitkSimpleExampleFunctionality::Activated() { QmitkFunctionality::Activated(); assert( multiWidget != NULL ); // init widget 4 as a 3D widget multiWidget->mitkWidget4->GetRenderer()->SetMapperID(2); if(m_NavigatorsInitialized) { multiWidget->ReInitializeStandardViews(); } } void QmitkSimpleExampleFunctionality::stereoSelectionChanged( int id ) { vtkRenderWindow * vtkrenderwindow = ((mitk::OpenGLRenderer*)(multiWidget->mitkWidget4->GetRenderer()))->GetVtkRenderWindow(); switch(id) { case 0: vtkrenderwindow->StereoRenderOff(); break; case 1: vtkrenderwindow->SetStereoTypeToRedBlue(); vtkrenderwindow->StereoRenderOn(); break; case 2: vtkrenderwindow->SetStereoTypeToDresden(); vtkrenderwindow->StereoRenderOn(); break; } multiWidget->mitkWidget4->GetRenderer()->SetMapperID(2); multiWidget->mitkWidget4->GetRenderer()->GetRenderWindow()->RequestUpdate(); } <|endoftext|>
<commit_before>// -*- mode:c++; indent-tabs-mode:nil; -*- /* Copyright (c) 2014, Anders Ronnbrant, anders.ronnbrant@gmail.com 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 "RecorderBase.h" #include <algorithm> #include <atomic> #include <cstdlib> #include <cstring> #include <memory> #include <string> #include <zmq.hpp> #include "zmqutils.h" namespace { void Error(char const* msg) { std::fprintf(stderr, "%s\n", msg); } std::atomic<int16_t> g_recorder_id = ATOMIC_VAR_INIT(0); } // Static definitions for RecorderBase // ---------------------------------------------------------------------------- void RecorderBase::setContext(zmq::context_t* context) { socket_context = context; } void RecorderBase::setAddress(std::string address) { printf("Address: %s\n", address.c_str()); socket_address = address; } std::string RecorderBase::getAddress() { return RecorderBase::socket_address; } zmq::context_t* RecorderBase::socket_context = nullptr; std::string RecorderBase::socket_address = ""; thread_local RecorderBase::SendBuffer RecorderBase::send_buffer; thread_local RecorderBase::SendBuffer::size_type RecorderBase::send_buffer_index = 0; // ---------------------------------------------------------------------------- RecorderBase::RecorderBase(std::string name, int32_t id) : external_id_(id) , recorder_id_(g_recorder_id.fetch_add(1)) , recorder_name_(name) { bool error = false; if (RecorderBase::socket_context == nullptr) { Error("setContext() must be called before instantiation"); error = true; } if (RecorderBase::socket_address.empty()) { Error("Socket address empty, setAddress() must be called"); Error("before first instantiation"); error = true; } if (error) { std::exit(1); } int constexpr linger = 3000; int constexpr sendtimeout = 2; socket_.reset(new zmq::socket_t(*RecorderBase::socket_context, ZMQ_PUSH)); socket_->setsockopt(ZMQ_LINGER, &linger, sizeof(linger)); socket_->setsockopt(ZMQ_SNDTIMEO, &sendtimeout, sizeof(sendtimeout)); zmqutils::connect(socket_.get(), RecorderBase::socket_address); } RecorderBase::~RecorderBase() { flushSendBuffer(); socket_->close(); } void RecorderBase::flushSendBuffer() { auto constexpr frame = PayloadType::DATA; auto constexpr item_size = sizeof(decltype(send_buffer)::value_type); if (send_buffer_index > 0) { socket_->send(&frame, sizeof(frame), ZMQ_SNDMORE); socket_->send(send_buffer.data(), send_buffer_index * item_size); send_buffer_index = 0; } } void RecorderBase::setupRecorder(int32_t num_items) { auto constexpr frame = PayloadType::INIT_RECORDER; InitRecorder const init_rec( external_id_, recorder_id_, num_items, recorder_name_); socket_->send(&frame, sizeof(frame), ZMQ_SNDMORE); socket_->send(&init_rec, sizeof(init_rec)); } void RecorderBase::setupItem(InitItem const& init_item) { auto constexpr frame = PayloadType::INIT_ITEM; socket_->send(&frame, sizeof(frame), ZMQ_SNDMORE); socket_->send(&init_item, sizeof(init_item)); } void RecorderBase::record(Item const& item) { send_buffer[send_buffer_index++] = item; if (send_buffer_index == send_buffer.max_size()) { flushSendBuffer(); } } <commit_msg>Add socket creator, for thread local static initialization<commit_after>// -*- mode:c++; indent-tabs-mode:nil; -*- /* Copyright (c) 2014, Anders Ronnbrant, anders.ronnbrant@gmail.com 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 "RecorderBase.h" #include <algorithm> #include <atomic> #include <cstdlib> #include <cstring> #include <memory> #include <string> #include <zmq.hpp> #include "zmqutils.h" // Static definitions for RecorderBase // ---------------------------------------------------------------------------- void RecorderBase::setContext(zmq::context_t* context) { socket_context = context; } void RecorderBase::setAddress(std::string address) { printf("Address: %s\n", address.c_str()); socket_address = address; } std::string RecorderBase::getAddress() { return RecorderBase::socket_address; } zmq::context_t* RecorderBase::socket_context = nullptr; std::string RecorderBase::socket_address = ""; thread_local RecorderBase::SendBuffer RecorderBase::send_buffer; thread_local RecorderBase::SendBuffer::size_type RecorderBase::send_buffer_index = 0; // ---------------------------------------------------------------------------- namespace { void Error(char const* msg) { std::fprintf(stderr, "%s\n", msg); } std::atomic<int16_t> g_recorder_id = ATOMIC_VAR_INIT(0); // Socket creator class class SocketCreator { public: SocketCreator(zmq::context_t* ctx, std::string const& address, std::shared_ptr<zmq::socket_t>* socket) { printf("%s: %lu\n", __func__, std::this_thread::get_id()); int constexpr linger = 3000; int constexpr sendtimeout = 2; int constexpr sendhwm = 16000; socket->reset(new zmq::socket_t(*ctx, ZMQ_PUSH)); (*socket)->setsockopt(ZMQ_LINGER, &linger, sizeof(linger)); (*socket)->setsockopt(ZMQ_SNDTIMEO, &sendtimeout, sizeof(sendtimeout)); (*socket)->setsockopt(ZMQ_SNDHWM, &sendhwm, sizeof(sendhwm)); zmqutils::connect(socket->get(), address); } }; } // namespace RecorderBase::RecorderBase(std::string name, int32_t id) : external_id_(id) , recorder_id_(g_recorder_id.fetch_add(1)) , recorder_name_(name) { bool error = false; if (RecorderBase::socket_context == nullptr) { Error("setContext() must be called before instantiation"); error = true; } if (RecorderBase::socket_address.empty()) { Error("Socket address empty, setAddress() must be called"); Error("before first instantiation"); error = true; } if (error) { std::exit(1); } int constexpr linger = 3000; int constexpr sendtimeout = 2; socket_.reset(new zmq::socket_t(*RecorderBase::socket_context, ZMQ_PUSH)); socket_->setsockopt(ZMQ_LINGER, &linger, sizeof(linger)); socket_->setsockopt(ZMQ_SNDTIMEO, &sendtimeout, sizeof(sendtimeout)); zmqutils::connect(socket_.get(), RecorderBase::socket_address); } RecorderBase::~RecorderBase() { flushSendBuffer(); socket_->close(); } void RecorderBase::flushSendBuffer() { auto constexpr frame = PayloadType::DATA; auto constexpr item_size = sizeof(decltype(send_buffer)::value_type); if (send_buffer_index > 0) { socket_->send(&frame, sizeof(frame), ZMQ_SNDMORE); socket_->send(send_buffer.data(), send_buffer_index * item_size); send_buffer_index = 0; } } void RecorderBase::setupRecorder(int32_t num_items) { auto constexpr frame = PayloadType::INIT_RECORDER; InitRecorder const init_rec( external_id_, recorder_id_, num_items, recorder_name_); socket_->send(&frame, sizeof(frame), ZMQ_SNDMORE); socket_->send(&init_rec, sizeof(init_rec)); } void RecorderBase::setupItem(InitItem const& init_item) { auto constexpr frame = PayloadType::INIT_ITEM; socket_->send(&frame, sizeof(frame), ZMQ_SNDMORE); socket_->send(&init_item, sizeof(init_item)); } void RecorderBase::record(Item const& item) { send_buffer[send_buffer_index++] = item; if (send_buffer_index == send_buffer.max_size()) { flushSendBuffer(); } } <|endoftext|>
<commit_before>#include "vtkConditionVariable.h" #include "vtkObjectFactory.h" #include <errno.h> vtkStandardNewMacro(vtkConditionVariable); #ifndef EPERM # define EPERM 1 #endif #ifndef ENOMEM # define ENOMEM 12 #endif #ifndef EBUSY # define EBUSY 16 #endif #ifndef EINVAL # define EINVAL 22 #endif #ifndef EAGAIN # define EAGAIN 35 #endif #if ! defined(VTK_USE_PTHREADS) && ! defined(VTK_HP_PTHREADS) && ! defined(VTK_USE_WIN32_THREADS) typedef int pthread_condattr_t; int pthread_cond_init( vtkConditionType* cv, const pthread_condattr_t* ) { *cv = 0; return 0; } int pthread_cond_destroy( vtkConditionType* cv ) { if ( *cv ) return EBUSY; return 0; } int pthread_cond_signal( vtkConditionType* cv ) { *cv = 1; return 0; } int pthread_cond_broadcast( vtkConditionType* cv ) { *cv = 1; return 0; } int pthread_cond_wait( vtkConditionType* cv, vtkMutexType* lock ) { #ifdef VTK_USE_SPROC release_lock( lock ); #else // VTK_USE_SPROC *lock = 0; #endif // VTK_USE_SPROC while ( ! *cv ); #ifdef VTK_USE_SPROC spin_lock( lock ); #else // VTK_USE_SPROC *lock = 1; #endif // VTK_USE_SPROC } #endif // ! defined(VTK_USE_PTHREADS) && ! defined(VTK_HP_PTHREADS) && ! defined(VTK_USE_WIN32_THREADS) #ifdef VTK_USE_WIN32_THREADS typedef int pthread_condattr_t; # if 1 int pthread_cond_init( pthread_cond_t* cv, const pthread_condattr_t* ) { cv->WaitingThreadCount = 0; cv->WasBroadcast = 0; cv->Semaphore = CreateSemaphore( NULL, // no security 0, // initially 0 0x7fffffff, // max count NULL ); // unnamed InitializeCriticalSection( &cv->WaitingThreadCountCritSec ); cv->DoneWaiting = CreateEvent( NULL, // no security FALSE, // auto-reset FALSE, // non-signaled initially NULL ); // unnamed return 0; } int pthread_cond_wait( pthread_cond_t* cv, vtkMutexType* externalMutex ) { // Avoid race conditions. EnterCriticalSection( &cv->WaitingThreadCountCritSec ); ++ cv->WaitingThreadCount; LeaveCriticalSection( &cv->WaitingThreadCountCritSec ); // This call atomically releases the mutex and waits on the // semaphore until <pthread_cond_signal> or <pthread_cond_broadcast> // are called by another thread. SignalObjectAndWait( *externalMutex, cv->Semaphore, INFINITE, FALSE ); // Reacquire lock to avoid race conditions. EnterCriticalSection( &cv->WaitingThreadCountCritSec ); // We're no longer waiting... -- cv->WaitingThreadCount; // Check to see if we're the last waiter after <pthread_cond_broadcast>. int last_waiter = cv->WasBroadcast && cv->WaitingThreadCount == 0; LeaveCriticalSection( &cv->WaitingThreadCountCritSec ); // If we're the last waiter thread during this particular broadcast // then let all the other threads proceed. if ( last_waiter ) { // This call atomically signals the <DoneWaiting> event and waits until // it can acquire the <externalMutex>. This is required to ensure fairness. SignalObjectAndWait( cv->DoneWaiting, *externalMutex, INFINITE, FALSE ); } else { // Always regain the external mutex since that's the guarantee we // give to our callers. WaitForSingleObject( *externalMutex, INFINITE ); } return 0; } int pthread_cond_signal( pthread_cond_t* cv ) { EnterCriticalSection( &cv->WaitingThreadCountCritSec ); int have_waiters = cv->WaitingThreadCount > 0; LeaveCriticalSection( &cv->WaitingThreadCountCritSec ); // If there aren't any waiters, then this is a no-op. if ( have_waiters ) { ReleaseSemaphore( cv->Semaphore, 1, 0 ); } return 0; } int pthread_cond_broadcast( pthread_cond_t* cv ) { // This is needed to ensure that <WaitingThreadCount> and <WasBroadcast> are // consistent relative to each other. EnterCriticalSection( &cv->WaitingThreadCountCritSec ); int have_waiters = 0; if ( cv->WaitingThreadCount > 0 ) { // We are broadcasting, even if there is just one waiter... // Record that we are broadcasting, which helps optimize // pthread_cond_wait for the non-broadcast case. cv->WasBroadcast = 1; have_waiters = 1; } if (have_waiters) { // Wake up all the waiters atomically. ReleaseSemaphore( cv->Semaphore, cv->WaitingThreadCount, 0 ); LeaveCriticalSection( &cv->WaitingThreadCountCritSec ); // Wait for all the awakened threads to acquire the counting semaphore. WaitForSingleObject( cv->DoneWaiting, INFINITE ); // This assignment is okay, even without the <WaitingThreadCountCritSec> held // because no other waiter threads can wake up to access it. cv->WasBroadcast = 0; } else { LeaveCriticalSection( &cv->WaitingThreadCountCritSec ); } return 0; } int pthread_cond_destroy( pthread_cond_t* cv ) { DeleteCriticalSection( &cv->WaitingThreadCountCritSec ); CloseHandle( cv->Semaphore ); //CloseHandle( cv->Event ); if ( cv->WaitingThreadCount > 0 && ! cv->DoneWaiting ) { return EBUSY; } return 0; } # else // 0 int pthread_cond_init( pthread_cond_t* cv, const pthread_condattr_t * ) { if ( ! cv ) { return EINVAL; } cv->WaitingThreadCount = 0; cv->NotifyCount = 0; cv->ReleaseCount = 0; // Create a manual-reset event. cv->Event = CreateEvent( NULL, // no security TRUE, // manual-reset FALSE, // non-signaled initially NULL ); // unnamed InitializeCriticalSection( &cv->WaitingThreadCountCritSec ); return 0; } int pthread_cond_wait( pthread_cond_t* cv, vtkMutexType* externalMutex ) { // Avoid race conditions. EnterCriticalSection( &cv->WaitingThreadCountCritSec ); // Increment count of waiters. ++ cv->WaitingThreadCount; // Store the notification we should respond to. int tmpNotify = cv->NotifyCount; LeaveCriticalSection( &cv->WaitingThreadCountCritSec ); ReleaseMutex( *externalMutex ); while ( 1 ) { // Wait until the event is signaled. WaitForSingleObject( cv->Event, INFINITE ); EnterCriticalSection( &cv->WaitingThreadCountCritSec ); // Exit the loop when cv->Event is signaled, the // release count indicates more threads need to receive // the signal/broadcast, and the signal occurred after // we started waiting. int waitDone = ( cv->ReleaseCount > 0 ) && ( cv->NotifyCount != tmpNotify ); LeaveCriticalSection( &cv->WaitingThreadCountCritSec ); if ( waitDone ) break; } WaitForSingleObject( *externalMutex, INFINITE ); EnterCriticalSection( &cv->WaitingThreadCountCritSec ); -- cv->WaitingThreadCount; -- cv->ReleaseCount; int lastWaiter = ( cv->ReleaseCount == 0 ); LeaveCriticalSection( &cv->WaitingThreadCountCritSec ); // If we're the last waiter to be notified, reset the manual event. if ( lastWaiter ) ResetEvent( cv->Event ); return 0; } int pthread_cond_signal( pthread_cond_t* cv ) { EnterCriticalSection( &cv->WaitingThreadCountCritSec ); if ( cv->WaitingThreadCount > cv->ReleaseCount ) { SetEvent( cv->Event ); // Signal the manual-reset event. ++ cv->ReleaseCount; ++ cv->NotifyCount; } LeaveCriticalSection( &cv->WaitingThreadCountCritSec ); return 0; } int pthread_cond_broadcast( pthread_cond_t* cv ) { EnterCriticalSection( &cv->WaitingThreadCountCritSec ); if ( cv->WaitingThreadCount > 0 ) { SetEvent( cv->Event ); // Release all the threads in this generation. cv->ReleaseCount = cv->WaitingThreadCount; ++ cv->NotifyCount; } LeaveCriticalSection( &cv->WaitingThreadCountCritSec ); return 0; } int pthread_cond_destroy( pthread_cond_t* cv ) { if ( cv->WaitingThreadCount > 0 ) { return EBUSY; } CloseHandle( cv->Event ); DeleteCriticalSection( &cv->WaitingThreadCountCritSec ); return 0; } # endif // 0 #endif // VTK_USE_WIN32_THREADS vtkSimpleConditionVariable::vtkSimpleConditionVariable() { int result = pthread_cond_init( &this->ConditionVariable, 0 ); switch ( result ) { case EINVAL: { vtkGenericWarningMacro( "Invalid condition variable attributes." ); } break; case ENOMEM: { vtkGenericWarningMacro( "Not enough memory to create a condition variable." ); } break; case EAGAIN: { vtkGenericWarningMacro( "Temporarily not enough memory to create a condition variable." ); } break; } } vtkSimpleConditionVariable::~vtkSimpleConditionVariable() { int result = pthread_cond_destroy( &this->ConditionVariable ); switch ( result ) { case EINVAL: { vtkGenericWarningMacro( "Could not destroy condition variable (invalid value)" ); } break; case EBUSY: { vtkGenericWarningMacro( "Could not destroy condition variable (locked by another thread)" ); } break; } } void vtkSimpleConditionVariable::Signal() { pthread_cond_signal( &this->ConditionVariable ); } void vtkSimpleConditionVariable::Broadcast() { pthread_cond_broadcast( &this->ConditionVariable ); } int vtkSimpleConditionVariable::Wait( vtkSimpleMutexLock& lock ) { return pthread_cond_wait( &this->ConditionVariable, &lock.MutexLock ); } void vtkConditionVariable::PrintSelf( ostream& os, vtkIndent indent ) { this->Superclass::PrintSelf( os, indent ); os << indent << "SimpleConditionVariable: " << &this->SimpleConditionVariable << "\n"; os << indent << "ThreadingModel: " #ifdef VTK_USE_PTHREADS << "pthreads " #endif #ifdef VTK_HP_PTHREADS << "HP pthreads " #endif #ifdef VTK_USE_WIN32_THREADS << "win32 threads " #endif << "\n"; } <commit_msg>Place fake pthread symbols in namespace.<commit_after>#include "vtkConditionVariable.h" #include "vtkObjectFactory.h" #include <errno.h> vtkStandardNewMacro(vtkConditionVariable); #ifndef EPERM # define EPERM 1 #endif #ifndef ENOMEM # define ENOMEM 12 #endif #ifndef EBUSY # define EBUSY 16 #endif #ifndef EINVAL # define EINVAL 22 #endif #ifndef EAGAIN # define EAGAIN 35 #endif #if ! defined(VTK_USE_PTHREADS) && ! defined(VTK_HP_PTHREADS) && ! defined(VTK_USE_WIN32_THREADS) // Why is this encapsulated in a namespace? Because you can get errors if // these symbols (particularly the typedef) are already defined. We run // into this problem on a system that has pthread headers but no libraries // (which can happen when, for example, cross compiling). By using the // namespace, we will at worst get a warning. namespace { typedef int pthread_condattr_t; int pthread_cond_init( vtkConditionType* cv, const pthread_condattr_t* ) { *cv = 0; return 0; } int pthread_cond_destroy( vtkConditionType* cv ) { if ( *cv ) return EBUSY; return 0; } int pthread_cond_signal( vtkConditionType* cv ) { *cv = 1; return 0; } int pthread_cond_broadcast( vtkConditionType* cv ) { *cv = 1; return 0; } int pthread_cond_wait( vtkConditionType* cv, vtkMutexType* lock ) { #ifdef VTK_USE_SPROC release_lock( lock ); #else // VTK_USE_SPROC *lock = 0; #endif // VTK_USE_SPROC while ( ! *cv ); #ifdef VTK_USE_SPROC spin_lock( lock ); #else // VTK_USE_SPROC *lock = 1; #endif // VTK_USE_SPROC return 0; } } #endif // ! defined(VTK_USE_PTHREADS) && ! defined(VTK_HP_PTHREADS) && ! defined(VTK_USE_WIN32_THREADS) #ifdef VTK_USE_WIN32_THREADS typedef int pthread_condattr_t; # if 1 int pthread_cond_init( pthread_cond_t* cv, const pthread_condattr_t* ) { cv->WaitingThreadCount = 0; cv->WasBroadcast = 0; cv->Semaphore = CreateSemaphore( NULL, // no security 0, // initially 0 0x7fffffff, // max count NULL ); // unnamed InitializeCriticalSection( &cv->WaitingThreadCountCritSec ); cv->DoneWaiting = CreateEvent( NULL, // no security FALSE, // auto-reset FALSE, // non-signaled initially NULL ); // unnamed return 0; } int pthread_cond_wait( pthread_cond_t* cv, vtkMutexType* externalMutex ) { // Avoid race conditions. EnterCriticalSection( &cv->WaitingThreadCountCritSec ); ++ cv->WaitingThreadCount; LeaveCriticalSection( &cv->WaitingThreadCountCritSec ); // This call atomically releases the mutex and waits on the // semaphore until <pthread_cond_signal> or <pthread_cond_broadcast> // are called by another thread. SignalObjectAndWait( *externalMutex, cv->Semaphore, INFINITE, FALSE ); // Reacquire lock to avoid race conditions. EnterCriticalSection( &cv->WaitingThreadCountCritSec ); // We're no longer waiting... -- cv->WaitingThreadCount; // Check to see if we're the last waiter after <pthread_cond_broadcast>. int last_waiter = cv->WasBroadcast && cv->WaitingThreadCount == 0; LeaveCriticalSection( &cv->WaitingThreadCountCritSec ); // If we're the last waiter thread during this particular broadcast // then let all the other threads proceed. if ( last_waiter ) { // This call atomically signals the <DoneWaiting> event and waits until // it can acquire the <externalMutex>. This is required to ensure fairness. SignalObjectAndWait( cv->DoneWaiting, *externalMutex, INFINITE, FALSE ); } else { // Always regain the external mutex since that's the guarantee we // give to our callers. WaitForSingleObject( *externalMutex, INFINITE ); } return 0; } int pthread_cond_signal( pthread_cond_t* cv ) { EnterCriticalSection( &cv->WaitingThreadCountCritSec ); int have_waiters = cv->WaitingThreadCount > 0; LeaveCriticalSection( &cv->WaitingThreadCountCritSec ); // If there aren't any waiters, then this is a no-op. if ( have_waiters ) { ReleaseSemaphore( cv->Semaphore, 1, 0 ); } return 0; } int pthread_cond_broadcast( pthread_cond_t* cv ) { // This is needed to ensure that <WaitingThreadCount> and <WasBroadcast> are // consistent relative to each other. EnterCriticalSection( &cv->WaitingThreadCountCritSec ); int have_waiters = 0; if ( cv->WaitingThreadCount > 0 ) { // We are broadcasting, even if there is just one waiter... // Record that we are broadcasting, which helps optimize // pthread_cond_wait for the non-broadcast case. cv->WasBroadcast = 1; have_waiters = 1; } if (have_waiters) { // Wake up all the waiters atomically. ReleaseSemaphore( cv->Semaphore, cv->WaitingThreadCount, 0 ); LeaveCriticalSection( &cv->WaitingThreadCountCritSec ); // Wait for all the awakened threads to acquire the counting semaphore. WaitForSingleObject( cv->DoneWaiting, INFINITE ); // This assignment is okay, even without the <WaitingThreadCountCritSec> held // because no other waiter threads can wake up to access it. cv->WasBroadcast = 0; } else { LeaveCriticalSection( &cv->WaitingThreadCountCritSec ); } return 0; } int pthread_cond_destroy( pthread_cond_t* cv ) { DeleteCriticalSection( &cv->WaitingThreadCountCritSec ); CloseHandle( cv->Semaphore ); //CloseHandle( cv->Event ); if ( cv->WaitingThreadCount > 0 && ! cv->DoneWaiting ) { return EBUSY; } return 0; } # else // 0 int pthread_cond_init( pthread_cond_t* cv, const pthread_condattr_t * ) { if ( ! cv ) { return EINVAL; } cv->WaitingThreadCount = 0; cv->NotifyCount = 0; cv->ReleaseCount = 0; // Create a manual-reset event. cv->Event = CreateEvent( NULL, // no security TRUE, // manual-reset FALSE, // non-signaled initially NULL ); // unnamed InitializeCriticalSection( &cv->WaitingThreadCountCritSec ); return 0; } int pthread_cond_wait( pthread_cond_t* cv, vtkMutexType* externalMutex ) { // Avoid race conditions. EnterCriticalSection( &cv->WaitingThreadCountCritSec ); // Increment count of waiters. ++ cv->WaitingThreadCount; // Store the notification we should respond to. int tmpNotify = cv->NotifyCount; LeaveCriticalSection( &cv->WaitingThreadCountCritSec ); ReleaseMutex( *externalMutex ); while ( 1 ) { // Wait until the event is signaled. WaitForSingleObject( cv->Event, INFINITE ); EnterCriticalSection( &cv->WaitingThreadCountCritSec ); // Exit the loop when cv->Event is signaled, the // release count indicates more threads need to receive // the signal/broadcast, and the signal occurred after // we started waiting. int waitDone = ( cv->ReleaseCount > 0 ) && ( cv->NotifyCount != tmpNotify ); LeaveCriticalSection( &cv->WaitingThreadCountCritSec ); if ( waitDone ) break; } WaitForSingleObject( *externalMutex, INFINITE ); EnterCriticalSection( &cv->WaitingThreadCountCritSec ); -- cv->WaitingThreadCount; -- cv->ReleaseCount; int lastWaiter = ( cv->ReleaseCount == 0 ); LeaveCriticalSection( &cv->WaitingThreadCountCritSec ); // If we're the last waiter to be notified, reset the manual event. if ( lastWaiter ) ResetEvent( cv->Event ); return 0; } int pthread_cond_signal( pthread_cond_t* cv ) { EnterCriticalSection( &cv->WaitingThreadCountCritSec ); if ( cv->WaitingThreadCount > cv->ReleaseCount ) { SetEvent( cv->Event ); // Signal the manual-reset event. ++ cv->ReleaseCount; ++ cv->NotifyCount; } LeaveCriticalSection( &cv->WaitingThreadCountCritSec ); return 0; } int pthread_cond_broadcast( pthread_cond_t* cv ) { EnterCriticalSection( &cv->WaitingThreadCountCritSec ); if ( cv->WaitingThreadCount > 0 ) { SetEvent( cv->Event ); // Release all the threads in this generation. cv->ReleaseCount = cv->WaitingThreadCount; ++ cv->NotifyCount; } LeaveCriticalSection( &cv->WaitingThreadCountCritSec ); return 0; } int pthread_cond_destroy( pthread_cond_t* cv ) { if ( cv->WaitingThreadCount > 0 ) { return EBUSY; } CloseHandle( cv->Event ); DeleteCriticalSection( &cv->WaitingThreadCountCritSec ); return 0; } # endif // 0 #endif // VTK_USE_WIN32_THREADS vtkSimpleConditionVariable::vtkSimpleConditionVariable() { int result = pthread_cond_init( &this->ConditionVariable, 0 ); switch ( result ) { case EINVAL: { vtkGenericWarningMacro( "Invalid condition variable attributes." ); } break; case ENOMEM: { vtkGenericWarningMacro( "Not enough memory to create a condition variable." ); } break; case EAGAIN: { vtkGenericWarningMacro( "Temporarily not enough memory to create a condition variable." ); } break; } } vtkSimpleConditionVariable::~vtkSimpleConditionVariable() { int result = pthread_cond_destroy( &this->ConditionVariable ); switch ( result ) { case EINVAL: { vtkGenericWarningMacro( "Could not destroy condition variable (invalid value)" ); } break; case EBUSY: { vtkGenericWarningMacro( "Could not destroy condition variable (locked by another thread)" ); } break; } } void vtkSimpleConditionVariable::Signal() { pthread_cond_signal( &this->ConditionVariable ); } void vtkSimpleConditionVariable::Broadcast() { pthread_cond_broadcast( &this->ConditionVariable ); } int vtkSimpleConditionVariable::Wait( vtkSimpleMutexLock& lock ) { return pthread_cond_wait( &this->ConditionVariable, &lock.MutexLock ); } void vtkConditionVariable::PrintSelf( ostream& os, vtkIndent indent ) { this->Superclass::PrintSelf( os, indent ); os << indent << "SimpleConditionVariable: " << &this->SimpleConditionVariable << "\n"; os << indent << "ThreadingModel: " #ifdef VTK_USE_PTHREADS << "pthreads " #endif #ifdef VTK_HP_PTHREADS << "HP pthreads " #endif #ifdef VTK_USE_WIN32_THREADS << "win32 threads " #endif << "\n"; } <|endoftext|>
<commit_before>/* * libMaia - maiaXmlRpcClient.cpp * Copyright (c) 2007 Sebastian Wiedenroth <wiedi@frubar.net> * and Karl Glatz * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN 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 "maiaXmlRpcClient.h" #include "maiaFault.h" MaiaXmlRpcClient::MaiaXmlRpcClient(QObject* parent) : QObject(parent), manager(this), request() { request.setRawHeader("User-Agent", "libmaia 0.2"); request.setHeader(QNetworkRequest::ContentTypeHeader, "text/xml"); connect(&manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*))); } MaiaXmlRpcClient::MaiaXmlRpcClient(QUrl url, QObject* parent) : QObject(parent), manager(this), request(url) { request.setRawHeader("User-Agent", "libmaia 0.2"); request.setHeader(QNetworkRequest::ContentTypeHeader, "text/xml"); connect(&manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*))); setUrl(url); } void MaiaXmlRpcClient::setUrl(QUrl url) { if(!url.isValid()) return; request.setUrl(url); } QNetworkReply* MaiaXmlRpcClient::call(QString method, QList<QVariant> args, QObject* responseObject, const char* responseSlot, QObject* faultObject, const char* faultSlot) { MaiaObject* call = new MaiaObject(this); connect(call, SIGNAL(aresponse(QVariant &, QNetworkReply *)), responseObject, responseSlot); connect(call, SIGNAL(fault(int, const QString &, QNetworkReply *)), faultObject, faultSlot); QNetworkReply* reply = manager.post( request, call->prepareCall(method, args).toUtf8() ); callmap[reply] = call; return reply; } void MaiaXmlRpcClient::replyFinished(QNetworkReply* reply) { QString response; if(!callmap.contains(reply)) return; if(reply->error() != QNetworkReply::NoError) { MaiaFault fault(-32300, reply->errorString()); response = fault.toString(); } else { response = QString::fromUtf8(reply->readAll()); } // parseResponse deletes the MaiaObject callmap[reply]->parseResponse(response, reply); delete reply; callmap.remove(reply); } <commit_msg>bugfix: use deleteLater() for the reply<commit_after>/* * libMaia - maiaXmlRpcClient.cpp * Copyright (c) 2007 Sebastian Wiedenroth <wiedi@frubar.net> * and Karl Glatz * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN 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 "maiaXmlRpcClient.h" #include "maiaFault.h" MaiaXmlRpcClient::MaiaXmlRpcClient(QObject* parent) : QObject(parent), manager(this), request() { request.setRawHeader("User-Agent", "libmaia 0.2"); request.setHeader(QNetworkRequest::ContentTypeHeader, "text/xml"); connect(&manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*))); } MaiaXmlRpcClient::MaiaXmlRpcClient(QUrl url, QObject* parent) : QObject(parent), manager(this), request(url) { request.setRawHeader("User-Agent", "libmaia 0.2"); request.setHeader(QNetworkRequest::ContentTypeHeader, "text/xml"); connect(&manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*))); setUrl(url); } void MaiaXmlRpcClient::setUrl(QUrl url) { if(!url.isValid()) return; request.setUrl(url); } QNetworkReply* MaiaXmlRpcClient::call(QString method, QList<QVariant> args, QObject* responseObject, const char* responseSlot, QObject* faultObject, const char* faultSlot) { MaiaObject* call = new MaiaObject(this); connect(call, SIGNAL(aresponse(QVariant &, QNetworkReply *)), responseObject, responseSlot); connect(call, SIGNAL(fault(int, const QString &, QNetworkReply *)), faultObject, faultSlot); QNetworkReply* reply = manager.post( request, call->prepareCall(method, args).toUtf8() ); callmap[reply] = call; return reply; } void MaiaXmlRpcClient::replyFinished(QNetworkReply* reply) { QString response; if(!callmap.contains(reply)) return; if(reply->error() != QNetworkReply::NoError) { MaiaFault fault(-32300, reply->errorString()); response = fault.toString(); } else { response = QString::fromUtf8(reply->readAll()); } // parseResponse deletes the MaiaObject callmap[reply]->parseResponse(response, reply); reply->deleteLater(); callmap.remove(reply); } <|endoftext|>
<commit_before>/**************************************************************************** * * Copyright (c) 2015 PX4 Development Team. All rights reserved. * Author: Mohammed Kabir <mhkabir98@gmail.com> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /** * @file camera_trigger.cpp * * External camera-IMU synchronisation and triggering via FMU auxillary pins. * * @author Mohammed Kabir <mhkabir98@gmail.com> */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <fcntl.h> #include <stdbool.h> #include <nuttx/clock.h> #include <nuttx/arch.h> #include <systemlib/systemlib.h> #include <systemlib/err.h> #include <systemlib/param/param.h> #include <uORB/uORB.h> #include <uORB/topics/camera_trigger.h> #include <uORB/topics/sensor_combined.h> #include <uORB/topics/vehicle_command.h> #include <poll.h> #include <drivers/drv_gpio.h> #include <drivers/drv_hrt.h> #include <mavlink/mavlink_log.h> #include <board_config.h> extern "C" __EXPORT int camera_trigger_main(int argc, char *argv[]); class CameraTrigger { public: /** * Constructor */ CameraTrigger(); /** * Destructor, also kills task. */ ~CameraTrigger(); /** * Start the task. */ void start(); /** * Stop the task. */ void stop(); /** * Display info. */ void info(); int pin; private: struct hrt_call _pollcall; struct hrt_call _firecall; int _gpio_fd; int _polarity; float _activation_time; float _integration_time; float _transfer_time; uint32_t _trigger_seq; bool _trigger_enabled; int _sensor_sub; int _vcommand_sub; orb_advert_t _trigger_pub; struct camera_trigger_s _trigger; struct sensor_combined_s _sensor; struct vehicle_command_s _command; param_t polarity ; param_t activation_time ; param_t integration_time ; param_t transfer_time ; /** * Topic poller to check for fire info. */ static void poll(void *arg); /** * Fires trigger */ static void engage(void *arg); /** * Resets trigger */ static void disengage(void *arg); }; namespace camera_trigger { CameraTrigger *g_camera_trigger; } CameraTrigger::CameraTrigger() : pin(1), _pollcall{}, _firecall{}, _gpio_fd(-1), _polarity(0), _activation_time(0.0f), _integration_time(0.0f), _transfer_time(0.0f), _trigger_seq(0), _trigger_enabled(false), _sensor_sub(-1), _vcommand_sub(-1), _trigger_pub(nullptr), _trigger{}, _sensor{}, _command{} { memset(&_trigger, 0, sizeof(_trigger)); memset(&_sensor, 0, sizeof(_sensor)); memset(&_command, 0, sizeof(_command)); memset(&_pollcall, 0, sizeof(_pollcall)); memset(&_firecall, 0, sizeof(_firecall)); // Parameters polarity = param_find("TRIG_POLARITY"); activation_time = param_find("TRIG_ACT_TIME"); integration_time = param_find("TRIG_INT_TIME"); transfer_time = param_find("TRIG_TRANS_TIME"); } CameraTrigger::~CameraTrigger() { camera_trigger::g_camera_trigger = nullptr; } void CameraTrigger::start() { _sensor_sub = orb_subscribe(ORB_ID(sensor_combined)); _vcommand_sub = orb_subscribe(ORB_ID(vehicle_command)); param_get(polarity, &_polarity); param_get(activation_time, &_activation_time); param_get(integration_time, &_integration_time); param_get(transfer_time, &_transfer_time); stm32_configgpio(GPIO_GPIO0_OUTPUT); if (_polarity == 0) { stm32_gpiowrite(GPIO_GPIO0_OUTPUT, 1); // GPIO pin pull high } else if (_polarity == 1) { stm32_gpiowrite(GPIO_GPIO0_OUTPUT, 0); // GPIO pin pull low } else { warnx(" invalid trigger polarity setting. stopping."); stop(); } poll(this); // Trampoline call } void CameraTrigger::stop() { hrt_cancel(&_firecall); hrt_cancel(&_pollcall); if (camera_trigger::g_camera_trigger != nullptr) { delete(camera_trigger::g_camera_trigger); } } void CameraTrigger::poll(void *arg) { CameraTrigger *trig = reinterpret_cast<CameraTrigger *>(arg); bool updated; orb_check(trig->_vcommand_sub, &updated); if (updated) { orb_copy(ORB_ID(vehicle_command), trig->_vcommand_sub, &trig->_command); if (trig->_command.command == vehicle_command_s::VEHICLE_CMD_DO_TRIGGER_CONTROL) { if (trig->_command.param1 < 1) { if (trig->_trigger_enabled) { trig->_trigger_enabled = false ; } } else if (trig->_command.param1 >= 1) { if (!trig->_trigger_enabled) { trig->_trigger_enabled = true ; } } // Set trigger rate from command if (trig->_command.param2 > 0) { trig->_integration_time = trig->_command.param2; param_set(trig->integration_time, &(trig->_integration_time)); } } } if (!trig->_trigger_enabled) { hrt_call_after(&trig->_pollcall, 1e6, (hrt_callout)&CameraTrigger::poll, trig); return; } else { engage(trig); hrt_call_after(&trig->_firecall, trig->_activation_time * 1000, (hrt_callout)&CameraTrigger::disengage, trig); orb_copy(ORB_ID(sensor_combined), trig->_sensor_sub, &trig->_sensor); trig->_trigger.timestamp = trig->_sensor.timestamp; // get IMU timestamp trig->_trigger.seq = trig->_trigger_seq++; if (trig->_trigger_pub != nullptr) { orb_publish(ORB_ID(camera_trigger), trig->_trigger_pub, &trig->_trigger); } else { trig->_trigger_pub = orb_advertise(ORB_ID(camera_trigger), &trig->_trigger); } hrt_call_after(&trig->_pollcall, (trig->_transfer_time + trig->_integration_time) * 1000, (hrt_callout)&CameraTrigger::poll, trig); } } void CameraTrigger::engage(void *arg) { CameraTrigger *trig = reinterpret_cast<CameraTrigger *>(arg); stm32_configgpio(GPIO_GPIO0_OUTPUT); if (trig->_polarity == 0) { // ACTIVE_LOW stm32_gpiowrite(GPIO_GPIO0_OUTPUT, 0); } else if (trig->_polarity == 1) { // ACTIVE_HIGH stm32_gpiowrite(GPIO_GPIO0_OUTPUT, 1); } } void CameraTrigger::disengage(void *arg) { CameraTrigger *trig = reinterpret_cast<CameraTrigger *>(arg); stm32_configgpio(GPIO_GPIO0_OUTPUT); if (trig->_polarity == 0) { // ACTIVE_LOW stm32_gpiowrite(GPIO_GPIO0_OUTPUT, 1); } else if (trig->_polarity == 1) { // ACTIVE_HIGH stm32_gpiowrite(GPIO_GPIO0_OUTPUT, 0); } } void CameraTrigger::info() { warnx("Trigger state : %s", _trigger_enabled ? "enabled" : "disabled"); warnx("Trigger pin : %i", pin); warnx("Trigger polarity : %s", _polarity ? "ACTIVE_HIGH" : "ACTIVE_LOW"); warnx("Shutter integration time : %.2f", (double)_integration_time); } static void usage() { errx(1, "usage: camera_trigger {start|stop|info} [-p <n>]\n" "\t-p <n>\tUse specified AUX OUT pin number (default: 1)" ); } int camera_trigger_main(int argc, char *argv[]) { if (argc < 2) { usage(); } if (!strcmp(argv[1], "start")) { if (camera_trigger::g_camera_trigger != nullptr) { errx(0, "already running"); } camera_trigger::g_camera_trigger = new CameraTrigger; if (camera_trigger::g_camera_trigger == nullptr) { errx(1, "alloc failed"); } if (argc > 3) { camera_trigger::g_camera_trigger->pin = (int)argv[3]; if (atoi(argv[3]) > 0 && atoi(argv[3]) < 6) { warnx("starting trigger on pin : %li ", atoi(argv[3])); camera_trigger::g_camera_trigger->pin = atoi(argv[3]); } else { usage(); } } camera_trigger::g_camera_trigger->start(); return 0; } if (camera_trigger::g_camera_trigger == nullptr) { errx(1, "not running"); } else if (!strcmp(argv[1], "stop")) { camera_trigger::g_camera_trigger->stop(); } else if (!strcmp(argv[1], "info")) { camera_trigger::g_camera_trigger->info(); } else { usage(); } return 0; } <commit_msg>camera trigger : multipin support<commit_after>/**************************************************************************** * * Copyright (c) 2015 PX4 Development Team. All rights reserved. * Author: Mohammed Kabir <mhkabir98@gmail.com> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /** * @file camera_trigger.cpp * * External camera-IMU synchronisation and triggering via FMU auxillary pins. * * @author Mohammed Kabir <mhkabir98@gmail.com> */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <fcntl.h> #include <stdbool.h> #include <nuttx/clock.h> #include <nuttx/arch.h> #include <systemlib/systemlib.h> #include <systemlib/err.h> #include <systemlib/param/param.h> #include <uORB/uORB.h> #include <uORB/topics/camera_trigger.h> #include <uORB/topics/sensor_combined.h> #include <uORB/topics/vehicle_command.h> #include <poll.h> #include <drivers/drv_gpio.h> #include <drivers/drv_hrt.h> #include <mavlink/mavlink_log.h> #include <board_config.h> extern "C" __EXPORT int camera_trigger_main(int argc, char *argv[]); class CameraTrigger { public: /** * Constructor */ CameraTrigger(); /** * Destructor, also kills task. */ ~CameraTrigger(); /** * Start the task. */ void start(); /** * Stop the task. */ void stop(); /** * Display info. */ void info(); int pin; private: struct hrt_call _pollcall; struct hrt_call _firecall; int _gpio_fd; int _polarity; float _activation_time; float _integration_time; float _transfer_time; uint32_t _trigger_seq; bool _trigger_enabled; int _sensor_sub; int _vcommand_sub; orb_advert_t _trigger_pub; struct camera_trigger_s _trigger; struct sensor_combined_s _sensor; struct vehicle_command_s _command; param_t polarity ; param_t activation_time ; param_t integration_time ; param_t transfer_time ; int32_t _gpios[6] = { GPIO_GPIO0_OUTPUT, GPIO_GPIO1_OUTPUT, GPIO_GPIO2_OUTPUT, GPIO_GPIO3_OUTPUT, GPIO_GPIO4_OUTPUT, GPIO_GPIO5_OUTPUT }; /** * Topic poller to check for fire info. */ static void poll(void *arg); /** * Fires trigger */ static void engage(void *arg); /** * Resets trigger */ static void disengage(void *arg); }; namespace camera_trigger { CameraTrigger *g_camera_trigger; } CameraTrigger::CameraTrigger() : pin(1), _pollcall {}, _firecall {}, _gpio_fd(-1), _polarity(0), _activation_time(0.0f), _integration_time(0.0f), _transfer_time(0.0f), _trigger_seq(0), _trigger_enabled(false), _sensor_sub(-1), _vcommand_sub(-1), _trigger_pub(nullptr), _trigger {}, _sensor {}, _command {}, _gpios{} { memset(&_pollcall, 0, sizeof(_pollcall)); memset(&_firecall, 0, sizeof(_firecall)); memset(&_trigger, 0, sizeof(_trigger)); memset(&_sensor, 0, sizeof(_sensor)); memset(&_command, 0, sizeof(_command)); memset(&_gpios, 0, sizeof(_gpios)); // Parameters polarity = param_find("TRIG_POLARITY"); activation_time = param_find("TRIG_ACT_TIME"); integration_time = param_find("TRIG_INT_TIME"); transfer_time = param_find("TRIG_TRANS_TIME"); } CameraTrigger::~CameraTrigger() { camera_trigger::g_camera_trigger = nullptr; } void CameraTrigger::start() { _sensor_sub = orb_subscribe(ORB_ID(sensor_combined)); _vcommand_sub = orb_subscribe(ORB_ID(vehicle_command)); param_get(polarity, &_polarity); param_get(activation_time, &_activation_time); param_get(integration_time, &_integration_time); param_get(transfer_time, &_transfer_time); stm32_configgpio(_gpios[pin - 1]); if (_polarity == 0) { stm32_gpiowrite(_gpios[pin - 1], 1); // GPIO pin pull high } else if (_polarity == 1) { stm32_gpiowrite(_gpios[pin - 1], 0); // GPIO pin pull low } else { warnx(" invalid trigger polarity setting. stopping."); stop(); } poll(this); // Trampoline call } void CameraTrigger::stop() { hrt_cancel(&_firecall); hrt_cancel(&_pollcall); if (camera_trigger::g_camera_trigger != nullptr) { delete(camera_trigger::g_camera_trigger); } } void CameraTrigger::poll(void *arg) { CameraTrigger *trig = reinterpret_cast<CameraTrigger *>(arg); bool updated; orb_check(trig->_vcommand_sub, &updated); if (updated) { orb_copy(ORB_ID(vehicle_command), trig->_vcommand_sub, &trig->_command); if (trig->_command.command == vehicle_command_s::VEHICLE_CMD_DO_TRIGGER_CONTROL) { if (trig->_command.param1 < 1) { if (trig->_trigger_enabled) { trig->_trigger_enabled = false ; } } else if (trig->_command.param1 >= 1) { if (!trig->_trigger_enabled) { trig->_trigger_enabled = true ; } } // Set trigger rate from command if (trig->_command.param2 > 0) { trig->_integration_time = trig->_command.param2; param_set(trig->integration_time, &(trig->_integration_time)); } } } if (!trig->_trigger_enabled) { hrt_call_after(&trig->_pollcall, 1e6, (hrt_callout)&CameraTrigger::poll, trig); return; } else { engage(trig); hrt_call_after(&trig->_firecall, trig->_activation_time * 1000, (hrt_callout)&CameraTrigger::disengage, trig); orb_copy(ORB_ID(sensor_combined), trig->_sensor_sub, &trig->_sensor); trig->_trigger.timestamp = trig->_sensor.timestamp; // get IMU timestamp trig->_trigger.seq = trig->_trigger_seq++; if (trig->_trigger_pub != nullptr) { orb_publish(ORB_ID(camera_trigger), trig->_trigger_pub, &trig->_trigger); } else { trig->_trigger_pub = orb_advertise(ORB_ID(camera_trigger), &trig->_trigger); } hrt_call_after(&trig->_pollcall, (trig->_transfer_time + trig->_integration_time) * 1000, (hrt_callout)&CameraTrigger::poll, trig); } } void CameraTrigger::engage(void *arg) { CameraTrigger *trig = reinterpret_cast<CameraTrigger *>(arg); stm32_configgpio(trig->_gpios[trig->pin - 1]); if (trig->_polarity == 0) { // ACTIVE_LOW stm32_gpiowrite(trig->_gpios[trig->pin - 1], 0); } else if (trig->_polarity == 1) { // ACTIVE_HIGH stm32_gpiowrite(trig->_gpios[trig->pin - 1], 1); } } void CameraTrigger::disengage(void *arg) { CameraTrigger *trig = reinterpret_cast<CameraTrigger *>(arg); stm32_configgpio(trig->_gpios[trig->pin - 1]); if (trig->_polarity == 0) { // ACTIVE_LOW stm32_gpiowrite(trig->_gpios[trig->pin - 1], 1); } else if (trig->_polarity == 1) { // ACTIVE_HIGH stm32_gpiowrite(trig->_gpios[trig->pin - 1], 0); } } void CameraTrigger::info() { warnx("Trigger state : %s", _trigger_enabled ? "enabled" : "disabled"); warnx("Trigger pin : %i", pin); warnx("Trigger polarity : %s", _polarity ? "ACTIVE_HIGH" : "ACTIVE_LOW"); warnx("Shutter integration time : %.2f", (double)_integration_time); } static void usage() { errx(1, "usage: camera_trigger {start|stop|info} [-p <n>]\n" "\t-p <n>\tUse specified AUX OUT pin number (default: 1)" ); } int camera_trigger_main(int argc, char *argv[]) { if (argc < 2) { usage(); } if (!strcmp(argv[1], "start")) { if (camera_trigger::g_camera_trigger != nullptr) { errx(0, "already running"); } camera_trigger::g_camera_trigger = new CameraTrigger; if (camera_trigger::g_camera_trigger == nullptr) { errx(1, "alloc failed"); } if (argc > 3) { camera_trigger::g_camera_trigger->pin = (int)argv[3]; if (atoi(argv[3]) > 0 && atoi(argv[3]) < 6) { warnx("starting trigger on pin : %li ", atoi(argv[3])); camera_trigger::g_camera_trigger->pin = atoi(argv[3]); } else { usage(); } } camera_trigger::g_camera_trigger->start(); return 0; } if (camera_trigger::g_camera_trigger == nullptr) { errx(1, "not running"); } else if (!strcmp(argv[1], "stop")) { camera_trigger::g_camera_trigger->stop(); } else if (!strcmp(argv[1], "info")) { camera_trigger::g_camera_trigger->info(); } else { usage(); } return 0; } <|endoftext|>
<commit_before>#include <iostream> template<class T> struct type_to_string; template<> struct type_to_string<char> { static constexpr const char *get(){return "char";}; }; template<> struct type_to_string<short int> { static constexpr const char *get(){return "short int";}; }; template<> struct type_to_string<int> { static constexpr const char *get(){return "int";}; }; template<> struct type_to_string<long int> { static constexpr const char *get(){return "long int";} }; struct Const { static constexpr const char* get() { return " const"; } }; struct Volatile { static constexpr const char* get() { return " volatile"; } }; struct Pointer { static constexpr const char* get() { return "*"; } }; struct LValRef { static constexpr const char* get() { return "&"; } }; struct RValRef { static constexpr const char* get() { return "&&"; } }; template<char... Cs> struct metastring {}; template<char... Cs> std::ostream& operator<<(std::ostream& os, metastring<Cs...>) { const char data[sizeof...(Cs)] = {Cs...}; os << data; return os; } template<size_t N, char... Cs> struct number_string { using type = typename number_string<N/10, '0'+(N%10), Cs...>::type; }; template<char... Cs> struct number_string<0,Cs...> { using type = metastring<'*','[',Cs...,']'>; }; template<size_t N> struct Array { using metastring = typename number_string<N>::type; static constexpr metastring get() { return metastring{}; } }; template<class...> struct QualPrinter { friend void operator<<(std::ostream &os, const QualPrinter &) {} }; template<class Qual, class... Quals> struct QualPrinter<Qual, Quals...> { friend std::ostream& operator<<(std::ostream& os, const QualPrinter&) { os << Qual::get()<< QualPrinter<Quals...>(); return os; } }; template<class Type, class... Quals> struct type_descriptor { friend std::ostream& operator<<(std::ostream& os, const type_descriptor&) { os << type_to_string<Type>::get() << QualPrinter<Quals...>(); return os; } }; template <class T, class... Quals> struct type_descriptor<T const, Quals...> : type_descriptor<T, Const, Quals...> {}; template <class T, class... Quals> struct type_descriptor<T volatile, Quals...> : type_descriptor<T, Volatile, Quals...> {}; template <class T, class... Quals> struct type_descriptor<T *, Quals...> : type_descriptor<T, Pointer, Quals...> {}; template <class T, class... Quals> struct type_descriptor<T &, Quals...> : type_descriptor<T, LValRef, Quals...> {}; template <class T, class... Quals> struct type_descriptor<T &&, Quals...> : type_descriptor<T, RValRef, Quals...> {}; template <class T, size_t N, class... Quals> struct type_descriptor<T *[N], Quals...> : type_descriptor<T, Array<N>, Quals...> {}; int main() { using namespace std; cout << type_descriptor<int>() << endl; cout << type_descriptor<long int>() << endl; cout << type_descriptor<char >() << endl; cout << type_descriptor<short >() << endl; cout << type_descriptor<int const*& >() << endl; cout << type_descriptor<int const*&& >() << endl; cout << type_descriptor<int const* volatile >() << endl; cout << type_descriptor<int * volatile >() << endl; cout << type_descriptor<long const* volatile>() << endl; cout << type_descriptor<long const*[29]>() << endl; } <commit_msg>put << operator inside metastring<commit_after>#include <iostream> template<class T> struct type_to_string; template<> struct type_to_string<char> { static constexpr const char *get(){return "char";}; }; template<> struct type_to_string<short int> { static constexpr const char *get(){return "short int";}; }; template<> struct type_to_string<int> { static constexpr const char *get(){return "int";}; }; template<> struct type_to_string<long int> { static constexpr const char *get(){return "long int";} }; struct Const { static constexpr const char* get() { return " const"; } }; struct Volatile { static constexpr const char* get() { return " volatile"; } }; struct Pointer { static constexpr const char* get() { return "*"; } }; struct LValRef { static constexpr const char* get() { return "&"; } }; struct RValRef { static constexpr const char* get() { return "&&"; } }; template<char... Cs> struct metastring { friend std::ostream &operator<<(std::ostream &os, metastring) { const char data[sizeof...(Cs)] = {Cs...}; os << data; return os; } }; template<size_t N, char... Cs> struct number_string { using type = typename number_string<N/10, '0'+(N%10), Cs...>::type; }; template<char... Cs> struct number_string<0,Cs...> { using type = metastring<'*','[',Cs...,']'>; }; template<size_t N> struct Array { using metastring = typename number_string<N>::type; static const metastring get() { return metastring{}; } }; template<class...> struct QualPrinter { friend void operator<<(std::ostream &os, const QualPrinter &) {} }; template<class Qual, class... Quals> struct QualPrinter<Qual, Quals...> { friend std::ostream& operator<<(std::ostream& os, const QualPrinter&) { os << Qual::get()<< QualPrinter<Quals...>(); return os; } }; template<class Type, class... Quals> struct type_descriptor { friend std::ostream& operator<<(std::ostream& os, const type_descriptor&) { os << type_to_string<Type>::get() << QualPrinter<Quals...>(); return os; } }; template <class T, class... Quals> struct type_descriptor<T const, Quals...> : type_descriptor<T, Const, Quals...> {}; template <class T, class... Quals> struct type_descriptor<T volatile, Quals...> : type_descriptor<T, Volatile, Quals...> {}; template <class T, class... Quals> struct type_descriptor<T *, Quals...> : type_descriptor<T, Pointer, Quals...> {}; template <class T, class... Quals> struct type_descriptor<T &, Quals...> : type_descriptor<T, LValRef, Quals...> {}; template <class T, class... Quals> struct type_descriptor<T &&, Quals...> : type_descriptor<T, RValRef, Quals...> {}; template <class T, size_t N, class... Quals> struct type_descriptor<T *[N], Quals...> : type_descriptor<T, Array<N>, Quals...> {}; int main() { using namespace std; cout << type_descriptor<int>() << endl; cout << type_descriptor<long int>() << endl; cout << type_descriptor<char >() << endl; cout << type_descriptor<short >() << endl; cout << type_descriptor<int const*& >() << endl; cout << type_descriptor<int const*&& >() << endl; cout << type_descriptor<int const* volatile >() << endl; cout << type_descriptor<int * volatile >() << endl; cout << type_descriptor<long const* volatile>() << endl; cout << type_descriptor<long const*[29]>() << endl; } <|endoftext|>
<commit_before>#include <QString> #include <QtTest> #include <libgpsbip/OptionTypes.h> #include <libgpsbip/OptionsGroupBase.h> class MockGroup : public gpsbip::OptionsGroupBase { Q_OBJECT public: MockGroup() { auto r = new gpsbip::BoolOption(); root = addOption(r); opt = addOption<gpsbip::BoolOption>("label"); strOpt = addOption<gpsbip::StringOption>(*r, "label"); } gpsbip::BoolOption* getRootOption() { return &get<gpsbip::BoolOption>(root); } gpsbip::BoolOption* getOption() { return &get<gpsbip::BoolOption>(opt); } gpsbip::StringOption* getStrOption() { return &get<gpsbip::StringOption>(strOpt); } private: int root, opt, strOpt; }; class Tst_optionsGroups : public QObject { Q_OBJECT public: Tst_optionsGroups(); private Q_SLOTS: void testOptionGroupMechanic(); }; Tst_optionsGroups::Tst_optionsGroups() { } void Tst_optionsGroups::testOptionGroupMechanic() { // Validates all 3 addOption variants MockGroup g; // Validates get<> gpsbip::BoolOption *root = g.getRootOption(); QVERIFY(root != nullptr); gpsbip::BoolOption *opt = g.getOption(); QVERIFY(opt != nullptr); } QTEST_APPLESS_MAIN(Tst_optionsGroups) #include "tst_optionsgroups.moc" <commit_msg>More base group checking (forgot to refresh before committing previous changes, sorry!)<commit_after>#include <QString> #include <QtTest> #include <libgpsbip/OptionTypes.h> #include <libgpsbip/OptionsGroupBase.h> class MockGroup : public gpsbip::OptionsGroupBase { Q_OBJECT public: MockGroup() { auto r = new gpsbip::BoolOption(); root = addOption(r); opt = addOption<gpsbip::BoolOption>("label"); strOpt = addOption<gpsbip::StringOption>(*r, "label"); } gpsbip::BoolOption* getRootOption() { return &get<gpsbip::BoolOption>(root); } gpsbip::BoolOption* getOption() { return &get<gpsbip::BoolOption>(opt); } gpsbip::StringOption* getStrOption() { return &get<gpsbip::StringOption>(strOpt); } private: int root, opt, strOpt; }; class Tst_optionsGroups : public QObject { Q_OBJECT public: Tst_optionsGroups(); private Q_SLOTS: void testOptionGroupMechanic(); }; Tst_optionsGroups::Tst_optionsGroups() { } void Tst_optionsGroups::testOptionGroupMechanic() { try { // Validates all 3 addOption variants (by definition, can't really assert that :/) MockGroup g; // Validates get<> gpsbip::BoolOption *root = g.getRootOption(); QVERIFY(root != nullptr); gpsbip::BoolOption *opt = g.getOption(); QVERIFY(opt != nullptr); gpsbip::StringOption *str = g.getStrOption(); QVERIFY(str != nullptr); // Confirm that the string option is dependant on the root one and that the expected addOption was used QCOMPARE(str->isEnabled(), false); *root = true; QCOMPARE(str->isEnabled(), true); } catch (std::exception &e) { QFAIL(e.what()); } } QTEST_APPLESS_MAIN(Tst_optionsGroups) #include "tst_optionsgroups.moc" <|endoftext|>
<commit_before>/** * acljobs.cpp * * Copyright (c) 2004 David Faure <faure@kde.org> * * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 2 of the License * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * In addition, as a special exception, the copyright holders give * permission to link the code of this program with any edition of * the Qt library by Trolltech AS, Norway (or with modified versions * of Qt that use the same license as Qt), and distribute linked * combinations including the two. You must obey the GNU General * Public License in all respects for all of the code used other than * Qt. If you modify this file, you may extend this exception to * your version of the file, but you are not obligated to do so. If * you do not wish to do so, delete this exception statement from * your version. */ #include "acljobs.h" #include <kio/scheduler.h> #include <kdebug.h> using namespace KMail; // Convert str to an ACLPermissions value. // url and user are there only for the error message static unsigned int IMAPRightsToPermission( const QString& str, const KURL& url, const QString& user ) { unsigned int perm = 0; bool foundSeenPerm = false; uint len = str.length(); for (uint i = 0; i < len; ++i) { QChar ch = str[i]; switch ( ch.latin1() ) { case 'l': perm |= ACLJobs::List; break; case 'r': perm |= ACLJobs::Read; break; case 's': foundSeenPerm = true; break; case 'w': perm |= ACLJobs::WriteFlags; break; case 'i': perm |= ACLJobs::Insert; break; case 'p': perm |= ACLJobs::Post; break; case 'c': perm |= ACLJobs::Create; break; case 'd': perm |= ACLJobs::Delete; break; case 'a': perm |= ACLJobs::Administer; break; default: break; } } if ( ( perm & ACLJobs::Read ) && str.find( 's' ) == -1 ) { // Reading without 'seen' is, well, annoying. Unusable, even. // So we treat 'rs' as a single one. // But if the permissions were set out of kmail, better check that both are set kdWarning(5006) << "IMAPRightsToPermission: found read (r) but not seen (s). Things will not work well for folder " << url << " and user " << ( user.isEmpty() ? "myself" : user ) << endl; if ( perm & ACLJobs::Administer ) kdWarning(5006) << "You can change this yourself in the ACL dialog" << endl; else kdWarning(5006) << "Ask your admin for 's' permissions." << endl; // Is the above correct enough to be turned into a KMessageBox? } return perm; } static QCString permissionsToIMAPRights( unsigned int permissions ) { QCString str = ""; if ( permissions & ACLJobs::List ) str += 'l'; if ( permissions & ACLJobs::Read ) str += "rs"; if ( permissions & ACLJobs::WriteFlags ) str += 'w'; if ( permissions & ACLJobs::Insert ) str += 'i'; if ( permissions & ACLJobs::Post ) str += 'p'; if ( permissions & ACLJobs::Create ) str += 'c'; if ( permissions & ACLJobs::Delete ) str += 'd'; if ( permissions & ACLJobs::Administer ) str += 'a'; return str; } #ifndef NDEBUG QString ACLJobs::permissionsToString( unsigned int permissions ) { QString str; if ( permissions & ACLJobs::List ) str += "List "; if ( permissions & ACLJobs::Read ) str += "Read "; if ( permissions & ACLJobs::WriteFlags ) str += "Write "; if ( permissions & ACLJobs::Insert ) str += "Insert "; if ( permissions & ACLJobs::Post ) str += "Post "; if ( permissions & ACLJobs::Create ) str += "Create "; if ( permissions & ACLJobs::Delete ) str += "Delete "; if ( permissions & ACLJobs::Administer ) str += "Administer "; if ( !str.isEmpty() ) str.truncate( str.length() - 1 ); return str; } #endif KIO::SimpleJob* ACLJobs::setACL( KIO::Slave* slave, const KURL& url, const QString& user, unsigned int permissions ) { QString perm = QString::fromLatin1( permissionsToIMAPRights( permissions ) ); QByteArray packedArgs; QDataStream stream( packedArgs, IO_WriteOnly ); stream << (int)'A' << (int)'S' << url << user << perm; KIO::SimpleJob* job = KIO::special( url, packedArgs, false ); KIO::Scheduler::assignJobToSlave( slave, job ); return job; } ACLJobs::DeleteACLJob* ACLJobs::deleteACL( KIO::Slave* slave, const KURL& url, const QString& user ) { QByteArray packedArgs; QDataStream stream( packedArgs, IO_WriteOnly ); stream << (int)'A' << (int)'D' << url << user; ACLJobs::DeleteACLJob* job = new ACLJobs::DeleteACLJob( url, user, packedArgs, false ); KIO::Scheduler::assignJobToSlave( slave, job ); return job; } ACLJobs::GetACLJob* ACLJobs::getACL( KIO::Slave* slave, const KURL& url ) { QByteArray packedArgs; QDataStream stream( packedArgs, IO_WriteOnly ); stream << (int)'A' << (int)'G' << url; ACLJobs::GetACLJob* job = new ACLJobs::GetACLJob( url, packedArgs, false ); KIO::Scheduler::assignJobToSlave( slave, job ); return job; } ACLJobs::GetUserRightsJob* ACLJobs::getUserRights( KIO::Slave* slave, const KURL& url ) { QByteArray packedArgs; QDataStream stream( packedArgs, IO_WriteOnly ); stream << (int)'A' << (int)'M' << url; ACLJobs::GetUserRightsJob* job = new ACLJobs::GetUserRightsJob( url, packedArgs, false ); KIO::Scheduler::assignJobToSlave( slave, job ); return job; } ACLJobs::GetACLJob::GetACLJob( const KURL& url, const QByteArray &packedArgs, bool showProgressInfo ) : KIO::SimpleJob( url, KIO::CMD_SPECIAL, packedArgs, showProgressInfo ) { connect( this, SIGNAL(infoMessage(KIO::Job*,const QString&)), SLOT(slotInfoMessage(KIO::Job*,const QString&)) ); } void ACLJobs::GetACLJob::slotInfoMessage( KIO::Job*, const QString& str ) { // Parse the result QStringList lst = QStringList::split( " ", str ); while ( lst.count() >= 2 ) // we take items 2 by 2 { QString user = lst.front(); lst.pop_front(); QString imapRights = lst.front(); lst.pop_front(); unsigned int perm = IMAPRightsToPermission( imapRights, url(), user ); m_entries.append( ACLListEntry( user, imapRights, perm ) ); } } ACLJobs::GetUserRightsJob::GetUserRightsJob( const KURL& url, const QByteArray &packedArgs, bool showProgressInfo ) : KIO::SimpleJob( url, KIO::CMD_SPECIAL, packedArgs, showProgressInfo ) { connect( this, SIGNAL(infoMessage(KIO::Job*,const QString&)), SLOT(slotInfoMessage(KIO::Job*,const QString&)) ); } void ACLJobs::GetUserRightsJob::slotInfoMessage( KIO::Job*, const QString& str ) { // Parse the result m_permissions = IMAPRightsToPermission( str, url(), QString::null ); } ACLJobs::DeleteACLJob::DeleteACLJob( const KURL& url, const QString& userId, const QByteArray &packedArgs, bool showProgressInfo ) : KIO::SimpleJob( url, KIO::CMD_SPECIAL, packedArgs, showProgressInfo ), mUserId( userId ) { } //// ACLJobs::MultiSetACLJob::MultiSetACLJob( KIO::Slave* slave, const KURL& url, const ACLList& acl, bool showProgressInfo ) : KIO::Job( showProgressInfo ), mSlave( slave ), mUrl( url ), mACLList( acl ), mACLListIterator( mACLList.begin() ) { QTimer::singleShot(0, this, SLOT(slotStart())); } void ACLJobs::MultiSetACLJob::slotStart() { // Skip over unchanged entries while ( mACLListIterator != mACLList.end() && !(*mACLListIterator).changed ) ++mACLListIterator; if ( mACLListIterator != mACLList.end() ) { const ACLListEntry& entry = *mACLListIterator; KIO::Job* job = 0; if ( entry.permissions > -1 ) job = setACL( mSlave, mUrl, entry.userId, entry.permissions ); else job = deleteACL( mSlave, mUrl, entry.userId ); addSubjob( job ); } else { // done! emitResult(); } } void ACLJobs::MultiSetACLJob::slotResult( KIO::Job *job ) { if ( job->error() ) { KIO::Job::slotResult( job ); // will set the error and emit result(this) return; } subjobs.remove(job); const ACLListEntry& entry = *mACLListIterator; emit aclChanged( entry.userId, entry.permissions ); // Move on to next one ++mACLListIterator; slotStart(); } ACLJobs::MultiSetACLJob* ACLJobs::multiSetACL( KIO::Slave* slave, const KURL& url, const ACLList& acl ) { return new MultiSetACLJob( slave, url, acl, false /*showProgressInfo*/ ); } #include "acljobs.moc" <commit_msg>Don't drop the empty fields of the ACL description.<commit_after>/** * acljobs.cpp * * Copyright (c) 2004 David Faure <faure@kde.org> * * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 2 of the License * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * In addition, as a special exception, the copyright holders give * permission to link the code of this program with any edition of * the Qt library by Trolltech AS, Norway (or with modified versions * of Qt that use the same license as Qt), and distribute linked * combinations including the two. You must obey the GNU General * Public License in all respects for all of the code used other than * Qt. If you modify this file, you may extend this exception to * your version of the file, but you are not obligated to do so. If * you do not wish to do so, delete this exception statement from * your version. */ #include "acljobs.h" #include <kio/scheduler.h> #include <kdebug.h> using namespace KMail; // Convert str to an ACLPermissions value. // url and user are there only for the error message static unsigned int IMAPRightsToPermission( const QString& str, const KURL& url, const QString& user ) { unsigned int perm = 0; bool foundSeenPerm = false; uint len = str.length(); for (uint i = 0; i < len; ++i) { QChar ch = str[i]; switch ( ch.latin1() ) { case 'l': perm |= ACLJobs::List; break; case 'r': perm |= ACLJobs::Read; break; case 's': foundSeenPerm = true; break; case 'w': perm |= ACLJobs::WriteFlags; break; case 'i': perm |= ACLJobs::Insert; break; case 'p': perm |= ACLJobs::Post; break; case 'c': perm |= ACLJobs::Create; break; case 'd': perm |= ACLJobs::Delete; break; case 'a': perm |= ACLJobs::Administer; break; default: break; } } if ( ( perm & ACLJobs::Read ) && str.find( 's' ) == -1 ) { // Reading without 'seen' is, well, annoying. Unusable, even. // So we treat 'rs' as a single one. // But if the permissions were set out of kmail, better check that both are set kdWarning(5006) << "IMAPRightsToPermission: found read (r) but not seen (s). Things will not work well for folder " << url << " and user " << ( user.isEmpty() ? "myself" : user ) << endl; if ( perm & ACLJobs::Administer ) kdWarning(5006) << "You can change this yourself in the ACL dialog" << endl; else kdWarning(5006) << "Ask your admin for 's' permissions." << endl; // Is the above correct enough to be turned into a KMessageBox? } return perm; } static QCString permissionsToIMAPRights( unsigned int permissions ) { QCString str = ""; if ( permissions & ACLJobs::List ) str += 'l'; if ( permissions & ACLJobs::Read ) str += "rs"; if ( permissions & ACLJobs::WriteFlags ) str += 'w'; if ( permissions & ACLJobs::Insert ) str += 'i'; if ( permissions & ACLJobs::Post ) str += 'p'; if ( permissions & ACLJobs::Create ) str += 'c'; if ( permissions & ACLJobs::Delete ) str += 'd'; if ( permissions & ACLJobs::Administer ) str += 'a'; return str; } #ifndef NDEBUG QString ACLJobs::permissionsToString( unsigned int permissions ) { QString str; if ( permissions & ACLJobs::List ) str += "List "; if ( permissions & ACLJobs::Read ) str += "Read "; if ( permissions & ACLJobs::WriteFlags ) str += "Write "; if ( permissions & ACLJobs::Insert ) str += "Insert "; if ( permissions & ACLJobs::Post ) str += "Post "; if ( permissions & ACLJobs::Create ) str += "Create "; if ( permissions & ACLJobs::Delete ) str += "Delete "; if ( permissions & ACLJobs::Administer ) str += "Administer "; if ( !str.isEmpty() ) str.truncate( str.length() - 1 ); return str; } #endif KIO::SimpleJob* ACLJobs::setACL( KIO::Slave* slave, const KURL& url, const QString& user, unsigned int permissions ) { QString perm = QString::fromLatin1( permissionsToIMAPRights( permissions ) ); QByteArray packedArgs; QDataStream stream( packedArgs, IO_WriteOnly ); stream << (int)'A' << (int)'S' << url << user << perm; KIO::SimpleJob* job = KIO::special( url, packedArgs, false ); KIO::Scheduler::assignJobToSlave( slave, job ); return job; } ACLJobs::DeleteACLJob* ACLJobs::deleteACL( KIO::Slave* slave, const KURL& url, const QString& user ) { QByteArray packedArgs; QDataStream stream( packedArgs, IO_WriteOnly ); stream << (int)'A' << (int)'D' << url << user; ACLJobs::DeleteACLJob* job = new ACLJobs::DeleteACLJob( url, user, packedArgs, false ); KIO::Scheduler::assignJobToSlave( slave, job ); return job; } ACLJobs::GetACLJob* ACLJobs::getACL( KIO::Slave* slave, const KURL& url ) { QByteArray packedArgs; QDataStream stream( packedArgs, IO_WriteOnly ); stream << (int)'A' << (int)'G' << url; ACLJobs::GetACLJob* job = new ACLJobs::GetACLJob( url, packedArgs, false ); KIO::Scheduler::assignJobToSlave( slave, job ); return job; } ACLJobs::GetUserRightsJob* ACLJobs::getUserRights( KIO::Slave* slave, const KURL& url ) { QByteArray packedArgs; QDataStream stream( packedArgs, IO_WriteOnly ); stream << (int)'A' << (int)'M' << url; ACLJobs::GetUserRightsJob* job = new ACLJobs::GetUserRightsJob( url, packedArgs, false ); KIO::Scheduler::assignJobToSlave( slave, job ); return job; } ACLJobs::GetACLJob::GetACLJob( const KURL& url, const QByteArray &packedArgs, bool showProgressInfo ) : KIO::SimpleJob( url, KIO::CMD_SPECIAL, packedArgs, showProgressInfo ) { connect( this, SIGNAL(infoMessage(KIO::Job*,const QString&)), SLOT(slotInfoMessage(KIO::Job*,const QString&)) ); } void ACLJobs::GetACLJob::slotInfoMessage( KIO::Job*, const QString& str ) { // Parse the result QStringList lst = QStringList::split( " ", str, true ); while ( lst.count() >= 2 ) // we take items 2 by 2 { QString user = lst.front(); lst.pop_front(); QString imapRights = lst.front(); lst.pop_front(); unsigned int perm = IMAPRightsToPermission( imapRights, url(), user ); m_entries.append( ACLListEntry( user, imapRights, perm ) ); } } ACLJobs::GetUserRightsJob::GetUserRightsJob( const KURL& url, const QByteArray &packedArgs, bool showProgressInfo ) : KIO::SimpleJob( url, KIO::CMD_SPECIAL, packedArgs, showProgressInfo ) { connect( this, SIGNAL(infoMessage(KIO::Job*,const QString&)), SLOT(slotInfoMessage(KIO::Job*,const QString&)) ); } void ACLJobs::GetUserRightsJob::slotInfoMessage( KIO::Job*, const QString& str ) { // Parse the result m_permissions = IMAPRightsToPermission( str, url(), QString::null ); } ACLJobs::DeleteACLJob::DeleteACLJob( const KURL& url, const QString& userId, const QByteArray &packedArgs, bool showProgressInfo ) : KIO::SimpleJob( url, KIO::CMD_SPECIAL, packedArgs, showProgressInfo ), mUserId( userId ) { } //// ACLJobs::MultiSetACLJob::MultiSetACLJob( KIO::Slave* slave, const KURL& url, const ACLList& acl, bool showProgressInfo ) : KIO::Job( showProgressInfo ), mSlave( slave ), mUrl( url ), mACLList( acl ), mACLListIterator( mACLList.begin() ) { QTimer::singleShot(0, this, SLOT(slotStart())); } void ACLJobs::MultiSetACLJob::slotStart() { // Skip over unchanged entries while ( mACLListIterator != mACLList.end() && !(*mACLListIterator).changed ) ++mACLListIterator; if ( mACLListIterator != mACLList.end() ) { const ACLListEntry& entry = *mACLListIterator; KIO::Job* job = 0; if ( entry.permissions > -1 ) job = setACL( mSlave, mUrl, entry.userId, entry.permissions ); else job = deleteACL( mSlave, mUrl, entry.userId ); addSubjob( job ); } else { // done! emitResult(); } } void ACLJobs::MultiSetACLJob::slotResult( KIO::Job *job ) { if ( job->error() ) { KIO::Job::slotResult( job ); // will set the error and emit result(this) return; } subjobs.remove(job); const ACLListEntry& entry = *mACLListIterator; emit aclChanged( entry.userId, entry.permissions ); // Move on to next one ++mACLListIterator; slotStart(); } ACLJobs::MultiSetACLJob* ACLJobs::multiSetACL( KIO::Slave* slave, const KURL& url, const ACLList& acl ) { return new MultiSetACLJob( slave, url, acl, false /*showProgressInfo*/ ); } #include "acljobs.moc" <|endoftext|>
<commit_before>/*************************************************************************** main.cpp - description ------------------- begin : Wed Aug 2 11:23:04 CEST 2000 copyright : (C) 2000 by Hans Dijkema email : kmailcvt@hum.org ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include <kcmdlineargs.h> #include <kaboutdata.h> #include <dcopclient.h> #include "kmailcvt.h" static const KCmdLineOptions options[] = { KCmdLineLastOption }; int main(int argc, char *argv[]) { KLocale::setMainCatalogue("kmailcvt"); KAboutData aboutData( "kmailcvt", I18N_NOOP("KMailCVT"), "3", I18N_NOOP("KMail Import Filters"), KAboutData::License_GPL_V2, I18N_NOOP("(c) 2000-2003, The KMailCVT developers")); aboutData.addAuthor("Hans Dijkema",I18N_NOOP("Original author"), "kmailcvt@hum.org"); aboutData.addAuthor("Laurence Anderson", I18N_NOOP("New GUI & cleanups"), "l.d.anderson@warwick.ac.uk"); aboutData.addCredit("Daniel Molkentin", I18N_NOOP("New GUI & cleanups"), "molkentin@kde.org"); KCmdLineArgs::init( argc, argv, &aboutData ); KCmdLineArgs::addCmdLineOptions( options ); // Add our own options. KApplication a; KMailCVT *kmailcvt = new KMailCVT(); a.setMainWidget(kmailcvt); kmailcvt->show(); DCOPClient *client=a.dcopClient(); if (!client->attach()) { return 1; } return a.exec(); } <commit_msg>- added me to authors<commit_after>/*************************************************************************** main.cpp - description ------------------- begin : Wed Aug 2 11:23:04 CEST 2000 copyright : (C) 2000 by Hans Dijkema email : kmailcvt@hum.org ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include <kcmdlineargs.h> #include <kaboutdata.h> #include <dcopclient.h> #include "kmailcvt.h" static const KCmdLineOptions options[] = { KCmdLineLastOption }; int main(int argc, char *argv[]) { KLocale::setMainCatalogue("kmailcvt"); KAboutData aboutData( "kmailcvt", I18N_NOOP("KMailCVT"), "3", I18N_NOOP("KMail Import Filters"), KAboutData::License_GPL_V2, I18N_NOOP("(c) 2000-2003, The KMailCVT developers")); aboutData.addAuthor("Hans Dijkema",I18N_NOOP("Original author"), "kmailcvt@hum.org"); aboutData.addAuthor("Laurence Anderson", I18N_NOOP("New GUI & cleanups"), "l.d.anderson@warwick.ac.uk"); aboutData.addAuthor("Danny Kukawka", I18N_NOOP("New GUI & cleanups"), "danny.kukawka@web.de"); aboutData.addCredit("Daniel Molkentin", I18N_NOOP("New GUI & cleanups"), "molkentin@kde.org"); KCmdLineArgs::init( argc, argv, &aboutData ); KCmdLineArgs::addCmdLineOptions( options ); // Add our own options. KApplication a; KMailCVT *kmailcvt = new KMailCVT(); a.setMainWidget(kmailcvt); kmailcvt->show(); DCOPClient *client=a.dcopClient(); if (!client->attach()) { return 1; } return a.exec(); } <|endoftext|>
<commit_before>#include <Common.hpp> #include <Engine.hpp> #include <Dispatch.hpp> #include <MessageProcessor.hpp> #include <functional> #include <iostream> #include <sstream> #include <fstream> #include <boost/regex.hpp> #include <boost/thread/thread.hpp> namespace K3 { std::string localhost = "127.0.0.1"; Address peer1; Address peer2; Address rendezvous; int nodeCounter(0); int numSent(0); string message; using std::cout; using std::endl; using std::bind; using std::string; using std::shared_ptr; // "Trigger" Declarations void join(shared_ptr<Engine> engine, string message_contents) { Message m = Message(rendezvous, "register", message); engine->send(m); } void register2(shared_ptr<Engine> engine, string message_contents) { int n = 1; nodeCounter += n; std::cout << "Length (mB)" << message_contents.length() / (1024*1024.0) << ". Number:" << nodeCounter<< std::endl; } // MP setup TriggerDispatch buildTable(shared_ptr<Engine> engine) { TriggerDispatch table = TriggerDispatch(); table["join"] = bind(&K3::join, engine, std::placeholders::_1); table["register"] = bind(&K3::register2, engine, std::placeholders::_1); return table; } shared_ptr<MessageProcessor> buildMP(shared_ptr<Engine> engine) { auto table = buildTable(engine); shared_ptr<MessageProcessor> mp = make_shared<DispatchMessageProcessor>(DispatchMessageProcessor(table)); return mp; } // Engine setup shared_ptr<Engine> buildEngine(bool simulation, SystemEnvironment s_env) { // Configure engine components shared_ptr<InternalCodec> i_cdec = make_shared<LengthHeaderInternalCodec>(LengthHeaderInternalCodec()); // Construct an engine Engine engine = Engine(simulation, s_env, i_cdec); return make_shared<Engine>(engine); } } void runReceiver(int num_messages) { K3::peer1 = K3::make_address("192.168.0.11", 3000); K3::nodeCounter = 0; using boost::thread; using boost::thread_group; using std::shared_ptr; // Create engines auto engine1 = K3::buildEngine(false, K3::defaultEnvironment(K3::peer1)); // Create MPs auto mp1 = K3::buildMP(engine1); // Fork a thread for each engine auto service_threads = std::shared_ptr<thread_group>(new thread_group()); shared_ptr<thread> t1 = engine1->forkEngine(mp1); service_threads->add_thread(t1.get()); int desired = num_messages; while ((K3::nodeCounter < desired)) { continue; } engine1->forceTerminateEngine(); service_threads->join_all(); service_threads->remove_thread(t1.get()); } void runSender(int num_messages, int message_len, string rendez) { K3::message = ""; for (int i=0; i< message_len; i++) { K3::message += "a"; } using boost::thread; using boost::thread_group; using std::shared_ptr; // Create peers K3::peer1 = K3::make_address(rendez, 3000); K3::peer2 = K3::make_address(K3::localhost, 3000); K3::rendezvous = K3::peer1; // Create engines auto engine2 = K3::buildEngine(false, K3::defaultEnvironment(K3::peer2)); // Create MPs auto mp2 = K3::buildMP(engine2); // Create initial messages (source) K3::Message m2 = K3::Message(K3::peer2, "join", "()"); for (int i = 0; i < num_messages; i++) { engine2->send(m2); } engine2->runEngine(mp2); } int main(int argc, char** argv) { if (argc < 3) { std::cout << "usage: " << argv[0] << " num_messages" << " sender|receiver (IP of receiver)" << std::endl; return -1; } int num_messages = std::atoi(argv[1]); std::string mode = argv[2]; if (mode == "receiver") { runReceiver(num_messages); } else { if (argc < 4) { std::cout << "must provide ip of reciever!" << std::endl; return -1; } runSender(num_messages, 10, argv[3]); } return 0; } <commit_msg>fixed missing std:: prefix<commit_after>#include <Common.hpp> #include <Engine.hpp> #include <Dispatch.hpp> #include <MessageProcessor.hpp> #include <functional> #include <iostream> #include <sstream> #include <fstream> #include <boost/regex.hpp> #include <boost/thread/thread.hpp> namespace K3 { std::string localhost = "127.0.0.1"; Address peer1; Address peer2; Address rendezvous; int nodeCounter(0); int numSent(0); string message; using std::cout; using std::endl; using std::bind; using std::string; using std::shared_ptr; // "Trigger" Declarations void join(shared_ptr<Engine> engine, string message_contents) { Message m = Message(rendezvous, "register", message); engine->send(m); } void register2(shared_ptr<Engine> engine, string message_contents) { int n = 1; nodeCounter += n; std::cout << "Length (mB)" << message_contents.length() / (1024*1024.0) << ". Number:" << nodeCounter<< std::endl; } // MP setup TriggerDispatch buildTable(shared_ptr<Engine> engine) { TriggerDispatch table = TriggerDispatch(); table["join"] = bind(&K3::join, engine, std::placeholders::_1); table["register"] = bind(&K3::register2, engine, std::placeholders::_1); return table; } shared_ptr<MessageProcessor> buildMP(shared_ptr<Engine> engine) { auto table = buildTable(engine); shared_ptr<MessageProcessor> mp = make_shared<DispatchMessageProcessor>(DispatchMessageProcessor(table)); return mp; } // Engine setup shared_ptr<Engine> buildEngine(bool simulation, SystemEnvironment s_env) { // Configure engine components shared_ptr<InternalCodec> i_cdec = make_shared<LengthHeaderInternalCodec>(LengthHeaderInternalCodec()); // Construct an engine Engine engine = Engine(simulation, s_env, i_cdec); return make_shared<Engine>(engine); } } void runReceiver(int num_messages) { K3::peer1 = K3::make_address("192.168.0.11", 3000); K3::nodeCounter = 0; using boost::thread; using boost::thread_group; using std::shared_ptr; // Create engines auto engine1 = K3::buildEngine(false, K3::defaultEnvironment(K3::peer1)); // Create MPs auto mp1 = K3::buildMP(engine1); // Fork a thread for each engine auto service_threads = std::shared_ptr<thread_group>(new thread_group()); shared_ptr<thread> t1 = engine1->forkEngine(mp1); service_threads->add_thread(t1.get()); int desired = num_messages; while ((K3::nodeCounter < desired)) { continue; } engine1->forceTerminateEngine(); service_threads->join_all(); service_threads->remove_thread(t1.get()); } void runSender(int num_messages, int message_len, std::string rendez) { K3::message = ""; for (int i=0; i< message_len; i++) { K3::message += "a"; } using boost::thread; using boost::thread_group; using std::shared_ptr; // Create peers K3::peer1 = K3::make_address(rendez, 3000); K3::peer2 = K3::make_address(K3::localhost, 3000); K3::rendezvous = K3::peer1; // Create engines auto engine2 = K3::buildEngine(false, K3::defaultEnvironment(K3::peer2)); // Create MPs auto mp2 = K3::buildMP(engine2); // Create initial messages (source) K3::Message m2 = K3::Message(K3::peer2, "join", "()"); for (int i = 0; i < num_messages; i++) { engine2->send(m2); } engine2->runEngine(mp2); } int main(int argc, char** argv) { if (argc < 3) { std::cout << "usage: " << argv[0] << " num_messages" << " sender|receiver (IP of receiver)" << std::endl; return -1; } int num_messages = std::atoi(argv[1]); std::string mode = argv[2]; if (mode == "receiver") { runReceiver(num_messages); } else { if (argc < 4) { std::cout << "must provide ip of reciever!" << std::endl; return -1; } runSender(num_messages, 10, argv[3]); } return 0; } <|endoftext|>
<commit_before>#include <algorithm> #include <fstream> #include <iomanip> #include <iostream> #include <sstream> #include <string> #include <vector> #include <popt.h> #include "defs.hh" #include "StringSet.hh" #include "FactorEncoder.hh" #include "GreedyUnigrams.hh" using namespace std; void assert_single_chars(map<string, flt_type> &vocab, const map<string, flt_type> &chars, flt_type val) { for (auto it = chars.cbegin(); it != chars.cend(); ++it) if (vocab.find(it->first) == vocab.end()) vocab[it->first] = val; } int main(int argc, char* argv[]) { float cutoff_value = 0.0; int min_removals_per_iter = 0; float threshold = -25.0; float threshold_decrease = 25.0; int target_vocab_size = 50000; bool enable_forward_backward = false; flt_type one_char_min_lp = -25.0; string vocab_fname; string wordlist_fname; // Popt documentation: // http://linux.die.net/man/3/popt // http://privatemisc.blogspot.fi/2012/12/popt-basic-example.html poptContext pc; struct poptOption po[] = { {"cutoff", 'u', POPT_ARG_FLOAT, &cutoff_value, 11001, NULL, "Cutoff value for each iteration"}, {"min_removals", 'i', POPT_ARG_INT, &min_removals_per_iter, 11004, NULL, "Minimum number of removals per iteration (stopping criterion)"}, {"threshold", 't', POPT_ARG_FLOAT, &threshold, 11005, NULL, "Likelihood threshold for removals"}, {"threshold_decrease", 'd', POPT_ARG_FLOAT, &threshold_decrease, 11006, NULL, "Threshold decrease between iterations"}, {"vocab_size", 'g', POPT_ARG_INT, &target_vocab_size, 11007, NULL, "Target vocabulary size (stopping criterion)"}, {"forward_backward", 'f', POPT_ARG_NONE, &enable_forward_backward, 11007, "Use Forward-backward segmentation instead of Viterbi", NULL}, POPT_AUTOHELP {NULL} }; pc = poptGetContext(NULL, argc, (const char **)argv, po, 0); poptSetOtherOptionHelp(pc, "[INITIAL VOCABULARY] [WORDLIST]"); int val; while ((val = poptGetNextOpt(pc)) >= 0) continue; // poptGetNextOpt returns -1 when the final argument has been parsed // otherwise an error occured if (val != -1) { switch (val) { case POPT_ERROR_NOARG: cerr << "Argument missing for an option" << endl; exit(1); case POPT_ERROR_BADOPT: cerr << "Option's argument could not be parsed" << endl; exit(1); case POPT_ERROR_BADNUMBER: case POPT_ERROR_OVERFLOW: cerr << "Option could not be converted to number" << endl; exit(1); default: cerr << "Unknown error in option processing" << endl; exit(1); } } // Handle ARG part of command line if (poptPeekArg(pc) != NULL) vocab_fname.assign((char*)poptGetArg(pc)); else { cerr << "Initial vocabulary file not set" << endl; exit(1); } if (poptPeekArg(pc) != NULL) wordlist_fname.assign((char*)poptGetArg(pc)); else { cerr << "Wordlist file not set" << endl; exit(1); } cerr << "parameters, initial vocabulary: " << vocab_fname << endl; cerr << "parameters, wordlist: " << wordlist_fname << endl; cerr << "parameters, cutoff: " << setprecision(15) << cutoff_value << endl; cerr << "parameters, threshold: " << threshold << endl; cerr << "parameters, threshold decrease per iteration: " << threshold_decrease << endl; cerr << "parameters, min removals per iteration: " << min_removals_per_iter << endl; cerr << "parameters, target vocab size: " << target_vocab_size << endl; cerr << "parameters, use forward-backward: " << enable_forward_backward << endl; int maxlen, word_maxlen; map<string, flt_type> all_chars; map<string, flt_type> vocab; map<string, flt_type> freqs; map<string, flt_type> words; cerr << "Reading vocabulary " << vocab_fname << endl; int retval = read_vocab(vocab_fname, vocab, maxlen); if (retval < 0) { cerr << "something went wrong reading vocabulary" << endl; exit(0); } cerr << "\t" << "size: " << vocab.size() << endl; cerr << "\t" << "maximum string length: " << maxlen << endl; for (auto it = vocab.cbegin(); it != vocab.end(); ++it) if (it->first.length() == 1) all_chars[it->first] = 0.0; cerr << "Reading word list " << wordlist_fname << endl; retval = read_vocab(wordlist_fname, words, word_maxlen); if (retval < 0) { cerr << "something went wrong reading word list" << endl; exit(0); } cerr << "\t" << "wordlist size: " << words.size() << endl; cerr << "\t" << "maximum word length: " << word_maxlen << endl; GreedyUnigrams gg; if (enable_forward_backward) gg.set_segmentation_method(forward_backward); else gg.set_segmentation_method(viterbi); cerr << "Initial cutoff" << endl; gg.resegment_words(words, vocab, freqs); flt_type densum = gg.get_sum(freqs); flt_type cost = gg.get_cost(freqs, densum); cerr << "cost: " << cost << endl; gg.cutoff(freqs, (flt_type)cutoff_value); cerr << "\tcutoff: " << cutoff_value << "\t" << "vocabulary size: " << freqs.size() << endl; vocab = freqs; densum = gg.get_sum(vocab); gg.freqs_to_logprobs(vocab, densum); assert_single_chars(vocab, all_chars, one_char_min_lp); cerr << "Removing subwords one by one" << endl; int itern = 1; while (true) { cerr << "iteration " << itern << endl; vector<pair<string, flt_type> > sorted_vocab; sort_vocab(freqs, sorted_vocab, false); // Perform removals one by one if likelihood change above threshold flt_type curr_densum = gg.get_sum(freqs); flt_type curr_cost = gg.get_cost(freqs, curr_densum); map<string, map<string, flt_type> > backpointers; gg.get_backpointers(words, vocab, backpointers); cerr << "starting cost before removing subwords one by one: " << curr_cost << endl; unsigned int n_removals = 0; unsigned int non_removals_in_row = 0; for (unsigned int i=0; i<sorted_vocab.size(); i++) { if (sorted_vocab[i].first.length() == 1) continue; if (vocab.find(sorted_vocab[i].first) == vocab.end()) continue; if (backpointers.find(sorted_vocab[i].first) == backpointers.end()) { vocab.erase(sorted_vocab[i].first); continue; } cout << "trying to remove: " << sorted_vocab[i].first << endl; map<string, flt_type> freq_diffs; map<string, map<string, flt_type> > backpointers_to_remove; map<string, map<string, flt_type> > backpointers_to_add; StringSet<flt_type> stringset_vocab(vocab); gg.hypo_removal(stringset_vocab, sorted_vocab[i].first, backpointers, backpointers_to_remove, backpointers_to_add, freq_diffs); flt_type hypo_densum = gg.get_sum(freqs, freq_diffs); flt_type hypo_cost = gg.get_cost(freqs, freq_diffs, hypo_densum); cout << sorted_vocab[i].first << "\t" << "change in likelihood: " << hypo_cost-curr_cost; if (hypo_cost-curr_cost < threshold) { cout << " was below threshold " << threshold << endl; non_removals_in_row++; if (non_removals_in_row > 1000) break; continue; } non_removals_in_row=0; cout << " removed, was above threshold " << threshold << endl; gg.apply_freq_diffs(freqs, freq_diffs); freqs.erase(sorted_vocab[i].first); gg.apply_backpointer_changes(backpointers, backpointers_to_remove, backpointers_to_add); backpointers.erase(sorted_vocab[i].first); curr_densum = hypo_densum; curr_cost = hypo_cost; vocab = freqs; gg.freqs_to_logprobs(vocab, hypo_densum); assert_single_chars(vocab, all_chars, one_char_min_lp); n_removals++; if (vocab.size() % 5000 == 0) { ostringstream vocabfname; vocabfname << "iter" << itern << "_" << vocab.size() << ".vocab"; write_vocab(vocabfname.str(), vocab); } if (vocab.size() <= target_vocab_size) break; } int n_cutoff = gg.cutoff(freqs, cutoff_value); flt_type co_densum = gg.get_sum(freqs); vocab = freqs; gg.freqs_to_logprobs(vocab, co_densum); assert_single_chars(vocab, all_chars, one_char_min_lp); gg.resegment_words(words, vocab, freqs); curr_densum = gg.get_sum(freqs); curr_cost = gg.get_cost(freqs, densum); cerr << "subwords removed in this iteration: " << n_removals << endl; cerr << "subwords removed with cutoff this iteration: " << n_cutoff << endl; cerr << "current vocabulary size: " << vocab.size() << endl; cerr << "likelihood after the removals: " << curr_cost << endl; ostringstream vocabfname; vocabfname << "iter" << itern << ".vocab"; write_vocab(vocabfname.str(), vocab); itern++; threshold -= threshold_decrease; if (n_removals < min_removals_per_iter) { cerr << "stopping by min_removals_per_iter." << endl; break; } if (vocab.size() <= target_vocab_size) { cerr << "stopping by min_vocab_size." << endl; break; } } exit(1); } <commit_msg>Keep scores internally in log10, output and thresholds in log2.<commit_after>#include <algorithm> #include <cmath> #include <fstream> #include <iomanip> #include <iostream> #include <sstream> #include <string> #include <vector> #include <popt.h> #include "defs.hh" #include "StringSet.hh" #include "FactorEncoder.hh" #include "GreedyUnigrams.hh" using namespace std; void assert_single_chars(map<string, flt_type> &vocab, const map<string, flt_type> &chars, flt_type val) { for (auto it = chars.cbegin(); it != chars.cend(); ++it) if (vocab.find(it->first) == vocab.end()) vocab[it->first] = val; } int main(int argc, char* argv[]) { float cutoff_value = 0.0; int min_removals_per_iter = 0; float threshold = -25.0; float threshold_decrease = 25.0; int target_vocab_size = 50000; bool enable_forward_backward = false; flt_type one_char_min_lp = -25.0 / log2(10); string vocab_fname; string wordlist_fname; // Popt documentation: // http://linux.die.net/man/3/popt // http://privatemisc.blogspot.fi/2012/12/popt-basic-example.html poptContext pc; struct poptOption po[] = { {"cutoff", 'u', POPT_ARG_FLOAT, &cutoff_value, 11001, NULL, "Cutoff value for each iteration"}, {"min_removals", 'i', POPT_ARG_INT, &min_removals_per_iter, 11004, NULL, "Minimum number of removals per iteration (stopping criterion)"}, {"threshold", 't', POPT_ARG_FLOAT, &threshold, 11005, NULL, "Likelihood threshold for removals"}, {"threshold_decrease", 'd', POPT_ARG_FLOAT, &threshold_decrease, 11006, NULL, "Threshold decrease between iterations"}, {"vocab_size", 'g', POPT_ARG_INT, &target_vocab_size, 11007, NULL, "Target vocabulary size (stopping criterion)"}, {"forward_backward", 'f', POPT_ARG_NONE, &enable_forward_backward, 11007, "Use Forward-backward segmentation instead of Viterbi", NULL}, POPT_AUTOHELP {NULL} }; pc = poptGetContext(NULL, argc, (const char **)argv, po, 0); poptSetOtherOptionHelp(pc, "[INITIAL VOCABULARY] [WORDLIST]"); int val; while ((val = poptGetNextOpt(pc)) >= 0) continue; // poptGetNextOpt returns -1 when the final argument has been parsed // otherwise an error occured if (val != -1) { switch (val) { case POPT_ERROR_NOARG: cerr << "Argument missing for an option" << endl; exit(1); case POPT_ERROR_BADOPT: cerr << "Option's argument could not be parsed" << endl; exit(1); case POPT_ERROR_BADNUMBER: case POPT_ERROR_OVERFLOW: cerr << "Option could not be converted to number" << endl; exit(1); default: cerr << "Unknown error in option processing" << endl; exit(1); } } // Handle ARG part of command line if (poptPeekArg(pc) != NULL) vocab_fname.assign((char*)poptGetArg(pc)); else { cerr << "Initial vocabulary file not set" << endl; exit(1); } if (poptPeekArg(pc) != NULL) wordlist_fname.assign((char*)poptGetArg(pc)); else { cerr << "Wordlist file not set" << endl; exit(1); } cerr << "parameters, initial vocabulary: " << vocab_fname << endl; cerr << "parameters, wordlist: " << wordlist_fname << endl; cerr << "parameters, cutoff: " << setprecision(15) << cutoff_value << endl; cerr << "parameters, threshold: " << threshold << endl; cerr << "parameters, threshold decrease per iteration: " << threshold_decrease << endl; cerr << "parameters, min removals per iteration: " << min_removals_per_iter << endl; cerr << "parameters, target vocab size: " << target_vocab_size << endl; cerr << "parameters, use forward-backward: " << enable_forward_backward << endl; int maxlen, word_maxlen; map<string, flt_type> all_chars; map<string, flt_type> vocab; map<string, flt_type> freqs; map<string, flt_type> words; cerr << "Reading vocabulary " << vocab_fname << endl; int retval = read_vocab(vocab_fname, vocab, maxlen); if (retval < 0) { cerr << "something went wrong reading vocabulary" << endl; exit(0); } cerr << "\t" << "size: " << vocab.size() << endl; cerr << "\t" << "maximum string length: " << maxlen << endl; for (auto it = vocab.cbegin(); it != vocab.end(); ++it) if (it->first.length() == 1) all_chars[it->first] = 0.0; cerr << "Reading word list " << wordlist_fname << endl; retval = read_vocab(wordlist_fname, words, word_maxlen); if (retval < 0) { cerr << "something went wrong reading word list" << endl; exit(0); } cerr << "\t" << "wordlist size: " << words.size() << endl; cerr << "\t" << "maximum word length: " << word_maxlen << endl; GreedyUnigrams gg; if (enable_forward_backward) gg.set_segmentation_method(forward_backward); else gg.set_segmentation_method(viterbi); gg.resegment_words(words, vocab, freqs); flt_type densum = gg.get_sum(freqs); flt_type cost = gg.get_cost(freqs, densum); cerr << "cost: " << cost * log2(10.0) << endl; cerr << "Initial cutoff" << endl; gg.cutoff(freqs, (flt_type)cutoff_value); cerr << "\tcutoff: " << cutoff_value << "\t" << "vocabulary size: " << freqs.size() << endl; densum = gg.get_sum(freqs); cost = gg.get_cost(freqs, densum); cerr << "cost: " << cost * log2(10.0) << endl; vocab = freqs; gg.freqs_to_logprobs(vocab, densum); assert_single_chars(vocab, all_chars, one_char_min_lp); cerr << "Removing subwords one by one" << endl; int itern = 1; while (true) { cerr << "iteration " << itern << endl; vector<pair<string, flt_type> > sorted_vocab; sort_vocab(freqs, sorted_vocab, false); // Perform removals one by one if likelihood change above threshold flt_type curr_densum = gg.get_sum(freqs); flt_type curr_cost = gg.get_cost(freqs, curr_densum); map<string, map<string, flt_type> > backpointers; gg.get_backpointers(words, vocab, backpointers); cerr << "starting cost before removing subwords one by one: " << curr_cost * log2(10.0) << endl; unsigned int n_removals = 0; unsigned int non_removals_in_row = 0; for (unsigned int i=0; i<sorted_vocab.size(); i++) { if (sorted_vocab[i].first.length() == 1) continue; if (vocab.find(sorted_vocab[i].first) == vocab.end()) continue; if (backpointers.find(sorted_vocab[i].first) == backpointers.end()) { vocab.erase(sorted_vocab[i].first); continue; } cout << "trying to remove: " << sorted_vocab[i].first << endl; map<string, flt_type> freq_diffs; map<string, map<string, flt_type> > backpointers_to_remove; map<string, map<string, flt_type> > backpointers_to_add; StringSet<flt_type> stringset_vocab(vocab); gg.hypo_removal(stringset_vocab, sorted_vocab[i].first, backpointers, backpointers_to_remove, backpointers_to_add, freq_diffs); flt_type hypo_densum = gg.get_sum(freqs, freq_diffs); flt_type hypo_cost = gg.get_cost(freqs, freq_diffs, hypo_densum); cout << sorted_vocab[i].first << "\t" << "change in likelihood: " << (hypo_cost-curr_cost) * log2(10.0); if ((hypo_cost-curr_cost) * log2(10.0) < threshold) { cout << " was below threshold " << threshold << endl; non_removals_in_row++; if (non_removals_in_row > 1000) break; continue; } non_removals_in_row=0; cout << " removed, was above threshold " << threshold << endl; gg.apply_freq_diffs(freqs, freq_diffs); freqs.erase(sorted_vocab[i].first); gg.apply_backpointer_changes(backpointers, backpointers_to_remove, backpointers_to_add); backpointers.erase(sorted_vocab[i].first); curr_densum = hypo_densum; curr_cost = hypo_cost; vocab = freqs; gg.freqs_to_logprobs(vocab, hypo_densum); assert_single_chars(vocab, all_chars, one_char_min_lp); n_removals++; if (vocab.size() % 5000 == 0) { ostringstream vocabfname; vocabfname << "iter" << itern << "_" << vocab.size() << ".vocab"; write_vocab(vocabfname.str(), vocab); } if (vocab.size() <= target_vocab_size) break; } int n_cutoff = gg.cutoff(freqs, cutoff_value); flt_type co_densum = gg.get_sum(freqs); vocab = freqs; gg.freqs_to_logprobs(vocab, co_densum); assert_single_chars(vocab, all_chars, one_char_min_lp); gg.resegment_words(words, vocab, freqs); curr_densum = gg.get_sum(freqs); curr_cost = gg.get_cost(freqs, densum); cerr << "subwords removed in this iteration: " << n_removals << endl; cerr << "subwords removed with cutoff this iteration: " << n_cutoff << endl; cerr << "current vocabulary size: " << vocab.size() << endl; cerr << "likelihood after the removals: " << curr_cost * log2(10.0) << endl; ostringstream vocabfname; vocabfname << "iter" << itern << ".vocab"; write_vocab(vocabfname.str(), vocab); itern++; threshold -= threshold_decrease; if (n_removals < min_removals_per_iter) { cerr << "stopping by min_removals_per_iter." << endl; break; } if (vocab.size() <= target_vocab_size) { cerr << "stopping by min_vocab_size." << endl; break; } } exit(1); } <|endoftext|>
<commit_before>/* * game: the game of arithmetic - interactive gui - implementation * Copyright(c) 2005 by wave++ "Yuri D'Elia" <wavexx@users.sf.net> */ /* * Headers */ #include "game.hh" #include "interp.hh" using std::string; #include <algorithm> using std::max; #include <cstdlib> using std::sprintf; #include <GL/freeglut.h> /* * Implementation */ void Game::drawFWString(const char* str, const Point& pos) { glPushMatrix(); glTranslatef(pos.x, pos.y, 0.); for(int c = 0; *str; ++str, ++c) { // center the character glPushMatrix(); const Bounds& cur = resources.cm->getChar(*str).metrics.bounds; glTranslatef( (nmHSpace * c) + (nmHSpace - (cur.ur.x - cur.ll.x)) / 2 - cur.ll.x, (nmVSpace - (cur.ur.y - cur.ll.y)) / 2 - cur.ll.y, 0.); resources.cm->draw(*str); glPopMatrix(); } glPopMatrix(); } void Game::drawStackElem(const Question& q, const Point& pos) { // get the correct color Color color = (q.errs? resources.error: interpolate(q.cum / max(1., avgTime), resources.normal, resources.timeout)); // background color.rgba[3] = 0.5; glColor4fv(color); glBegin(GL_QUADS); glVertex2f(pos.x, pos.y); glVertex2f(pos.x, pos.y + nmVSpace); glVertex2f(pos.x + stackW, pos.y + nmVSpace); glVertex2f(pos.x + stackW, pos.y); glEnd(); // contour color.rgba[3] = 1.; glColor4fv(color); glBegin(GL_LINE_STRIP); glVertex2f(pos.x, pos.y + nmVSpace); glVertex2f(pos.x + stackW, pos.y + nmVSpace); glVertex2f(pos.x + stackW, pos.y); glEnd(); // string char fmt[32]; sprintf(fmt, "%%%dd%%c%%%dd", maxLenA, maxLenB); char* buf = new char[maxLen + 1]; sprintf(buf, fmt, q.na, q.kernel->first.o->sym(), q.kernel->first.b); glColor4fv(resources.foreground); drawFWString(buf, pos); delete []buf; } void Game::drawBar() { Color color; // background glBegin(GL_QUADS); color = resources.bar[0]; color.rgba[3] = 0.5; glColor4fv(color); glVertex2f(urGeom.x - nmVSpace, urGeom.y); glVertex2f(urGeom.x, urGeom.y); color = resources.bar[1]; color.rgba[3] = 0.5; glColor4fv(color); glVertex2f(urGeom.x, 0); glVertex2f(urGeom.x - nmVSpace, 0); glEnd(); if(state == playing) { float r = interpLinear(frame, now); float ry = urGeom.y - r * urGeom.y; // hilight color = interpolate(r, resources.bar[0], resources.bar[1]); glColor4fv(color); glBegin(GL_QUADS); glVertex2f(urGeom.x - nmVSpace, 0); glVertex2f(urGeom.x - nmVSpace, ry); glVertex2f(urGeom.x, ry); glVertex2f(urGeom.x, 0); glEnd(); // timer glPushMatrix(); const Font& font = resources.cm->getFont(); glTranslatef(urGeom.x - nmVSpace - font.bounds.ll.y, urGeom.y + font.bounds.ll.x, 0); glRotatef(-90., 0., 0., 1.); char buf[sizeof(int) * 4]; sprintf(buf, "%d", static_cast<int>(frame.end - now)); glColor4fv(resources.background); resources.cm->draw(buf); glPopMatrix(); } // separator glColor4fv(resources.foreground); glBegin(GL_LINES); glVertex2f(urGeom.x - nmVSpace, 0); glVertex2f(urGeom.x - nmVSpace, urGeom.y); glEnd(); } void Game::drawAnswer(const float y) { string buf("="); buf += answer; glColor4fv(resources.foreground); drawFWString(buf.c_str(), Point(stackW, y)); } void Game::updateAvg() { // time averages AvgTime res; for(TimeMap::iterator it = data.times.begin(); it != data.times.end(); ++it) { // only for the active operators if(data.ops.find(it->first) != data.ops.end()) res.add(it->second.avg()); } avgTime = res.avg(); } void Game::updateTimes(const Time shift) { playingTime += shift; question.cum += shift; } void Game::resetQuestion() { question.kernel = randFind(data.kernels, NrPred(*this)); const Kernel& kernel(question.kernel->first); question.r = kernel.o->result(kernel.a, kernel.b, question.na); question.cum = 0.; question.errs = 0; } void Game::initAnim() { // basic animation data state = animating; frame.begin = now; frame.end = now + resources.animTime; } void Game::initGame() { // basic animation data state = playing; frame.begin = now; frame.end = now + avgTime; } void Game::drawState() { // always draw the stack QDeque::iterator it = stack.begin(); for(int i = 0; it != stack.end(); ++i, ++it) drawStackElem(*it, Point(0, nmVSpace * i)); // common variables float stackHead = nmVSpace * stack.size(); if(state == animating) { // animating parts float oldHead = nmVSpace * oldSize; float ci = interpCubic(frame, now); // dropping element if(static_cast<int>(stack.size()) >= oldSize) drawStackElem(question, interpolate(ci, Point(0, urGeom.y), Point(0, stackHead))); else drawStackElem(question, Point(0, stackHead)); // removing element if(lastResult) drawStackElem(lastQuestion, Point(-ci * stackW * 2, oldHead)); // answer symbol drawAnswer(interpolate(ci, oldHead, stackHead)); } else { // current element and answer drawStackElem(question, Point(0, stackHead)); drawAnswer(stackHead); } // remaining time drawBar(); } void Game::nextState() { if(state == animating) initGame(); else if(state == playing) timeOut(); } void Game::contGame() { // check game status if(stack.size() == data.stackSize) stopGame(); else { // continue answer.clear(); initAnim(); } } void Game::stopGame() { state = gameOver; } void Game::timeOut() { // update stack lastResult = false; oldSize = stack.size(); stack.push_back(question); resetQuestion(); contGame(); } void Game::submitAnswer() { // check result int r = strtol(answer.c_str(), NULL, 10); lastResult = (r == question.r); oldSize = stack.size(); if(lastResult) { // correct, update the stack lastQuestion = question; data.update(question.kernel, question.errs, question.cum); updateAvg(); if(stack.size()) { // recover and old question question = stack.back(); stack.pop_back(); } else resetQuestion(); } else { // wrong answers ++question.errs; stack.push_back(question); resetQuestion(); } contGame(); } bool Game::NrPred::operator()(const Kernel& kernel) const { // exclude disabled operations if(ref.data.ops.find(kernel.o) == ref.data.ops.end()) return false; // exclude all kernels already present in the stack for(QDeque::const_iterator it = ref.stack.begin(); it != ref.stack.end(); ++it) if(kernel == it->kernel->first) return false; return true; } Game::Game(const Resources& resources, const Time now, GameData& data) : State(resources, now, data) { // font spacing Bounds nmBounds; resources.cm->maxOf(nmBounds, "0123456789+-*/=~"); nmHSpace = nmBounds.ur.x - nmBounds.ll.x; nmHSpace += nmHSpace * 0.1; nmVSpace = 1.1; // sizes maxLenA = maxLenB = maxLenR = 0; for(KernMap::iterator it = data.kernels.begin(); it != data.kernels.end(); ++it) { // only consider active operations if(data.ops.find(it->first.o) == data.ops.end()) continue; int na; char buf[sizeof(int) * 4]; int r = it->first.o->result(it->first.a, it->first.b, na); maxLenA = max(maxLenA, sprintf(buf, "%d", na)); maxLenB = max(maxLenB, sprintf(buf, "%d", it->first.b)); maxLenR = max(maxLenR, sprintf(buf, "%d", r)); } // misc geometry maxLen = maxLenA + 1 + maxLenB; stackW = nmHSpace * maxLen; // initial state playingTime = 0.; this->now = now; lastResult = false; oldSize = -1; updateAvg(); resetQuestion(); initAnim(); } void Game::reshape(const int w, const int h) { // calculate enough vertical space to fit the stack exactly urGeom.y = nmVSpace * data.stackSize; urGeom.x = urGeom.y * static_cast<float>(w) / h * resources.videoRatio; gluOrtho2D(0, urGeom.x, 0, urGeom.y); } void Game::display(const Time now) { // update times if(state == playing) updateTimes(now - this->now); this->now = now; // update status if(now > frame.end) nextState(); // actual drawing drawState(); } void Game::keyboard(const unsigned char key) { if(state != playing) return; if(key == 8) { // backspace if(answer.size()) answer.resize(answer.size() - 1); } else if(key >= '0' && key <= '9') { // number if(answer.size() < maxLenR) answer += key; } else if(key == 13) { // empty answers as timeouts if(answer.size()) submitAnswer(); else timeOut(); } } <commit_msg>Implemented "practice" and "veryHard".<commit_after>/* * game: the game of arithmetic - interactive gui - implementation * Copyright(c) 2005 by wave++ "Yuri D'Elia" <wavexx@users.sf.net> */ /* * Headers */ #include "game.hh" #include "interp.hh" using std::string; #include <algorithm> using std::max; #include <cstdlib> using std::sprintf; #include <GL/freeglut.h> /* * Implementation */ void Game::drawFWString(const char* str, const Point& pos) { glPushMatrix(); glTranslatef(pos.x, pos.y, 0.); for(int c = 0; *str; ++str, ++c) { // center the character glPushMatrix(); const Bounds& cur = resources.cm->getChar(*str).metrics.bounds; glTranslatef( (nmHSpace * c) + (nmHSpace - (cur.ur.x - cur.ll.x)) / 2 - cur.ll.x, (nmVSpace - (cur.ur.y - cur.ll.y)) / 2 - cur.ll.y, 0.); resources.cm->draw(*str); glPopMatrix(); } glPopMatrix(); } void Game::drawStackElem(const Question& q, const Point& pos) { // get the correct color Color color = (q.errs? resources.error: interpolate(q.cum / max(1., avgTime), resources.normal, resources.timeout)); // background color.rgba[3] = 0.5; glColor4fv(color); glBegin(GL_QUADS); glVertex2f(pos.x, pos.y); glVertex2f(pos.x, pos.y + nmVSpace); glVertex2f(pos.x + stackW, pos.y + nmVSpace); glVertex2f(pos.x + stackW, pos.y); glEnd(); // contour color.rgba[3] = 1.; glColor4fv(color); glBegin(GL_LINE_STRIP); glVertex2f(pos.x, pos.y + nmVSpace); glVertex2f(pos.x + stackW, pos.y + nmVSpace); glVertex2f(pos.x + stackW, pos.y); glEnd(); // string char fmt[32]; sprintf(fmt, "%%%dd%%c%%%dd", maxLenA, maxLenB); char* buf = new char[maxLen + 1]; sprintf(buf, fmt, q.na, q.kernel->first.o->sym(), q.kernel->first.b); glColor4fv(resources.foreground); drawFWString(buf, pos); delete []buf; } void Game::drawBar() { Color color; // background glBegin(GL_QUADS); color = resources.bar[0]; color.rgba[3] = 0.5; glColor4fv(color); glVertex2f(urGeom.x - nmVSpace, urGeom.y); glVertex2f(urGeom.x, urGeom.y); color = resources.bar[1]; color.rgba[3] = 0.5; glColor4fv(color); glVertex2f(urGeom.x, 0); glVertex2f(urGeom.x - nmVSpace, 0); glEnd(); if(state == playing) { float r = interpLinear(frame, now); float ry = urGeom.y - r * urGeom.y; // hilight color = interpolate(r, resources.bar[0], resources.bar[1]); glColor4fv(color); glBegin(GL_QUADS); glVertex2f(urGeom.x - nmVSpace, 0); glVertex2f(urGeom.x - nmVSpace, ry); glVertex2f(urGeom.x, ry); glVertex2f(urGeom.x, 0); glEnd(); // timer glPushMatrix(); const Font& font = resources.cm->getFont(); glTranslatef(urGeom.x - nmVSpace - font.bounds.ll.y, urGeom.y + font.bounds.ll.x, 0); glRotatef(-90., 0., 0., 1.); char buf[sizeof(int) * 4]; sprintf(buf, "%d", static_cast<int>(frame.end - now)); glColor4fv(resources.background); resources.cm->draw(buf); glPopMatrix(); } // separator glColor4fv(resources.foreground); glBegin(GL_LINES); glVertex2f(urGeom.x - nmVSpace, 0); glVertex2f(urGeom.x - nmVSpace, urGeom.y); glEnd(); } void Game::drawAnswer(const float y) { string buf("="); buf += answer; glColor4fv(resources.foreground); drawFWString(buf.c_str(), Point(stackW, y)); } void Game::updateAvg() { // time averages AvgTime res; for(TimeMap::iterator it = data.times.begin(); it != data.times.end(); ++it) { // only for the active operators if(data.ops.find(it->first) != data.ops.end()) res.add(it->second.avg()); } avgTime = res.avg(); } void Game::updateTimes(const Time shift) { playingTime += shift; question.cum += shift; } void Game::resetQuestion() { question.kernel = randFind(data.kernels, NrPred(*this)); const Kernel& kernel(question.kernel->first); question.r = kernel.o->result(kernel.a, kernel.b, question.na); question.cum = 0.; question.errs = 0; } void Game::initAnim() { // basic animation data state = animating; frame.begin = now; frame.end = now + resources.animTime; } void Game::initGame() { // basic animation data state = playing; frame.begin = now; frame.end = now + avgTime; } void Game::drawState() { // always draw the stack QDeque::iterator it = stack.begin(); for(int i = 0; it != stack.end(); ++i, ++it) drawStackElem(*it, Point(0, nmVSpace * i)); // common variables float stackHead = nmVSpace * stack.size(); if(state == animating) { // animating parts float oldHead = nmVSpace * oldSize; float ci = interpCubic(frame, now); // dropping element if(static_cast<int>(stack.size()) >= oldSize) drawStackElem(question, interpolate(ci, Point(0, urGeom.y), Point(0, stackHead))); else drawStackElem(question, Point(0, stackHead)); // removing element if(lastResult) drawStackElem(lastQuestion, Point(-ci * stackW * 2, oldHead)); // answer symbol drawAnswer(interpolate(ci, oldHead, stackHead)); } else { // current element and answer drawStackElem(question, Point(0, stackHead)); drawAnswer(stackHead); } // remaining time drawBar(); } void Game::nextState() { if(state == animating) initGame(); else if(state == playing && data.mode != GameData::practice) timeOut(); } void Game::contGame() { // check game status if(stack.size() == data.stackSize) stopGame(); else { // continue answer.clear(); initAnim(); } } void Game::stopGame() { state = gameOver; } void Game::timeOut() { // update stack lastResult = false; oldSize = stack.size(); stack.push_back(question); resetQuestion(); contGame(); } void Game::submitAnswer() { // check result int r = strtol(answer.c_str(), NULL, 10); lastResult = (r == question.r); oldSize = stack.size(); if(lastResult) { // correct, update the stack lastQuestion = question; data.update(question.kernel, question.errs, question.cum); updateAvg(); if(stack.size() && data.mode != GameData::veryHard) { // recover and old question question = stack.back(); stack.pop_back(); } else resetQuestion(); } else { // wrong answers ++question.errs; stack.push_back(question); resetQuestion(); } contGame(); } bool Game::NrPred::operator()(const Kernel& kernel) const { // exclude disabled operations if(ref.data.ops.find(kernel.o) == ref.data.ops.end()) return false; // exclude all kernels already present in the stack for(QDeque::const_iterator it = ref.stack.begin(); it != ref.stack.end(); ++it) if(kernel == it->kernel->first) return false; return true; } Game::Game(const Resources& resources, const Time now, GameData& data) : State(resources, now, data) { // font spacing Bounds nmBounds; resources.cm->maxOf(nmBounds, "0123456789+-*/=~"); nmHSpace = nmBounds.ur.x - nmBounds.ll.x; nmHSpace += nmHSpace * 0.1; nmVSpace = 1.1; // sizes maxLenA = maxLenB = maxLenR = 0; for(KernMap::iterator it = data.kernels.begin(); it != data.kernels.end(); ++it) { // only consider active operations if(data.ops.find(it->first.o) == data.ops.end()) continue; int na; char buf[sizeof(int) * 4]; int r = it->first.o->result(it->first.a, it->first.b, na); maxLenA = max(maxLenA, sprintf(buf, "%d", na)); maxLenB = max(maxLenB, sprintf(buf, "%d", it->first.b)); maxLenR = max(maxLenR, sprintf(buf, "%d", r)); } // misc geometry maxLen = maxLenA + 1 + maxLenB; stackW = nmHSpace * maxLen; // initial state playingTime = 0.; this->now = now; lastResult = false; oldSize = -1; updateAvg(); resetQuestion(); initAnim(); } void Game::reshape(const int w, const int h) { // calculate enough vertical space to fit the stack exactly urGeom.y = nmVSpace * data.stackSize; urGeom.x = urGeom.y * static_cast<float>(w) / h * resources.videoRatio; gluOrtho2D(0, urGeom.x, 0, urGeom.y); } void Game::display(const Time now) { // update times if(state == playing) updateTimes(now - this->now); this->now = now; // update status if(now > frame.end) nextState(); // actual drawing drawState(); } void Game::keyboard(const unsigned char key) { if(state != playing) return; if(key == 8) { // backspace if(answer.size()) answer.resize(answer.size() - 1); } else if(key >= '0' && key <= '9') { // number if(answer.size() < maxLenR) answer += key; } else if(key == 13) { // empty answers as timeouts if(answer.size()) submitAnswer(); else timeOut(); } } <|endoftext|>
<commit_before>/* * copyright: (c) RDO-Team, 2009 * filename : rdoparser_base.cpp * author : , * date : * bref : * indent : 4T */ // ====================================================================== PCH #include "rdo_lib/rdo_converter/pch.h" // ====================================================================== INCLUDES // ====================================================================== SYNOPSIS #include "rdo_lib/rdo_converter/rdoparser_base.h" #include "rdo_lib/rdo_converter/rdoparser_rdo.h" #include "rdo_lib/rdo_converter/rdoparser_corba.h" #include "rdo_lib/rdo_converter/rdopat.h" #include "rdo_lib/rdo_converter/rdoopr.h" #include "rdo_lib/rdo_converter/rdodpt.h" #include "rdo_lib/rdo_converter/rdosmr.h" #include "rdo_lib/rdo_converter/rdofrm.h" #include "rdo_lib/rdo_converter/rdopmd.h" #include "rdo_lib/rdo_converter/rdortp.h" // =============================================================================== OPEN_RDO_CONVERTER_NAMESPACE // ---------------------------------------------------------------------------- // ---------- RDOParserContainer // ---------------------------------------------------------------------------- RDOParserContainer::RDOParserContainer() {} RDOParserContainer::~RDOParserContainer() {} ruint RDOParserContainer::insert(rdoModelObjectsConvertor::RDOParseType type, CREF(LPRDOParserItem) pParser) { ASSERT(pParser); ruint min, max; RDOParserContainer::getMinMax(type, min, max); if (min != UNDEFINED_ID && max != UNDEFINED_ID) { List::iterator it = m_list.find(min); if (it == m_list.end()) { m_list[min] = pParser; return min; } else { ruint index = it->first; while (it != m_list.end() && it->first <= max) { index++; it++; } if (index <= max) { m_list[index] = pParser; return index; } else { return 0; } } } return 0; } void RDOParserContainer::getMinMax(rdoModelObjectsConvertor::RDOParseType type, REF(ruint) min, REF(ruint) max) { switch (type) { case rdoModelObjectsConvertor::obPRE : min = 100; max = 199; break; case rdoModelObjectsConvertor::obRTP : min = 200; max = 299; break; case rdoModelObjectsConvertor::obRSS : min = 300; max = 399; break; case rdoModelObjectsConvertor::obFUN : min = 400; max = 499; break; case rdoModelObjectsConvertor::obPAT : min = 500; max = 599; break; case rdoModelObjectsConvertor::obOPR : min = 600; max = 699; break; case rdoModelObjectsConvertor::obDPT : min = 700; max = 799; break; case rdoModelObjectsConvertor::obPMD : min = 800; max = 899; break; case rdoModelObjectsConvertor::obFRM : min = 900; max = 999; break; case rdoModelObjectsConvertor::obSMR : min = 1000; max = 1099; break; case rdoModelObjectsConvertor::obPOST: min = 1100; max = 1199; break; default : min = UNDEFINED_ID; max = UNDEFINED_ID; break; } } // ---------------------------------------------------------------------------- // ---------- RDOParserContainerModel // ---------------------------------------------------------------------------- RDOParserContainerModel::RDOParserContainerModel() : RDOParserContainer() { insert(rdoModelObjectsConvertor::obPRE, rdo::Factory<RDOParserSTDFUN> ::create()); insert(rdoModelObjectsConvertor::obPRE, rdo::Factory<RDOParserRDOItem>::create(rdoModelObjectsConvertor::SMR, cnv_smr_file_parse, cnv_smr_file_error, cnv_smr_file_lex)); insert(rdoModelObjectsConvertor::obRTP, rdo::Factory<RDOParserRDOItem>::create(rdoModelObjectsConvertor::RTP, cnv_rtpparse, cnv_rtperror, cnv_rtplex)); insert(rdoModelObjectsConvertor::obRTP, rdo::Factory<RDOParserRDOItem>::create(rdoModelObjectsConvertor::DPT, cnv_proc_rtp_parse, cnv_proc_rtp_error, cnv_proc_rtp_lex)); insert(rdoModelObjectsConvertor::obRSS, rdo::Factory<RDOParserRSS> ::create()); insert(rdoModelObjectsConvertor::obRSS, rdo::Factory<RDOParserRDOItem>::create(rdoModelObjectsConvertor::DPT, cnv_proc_rss_parse, cnv_proc_rss_error, cnv_proc_rss_lex)); insert(rdoModelObjectsConvertor::obFUN, rdo::Factory<RDOParserRDOItem>::create(rdoModelObjectsConvertor::FUN, cnv_funparse, cnv_funerror, cnv_funlex)); insert(rdoModelObjectsConvertor::obPAT, rdo::Factory<RDOParserRDOItem>::create(rdoModelObjectsConvertor::PAT, cnv_patparse, cnv_paterror, cnv_patlex)); insert(rdoModelObjectsConvertor::obOPR, rdo::Factory<RDOParserRDOItem>::create(rdoModelObjectsConvertor::OPR, cnv_oprparse, cnv_oprerror, cnv_oprlex)); insert(rdoModelObjectsConvertor::obDPT, rdo::Factory<RDOParserRDOItem>::create(rdoModelObjectsConvertor::DPT, cnv_proc_opr_parse, cnv_proc_opr_error, cnv_proc_opr_lex)); insert(rdoModelObjectsConvertor::obDPT, rdo::Factory<RDOParserRDOItem>::create(rdoModelObjectsConvertor::DPT, cnv_dptparse, cnv_dpterror, cnv_dptlex)); insert(rdoModelObjectsConvertor::obPMD, rdo::Factory<RDOParserRDOItem>::create(rdoModelObjectsConvertor::PMD, cnv_pmdparse, cnv_pmderror, cnv_pmdlex)); insert(rdoModelObjectsConvertor::obFRM, rdo::Factory<RDOParserRDOItem>::create(rdoModelObjectsConvertor::FRM, cnv_frmparse, cnv_frmerror, cnv_frmlex)); insert(rdoModelObjectsConvertor::obSMR, rdo::Factory<RDOParserRSSPost>::create()); insert(rdoModelObjectsConvertor::obSMR, rdo::Factory<RDOParserRDOItem>::create(rdoModelObjectsConvertor::SMR, cnv_smr_sim_parse, cnv_smr_sim_error, cnv_smr_sim_lex)); } // ---------------------------------------------------------------------------- // ---------- RDOParserContainerSMRInfo // ---------------------------------------------------------------------------- RDOParserContainerSMRInfo::RDOParserContainerSMRInfo() : RDOParserContainer() { insert(rdoModelObjectsConvertor::obPRE, rdo::Factory<RDOParserRDOItem>::create(rdoModelObjectsConvertor::SMR, cnv_smr_file_parse, cnv_smr_file_error, cnv_smr_file_lex)); } CLOSE_RDO_CONVERTER_NAMESPACE <commit_msg> - из конвертора удалена корба<commit_after>/* * copyright: (c) RDO-Team, 2009 * filename : rdoparser_base.cpp * author : , * date : * bref : * indent : 4T */ // ====================================================================== PCH #include "rdo_lib/rdo_converter/pch.h" // ====================================================================== INCLUDES // ====================================================================== SYNOPSIS #include "rdo_lib/rdo_converter/rdoparser_base.h" #include "rdo_lib/rdo_converter/rdoparser_rdo.h" #include "rdo_lib/rdo_converter/rdopat.h" #include "rdo_lib/rdo_converter/rdoopr.h" #include "rdo_lib/rdo_converter/rdodpt.h" #include "rdo_lib/rdo_converter/rdosmr.h" #include "rdo_lib/rdo_converter/rdofrm.h" #include "rdo_lib/rdo_converter/rdopmd.h" #include "rdo_lib/rdo_converter/rdortp.h" // =============================================================================== OPEN_RDO_CONVERTER_NAMESPACE // ---------------------------------------------------------------------------- // ---------- RDOParserContainer // ---------------------------------------------------------------------------- RDOParserContainer::RDOParserContainer() {} RDOParserContainer::~RDOParserContainer() {} ruint RDOParserContainer::insert(rdoModelObjectsConvertor::RDOParseType type, CREF(LPRDOParserItem) pParser) { ASSERT(pParser); ruint min, max; RDOParserContainer::getMinMax(type, min, max); if (min != UNDEFINED_ID && max != UNDEFINED_ID) { List::iterator it = m_list.find(min); if (it == m_list.end()) { m_list[min] = pParser; return min; } else { ruint index = it->first; while (it != m_list.end() && it->first <= max) { index++; it++; } if (index <= max) { m_list[index] = pParser; return index; } else { return 0; } } } return 0; } void RDOParserContainer::getMinMax(rdoModelObjectsConvertor::RDOParseType type, REF(ruint) min, REF(ruint) max) { switch (type) { case rdoModelObjectsConvertor::obPRE : min = 100; max = 199; break; case rdoModelObjectsConvertor::obRTP : min = 200; max = 299; break; case rdoModelObjectsConvertor::obRSS : min = 300; max = 399; break; case rdoModelObjectsConvertor::obFUN : min = 400; max = 499; break; case rdoModelObjectsConvertor::obPAT : min = 500; max = 599; break; case rdoModelObjectsConvertor::obOPR : min = 600; max = 699; break; case rdoModelObjectsConvertor::obDPT : min = 700; max = 799; break; case rdoModelObjectsConvertor::obPMD : min = 800; max = 899; break; case rdoModelObjectsConvertor::obFRM : min = 900; max = 999; break; case rdoModelObjectsConvertor::obSMR : min = 1000; max = 1099; break; case rdoModelObjectsConvertor::obPOST: min = 1100; max = 1199; break; default : min = UNDEFINED_ID; max = UNDEFINED_ID; break; } } // ---------------------------------------------------------------------------- // ---------- RDOParserContainerModel // ---------------------------------------------------------------------------- RDOParserContainerModel::RDOParserContainerModel() : RDOParserContainer() { insert(rdoModelObjectsConvertor::obPRE, rdo::Factory<RDOParserSTDFUN> ::create()); insert(rdoModelObjectsConvertor::obPRE, rdo::Factory<RDOParserRDOItem>::create(rdoModelObjectsConvertor::SMR, cnv_smr_file_parse, cnv_smr_file_error, cnv_smr_file_lex)); insert(rdoModelObjectsConvertor::obRTP, rdo::Factory<RDOParserRDOItem>::create(rdoModelObjectsConvertor::RTP, cnv_rtpparse, cnv_rtperror, cnv_rtplex)); insert(rdoModelObjectsConvertor::obRTP, rdo::Factory<RDOParserRDOItem>::create(rdoModelObjectsConvertor::DPT, cnv_proc_rtp_parse, cnv_proc_rtp_error, cnv_proc_rtp_lex)); insert(rdoModelObjectsConvertor::obRSS, rdo::Factory<RDOParserRSS> ::create()); insert(rdoModelObjectsConvertor::obRSS, rdo::Factory<RDOParserRDOItem>::create(rdoModelObjectsConvertor::DPT, cnv_proc_rss_parse, cnv_proc_rss_error, cnv_proc_rss_lex)); insert(rdoModelObjectsConvertor::obFUN, rdo::Factory<RDOParserRDOItem>::create(rdoModelObjectsConvertor::FUN, cnv_funparse, cnv_funerror, cnv_funlex)); insert(rdoModelObjectsConvertor::obPAT, rdo::Factory<RDOParserRDOItem>::create(rdoModelObjectsConvertor::PAT, cnv_patparse, cnv_paterror, cnv_patlex)); insert(rdoModelObjectsConvertor::obOPR, rdo::Factory<RDOParserRDOItem>::create(rdoModelObjectsConvertor::OPR, cnv_oprparse, cnv_oprerror, cnv_oprlex)); insert(rdoModelObjectsConvertor::obDPT, rdo::Factory<RDOParserRDOItem>::create(rdoModelObjectsConvertor::DPT, cnv_proc_opr_parse, cnv_proc_opr_error, cnv_proc_opr_lex)); insert(rdoModelObjectsConvertor::obDPT, rdo::Factory<RDOParserRDOItem>::create(rdoModelObjectsConvertor::DPT, cnv_dptparse, cnv_dpterror, cnv_dptlex)); insert(rdoModelObjectsConvertor::obPMD, rdo::Factory<RDOParserRDOItem>::create(rdoModelObjectsConvertor::PMD, cnv_pmdparse, cnv_pmderror, cnv_pmdlex)); insert(rdoModelObjectsConvertor::obFRM, rdo::Factory<RDOParserRDOItem>::create(rdoModelObjectsConvertor::FRM, cnv_frmparse, cnv_frmerror, cnv_frmlex)); insert(rdoModelObjectsConvertor::obSMR, rdo::Factory<RDOParserRSSPost>::create()); insert(rdoModelObjectsConvertor::obSMR, rdo::Factory<RDOParserRDOItem>::create(rdoModelObjectsConvertor::SMR, cnv_smr_sim_parse, cnv_smr_sim_error, cnv_smr_sim_lex)); } // ---------------------------------------------------------------------------- // ---------- RDOParserContainerSMRInfo // ---------------------------------------------------------------------------- RDOParserContainerSMRInfo::RDOParserContainerSMRInfo() : RDOParserContainer() { insert(rdoModelObjectsConvertor::obPRE, rdo::Factory<RDOParserRDOItem>::create(rdoModelObjectsConvertor::SMR, cnv_smr_file_parse, cnv_smr_file_error, cnv_smr_file_lex)); } CLOSE_RDO_CONVERTER_NAMESPACE <|endoftext|>
<commit_before>#include "ScriptManager.hpp" #include <angelscript.h> #include <scriptbuilder/scriptbuilder.h> #include <scriptstdstring/scriptstdstring.h> #include "../Util/Log.hpp" #include "../Util/FileSystem.hpp" #include "../Hymn.hpp" #include "../Scene/Scene.hpp" #include "../Component/Script.hpp" #include "../Entity/Entity.hpp" void print(const std::string& message) { Log() << message; } ScriptManager::ScriptManager() { // Create the script engine engine = asCreateScriptEngine(); // Set the message callback to receive information on errors in human readable form. engine->SetMessageCallback(asFUNCTION(AngelScriptMessageCallback), 0, asCALL_CDECL); // Register add-ons. RegisterStdString(engine); // Register functions. engine->RegisterGlobalFunction("void print(const string &in)", asFUNCTION(print), asCALL_CDECL); } ScriptManager::~ScriptManager() { engine->ShutDownAndRelease(); } void ScriptManager::BuildScript(const std::string& name) { std::string filename = Hymn().GetPath() + FileSystem::DELIMITER + "Scripts" + FileSystem::DELIMITER + name + ".as"; if (!FileSystem::FileExists(filename.c_str())) { Log() << "Script file does not exist: " << filename << "\n"; return; } CScriptBuilder builder; int r = builder.StartNewModule(engine, name.c_str()); if (r < 0) Log() << "Couldn't start new module: " << name << ".\n"; r = builder.AddSectionFromFile(filename.c_str()); if (r < 0) Log() << "File section could not be added: " << filename << ".\n"; r = builder.BuildModule(); if (r < 0) Log() << "Compile errors.\n"; } void ScriptManager::Update(Scene& scene) { for (Component::Script* script : scene.GetComponents<Component::Script>()) { if (!script->initialized) { // Create, load and build script module. asIScriptModule* module = engine->GetModule(script->entity->name.c_str(), asGM_ONLY_IF_EXISTS); // Find function to call. asIScriptFunction* function = module->GetFunctionByDecl("void Init()"); if (function == nullptr) Log() << "Couldn't find \"void Init()\" function.\n"; // Create context, prepare it and execute. asIScriptContext* context = engine->CreateContext(); context->Prepare(function); int r = context->Execute(); if (r != asEXECUTION_FINISHED) { // The execution didn't complete as expected. Determine what happened. if (r == asEXECUTION_EXCEPTION) { // An exception occurred, let the script writer know what happened so it can be corrected. Log() << "An exception '" << context->GetExceptionString() << "' occurred. Please correct the code and try again.\n"; } } // Clean up. context->Release(); script->initialized = true; } } } <commit_msg>Register Entity type<commit_after>#include "ScriptManager.hpp" #include <angelscript.h> #include <scriptbuilder/scriptbuilder.h> #include <scriptstdstring/scriptstdstring.h> #include "../Util/Log.hpp" #include "../Util/FileSystem.hpp" #include "../Hymn.hpp" #include "../Scene/Scene.hpp" #include "../Component/Script.hpp" #include "../Entity/Entity.hpp" void print(const std::string& message) { Log() << message; } ScriptManager::ScriptManager() { // Create the script engine engine = asCreateScriptEngine(); // Set the message callback to receive information on errors in human readable form. engine->SetMessageCallback(asFUNCTION(AngelScriptMessageCallback), 0, asCALL_CDECL); // Register add-ons. RegisterStdString(engine); // Register Entity. engine->RegisterObjectType("Entity", 0, asOBJ_REF | asOBJ_NOCOUNT); engine->RegisterObjectProperty("Entity", "string name", asOFFSET(Entity, name)); // Register functions. engine->RegisterGlobalFunction("void print(const string &in)", asFUNCTION(print), asCALL_CDECL); } ScriptManager::~ScriptManager() { engine->ShutDownAndRelease(); } void ScriptManager::BuildScript(const std::string& name) { std::string filename = Hymn().GetPath() + FileSystem::DELIMITER + "Scripts" + FileSystem::DELIMITER + name + ".as"; if (!FileSystem::FileExists(filename.c_str())) { Log() << "Script file does not exist: " << filename << "\n"; return; } CScriptBuilder builder; int r = builder.StartNewModule(engine, name.c_str()); if (r < 0) Log() << "Couldn't start new module: " << name << ".\n"; r = builder.AddSectionFromFile(filename.c_str()); if (r < 0) Log() << "File section could not be added: " << filename << ".\n"; r = builder.BuildModule(); if (r < 0) Log() << "Compile errors.\n"; } void ScriptManager::Update(Scene& scene) { for (Component::Script* script : scene.GetComponents<Component::Script>()) { if (!script->initialized) { // Create, load and build script module. asIScriptModule* module = engine->GetModule(script->entity->name.c_str(), asGM_ONLY_IF_EXISTS); // Find function to call. asIScriptFunction* function = module->GetFunctionByDecl("void Init()"); if (function == nullptr) Log() << "Couldn't find \"void Init()\" function.\n"; // Create context, prepare it and execute. asIScriptContext* context = engine->CreateContext(); context->Prepare(function); int r = context->Execute(); if (r != asEXECUTION_FINISHED) { // The execution didn't complete as expected. Determine what happened. if (r == asEXECUTION_EXCEPTION) { // An exception occurred, let the script writer know what happened so it can be corrected. Log() << "An exception '" << context->GetExceptionString() << "' occurred. Please correct the code and try again.\n"; } } // Clean up. context->Release(); script->initialized = true; } } } <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkBSplineInterpolateImageFunctionTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. Portions of this code are covered under the VTK copyright. See VTKCopyright.txt or http://www.kitware.com/VTKCopyright.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 notices for more information. =========================================================================*/ #include <iostream> #include "itkImage.h" #include "itkSize.h" #include "itkBSplineInterpolateImageFunction.h" #include "itkImageRegionIterator.h" #include "vnl/vnl_math.h" typedef double InputPixelType; typedef double CoordRepType; // Set up for 1D Images enum { ImageDimension1D = 1 }; typedef itk::Image< InputPixelType, ImageDimension1D > ImageType1D; typedef ImageType1D::Pointer ImageTypePtr1D; typedef ImageType1D::SizeType SizeType1D; typedef itk::BSplineInterpolateImageFunction<ImageType1D,CoordRepType> InterpolatorType1D; // typedef InterpolatorType1D::IndexType IndexType1D; typedef InterpolatorType1D::PointType PointType1D; typedef InterpolatorType1D::ContinuousIndexType ContinuousIndexType1D; void set1DData(ImageType1D::Pointer); // Set up for 2D Images enum { ImageDimension2D = 2 }; typedef itk::Image< InputPixelType, ImageDimension2D > ImageType2D; typedef ImageType2D::Pointer ImageTypePtr2D; typedef ImageType2D::SizeType SizeType2D; typedef itk::BSplineInterpolateImageFunction<ImageType2D,CoordRepType> InterpolatorType2D; // typedef InterpolatorType2D::IndexType IndexType2D; typedef InterpolatorType2D::PointType PointType2D; typedef InterpolatorType2D::ContinuousIndexType ContinuousIndexType2D; void set2DData(ImageType2D::Pointer); // Set up for 3D Images enum { ImageDimension3D = 3 }; typedef itk::Image< InputPixelType, ImageDimension3D > ImageType3D; typedef ImageType3D::Pointer ImageTypePtr3D; typedef ImageType3D::SizeType SizeType3D; typedef itk::BSplineInterpolateImageFunction<ImageType3D,CoordRepType> InterpolatorType3D; typedef InterpolatorType3D::IndexType IndexType3D; typedef InterpolatorType3D::PointType PointType3D; typedef InterpolatorType3D::ContinuousIndexType ContinuousIndexType3D; void set3DData(ImageType3D::Pointer); void set3DDerivativeData(ImageType3D::Pointer); /** * Test a geometric point. Returns true if test has passed, * returns false otherwise */ template <class TInterpolator, class PointType> bool TestGeometricPoint( const TInterpolator * interp, const PointType& point, bool isInside, double trueValue ) { std::cout << " Point: " << point; bool bvalue = interp->IsInsideBuffer( point ); std::cout << " Inside: " << bvalue << " "; if( bvalue != isInside ) { std::cout << "*** Error: inside should be " << isInside << std::endl; return false; } if( isInside ) { double value = interp->Evaluate( point ); std::cout << " Value: " << value; if( vnl_math_abs( value - trueValue ) > 1e-9 ) { std::cout << "*** Error: value should be " << trueValue << std::endl; return false; } } std::cout << std::endl; return true; } /** * Test a continuous index. Returns true if test has passed, * returns false otherwise */ template<class TInterpolator, class ContinuousIndexType> bool TestContinuousIndex( const TInterpolator * interp, const ContinuousIndexType& index, bool isInside, double trueValue ) { std::cout << " Index: " << index; bool bvalue = interp->IsInsideBuffer( index ); std::cout << " Inside: " << bvalue; if( bvalue != isInside ) { std::cout << "*** Error: inside should be " << isInside << std::endl; return false; } if( isInside ) { double value = interp->EvaluateAtContinuousIndex( index ); std::cout << " Value: " << value; if( vnl_math_abs( value - trueValue ) > 1e-4 ) { std::cout << "*** Error: value should be " << trueValue << std::endl; return false; } } std::cout << std::endl; return true; } /** * Test a continuous index Derivative. Returns true if test has passed, * returns false otherwise */ template<class TInterpolator, class ContinuousIndexType> bool TestContinuousIndexDerivative( const TInterpolator * interp, const ContinuousIndexType& index, bool isInside, double * trueValue ) { std::cout << " Index: " << index; bool bvalue = interp->IsInsideBuffer( index ); std::cout << " Inside: " << bvalue << "\n"; if( bvalue != isInside ) { std::cout << "*** Error: inside should be " << isInside << std::endl; return false; } if( isInside ) { typename TInterpolator::CovariantVectorType value; double value2 = interp->EvaluateAtContinuousIndex( index ); std::cout << "Interpolated Value: " << value2 << "\n"; value = interp->EvaluateDerivativeAtContinuousIndex( index ); std::cout << " Value: "; for (int i=0; i < ImageDimension3D; i++) { if (i != 0) { std::cout << ", "; } std::cout << value[i] ; if ( vnl_math_abs( value[i] - trueValue[i] ) > 1e-4 ) { std::cout << "*** Error: value should be " << trueValue[i] << std::endl; return false; } } } std::cout << std::endl; return true; } // Run a series of tests to validate the 1D // cubic spline implementation. int test1DCubicSpline() { int flag = 0; // Allocate a simple test image ImageTypePtr1D image = ImageType1D::New(); set1DData(image); // Set origin and spacing of physical coordinates double origin [] = { 0.5 }; double spacing[] = { 0.1 }; image->SetOrigin(origin); image->SetSpacing(spacing); // Create and initialize the interpolator InterpolatorType1D::Pointer interp = InterpolatorType1D::New(); // interp->SetSplineOrder(1); interp->SetInputImage(image); interp->Print( std::cout ); // Test evaluation at continuous indices and corresponding //gemetric points std::cout << "Testing 1D Cubic B-Spline:\n"; std::cout << "Evaluate at: " << std::endl; ContinuousIndexType1D cindex; PointType1D point; bool passed; // These values test 1) near border, // 2) inside // 3) integer value // 4) outside image #define NPOINTS 4 // number of points double darray1[NPOINTS] = {1.4, 8.9, 10.0, 40.0}; double truth[NPOINTS] = {334.41265437584, 18.158173426944, 4.0000, 0}; bool b_Inside[NPOINTS] = {true, true, true, false}; // an integer position inside the image for (int ii=0; ii < NPOINTS; ii++) { cindex = ContinuousIndexType1D(&darray1[ii]); passed = TestContinuousIndex<InterpolatorType1D, ContinuousIndexType1D >( interp, cindex, b_Inside[ii], truth[ii] ); if( !passed ) flag += 1; interp->ConvertContinuousIndexToPoint( cindex, point ); passed = TestGeometricPoint<InterpolatorType1D, PointType1D>( interp, point, b_Inside[ii], truth[ii] ); if( !passed ) flag += 1; } return (flag); } int test2DSpline() { int flag = 0; /* Allocate a simple test image */ ImageTypePtr2D image = ImageType2D::New(); set2DData(image); /* Set origin and spacing of physical coordinates */ double origin [] = { 0.5, 1.0 }; double spacing[] = { 0.1, 0.5 }; image->SetOrigin(origin); image->SetSpacing(spacing); /* Create and initialize the interpolator */ for (unsigned int splineOrder = 0; splineOrder<=5; splineOrder++) { InterpolatorType2D::Pointer interp = InterpolatorType2D::New(); interp->SetSplineOrder(splineOrder); interp->SetInputImage(image); interp->Print( std::cout ); /* Test evaluation at continuous indices and corresponding gemetric points */ std::cout << "Testing 2D B-Spline of Order "<< splineOrder << ":\n"; std::cout << "Evaluate at: " << std::endl; ContinuousIndexType2D cindex; PointType2D point; bool passed; // These values test 1) near border, // 2) inside // 3) integer value // 4) outside image #define NPOINTS2 4 // number of points double darray1[NPOINTS2][2] = {{0.1, 0.2}, {3.4, 5.8}, {4.0, 6.0}, { 2.1, 8.0}}; double truth[NPOINTS2][6] = {{154.5, 140.14, 151.86429192392, 151.650316034, 151.865916515, 151.882483111}, { 0, 13.84, 22.688125812495, 22.411473093, 22.606968306, 22.908345604}, { 36.2, 36.2, 36.2, 36.2, 36.2, 36.2 }, {0, 0, 0,0,0,0}}; bool b_Inside[NPOINTS2] = {true, true, true, false}; // double darray1[2]; // an integer position inside the image for (int ii=0; ii < NPOINTS2; ii++) { // darray1[0] = darray[ii][0]; // darray1[1] = darray[ii][1]; cindex = ContinuousIndexType2D(&darray1[ii][0]); passed = TestContinuousIndex<InterpolatorType2D, ContinuousIndexType2D >( interp, cindex, b_Inside[ii], truth[ii][splineOrder] ); if( !passed ) flag += 1; interp->ConvertContinuousIndexToPoint( cindex, point ); passed = TestGeometricPoint<InterpolatorType2D, PointType2D>( interp, point, b_Inside[ii], truth[ii][splineOrder ] ); if( !passed ) flag += 1; } } // end of splineOrder return (flag); } int test3DSpline() { int flag = 0; /* Allocate a simple test image */ ImageTypePtr3D image = ImageType3D::New(); set3DData(image); /* Set origin and spacing of physical coordinates */ double origin [] = { 0.5, 1.0, 1.333}; double spacing[] = { 0.1, 0.5, 0.75 }; image->SetOrigin(origin); image->SetSpacing(spacing); /* Create and initialize the interpolator */ for (int splineOrder = 2; splineOrder<=5; splineOrder++) { InterpolatorType3D::Pointer interp = InterpolatorType3D::New(); interp->SetSplineOrder(splineOrder); interp->SetInputImage(image); interp->Print( std::cout ); /* Test evaluation at continuous indices and corresponding gemetric points */ std::cout << "Testing 3D B-Spline of Order "<< splineOrder << ":\n"; std::cout << "Evaluate at: " << std::endl; ContinuousIndexType3D cindex; PointType3D point; bool passed; // These values test // 1) near border, // 2) inside // 3) integer value // 4) outside image #define NPOINTS3 4 // number of points double darray1[NPOINTS3][ImageDimension3D] = {{0.1, 20.1, 28.4}, {21.58, 34.5, 17.2 }, {10, 20, 12}, { 15, 20.2, 31}}; double truth[NPOINTS3][4] = {{48.621593795, 48.651173138, 48.656914878, 48.662256571}, { 73.280126903, 73.280816965, 73.282780615, 73.285315943}, { 42.0, 42.0, 42.0, 42.0}, {0,0,0,0}}; bool b_Inside[NPOINTS3] = {true, true, true, false}; // double darray1[2]; // an integer position inside the image for (int ii=0; ii < NPOINTS3; ii++) { // darray1[0] = darray[ii][0]; // darray1[1] = darray[ii][1]; cindex = ContinuousIndexType3D(&darray1[ii][0]); passed = TestContinuousIndex<InterpolatorType3D, ContinuousIndexType3D >( interp, cindex, b_Inside[ii], truth[ii][splineOrder -2] ); if( !passed ) flag += 1; interp->ConvertContinuousIndexToPoint( cindex, point ); passed = TestGeometricPoint<InterpolatorType3D, PointType3D>( interp, point, b_Inside[ii], truth[ii][splineOrder -2] ); if( !passed ) flag += 1; } } // end of splineOrder return (flag); } int test3DSplineDerivative() { int flag = 0; /* Allocate a simple test image */ ImageTypePtr3D image = ImageType3D::New(); set3DDerivativeData(image); /* Set origin and spacing of physical coordinates */ // double origin [] = { 0.5, 1.0, 1.333}; // double spacing[] = { 0.1, 0.5, 0.75 }; double origin [] = { 0.0, 0.0, 0.0}; double spacing[] = { 1,1,1 }; image->SetOrigin(origin); image->SetSpacing(spacing); /* Create and initialize the interpolator */ for (int splineOrder = 1; splineOrder<=5; splineOrder++) { InterpolatorType3D::Pointer interp = InterpolatorType3D::New(); interp->SetSplineOrder(splineOrder); interp->SetInputImage(image); interp->Print( std::cout ); /* Test evaluation at continuous indices and corresponding gemetric points */ std::cout << "Testing Derivatives of 3D B-Spline of Order "<< splineOrder << ":\n"; std::cout << "Evaluate at: " << std::endl; ContinuousIndexType3D cindex; PointType3D point; bool passed; // These values test // 1) near border, // 2) inside // 3) integer value // 4) outside image #define NPOINTS4 4 // number of points double darray1[NPOINTS4][ImageDimension3D] = {{25.3,26.8,24.5}, {21.0, 1.4, 0.6}, {18, 31, 10 }, { 4.3, 17.9, 42} }; // Calculated Truth is: {19.4158,5,-24}, {0.9,5,71.6}, {-7.2, 5, 34}, {0,0,0} // TODO: Value near border is way off, is this an algorithm problem? Also, // Is error for 1st order splines in the expected range? double truth[5][NPOINTS4][ImageDimension3D] = { { {23.6, 5,-24}, {0, 5, 72.0}, {-3.0, 5, 32}, {0,0,0} }, { {19.345, 5,-24}, {0.875, 4.8873, 98.6607}, {-7.525, 5, 34}, {0,0,0} }, { {19.399, 5,-24}, {0.9, 4.95411, 92.9006}, {-7.2, 5, 33.9999}, {0,0,0} }, { {19.4164,5,-24}, {0.9, 4.9925, 94.5082}, {-7.2, 5.00044, 33.9976}, {0,0,0} }, { {19.4223,5,-24}, {0.900157, 5.0544, 93.8607}, {-7.19929, 5.00189, 33.9879}, {0,0,0} }}; bool b_Inside[NPOINTS4] = {true, true, true, false}; // double darray1[2]; // an integer position inside the image for (int ii=0; ii < NPOINTS4; ii++) { // darray1[0] = darray[ii][0]; // darray1[1] = darray[ii][1]; cindex = ContinuousIndexType3D(&darray1[ii][0]); passed = TestContinuousIndexDerivative<InterpolatorType3D, ContinuousIndexType3D >( interp, cindex, b_Inside[ii], &truth[splineOrder - 1][ii][0] ); if( !passed ) flag += 1; // interp->ConvertContinuousIndexToPoint( cindex, point ); // passed = TestGeometricPoint<InterpolatorType3D, PointType3D>( interp, point, b_Inside[ii], truth[ii][splineOrder -2] ); if( !passed ) flag += 1; } } // end of splineOrder return (flag); } int itkBSplineInterpolateImageFunctionTest( int argc, char **argv) { int flag = 0; /* Did this test program work? */ std::cout << "Testing B Spline interpolation methods:\n"; flag += test1DCubicSpline(); flag += test2DSpline(); flag += test3DSpline(); flag += test3DSplineDerivative(); /* Return results of test */ if (flag != 0) { std::cout << "*** " << flag << " tests failed" << std::endl; return 1; } else { std::cout << "All tests successfully passed" << std::endl; return 0; } } void set1DData(ImageType1D::Pointer imgPtr) { SizeType1D size = {{36}}; double mydata[36] = {454.0000, 369.4000, 295.2000, 230.8000, 175.6000, 129.0000, 90.4000, 59.2000, 34.8000, 16.6000, 4.0000, -3.6000, -6.8000, -6.2000, -2.4000, 4.0000, 12.4000, 22.2000, 32.8000, 43.6000, 54.0000, 63.4000, 71.2000, 76.8000, 79.6000, 79.0000, 74.4000, 65.2000, 50.8000, 30.6000, 4.0000, -29.6000, -70.8000, -120.2000, -178.4000, -246.0000 }; ImageType1D::RegionType region; region.SetSize( size ); imgPtr->SetLargestPossibleRegion( region ); imgPtr->SetBufferedRegion( region ); imgPtr->Allocate(); typedef itk::ImageRegionIterator<ImageType1D> InputIterator; InputIterator inIter( imgPtr, region ); int j = 0; while( !inIter.IsAtEnd() ) { inIter.Set(mydata[j]); ++inIter; ++j; } } void set2DData(ImageType2D::Pointer imgPtr) { SizeType2D size = {{7,7}}; double mydata[ 49 ] = { 154.5000, 82.4000, 30.9000, 0, -10.3000, 0, 30.9000 , 117.0000, 62.4000, 23.4000, 0, -7.8000, 0, 23.4000 , 18.0000, 9.6000, 3.6000, 0, -1.2000, 0, 3.6000 , -120.0000, -64.0000, -24.0000, 0, 8.0000, 0, -24.0000 , -274.5000, -146.4000, -54.9000, 0, 18.3000, 0, -54.9000 , -423.0000, -225.6000, -84.6000, 0, 28.2000, 0, -84.6000 , -543.0000, -289.6000, -108.6000, 0, 36.2000, 0, -108.6000 }; ImageType2D::RegionType region; region.SetSize( size ); imgPtr->SetLargestPossibleRegion( region ); imgPtr->SetBufferedRegion( region ); imgPtr->Allocate(); typedef itk::ImageRegionIterator<ImageType2D> InputIterator; InputIterator inIter( imgPtr, region ); int j = 0; while( !inIter.IsAtEnd() ) { inIter.Set(mydata[j]); ++inIter; ++j; } } void set3DData(ImageType3D::Pointer imgPtr) { SizeType3D size = {{80,40,30}}; /* Allocate a simple test image */ ImageType3D::RegionType region; region.SetSize( size ); imgPtr->SetLargestPossibleRegion( region ); imgPtr->SetBufferedRegion( region ); imgPtr->Allocate(); /* Set origin and spacing of physical coordinates */ /* Initialize the image contents */ IndexType3D index; for (unsigned int slice = 0; slice < size[2]; slice++) { index[2] = slice; for (unsigned int row = 0; row < size[1]; row++) { index[1] = row; for (unsigned int col = 0; col < size[0]; col++) { index[0] = col; imgPtr->SetPixel(index, slice+row+col); } } } } void set3DDerivativeData(ImageType3D::Pointer imgPtr) { SizeType3D size = {{41,41,41}}; /* Allocate a simple test image */ ImageType3D::RegionType region; region.SetSize( size ); imgPtr->SetLargestPossibleRegion( region ); imgPtr->SetBufferedRegion( region ); imgPtr->Allocate(); /* Set origin and spacing of physical coordinates */ /* Initialize the image contents */ // Note [x,y,z] = [x,y,z] - 20 so that image ranges from -20 + 20; // f(x) = 0.1x^4 - 0.5x^3 + 2x - 43 // f(y) = 5y + 7 // f(z) = -2z^2 - 6z + 10 // df(x)/dx = 0.4x^3 - 1.5x^2 + 2 // df(y)/dy = 5 // df(z)/dz = -4z - 6 double value; double slice1, row1, col1; IndexType3D index; for (unsigned int slice = 0; slice < size[2]; slice++) { index[2] = slice; slice1 = slice - 20.0; // Center offset for (unsigned int row = 0; row < size[1]; row++) { index[1] = row; row1 = row - 20.0; // Center for (unsigned int col = 0; col < size[0]; col++) { index[0] = col; col1 = col - 20.0; //Center value = 0.1*col1*col1*col1*col1 - 0.5* col1*col1*col1 + 2.0*col1 - 43.0; value += 5.0*row1 + 7.0; value += -2.0*slice1*slice1 - 6.0* slice1 + 10.0; imgPtr->SetPixel(index, value); // imgPtr->SetPixel(index, row); } } } } <commit_msg>STYLE: Moved itkBSplineInterpolateImageFunctionTest to BasicFilters<commit_after><|endoftext|>
<commit_before>// // This file is part of the Marble Desktop Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2007 Torsten Rahn <tackat@kde.org>" // #include "GlobeScanlineTextureMapper.h" #include <cmath> #include <QtCore/QDebug> #include "GeoPoint.h" #include "GeoPolygon.h" #include "katlasdirs.h" #include "TextureTile.h" #include "TileLoader.h" // Defining INTERLACE will make sure that for two subsequent scanlines // every second scanline will be a deep copy of the first scanline. // This results in a more coarse resolution and in a speedup for the // texture mapping of approx. 25%. // #define INTERLACE GlobeScanlineTextureMapper::GlobeScanlineTextureMapper( const QString& path, QObject * parent ) : AbstractScanlineTextureMapper( path, parent ) { m_interpolate = false; m_nBest = 0; m_n = 0; m_nInverse = 0.0; m_x = 0; m_y = 0; m_qr = 0.0; m_qx = 0.0; m_qy = 0.0; m_qz = 0.0; m_interlaced = true; } GlobeScanlineTextureMapper::~GlobeScanlineTextureMapper() { } void GlobeScanlineTextureMapper::resizeMap(int width, int height) { AbstractScanlineTextureMapper::resizeMap( width, height ); // Find the optimal interpolation interval m_n for the // current image canvas width m_nBest = 2; int nEvalMin = m_imageWidth - 1; for ( int it = 1; it < 48; ++it ) { int nEval = ( m_imageWidth - 1 ) / it + ( m_imageWidth - 1 ) % it; if ( nEval < nEvalMin ) { nEvalMin = nEval; m_nBest = it; } } // qDebug() << QString( "Optimized n = %1, remainder: %2" ) //.arg(m_nBest).arg( ( m_imageWidth ) % m_nBest ); } void GlobeScanlineTextureMapper::mapTexture(QImage* canvasImage, const int& radius, Quaternion& planetAxis) { // Scanline based algorithm to texture map a sphere // Initialize needed variables: double lon = 0.0; double lat = 0.0; const double inverseRadius = 1.0 / (double)(radius); m_tilePosX = 65535; m_tilePosY = 65535; m_fullNormLon = m_fullRangeLon - m_tilePosX; m_halfNormLon = m_halfRangeLon - m_tilePosX; m_halfNormLat = m_halfRangeLat - m_tilePosY; m_quatNormLat = m_quatRangeLat - m_tilePosY; // Reset backend m_tileLoader->resetTilehash(); selectTileLevel(radius); // Evaluate the degree of interpolation m_n = ( m_imageRadius < radius * radius ) ? m_nBest : 8; m_nInverse = 1.0 / (double)(m_n); // Calculate north pole position to decrease pole distortion later on Quaternion northPole = GeoPoint( 0.0, (double)( -M_PI * 0.5 ) ).quaternion(); Quaternion inversePlanetAxis = planetAxis; inversePlanetAxis = inversePlanetAxis.inverse(); northPole.rotateAroundAxis( inversePlanetAxis ); // Calculate axis matrix to represent the planet's rotation. matrix planetAxisMatrix; planetAxis.toMatrix( planetAxisMatrix ); int skip = ( m_interlaced == true ) ? 1 : 0; // Calculate the actual y-range of the map on the screen const int yTop = ( ( m_imageHeight / 2 - radius < 0 ) ? 0 : m_imageHeight / 2 - radius ); const int yBottom = ( (yTop == 0) ? m_imageHeight - skip : yTop + radius + radius - skip ); for ( m_y = yTop; m_y < yBottom ; ++m_y ) { // Evaluate coordinates for the 3D position vector of the current pixel m_qy = inverseRadius * (double)( m_y - m_imageHeight / 2 ); m_qr = 1.0 - m_qy * m_qy; // rx is the radius component in x direction int rx = (int)sqrt( (double)( radius * radius - ( ( m_y - m_imageHeight / 2 ) * ( m_y - m_imageHeight / 2 ) ) ) ); // Calculate the actual x-range of the map within the current scanline const int xLeft = ( ( m_imageWidth / 2 - rx > 0 ) ? m_imageWidth / 2 - rx : 0 ); const int xRight = ( ( m_imageWidth / 2 - rx > 0 ) ? xLeft + rx + rx : canvasImage -> width() ); m_scanLine = (QRgb*)( canvasImage->scanLine( m_y ) ) + xLeft; int xIpLeft = 1; int xIpRight = m_n * (int)( xRight / m_n - 1) + 1; if ( m_imageWidth / 2 - rx > 0 ) { xIpLeft = m_n * (int)( xLeft / m_n + 1 ); xIpRight = m_n * (int)( xRight / m_n - 1 ); } // Decrease pole distortion due to linear approximation ( y-axis ) bool crossingPoleArea = false; int northPoleY = m_imageHeight / 2 + (int)( radius * northPole.v[Q_Y] ); if ( northPole.v[Q_Z] > 0 && northPoleY - ( m_n * 0.75 ) <= m_y && northPoleY + ( m_n * 0.75 ) >= m_y ) { crossingPoleArea = true; } int ncount = 0; for ( int m_x = xLeft; m_x < xRight; ++m_x ) { // Prepare for interpolation int leftInterval = xIpLeft + ncount * m_n; if ( m_x >= xIpLeft && m_x <= xIpRight ) { // Decrease pole distortion due to linear approximation ( x-axis ) int northPoleX = m_imageWidth / 2 + (int)( radius * northPole.v[Q_X] ); // qDebug() << QString("NorthPole X: %1, LeftInterval: %2").arg( northPoleX ).arg( leftInterval ); if ( crossingPoleArea == true && northPoleX >= leftInterval + m_n && northPoleX < leftInterval + 2*m_n && m_x < leftInterval + 3 * m_n ) { m_interpolate = false; } else { m_x += m_n - 1; m_interpolate = true; ++ncount; } } else m_interpolate = false; // Evaluate more coordinates for the 3D position vector of // the current pixel. m_qx = (double)( m_x - m_imageWidth / 2 ) * inverseRadius; double qr2z = m_qr - m_qx * m_qx; m_qz = ( qr2z > 0.0 ) ? sqrt( qr2z ) : 0.0; // Create Quaternion from vector coordinates and rotate it // around globe axis m_qpos.set( 0.0, m_qx, m_qy, m_qz ); m_qpos.rotateAroundAxis( planetAxisMatrix ); m_qpos.getSpherical( lon, lat ); // Approx for m_n-1 out of n pixels within the boundary of // xIpLeft to xIpRight if ( m_interpolate ) { pixelValueApprox( lon, lat, m_scanLine ); m_scanLine += ( m_n - 1 ); } // You can temporarily comment out this line and run Marble // to understand the interpolation: pixelValue( lon, lat, m_scanLine ); m_prevLat = lat; // preparing for interpolation m_prevLon = lon; ++m_scanLine; } if ( m_interlaced == true ) { // copy scanline to improve performance int pixelByteSize = canvasImage->bytesPerLine() / m_imageWidth; memcpy( canvasImage->scanLine( m_y + 1 ) + xLeft * pixelByteSize, canvasImage->scanLine( m_y ) + xLeft * pixelByteSize, ( xRight - xLeft ) * pixelByteSize ); ++m_y; } } m_tileLoader->cleanupTilehash(); } // This method interpolates color values for skipped pixels in a scanline. // // While moving along the scanline we don't move from pixel to pixel but // leave out m_n pixels each time and calculate the exact position and // color value for the new pixel. The pixel values in between get // approximated through linear interpolation across the direct connecting // line on the original tiles directly. // This method will do by far most of the calculations for the // texturemapping, so we move towards integer math to improve speed. void GlobeScanlineTextureMapper::pixelValueApprox(const double& lon, const double& lat, QRgb *scanLine) { // stepLon/Lat: Distance between two subsequent approximated positions double stepLat = lat - m_prevLat; double stepLon = lon - m_prevLon; // As long as the distance is smaller than 180 deg we can assume that // we didn't cross the dateline. if ( fabs(stepLon) < M_PI ) { const int itStepLon = (int)( stepLon * m_nInverse * m_rad2PixelX * 128.0 ); const int itStepLat = (int)( stepLat * m_nInverse * m_rad2PixelY * 128.0 ); m_prevLon *= m_rad2PixelX; m_prevLat *= m_rad2PixelY; // To improve speed we unroll // AbstractScanlineTextureMapper::pixelValue(...) here and // calculate the performance critical issues via integers int itLon = (int)( ( m_prevLon + m_halfNormLon ) * 128.0 ); int itLat = (int)( ( m_prevLat + m_quatNormLat ) * 128.0 ); if ( m_tile->depth() == 8 ) { for ( int j=1; j < m_n; ++j ) { m_posX = ( itLon + itStepLon * j ) >> 7; m_posY = ( itLat + itStepLat * j ) >> 7; if ( m_posX >= m_tileLoader->tileWidth() || m_posX < 0 || m_posY >= m_tileLoader->tileHeight() || m_posY < 0 ) { nextTile(); itLon = (int)( ( m_prevLon + m_halfNormLon ) * 128.0 ); itLat = (int)( ( m_prevLat + m_quatNormLat ) * 128.0 ); m_posX = ( itLon + itStepLon * j ) >> 7; m_posY = ( itLat + itStepLat * j ) >> 7; } *scanLine = m_tile->jumpTable8[m_posY][m_posX ]; ++scanLine; } } else { for ( int j=1; j < m_n; ++j ) { m_posX = ( itLon + itStepLon * j ) >> 7; m_posY = ( itLat + itStepLat * j ) >> 7; if ( m_posX >= m_tileLoader->tileWidth() || m_posX < 0 || m_posY >= m_tileLoader->tileHeight() || m_posY < 0 ) { nextTile(); itLon = (int)( ( m_prevLon + m_halfNormLon ) * 128.0 ); itLat = (int)( ( m_prevLat + m_quatNormLat ) * 128.0 ); m_posX = ( itLon + itStepLon * j ) >> 7; m_posY = ( itLat + itStepLat * j ) >> 7; } *scanLine = m_tile->jumpTable32[m_posY][m_posX ]; ++scanLine; } } } // For the case where we cross the dateline between (lon, lat) and // (prevlon, prevlat) we need a more sophisticated calculation. // However as this will happen rather rarely, we use // pixelValue(...) directly to make the code more readable. else { stepLon = ( TWOPI - fabs(stepLon) ) * m_nInverse; stepLat = stepLat * m_nInverse; // We need to distinguish two cases: // crossing the dateline from east to west ... if ( m_prevLon < lon ) { for ( int j = 1; j < m_n; ++j ) { m_prevLat += stepLat; m_prevLon -= stepLon; if ( m_prevLon <= -M_PI ) m_prevLon += TWOPI; pixelValue( m_prevLon, m_prevLat, scanLine ); ++scanLine; } } // ... and vice versa: from west to east. else { double curStepLon = lon - m_n * stepLon; for ( int j = 1; j < m_n; ++j ) { m_prevLat += stepLat; curStepLon += stepLon; double evalLon = curStepLon; if ( curStepLon <= -M_PI ) evalLon += TWOPI; pixelValue( evalLon, m_prevLat, scanLine); ++scanLine; } } } } <commit_msg>Ooops, disable by default<commit_after>// // This file is part of the Marble Desktop Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2007 Torsten Rahn <tackat@kde.org>" // #include "GlobeScanlineTextureMapper.h" #include <cmath> #include <QtCore/QDebug> #include "GeoPoint.h" #include "GeoPolygon.h" #include "katlasdirs.h" #include "TextureTile.h" #include "TileLoader.h" // Defining INTERLACE will make sure that for two subsequent scanlines // every second scanline will be a deep copy of the first scanline. // This results in a more coarse resolution and in a speedup for the // texture mapping of approx. 25%. // #define INTERLACE GlobeScanlineTextureMapper::GlobeScanlineTextureMapper( const QString& path, QObject * parent ) : AbstractScanlineTextureMapper( path, parent ) { m_interpolate = false; m_nBest = 0; m_n = 0; m_nInverse = 0.0; m_x = 0; m_y = 0; m_qr = 0.0; m_qx = 0.0; m_qy = 0.0; m_qz = 0.0; m_interlaced = false; } GlobeScanlineTextureMapper::~GlobeScanlineTextureMapper() { } void GlobeScanlineTextureMapper::resizeMap(int width, int height) { AbstractScanlineTextureMapper::resizeMap( width, height ); // Find the optimal interpolation interval m_n for the // current image canvas width m_nBest = 2; int nEvalMin = m_imageWidth - 1; for ( int it = 1; it < 48; ++it ) { int nEval = ( m_imageWidth - 1 ) / it + ( m_imageWidth - 1 ) % it; if ( nEval < nEvalMin ) { nEvalMin = nEval; m_nBest = it; } } // qDebug() << QString( "Optimized n = %1, remainder: %2" ) //.arg(m_nBest).arg( ( m_imageWidth ) % m_nBest ); } void GlobeScanlineTextureMapper::mapTexture(QImage* canvasImage, const int& radius, Quaternion& planetAxis) { // Scanline based algorithm to texture map a sphere // Initialize needed variables: double lon = 0.0; double lat = 0.0; const double inverseRadius = 1.0 / (double)(radius); m_tilePosX = 65535; m_tilePosY = 65535; m_fullNormLon = m_fullRangeLon - m_tilePosX; m_halfNormLon = m_halfRangeLon - m_tilePosX; m_halfNormLat = m_halfRangeLat - m_tilePosY; m_quatNormLat = m_quatRangeLat - m_tilePosY; // Reset backend m_tileLoader->resetTilehash(); selectTileLevel(radius); // Evaluate the degree of interpolation m_n = ( m_imageRadius < radius * radius ) ? m_nBest : 8; m_nInverse = 1.0 / (double)(m_n); // Calculate north pole position to decrease pole distortion later on Quaternion northPole = GeoPoint( 0.0, (double)( -M_PI * 0.5 ) ).quaternion(); Quaternion inversePlanetAxis = planetAxis; inversePlanetAxis = inversePlanetAxis.inverse(); northPole.rotateAroundAxis( inversePlanetAxis ); // Calculate axis matrix to represent the planet's rotation. matrix planetAxisMatrix; planetAxis.toMatrix( planetAxisMatrix ); int skip = ( m_interlaced == true ) ? 1 : 0; // Calculate the actual y-range of the map on the screen const int yTop = ( ( m_imageHeight / 2 - radius < 0 ) ? 0 : m_imageHeight / 2 - radius ); const int yBottom = ( (yTop == 0) ? m_imageHeight - skip : yTop + radius + radius - skip ); for ( m_y = yTop; m_y < yBottom ; ++m_y ) { // Evaluate coordinates for the 3D position vector of the current pixel m_qy = inverseRadius * (double)( m_y - m_imageHeight / 2 ); m_qr = 1.0 - m_qy * m_qy; // rx is the radius component in x direction int rx = (int)sqrt( (double)( radius * radius - ( ( m_y - m_imageHeight / 2 ) * ( m_y - m_imageHeight / 2 ) ) ) ); // Calculate the actual x-range of the map within the current scanline const int xLeft = ( ( m_imageWidth / 2 - rx > 0 ) ? m_imageWidth / 2 - rx : 0 ); const int xRight = ( ( m_imageWidth / 2 - rx > 0 ) ? xLeft + rx + rx : canvasImage -> width() ); m_scanLine = (QRgb*)( canvasImage->scanLine( m_y ) ) + xLeft; int xIpLeft = 1; int xIpRight = m_n * (int)( xRight / m_n - 1) + 1; if ( m_imageWidth / 2 - rx > 0 ) { xIpLeft = m_n * (int)( xLeft / m_n + 1 ); xIpRight = m_n * (int)( xRight / m_n - 1 ); } // Decrease pole distortion due to linear approximation ( y-axis ) bool crossingPoleArea = false; int northPoleY = m_imageHeight / 2 + (int)( radius * northPole.v[Q_Y] ); if ( northPole.v[Q_Z] > 0 && northPoleY - ( m_n * 0.75 ) <= m_y && northPoleY + ( m_n * 0.75 ) >= m_y ) { crossingPoleArea = true; } int ncount = 0; for ( int m_x = xLeft; m_x < xRight; ++m_x ) { // Prepare for interpolation int leftInterval = xIpLeft + ncount * m_n; if ( m_x >= xIpLeft && m_x <= xIpRight ) { // Decrease pole distortion due to linear approximation ( x-axis ) int northPoleX = m_imageWidth / 2 + (int)( radius * northPole.v[Q_X] ); // qDebug() << QString("NorthPole X: %1, LeftInterval: %2").arg( northPoleX ).arg( leftInterval ); if ( crossingPoleArea == true && northPoleX >= leftInterval + m_n && northPoleX < leftInterval + 2*m_n && m_x < leftInterval + 3 * m_n ) { m_interpolate = false; } else { m_x += m_n - 1; m_interpolate = true; ++ncount; } } else m_interpolate = false; // Evaluate more coordinates for the 3D position vector of // the current pixel. m_qx = (double)( m_x - m_imageWidth / 2 ) * inverseRadius; double qr2z = m_qr - m_qx * m_qx; m_qz = ( qr2z > 0.0 ) ? sqrt( qr2z ) : 0.0; // Create Quaternion from vector coordinates and rotate it // around globe axis m_qpos.set( 0.0, m_qx, m_qy, m_qz ); m_qpos.rotateAroundAxis( planetAxisMatrix ); m_qpos.getSpherical( lon, lat ); // Approx for m_n-1 out of n pixels within the boundary of // xIpLeft to xIpRight if ( m_interpolate ) { pixelValueApprox( lon, lat, m_scanLine ); m_scanLine += ( m_n - 1 ); } // You can temporarily comment out this line and run Marble // to understand the interpolation: pixelValue( lon, lat, m_scanLine ); m_prevLat = lat; // preparing for interpolation m_prevLon = lon; ++m_scanLine; } if ( m_interlaced == true ) { // copy scanline to improve performance int pixelByteSize = canvasImage->bytesPerLine() / m_imageWidth; memcpy( canvasImage->scanLine( m_y + 1 ) + xLeft * pixelByteSize, canvasImage->scanLine( m_y ) + xLeft * pixelByteSize, ( xRight - xLeft ) * pixelByteSize ); ++m_y; } } m_tileLoader->cleanupTilehash(); } // This method interpolates color values for skipped pixels in a scanline. // // While moving along the scanline we don't move from pixel to pixel but // leave out m_n pixels each time and calculate the exact position and // color value for the new pixel. The pixel values in between get // approximated through linear interpolation across the direct connecting // line on the original tiles directly. // This method will do by far most of the calculations for the // texturemapping, so we move towards integer math to improve speed. void GlobeScanlineTextureMapper::pixelValueApprox(const double& lon, const double& lat, QRgb *scanLine) { // stepLon/Lat: Distance between two subsequent approximated positions double stepLat = lat - m_prevLat; double stepLon = lon - m_prevLon; // As long as the distance is smaller than 180 deg we can assume that // we didn't cross the dateline. if ( fabs(stepLon) < M_PI ) { const int itStepLon = (int)( stepLon * m_nInverse * m_rad2PixelX * 128.0 ); const int itStepLat = (int)( stepLat * m_nInverse * m_rad2PixelY * 128.0 ); m_prevLon *= m_rad2PixelX; m_prevLat *= m_rad2PixelY; // To improve speed we unroll // AbstractScanlineTextureMapper::pixelValue(...) here and // calculate the performance critical issues via integers int itLon = (int)( ( m_prevLon + m_halfNormLon ) * 128.0 ); int itLat = (int)( ( m_prevLat + m_quatNormLat ) * 128.0 ); if ( m_tile->depth() == 8 ) { for ( int j=1; j < m_n; ++j ) { m_posX = ( itLon + itStepLon * j ) >> 7; m_posY = ( itLat + itStepLat * j ) >> 7; if ( m_posX >= m_tileLoader->tileWidth() || m_posX < 0 || m_posY >= m_tileLoader->tileHeight() || m_posY < 0 ) { nextTile(); itLon = (int)( ( m_prevLon + m_halfNormLon ) * 128.0 ); itLat = (int)( ( m_prevLat + m_quatNormLat ) * 128.0 ); m_posX = ( itLon + itStepLon * j ) >> 7; m_posY = ( itLat + itStepLat * j ) >> 7; } *scanLine = m_tile->jumpTable8[m_posY][m_posX ]; ++scanLine; } } else { for ( int j=1; j < m_n; ++j ) { m_posX = ( itLon + itStepLon * j ) >> 7; m_posY = ( itLat + itStepLat * j ) >> 7; if ( m_posX >= m_tileLoader->tileWidth() || m_posX < 0 || m_posY >= m_tileLoader->tileHeight() || m_posY < 0 ) { nextTile(); itLon = (int)( ( m_prevLon + m_halfNormLon ) * 128.0 ); itLat = (int)( ( m_prevLat + m_quatNormLat ) * 128.0 ); m_posX = ( itLon + itStepLon * j ) >> 7; m_posY = ( itLat + itStepLat * j ) >> 7; } *scanLine = m_tile->jumpTable32[m_posY][m_posX ]; ++scanLine; } } } // For the case where we cross the dateline between (lon, lat) and // (prevlon, prevlat) we need a more sophisticated calculation. // However as this will happen rather rarely, we use // pixelValue(...) directly to make the code more readable. else { stepLon = ( TWOPI - fabs(stepLon) ) * m_nInverse; stepLat = stepLat * m_nInverse; // We need to distinguish two cases: // crossing the dateline from east to west ... if ( m_prevLon < lon ) { for ( int j = 1; j < m_n; ++j ) { m_prevLat += stepLat; m_prevLon -= stepLon; if ( m_prevLon <= -M_PI ) m_prevLon += TWOPI; pixelValue( m_prevLon, m_prevLat, scanLine ); ++scanLine; } } // ... and vice versa: from west to east. else { double curStepLon = lon - m_n * stepLon; for ( int j = 1; j < m_n; ++j ) { m_prevLat += stepLat; curStepLon += stepLon; double evalLon = curStepLon; if ( curStepLon <= -M_PI ) evalLon += TWOPI; pixelValue( evalLon, m_prevLat, scanLine); ++scanLine; } } } } <|endoftext|>
<commit_before><commit_msg>removing #<commit_after><|endoftext|>
<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "attribute_aspect_delayer.h" #include <vespa/searchlib/attribute/configconverter.h> #include <vespa/searchcore/proton/common/i_document_type_inspector.h> #include <vespa/searchcore/proton/common/i_indexschema_inspector.h> #include <vespa/searchcore/proton/common/config_hash.hpp> #include <vespa/vespalib/stllike/hash_set.hpp> #include <vespa/config-attributes.h> #include <vespa/config-summary.h> #include <vespa/config-summarymap.h> using search::attribute::ConfigConverter; using vespa::config::search::AttributesConfig; using vespa::config::search::AttributesConfigBuilder; using vespa::config::search::SummarymapConfig; using vespa::config::search::SummarymapConfigBuilder; using vespa::config::search::SummaryConfig; using search::attribute::BasicType; namespace proton { namespace { using AttributesConfigHash = ConfigHash<AttributesConfig::Attribute>; bool fastPartialUpdateAttribute(const search::attribute::Config &cfg) { auto basicType = cfg.basicType().type(); return ((basicType != BasicType::Type::PREDICATE) && (basicType != BasicType::Type::TENSOR) && (basicType != BasicType::Type::REFERENCE)); } bool isStructFieldAttribute(const vespalib::string &name) { return name.find('.') != vespalib::string::npos; } bool willTriggerReprocessOnAttributeAspectRemoval(const search::attribute::Config &cfg, const IIndexschemaInspector &indexschemaInspector, const vespalib::string &name) { return fastPartialUpdateAttribute(cfg) && !indexschemaInspector.isStringIndex(name) && !isStructFieldAttribute(name); } class KnownSummaryFields { vespalib::hash_set<vespalib::string> _fields; public: KnownSummaryFields(const SummaryConfig &summaryConfig); ~KnownSummaryFields(); bool known(const vespalib::string &fieldName) const { return _fields.find(fieldName) != _fields.end(); } }; KnownSummaryFields::KnownSummaryFields(const SummaryConfig &summaryConfig) : _fields() { for (const auto &summaryClass : summaryConfig.classes) { for (const auto &summaryField : summaryClass.fields) { _fields.insert(summaryField.name); } } } KnownSummaryFields::~KnownSummaryFields() = default; } AttributeAspectDelayer::AttributeAspectDelayer() : _attributesConfig(std::make_shared<AttributesConfigBuilder>()), _summarymapConfig(std::make_shared<SummarymapConfigBuilder>()) { } AttributeAspectDelayer::~AttributeAspectDelayer() { } std::shared_ptr<AttributeAspectDelayer::AttributesConfig> AttributeAspectDelayer::getAttributesConfig() const { return _attributesConfig; } std::shared_ptr<AttributeAspectDelayer::SummarymapConfig> AttributeAspectDelayer::getSummarymapConfig() const { return _summarymapConfig; } namespace { void handleNewAttributes(const AttributesConfig &oldAttributesConfig, const AttributesConfig &newAttributesConfig, const SummarymapConfig &newSummarymapConfig, const IIndexschemaInspector &oldIndexschemaInspector, const IDocumentTypeInspector &inspector, AttributesConfigBuilder &attributesConfig, SummarymapConfigBuilder &summarymapConfig) { vespalib::hash_set<vespalib::string> delayed; vespalib::hash_set<vespalib::string> delayedStruct; AttributesConfigHash oldAttrs(oldAttributesConfig.attribute); for (const auto &newAttr : newAttributesConfig.attribute) { search::attribute::Config newCfg = ConfigConverter::convert(newAttr); if (!inspector.hasUnchangedField(newAttr.name)) { // No reprocessing due to field type change, just use new config attributesConfig.attribute.emplace_back(newAttr); } else { auto oldAttr = oldAttrs.lookup(newAttr.name); if (oldAttr != nullptr) { search::attribute::Config oldCfg = ConfigConverter::convert(*oldAttr); if (willTriggerReprocessOnAttributeAspectRemoval(oldCfg, oldIndexschemaInspector, newAttr.name) || !oldAttr->fastaccess) { // Delay change of fast access flag newCfg.setFastAccess(oldAttr->fastaccess); auto modNewAttr = newAttr; modNewAttr.fastaccess = oldAttr->fastaccess; attributesConfig.attribute.emplace_back(modNewAttr); // TODO: Don't delay change of fast access flag if // attribute type can change without doucment field // type changing (needs a smarter attribute // reprocessing initializer). } else { // Don't delay change of fast access flag from true to // false when removing attribute aspect in a way that // doesn't trigger reprocessing. attributesConfig.attribute.emplace_back(newAttr); } } else { // Delay addition of attribute aspect delayed.insert(newAttr.name); auto pos = newAttr.name.find('.'); if (pos != vespalib::string::npos) { delayedStruct.insert(newAttr.name.substr(0, pos)); } } } } for (const auto &override : newSummarymapConfig.override) { if (override.command == "attribute") { auto itr = delayed.find(override.field); if (itr == delayed.end()) { summarymapConfig.override.emplace_back(override); } } else if (override.command == "attributecombiner") { auto itr = delayedStruct.find(override.field); if (itr == delayedStruct.end()) { summarymapConfig.override.emplace_back(override); } } else { summarymapConfig.override.emplace_back(override); } } } void handleOldAttributes(const AttributesConfig &oldAttributesConfig, const AttributesConfig &newAttributesConfig, const SummarymapConfig &oldSummarymapConfig, const SummaryConfig &newSummaryConfig, const IIndexschemaInspector &oldIndexschemaInspector, const IDocumentTypeInspector &inspector, AttributesConfigBuilder &attributesConfig, SummarymapConfigBuilder &summarymapConfig) { vespalib::hash_set<vespalib::string> delayed; KnownSummaryFields knownSummaryFields(newSummaryConfig); AttributesConfigHash newAttrs(newAttributesConfig.attribute); for (const auto &oldAttr : oldAttributesConfig.attribute) { search::attribute::Config oldCfg = ConfigConverter::convert(oldAttr); if (inspector.hasUnchangedField(oldAttr.name)) { auto newAttr = newAttrs.lookup(oldAttr.name); if (newAttr == nullptr) { // Delay removal of attribute aspect if it would trigger // reprocessing. if (willTriggerReprocessOnAttributeAspectRemoval(oldCfg, oldIndexschemaInspector, oldAttr.name)) { attributesConfig.attribute.emplace_back(oldAttr); delayed.insert(oldAttr.name); } } } } for (const auto &override : oldSummarymapConfig.override) { if (override.command == "attribute") { auto itr = delayed.find(override.field); if (itr != delayed.end() && knownSummaryFields.known(override.field)) { summarymapConfig.override.emplace_back(override); } } } } } void AttributeAspectDelayer::setup(const AttributesConfig &oldAttributesConfig, const SummarymapConfig &oldSummarymapConfig, const AttributesConfig &newAttributesConfig, const SummaryConfig &newSummaryConfig, const SummarymapConfig &newSummarymapConfig, const IIndexschemaInspector &oldIndexschemaInspector, const IDocumentTypeInspector &inspector) { (void) newSummaryConfig; handleNewAttributes(oldAttributesConfig, newAttributesConfig, newSummarymapConfig, oldIndexschemaInspector, inspector, *_attributesConfig, *_summarymapConfig); handleOldAttributes(oldAttributesConfig, newAttributesConfig, oldSummarymapConfig, newSummaryConfig, oldIndexschemaInspector, inspector, *_attributesConfig, *_summarymapConfig); } } // namespace proton <commit_msg>Remove unneeded use of variable.<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "attribute_aspect_delayer.h" #include <vespa/searchlib/attribute/configconverter.h> #include <vespa/searchcore/proton/common/i_document_type_inspector.h> #include <vespa/searchcore/proton/common/i_indexschema_inspector.h> #include <vespa/searchcore/proton/common/config_hash.hpp> #include <vespa/vespalib/stllike/hash_set.hpp> #include <vespa/config-attributes.h> #include <vespa/config-summary.h> #include <vespa/config-summarymap.h> using search::attribute::ConfigConverter; using vespa::config::search::AttributesConfig; using vespa::config::search::AttributesConfigBuilder; using vespa::config::search::SummarymapConfig; using vespa::config::search::SummarymapConfigBuilder; using vespa::config::search::SummaryConfig; using search::attribute::BasicType; namespace proton { namespace { using AttributesConfigHash = ConfigHash<AttributesConfig::Attribute>; bool fastPartialUpdateAttribute(const search::attribute::Config &cfg) { auto basicType = cfg.basicType().type(); return ((basicType != BasicType::Type::PREDICATE) && (basicType != BasicType::Type::TENSOR) && (basicType != BasicType::Type::REFERENCE)); } bool isStructFieldAttribute(const vespalib::string &name) { return name.find('.') != vespalib::string::npos; } bool willTriggerReprocessOnAttributeAspectRemoval(const search::attribute::Config &cfg, const IIndexschemaInspector &indexschemaInspector, const vespalib::string &name) { return fastPartialUpdateAttribute(cfg) && !indexschemaInspector.isStringIndex(name) && !isStructFieldAttribute(name); } class KnownSummaryFields { vespalib::hash_set<vespalib::string> _fields; public: KnownSummaryFields(const SummaryConfig &summaryConfig); ~KnownSummaryFields(); bool known(const vespalib::string &fieldName) const { return _fields.find(fieldName) != _fields.end(); } }; KnownSummaryFields::KnownSummaryFields(const SummaryConfig &summaryConfig) : _fields() { for (const auto &summaryClass : summaryConfig.classes) { for (const auto &summaryField : summaryClass.fields) { _fields.insert(summaryField.name); } } } KnownSummaryFields::~KnownSummaryFields() = default; } AttributeAspectDelayer::AttributeAspectDelayer() : _attributesConfig(std::make_shared<AttributesConfigBuilder>()), _summarymapConfig(std::make_shared<SummarymapConfigBuilder>()) { } AttributeAspectDelayer::~AttributeAspectDelayer() { } std::shared_ptr<AttributeAspectDelayer::AttributesConfig> AttributeAspectDelayer::getAttributesConfig() const { return _attributesConfig; } std::shared_ptr<AttributeAspectDelayer::SummarymapConfig> AttributeAspectDelayer::getSummarymapConfig() const { return _summarymapConfig; } namespace { void handleNewAttributes(const AttributesConfig &oldAttributesConfig, const AttributesConfig &newAttributesConfig, const SummarymapConfig &newSummarymapConfig, const IIndexschemaInspector &oldIndexschemaInspector, const IDocumentTypeInspector &inspector, AttributesConfigBuilder &attributesConfig, SummarymapConfigBuilder &summarymapConfig) { vespalib::hash_set<vespalib::string> delayed; vespalib::hash_set<vespalib::string> delayedStruct; AttributesConfigHash oldAttrs(oldAttributesConfig.attribute); for (const auto &newAttr : newAttributesConfig.attribute) { search::attribute::Config newCfg = ConfigConverter::convert(newAttr); if (!inspector.hasUnchangedField(newAttr.name)) { // No reprocessing due to field type change, just use new config attributesConfig.attribute.emplace_back(newAttr); } else { auto oldAttr = oldAttrs.lookup(newAttr.name); if (oldAttr != nullptr) { search::attribute::Config oldCfg = ConfigConverter::convert(*oldAttr); if (willTriggerReprocessOnAttributeAspectRemoval(oldCfg, oldIndexschemaInspector, newAttr.name) || !oldAttr->fastaccess) { // Delay change of fast access flag newCfg.setFastAccess(oldAttr->fastaccess); auto modNewAttr = newAttr; modNewAttr.fastaccess = oldAttr->fastaccess; attributesConfig.attribute.emplace_back(modNewAttr); // TODO: Don't delay change of fast access flag if // attribute type can change without doucment field // type changing (needs a smarter attribute // reprocessing initializer). } else { // Don't delay change of fast access flag from true to // false when removing attribute aspect in a way that // doesn't trigger reprocessing. attributesConfig.attribute.emplace_back(newAttr); } } else { // Delay addition of attribute aspect delayed.insert(newAttr.name); auto pos = newAttr.name.find('.'); if (pos != vespalib::string::npos) { delayedStruct.insert(newAttr.name.substr(0, pos)); } } } } for (const auto &override : newSummarymapConfig.override) { if (override.command == "attribute") { auto itr = delayed.find(override.field); if (itr == delayed.end()) { summarymapConfig.override.emplace_back(override); } } else if (override.command == "attributecombiner") { auto itr = delayedStruct.find(override.field); if (itr == delayedStruct.end()) { summarymapConfig.override.emplace_back(override); } } else { summarymapConfig.override.emplace_back(override); } } } void handleOldAttributes(const AttributesConfig &oldAttributesConfig, const AttributesConfig &newAttributesConfig, const SummarymapConfig &oldSummarymapConfig, const SummaryConfig &newSummaryConfig, const IIndexschemaInspector &oldIndexschemaInspector, const IDocumentTypeInspector &inspector, AttributesConfigBuilder &attributesConfig, SummarymapConfigBuilder &summarymapConfig) { vespalib::hash_set<vespalib::string> delayed; KnownSummaryFields knownSummaryFields(newSummaryConfig); AttributesConfigHash newAttrs(newAttributesConfig.attribute); for (const auto &oldAttr : oldAttributesConfig.attribute) { search::attribute::Config oldCfg = ConfigConverter::convert(oldAttr); if (inspector.hasUnchangedField(oldAttr.name)) { auto newAttr = newAttrs.lookup(oldAttr.name); if (newAttr == nullptr) { // Delay removal of attribute aspect if it would trigger // reprocessing. if (willTriggerReprocessOnAttributeAspectRemoval(oldCfg, oldIndexschemaInspector, oldAttr.name)) { attributesConfig.attribute.emplace_back(oldAttr); delayed.insert(oldAttr.name); } } } } for (const auto &override : oldSummarymapConfig.override) { if (override.command == "attribute") { auto itr = delayed.find(override.field); if (itr != delayed.end() && knownSummaryFields.known(override.field)) { summarymapConfig.override.emplace_back(override); } } } } } void AttributeAspectDelayer::setup(const AttributesConfig &oldAttributesConfig, const SummarymapConfig &oldSummarymapConfig, const AttributesConfig &newAttributesConfig, const SummaryConfig &newSummaryConfig, const SummarymapConfig &newSummarymapConfig, const IIndexschemaInspector &oldIndexschemaInspector, const IDocumentTypeInspector &inspector) { handleNewAttributes(oldAttributesConfig, newAttributesConfig, newSummarymapConfig, oldIndexschemaInspector, inspector, *_attributesConfig, *_summarymapConfig); handleOldAttributes(oldAttributesConfig, newAttributesConfig, oldSummarymapConfig, newSummaryConfig, oldIndexschemaInspector, inspector, *_attributesConfig, *_summarymapConfig); } } // namespace proton <|endoftext|>
<commit_before>#include "tateti_struct.h" #include <iostream> using namespace std ; tateti_struct::tateti_struct(MODE m) { this.table = new char[3][3] this.mode = m; this.activeplayer = get_player1(); } tateti_struct::init_game(){ while(!game_over()) { int x; int y; cout<< "gimme me ya move "<< actual_player() << "!: "; cin >> x >> y; set_slot(x,y, actual_player); this.activeplayer = !this.activeplayer } } tateti_struct::get_player1(){ default_random_engine generator; uniform_int_distribution<int> distribution(0,1); return distribution(generator); } tateti_struct::actual_player(){}//TODO tateti_struct::set_slot(){} //TODO tateti_struct::game_over() { return no_valid_moves(0,0) || someone_won(); }//TODO tateti_struct::someone_won(); { } <commit_msg>I MEAN; IT WAAAAS WY BETTER THAT NEMO!<commit_after>#include "tateti_struct.h" #include <iostream> using namespace std ; tateti_struct::tateti_struct(MODE m) { this.table = new char[3][3] this.mode = m; this.activeplayer = get_player1(); } tateti_struct::init_game(){ while(!game_over()) { int x; int y; cout<< "gimme me ya move "<< actual_player() << "!: "; cin >> x >> y; cout << endl; while(not_a_valid_move(x,y)){ cout<<"stop being a cunt!:"<< endl; cin >> x >> y; cout << endl; } set_slot(x,y, actual_player); print_ttt(); this.activeplayer = !this.activeplayer; } } bool tateti_struct::get_player1(){ default_random_engine generator; uniform_int_distribution<int> distribution(0,1); return (bool)distribution(generator); } bool tateti_struct::actual_player(){}//TODO void tateti_struct::set_slot(int x, int y, bool actPlyr ) { actPlyr?(this.table[x][y]='X'):(this.table[x][y]='O') //this.table[x][y] = (actPlyr? 'X' : 'O') } bool tateti_struct::game_over() { //return no_valid_moves(0,0) || someone_won(); }//TODO void tateti_struct::print_ttt() { for(i=0; i<3, i++) { for(j=0; j<3, j++) { cout << not_a_valid_move(i,j)?('-'):this.table[x][y] << "\t" } cout << endl; } } bool tateti_struct::not_a_valid_move(int x,int y); { return this.table[x][y]!=NULL; } <|endoftext|>
<commit_before>/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. You may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright (C) 2014 Cloudius Systems, Ltd. */ #pragma once #include <fmt/ostream.h> #include <fmt/printf.h> #include <iostream> #include <iomanip> #include <chrono> #include <sstream> #include "core/sstring.hh" #if 0 inline std::ostream& operator<<(std::ostream& os, const void* ptr) { auto flags = os.flags(); os << "0x" << std::hex << reinterpret_cast<uintptr_t>(ptr); os.flags(flags); return os; } #endif inline std::ostream& operator<<(std::ostream&& os, const void* ptr) { return os << ptr; // selects non-rvalue version } namespace seastar { template <typename... A> std::ostream& fprint(std::ostream& os, const char* fmt, A&&... a) { ::fmt::fprintf(os, fmt, std::forward<A>(a)...); return os; } template <typename... A> void print(const char* fmt, A&&... a) { ::fmt::printf(fmt, std::forward<A>(a)...); } template <typename... A> std::string sprint(const char* fmt, A&&... a) { std::ostringstream os; ::fmt::fprintf(os, fmt, std::forward<A>(a)...); return os.str(); } template <typename... A> std::string sprint(const sstring& fmt, A&&... a) { std::ostringstream os; ::fmt::fprintf(os, fmt.c_str(), std::forward<A>(a)...); return os.str(); } template <typename Iterator> std::string format_separated(Iterator b, Iterator e, const char* sep = ", ") { std::string ret; if (b == e) { return ret; } ret += *b++; while (b != e) { ret += sep; ret += *b++; } return ret; } template <typename TimePoint> struct usecfmt_wrapper { TimePoint val; }; template <typename TimePoint> inline usecfmt_wrapper<TimePoint> usecfmt(TimePoint tp) { return { tp }; }; template <typename Clock, typename Rep, typename Period> std::ostream& operator<<(std::ostream& os, usecfmt_wrapper<std::chrono::time_point<Clock, std::chrono::duration<Rep, Period>>> tp) { auto usec = std::chrono::duration_cast<std::chrono::microseconds>(tp.val.time_since_epoch()).count(); std::ostream tmp(os.rdbuf()); tmp << std::setw(12) << (usec / 1000000) << "." << std::setw(6) << std::setfill('0') << (usec % 1000000); return os; } template <typename... A> void log(A&&... a) { std::cout << usecfmt(std::chrono::high_resolution_clock::now()) << " "; print(std::forward<A>(a)...); } /** * Evaluate the formatted string in a native fmt library format * * @param fmt format string with the native fmt library syntax * @param a positional parameters * * @return sstring object with the result of applying the given positional * parameters on a given format string. */ template <typename... A> sstring format(const char* fmt, A&&... a) { fmt::memory_buffer out; fmt::format_to(out, fmt, std::forward<A>(a)...); return sstring{out.data(), out.size()}; } } <commit_msg>print: add fmt_print()<commit_after>/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. You may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright (C) 2014 Cloudius Systems, Ltd. */ #pragma once #include <fmt/ostream.h> #include <fmt/printf.h> #include <iostream> #include <iomanip> #include <chrono> #include <sstream> #include "core/sstring.hh" #if 0 inline std::ostream& operator<<(std::ostream& os, const void* ptr) { auto flags = os.flags(); os << "0x" << std::hex << reinterpret_cast<uintptr_t>(ptr); os.flags(flags); return os; } #endif inline std::ostream& operator<<(std::ostream&& os, const void* ptr) { return os << ptr; // selects non-rvalue version } namespace seastar { template <typename... A> std::ostream& fprint(std::ostream& os, const char* fmt, A&&... a) { ::fmt::fprintf(os, fmt, std::forward<A>(a)...); return os; } template <typename... A> void print(const char* fmt, A&&... a) { ::fmt::printf(fmt, std::forward<A>(a)...); } template <typename... A> std::string sprint(const char* fmt, A&&... a) { std::ostringstream os; ::fmt::fprintf(os, fmt, std::forward<A>(a)...); return os.str(); } template <typename... A> std::string sprint(const sstring& fmt, A&&... a) { std::ostringstream os; ::fmt::fprintf(os, fmt.c_str(), std::forward<A>(a)...); return os.str(); } template <typename Iterator> std::string format_separated(Iterator b, Iterator e, const char* sep = ", ") { std::string ret; if (b == e) { return ret; } ret += *b++; while (b != e) { ret += sep; ret += *b++; } return ret; } template <typename TimePoint> struct usecfmt_wrapper { TimePoint val; }; template <typename TimePoint> inline usecfmt_wrapper<TimePoint> usecfmt(TimePoint tp) { return { tp }; }; template <typename Clock, typename Rep, typename Period> std::ostream& operator<<(std::ostream& os, usecfmt_wrapper<std::chrono::time_point<Clock, std::chrono::duration<Rep, Period>>> tp) { auto usec = std::chrono::duration_cast<std::chrono::microseconds>(tp.val.time_since_epoch()).count(); std::ostream tmp(os.rdbuf()); tmp << std::setw(12) << (usec / 1000000) << "." << std::setw(6) << std::setfill('0') << (usec % 1000000); return os; } template <typename... A> void log(A&&... a) { std::cout << usecfmt(std::chrono::high_resolution_clock::now()) << " "; print(std::forward<A>(a)...); } /** * Evaluate the formatted string in a native fmt library format * * @param fmt format string with the native fmt library syntax * @param a positional parameters * * @return sstring object with the result of applying the given positional * parameters on a given format string. */ template <typename... A> sstring format(const char* fmt, A&&... a) { fmt::memory_buffer out; fmt::format_to(out, fmt, std::forward<A>(a)...); return sstring{out.data(), out.size()}; } // temporary, use fmt::print() instead template <typename... A> std::ostream& fmt_print(std::ostream& os, const char* format, A&&... a) { fmt::print(os, format, std::forward<A>(a)...); return os; } } <|endoftext|>
<commit_before>// Copyright *********************************************************** // // File ecmdCommandUtils.C // // IBM Confidential // OCO Source Materials // 9400 Licensed Internal Code // (C) COPYRIGHT IBM CORP. 1996 // // The source code for this program is not published or otherwise // divested of its trade secrets, irrespective of what has been // deposited with the U.S. Copyright Office. // // End Copyright ******************************************************* /* $Header$ */ // Module Description ************************************************** // // Description: // // End Module Description ********************************************** //---------------------------------------------------------------------- // Includes //---------------------------------------------------------------------- #define ecmdCommandUtils_C #include <list> #include <fstream> #include <inttypes.h> #include <string.h> #include <string> #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <ecmdCommandUtils.H> #include <ecmdReturnCodes.H> #include <ecmdClientCapi.H> #undef ecmdCommandUtils_C //---------------------------------------------------------------------- // User Types //---------------------------------------------------------------------- //---------------------------------------------------------------------- // Constants //---------------------------------------------------------------------- //---------------------------------------------------------------------- // Macros //---------------------------------------------------------------------- //---------------------------------------------------------------------- // Internal Function Prototypes //---------------------------------------------------------------------- //---------------------------------------------------------------------- // Global Variables //---------------------------------------------------------------------- //--------------------------------------------------------------------- // Member Function Specifications //--------------------------------------------------------------------- uint32_t ecmdCheckExpected (ecmdDataBuffer & i_data, ecmdDataBuffer & i_expected) { int wordCounter = 0; uint32_t maxBits = 32; uint32_t numBits = i_data.getBitLength(); uint32_t numToFetch = numBits < maxBits ? numBits : maxBits; uint32_t curData, curExpected; /* We are going to make sure they didn't expect more data then we had */ /* We are going to allow for odd bits in a nibble if the user provided data in hex */ /* We will just check below that all the extra data was zero's */ if ((i_data.getBitLength()-1)/4 > (i_expected.getBitLength()-1)/4) { ecmdOutputError("ecmdCheckExpected - Not enough expect data provided\n"); return 0; } else if ((i_data.getBitLength()-1)/4 < (i_expected.getBitLength()-1)/4) { ecmdOutputError("ecmdCheckExpected - More expect data provided than data that was retrieved\n"); return 0; /* Now we are going to check to see if expect bits we specified in any odd nibble bits */ } else if ((i_data.getBitLength() < i_expected.getBitLength()) && (!i_expected.isBitClear(i_data.getBitLength(), i_expected.getBitLength() - i_data.getBitLength()))) { ecmdOutputError("ecmdCheckExpected - More non-zero expect data provided in odd bits of a nibble then data retrieved\n"); return 0; } while (numToFetch > 0) { curData = i_data.getWord(wordCounter); curExpected = i_expected.getWord(wordCounter); if (numToFetch == maxBits) { if (curData != curExpected) return 0; } else { uint32_t mask = 0x80000000; for (int i = 0; i < numToFetch; i++, mask >>= 1) { if ( (curData & mask) != (curExpected & mask) ) { return 0; } } } numBits -= numToFetch; numToFetch = (numBits < maxBits) ? numBits : maxBits; wordCounter++; } return 1; } uint32_t ecmdApplyDataModifier (ecmdDataBuffer & io_data, ecmdDataBuffer & i_newData, int i_startbit, std::string i_modifier) { uint32_t rc = ECMD_SUCCESS; if ((i_startbit + i_newData.getBitLength()) > io_data.getBitLength()) { char buf[200]; sprintf(buf,"ecmdApplyDataModifier - startbit + numbits (%d) > data length (%d), buffer overflow!\n",i_startbit + i_newData.getBitLength(), io_data.getBitLength()); ecmdOutputError(buf); return ECMD_INVALID_ARGS; } if (i_modifier == "insert") { io_data.insert(i_newData, i_startbit, i_newData.getBitLength()); } else if (i_modifier == "and") { io_data.setAnd(i_newData, i_startbit, i_newData.getBitLength()); } else if (i_modifier == "or") { io_data.setOr(i_newData, i_startbit, i_newData.getBitLength()); } else { ecmdOutputError(("ecmdApplyDataModifier - Invalid Data Modifier specified with -b arg : "+i_modifier + "\n").c_str()); return ECMD_INVALID_ARGS; } return rc; } uint32_t ecmdPrintHelp(const char* i_command) { uint32_t rc = ECMD_SUCCESS; std::string file; ecmdChipTarget target; std::ifstream ins; std::string curLine; /* Get the path to the help text files */ rc = ecmdQueryFileLocation(target, ECMD_FILE_HELPTEXT, file); if (rc) return rc; file += i_command; file += ".htxt"; /* Let's go open this guy */ ins.open(file.c_str()); if (ins.fail()) { ecmdOutputError(("Error occured opening help text file: " + file + "\n").c_str()); return ECMD_INVALID_ARGS; //change this } while (getline(ins, curLine)) { curLine += '\n'; ecmdOutput(curLine.c_str()); } ins.close(); return rc; } uint32_t ecmdGenB32FromHex (uint32_t * o_numPtr, const char * i_hexChars, int startPos) { uint32_t tempB32 = 0; int counter = 0; char twoChars[2] = "0"; if ((o_numPtr == NULL) || (i_hexChars == NULL) || (strlen(i_hexChars) == 0)) return 0xFFFFFFFF; o_numPtr[0] = 0x0; o_numPtr[startPos>>3]= 0x0; for (counter = 0; counter < strlen(i_hexChars); counter++) { if (((counter + startPos) & 0xFFF8) == (counter + startPos)) o_numPtr[(counter+startPos)>>3] = 0x0; twoChars[0] = i_hexChars[counter]; tempB32 = strtoul((char *) & twoChars[0], NULL, 16); o_numPtr[(counter+startPos)>>3] |= (tempB32 << (28 - (4 * ((counter + startPos) & 0x07)))); } return o_numPtr[0]; } uint32_t ecmdGenB32FromHexLeft (uint32_t * o_numPtr, const char * i_hexChars) { if ((i_hexChars == NULL) || (o_numPtr == NULL)) return 0xFFFFFFFF; return ecmdGenB32FromHex(o_numPtr, i_hexChars, 0); } uint32_t ecmdGenB32FromHexRight (uint32_t * o_numPtr, const char * i_hexChars, int expectBits) { int stringSize; if ((i_hexChars == NULL) || (o_numPtr == NULL)) return 0xFFFFFFFF; /* ----------------------------------------------------------------- */ /* Telling us we are expecting few bits than the user input */ /* ----------------------------------------------------------------- */ stringSize = strlen(i_hexChars); if (expectBits==0) expectBits = ((stringSize << 2) + 31) & 0xFFFE0; /* ----------------------------------------------------------------- */ /* Can't figure out if this case is bad... */ /* ----------------------------------------------------------------- */ if (expectBits<(stringSize*4)) expectBits = (4-(expectBits & 0x3))+expectBits+(stringSize*4-expectBits&0xFFFC); expectBits = (expectBits - stringSize*4)>>2; return ecmdGenB32FromHex(o_numPtr, i_hexChars, expectBits ); } /* Returns true if all chars of str are decimal numbers */ bool ecmdIsAllDecimal(const char* str) { bool ret = true; int len = strlen(str); for (int x = 0; x < len; x ++) { if (!isdigit(str[x])) { ret = false; break; } } return ret; } /* Returns true if all chars of str are hex numbers */ bool ecmdIsAllHex(const char* str) { bool ret = true; int len = strlen(str); for (int x = 0; x < len; x ++) { if (!isxdigit(str[x])) { ret = false; break; } } return ret; } std::string ecmdParseReturnCode(uint32_t i_returnCode) { std::string ret; ecmdChipTarget dummy; std::string filePath; uint32_t rc = ecmdQueryFileLocation(dummy, ECMD_FILE_HELPTEXT, filePath); if (rc || (filePath.length()==0)) { ret = "ERROR FINDING DECODE FILE"; return ret; } filePath += "ecmdReturnCodes.H"; /* jtw 10/6/03 - code below largely copied from cronusrc.c */ char str[800]; char num[30]; char name[200]; int found = 0; char* tempstr = NULL; unsigned int comprc; std::ifstream ins(filePath.c_str()); if (ins.fail()) { ret = "ERROR OPENING DECODE FILE"; return ret; } while (!ins.eof()) { /* && (strlen(str) != 0) */ ins.getline(str,799,'\n'); if (!strncmp(str,"#define",7)) { strtok(str," \t"); /* get rid of the #define */ tempstr = strtok(NULL," \t"); if (tempstr == NULL) continue; strcpy(name,tempstr); tempstr = strtok(NULL," \t"); if (tempstr == NULL) continue; strcpy(num,tempstr); sscanf(num,"%x",&comprc); if (comprc == i_returnCode) { ret = name; found = 1; break; } } } ins.close(); if (!found) { ret = "UNDEFINED"; } return ret; } // Change Log ********************************************************* // // Flag Reason Vers Date Coder Description // ---- -------- ---- -------- -------- ------------------------------ // CENGEL Initial Creation // // End Change Log ***************************************************** <commit_msg>Updates to return code parsing for BZ#219<commit_after>// Copyright *********************************************************** // // File ecmdCommandUtils.C // // IBM Confidential // OCO Source Materials // 9400 Licensed Internal Code // (C) COPYRIGHT IBM CORP. 1996 // // The source code for this program is not published or otherwise // divested of its trade secrets, irrespective of what has been // deposited with the U.S. Copyright Office. // // End Copyright ******************************************************* /* $Header$ */ // Module Description ************************************************** // // Description: // // End Module Description ********************************************** //---------------------------------------------------------------------- // Includes //---------------------------------------------------------------------- #define ecmdCommandUtils_C #include <list> #include <fstream> #include <inttypes.h> #include <string.h> #include <string> #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <ecmdCommandUtils.H> #include <ecmdReturnCodes.H> #include <ecmdClientCapi.H> #include <ecmdSharedUtils.H> #undef ecmdCommandUtils_C //---------------------------------------------------------------------- // User Types //---------------------------------------------------------------------- //---------------------------------------------------------------------- // Constants //---------------------------------------------------------------------- //---------------------------------------------------------------------- // Macros //---------------------------------------------------------------------- //---------------------------------------------------------------------- // Internal Function Prototypes //---------------------------------------------------------------------- //---------------------------------------------------------------------- // Global Variables //---------------------------------------------------------------------- //--------------------------------------------------------------------- // Member Function Specifications //--------------------------------------------------------------------- uint32_t ecmdCheckExpected (ecmdDataBuffer & i_data, ecmdDataBuffer & i_expected) { int wordCounter = 0; uint32_t maxBits = 32; uint32_t numBits = i_data.getBitLength(); uint32_t numToFetch = numBits < maxBits ? numBits : maxBits; uint32_t curData, curExpected; /* We are going to make sure they didn't expect more data then we had */ /* We are going to allow for odd bits in a nibble if the user provided data in hex */ /* We will just check below that all the extra data was zero's */ if ((i_data.getBitLength()-1)/4 > (i_expected.getBitLength()-1)/4) { ecmdOutputError("ecmdCheckExpected - Not enough expect data provided\n"); return 0; } else if ((i_data.getBitLength()-1)/4 < (i_expected.getBitLength()-1)/4) { ecmdOutputError("ecmdCheckExpected - More expect data provided than data that was retrieved\n"); return 0; /* Now we are going to check to see if expect bits we specified in any odd nibble bits */ } else if ((i_data.getBitLength() < i_expected.getBitLength()) && (!i_expected.isBitClear(i_data.getBitLength(), i_expected.getBitLength() - i_data.getBitLength()))) { ecmdOutputError("ecmdCheckExpected - More non-zero expect data provided in odd bits of a nibble then data retrieved\n"); return 0; } while (numToFetch > 0) { curData = i_data.getWord(wordCounter); curExpected = i_expected.getWord(wordCounter); if (numToFetch == maxBits) { if (curData != curExpected) return 0; } else { uint32_t mask = 0x80000000; for (int i = 0; i < numToFetch; i++, mask >>= 1) { if ( (curData & mask) != (curExpected & mask) ) { return 0; } } } numBits -= numToFetch; numToFetch = (numBits < maxBits) ? numBits : maxBits; wordCounter++; } return 1; } uint32_t ecmdApplyDataModifier (ecmdDataBuffer & io_data, ecmdDataBuffer & i_newData, int i_startbit, std::string i_modifier) { uint32_t rc = ECMD_SUCCESS; if ((i_startbit + i_newData.getBitLength()) > io_data.getBitLength()) { char buf[200]; sprintf(buf,"ecmdApplyDataModifier - startbit + numbits (%d) > data length (%d), buffer overflow!\n",i_startbit + i_newData.getBitLength(), io_data.getBitLength()); ecmdOutputError(buf); return ECMD_INVALID_ARGS; } if (i_modifier == "insert") { io_data.insert(i_newData, i_startbit, i_newData.getBitLength()); } else if (i_modifier == "and") { io_data.setAnd(i_newData, i_startbit, i_newData.getBitLength()); } else if (i_modifier == "or") { io_data.setOr(i_newData, i_startbit, i_newData.getBitLength()); } else { ecmdOutputError(("ecmdApplyDataModifier - Invalid Data Modifier specified with -b arg : "+i_modifier + "\n").c_str()); return ECMD_INVALID_ARGS; } return rc; } uint32_t ecmdPrintHelp(const char* i_command) { uint32_t rc = ECMD_SUCCESS; std::string file; ecmdChipTarget target; std::ifstream ins; std::string curLine; /* Get the path to the help text files */ rc = ecmdQueryFileLocation(target, ECMD_FILE_HELPTEXT, file); if (rc) return rc; file += i_command; file += ".htxt"; /* Let's go open this guy */ ins.open(file.c_str()); if (ins.fail()) { ecmdOutputError(("Error occured opening help text file: " + file + "\n").c_str()); return ECMD_INVALID_ARGS; //change this } while (getline(ins, curLine)) { curLine += '\n'; ecmdOutput(curLine.c_str()); } ins.close(); return rc; } uint32_t ecmdGenB32FromHex (uint32_t * o_numPtr, const char * i_hexChars, int startPos) { uint32_t tempB32 = 0; int counter = 0; char twoChars[2] = "0"; if ((o_numPtr == NULL) || (i_hexChars == NULL) || (strlen(i_hexChars) == 0)) return 0xFFFFFFFF; o_numPtr[0] = 0x0; o_numPtr[startPos>>3]= 0x0; for (counter = 0; counter < strlen(i_hexChars); counter++) { if (((counter + startPos) & 0xFFF8) == (counter + startPos)) o_numPtr[(counter+startPos)>>3] = 0x0; twoChars[0] = i_hexChars[counter]; tempB32 = strtoul((char *) & twoChars[0], NULL, 16); o_numPtr[(counter+startPos)>>3] |= (tempB32 << (28 - (4 * ((counter + startPos) & 0x07)))); } return o_numPtr[0]; } uint32_t ecmdGenB32FromHexLeft (uint32_t * o_numPtr, const char * i_hexChars) { if ((i_hexChars == NULL) || (o_numPtr == NULL)) return 0xFFFFFFFF; return ecmdGenB32FromHex(o_numPtr, i_hexChars, 0); } uint32_t ecmdGenB32FromHexRight (uint32_t * o_numPtr, const char * i_hexChars, int expectBits) { int stringSize; if ((i_hexChars == NULL) || (o_numPtr == NULL)) return 0xFFFFFFFF; /* ----------------------------------------------------------------- */ /* Telling us we are expecting few bits than the user input */ /* ----------------------------------------------------------------- */ stringSize = strlen(i_hexChars); if (expectBits==0) expectBits = ((stringSize << 2) + 31) & 0xFFFE0; /* ----------------------------------------------------------------- */ /* Can't figure out if this case is bad... */ /* ----------------------------------------------------------------- */ if (expectBits<(stringSize*4)) expectBits = (4-(expectBits & 0x3))+expectBits+(stringSize*4-expectBits&0xFFFC); expectBits = (expectBits - stringSize*4)>>2; return ecmdGenB32FromHex(o_numPtr, i_hexChars, expectBits ); } /* Returns true if all chars of str are decimal numbers */ bool ecmdIsAllDecimal(const char* str) { bool ret = true; int len = strlen(str); for (int x = 0; x < len; x ++) { if (!isdigit(str[x])) { ret = false; break; } } return ret; } /* Returns true if all chars of str are hex numbers */ bool ecmdIsAllHex(const char* str) { bool ret = true; int len = strlen(str); for (int x = 0; x < len; x ++) { if (!isxdigit(str[x])) { ret = false; break; } } return ret; } std::string ecmdParseReturnCode(uint32_t i_returnCode) { std::string ret = ""; ecmdChipTarget dummy; std::string filePath; uint32_t rc = ecmdQueryFileLocation(dummy, ECMD_FILE_HELPTEXT, filePath); if (rc || (filePath.length()==0)) { ret = "ERROR FINDING DECODE FILE"; return ret; } filePath += "ecmdReturnCodes.H"; std::string line; std::vector< std::string > tokens; std::string source, retdefine; int found = 0; uint32_t comprc; std::ifstream ins(filePath.c_str()); if (ins.fail()) { ret = "ERROR OPENING DECODE FILE"; return ret; } /* This is what I am trying to parse from ecmdReturnCodes.H */ /* #define ECMD_ERR_UNKNOWN 0x00000000 ///< This error code wasn't flagged to which plugin it came from */ /* #define ECMD_ERR_ECMD 0x01000000 ///< Error came from eCMD */ /* #define ECMD_ERR_CRONUS 0x02000000 ///< Error came from Cronus */ /* #define ECMD_ERR_IP 0x04000000 ///< Error came from IP GFW */ /* #define ECMD_ERR_Z 0x08000000 ///< Error came from Z GFW */ /* #define ECMD_INVALID_DLL_VERSION (ECMD_ERR_ECMD | 0x1000) ///< Dll Version */ while (!ins.eof()) { /* && (strlen(str) != 0) */ getline(ins,line,'\n'); /* Let's strip off any comments */ line = line.substr(0, line.find_first_of("/")); ecmdParseTokens(line, " \n()|", tokens); /* Didn't find anything */ if (line.size() < 2) continue; if (tokens[0] == "#define") { /* Let's see if we have one of they return code source defines */ if ((tokens.size() == 3) && (tokens[1] != "ECMD_SUCCESS") && (tokens[1] != "ECMD_DBUF_SUCCESS")) { sscanf(tokens[2].c_str(),"0x%x",&comprc); if ((i_returnCode & 0xFF000000) == comprc) { /* This came from this source, we will save that as we may use it later */ source = tokens[1]; } } else if (i_returnCode & 0xFF000000 != ECMD_ERR_ECMD) { /* We aren't going to find this return code in here since it didn't come from us */ } else if (tokens.size() == 4) { /* This is a standard return code define */ sscanf(tokens[3].c_str(),"0x%x",&comprc); if ((i_returnCode & 0x00FFFFFF) == comprc) { /* This came from this source, we will save that as we may use it later */ retdefine = tokens[1]; found = 1; break; } } } } ins.close(); if (!found && source.length() == 0) { ret = "UNDEFINED"; } else if (!found) { ret = "UNDEFINED FROM " + source; } else { ret = retdefine; } return ret; } // Change Log ********************************************************* // // Flag Reason Vers Date Coder Description // ---- -------- ---- -------- -------- ------------------------------ // CENGEL Initial Creation // // End Change Log ***************************************************** <|endoftext|>
<commit_before>/// \file /// \ingroup tutorial_eve /// Demonstates usage of geometry aliases - merge ALICE ITS with ATLAS MUON. /// /// \image html eve_geom_alias.png /// \macro_code /// /// \author Matevz Tadel void geom_alias() { TEveManager::Create(); gEve->RegisterGeometryAlias("ALICE", "http://root.cern.ch/files/alice.root"); gEve->RegisterGeometryAlias("ATLAS", "http://root.cern.ch/files/atlas.root"); gGeoManager = gEve->GetGeometryByAlias("ALICE"); TGeoNode* node1 = gGeoManager->GetTopVolume()->FindNode("ITSV_1"); TEveGeoTopNode* its = new TEveGeoTopNode(gGeoManager, node1); gEve->AddGlobalElement(its); gGeoManager = gEve->GetGeometryByAlias("ATLAS"); TGeoNode* node2 = gGeoManager->GetTopVolume()->FindNode("OUTE_1"); TEveGeoTopNode* atlas = new TEveGeoTopNode(gGeoManager, node2); gEve->AddGlobalElement(atlas); gEve->FullRedraw3D(kTRUE); // EClipType not exported to CINT (see TGLUtil.h): // 0 - no clip, 1 - clip plane, 2 - clip box TGLViewer *v = gEve->GetDefaultGLViewer(); v->GetClipSet()->SetClipType(TGLClip::EType(2)); v->RefreshPadEditor(v); v->CurrentCamera().RotateRad(-0.5, -2.4); v->DoDraw(); } <commit_msg>- spell check - use auto<commit_after>/// \file /// \ingroup tutorial_eve /// Demonstrates usage of geometry aliases - merge ALICE ITS with ATLAS MUON. /// /// \image html eve_geom_alias.png /// \macro_code /// /// \author Matevz Tadel void geom_alias() { TEveManager::Create(); gEve->RegisterGeometryAlias("ALICE", "http://root.cern.ch/files/alice.root"); gEve->RegisterGeometryAlias("ATLAS", "http://root.cern.ch/files/atlas.root"); gGeoManager = gEve->GetGeometryByAlias("ALICE"); auto node1 = gGeoManager->GetTopVolume()->FindNode("ITSV_1"); auto its = new TEveGeoTopNode(gGeoManager, node1); gEve->AddGlobalElement(its); gGeoManager = gEve->GetGeometryByAlias("ATLAS"); auto node2 = gGeoManager->GetTopVolume()->FindNode("OUTE_1"); auto atlas = new TEveGeoTopNode(gGeoManager, node2); gEve->AddGlobalElement(atlas); gEve->FullRedraw3D(kTRUE); // EClipType not exported to CINT (see TGLUtil.h): // 0 - no clip, 1 - clip plane, 2 - clip box auto v = gEve->GetDefaultGLViewer(); v->GetClipSet()->SetClipType(TGLClip::EType(2)); v->RefreshPadEditor(v); v->CurrentCamera().RotateRad(-0.5, -2.4); v->DoDraw(); } <|endoftext|>
<commit_before>/// \file /// \ingroup tutorial_graphics /// \notebook /// This tutorial illustrates the special contour options. /// /// - "AITOFF" : Draw a contour via an AITOFF projection /// - "MERCATOR" : Draw a contour via an Mercator projection /// - "SINUSOIDAL" : Draw a contour via an Sinusoidal projection /// - "PARABOLIC" : Draw a contour via an Parabolic projection /// /// \macro_image /// \macro_code /// /// \author Olivier Couet (from an original macro sent by Ernst-Jan Buis) void earth(){ gStyle->SetOptTitle(1); gStyle->SetOptStat(0); auto c1 = new TCanvas("c1","earth_projections",700,700); c1->Divide(2,2); auto ha = new TH2F("ha","Aitoff", 180, -180, 180, 179, -89.5, 89.5); auto hm = new TH2F("hm","Mercator", 180, -180, 180, 161, -80.5, 80.5); auto hs = new TH2F("hs","Sinusoidal",180, -180, 180, 181, -90.5, 90.5); auto hp = new TH2F("hp","Parabolic", 180, -180, 180, 181, -90.5, 90.5); TString dat = gROOT->GetTutorialDir(); dat.Append("/graphics/earth.dat"); dat.ReplaceAll("/./","/"); ifstream in; in.open(dat.Data()); Float_t x,y; while (1) { in >> x >> y; if (!in.good()) break; ha->Fill(x,y, 1); hm->Fill(x,y, 1); hs->Fill(x,y, 1); hp->Fill(x,y, 1); } in.close(); c1->cd(1); ha->Draw("aitoff"); c1->cd(2); hm->Draw("mercator"); c1->cd(3); hs->Draw("sinusoidal"); c1->cd(4); hp->Draw("parabolic"); } <commit_msg>Revert "Modernise and simplify example"<commit_after>/// \file /// \ingroup tutorial_graphics /// \notebook /// This tutorial illustrates the special contour options. /// /// - "AITOFF" : Draw a contour via an AITOFF projection /// - "MERCATOR" : Draw a contour via an Mercator projection /// - "SINUSOIDAL" : Draw a contour via an Sinusoidal projection /// - "PARABOLIC" : Draw a contour via an Parabolic projection /// /// \macro_image /// \macro_code /// /// \author Olivier Couet (from an original macro sent by Ernst-Jan Buis) TCanvas *earth(){ gStyle->SetOptTitle(1); gStyle->SetOptStat(0); TCanvas *c1 = new TCanvas("c1","earth_projections",700,700); c1->Divide(2,2); TH2F *ha = new TH2F("ha","Aitoff", 180, -180, 180, 179, -89.5, 89.5); TH2F *hm = new TH2F("hm","Mercator", 180, -180, 180, 161, -80.5, 80.5); TH2F *hs = new TH2F("hs","Sinusoidal",180, -180, 180, 181, -90.5, 90.5); TH2F *hp = new TH2F("hp","Parabolic", 180, -180, 180, 181, -90.5, 90.5); TString dat = gROOT->GetTutorialDir(); dat.Append("/graphics/earth.dat"); dat.ReplaceAll("/./","/"); ifstream in; in.open(dat.Data()); Float_t x,y; while (1) { in >> x >> y; if (!in.good()) break; ha->Fill(x,y, 1); hm->Fill(x,y, 1); hs->Fill(x,y, 1); hp->Fill(x,y, 1); } in.close(); c1->cd(1); ha->Draw("aitoff"); c1->cd(2); hm->Draw("mercator"); c1->cd(3); hs->Draw("sinusoidal"); c1->cd(4); hp->Draw("parabolic"); return c1; } <|endoftext|>
<commit_before>// pythia8 basic example //Author: Andreas Morsch // // to run, do // root > .x pythia8.C // // Note that before executing this script, // -the env variable PYTHIA8 must point to the pythia8100 (or newer) directory // -the env variable PYTHIA8DATA must be defined and it must point to $PYTHIA8/xmldoc // void pythia8(Int_t nev = 100, Int_t ndeb = 1) { char *p8dataenv = gSystem->Getenv("PYTHIA8DATA"); if (!p8dataenv) { char *p8env = gSystem->Getenv("PYTHIA8"); if (!p8env) { Error("pythia8.C", "Environment variable PYTHIA8 must contain path to pythia directory!"); return; } TString p8d = p8env; p8d += "/xmldoc"; gSystem->Setenv("PYTHIA8DATA", p8d); } char* path = gSystem->ExpandPathName("$PYTHIA8DATA"); if (gSystem->AccessPathName(path)) { Error("pythia8.C", "Environment variable PYTHIA8DATA must contain path to $PYTHIA8/xmldoc directory !"); return; } // Load libraries gSystem->Load("$PYTHIA8/lib/libpythia8"); gSystem->Load("libEG"); gSystem->Load("libEGPythia8"); // Histograms TH1F* etaH = new TH1F("etaH", "Pseudorapidity", 120, -12., 12.); TH1F* ptH = new TH1F("ptH", "pt", 50, 0., 10.); // Array of particles TClonesArray* particles = new TClonesArray("TParticle", 1000); // Create pythia8 object TPythia8* pythia8 = new TPythia8(); // Configure pythia8->ReadString("SoftQCD:minBias = on"); pythia8->ReadString("SoftQCD:singleDiffractive = on"); pythia8->ReadString("SoftQCD:doubleDiffractive = on"); // Initialize pythia8->Initialize(2212 /* p */, 2212 /* p */, 14000. /* TeV */); // Event loop for (Int_t iev = 0; iev < nev; iev++) { pythia8->GenerateEvent(); if (iev < ndeb) pythia8->EventListing(); pythia8->ImportParticles(particles,"All"); Int_t np = particles->GetEntriesFast(); // Particle loop for (Int_t ip = 0; ip < np; ip++) { TParticle* part = (TParticle*) particles->At(ip); Int_t ist = part->GetStatusCode(); // Positive codes are final particles. if (ist <= 0) continue; Int_t pdg = part->GetPdgCode(); Float_t charge = TDatabasePDG::Instance()->GetParticle(pdg)->Charge(); if (charge == 0.) continue; Float_t eta = part->Eta(); Float_t pt = part->Pt(); etaH->Fill(eta); if (pt > 0.) ptH->Fill(pt, 1./(2. * pt)); } } pythia8->PrintStatistics(); TCanvas* c1 = new TCanvas("c1","Pythia8 test example",800,800); c1->Divide(1, 2); c1->cd(1); etaH->Scale(5./Float_t(nev)); etaH->Draw(); etaH->SetXTitle("#eta"); etaH->SetYTitle("dN/d#eta"); c1->cd(2); gPad->SetLogy(); ptH->Scale(5./Float_t(nev)); ptH->Draw(); ptH->SetXTitle("p_{t} [GeV/c]"); ptH->SetYTitle("dN/dp_{t}^{2} [GeV/c]^{-2}"); } <commit_msg>Since Pythia8 is a static library on Windows, don't call gSystem->Load("$PYTHIA8/lib/libpythia8")<commit_after>// pythia8 basic example //Author: Andreas Morsch // // to run, do // root > .x pythia8.C // // Note that before executing this script, // -the env variable PYTHIA8 must point to the pythia8100 (or newer) directory // -the env variable PYTHIA8DATA must be defined and it must point to $PYTHIA8/xmldoc // void pythia8(Int_t nev = 100, Int_t ndeb = 1) { char *p8dataenv = gSystem->Getenv("PYTHIA8DATA"); if (!p8dataenv) { char *p8env = gSystem->Getenv("PYTHIA8"); if (!p8env) { Error("pythia8.C", "Environment variable PYTHIA8 must contain path to pythia directory!"); return; } TString p8d = p8env; p8d += "/xmldoc"; gSystem->Setenv("PYTHIA8DATA", p8d); } char* path = gSystem->ExpandPathName("$PYTHIA8DATA"); if (gSystem->AccessPathName(path)) { Error("pythia8.C", "Environment variable PYTHIA8DATA must contain path to $PYTHIA8/xmldoc directory !"); return; } // Load libraries #ifndef G__WIN32 // Pythia8 is a static library on Windows gSystem->Load("$PYTHIA8/lib/libpythia8"); #endif gSystem->Load("libEG"); gSystem->Load("libEGPythia8"); // Histograms TH1F* etaH = new TH1F("etaH", "Pseudorapidity", 120, -12., 12.); TH1F* ptH = new TH1F("ptH", "pt", 50, 0., 10.); // Array of particles TClonesArray* particles = new TClonesArray("TParticle", 1000); // Create pythia8 object TPythia8* pythia8 = new TPythia8(); // Configure pythia8->ReadString("SoftQCD:minBias = on"); pythia8->ReadString("SoftQCD:singleDiffractive = on"); pythia8->ReadString("SoftQCD:doubleDiffractive = on"); // Initialize pythia8->Initialize(2212 /* p */, 2212 /* p */, 14000. /* TeV */); // Event loop for (Int_t iev = 0; iev < nev; iev++) { pythia8->GenerateEvent(); if (iev < ndeb) pythia8->EventListing(); pythia8->ImportParticles(particles,"All"); Int_t np = particles->GetEntriesFast(); // Particle loop for (Int_t ip = 0; ip < np; ip++) { TParticle* part = (TParticle*) particles->At(ip); Int_t ist = part->GetStatusCode(); // Positive codes are final particles. if (ist <= 0) continue; Int_t pdg = part->GetPdgCode(); Float_t charge = TDatabasePDG::Instance()->GetParticle(pdg)->Charge(); if (charge == 0.) continue; Float_t eta = part->Eta(); Float_t pt = part->Pt(); etaH->Fill(eta); if (pt > 0.) ptH->Fill(pt, 1./(2. * pt)); } } pythia8->PrintStatistics(); TCanvas* c1 = new TCanvas("c1","Pythia8 test example",800,800); c1->Divide(1, 2); c1->cd(1); etaH->Scale(5./Float_t(nev)); etaH->Draw(); etaH->SetXTitle("#eta"); etaH->SetYTitle("dN/d#eta"); c1->cd(2); gPad->SetLogy(); ptH->Scale(5./Float_t(nev)); ptH->Draw(); ptH->SetXTitle("p_{t} [GeV/c]"); ptH->SetYTitle("dN/dp_{t}^{2} [GeV/c]^{-2}"); } <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2000 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * $Log$ * Revision 1.7 2000/04/06 19:09:51 roddey * Some more improvements to output formatting. Now it will correctly * handle doing the 'replacement char' style of dealing with chars * that are unrepresentable. * * Revision 1.6 2000/04/05 00:20:32 roddey * More updates for the low level formatted output support * * Revision 1.5 2000/03/28 19:43:11 roddey * Fixes for signed/unsigned warnings. New work for two way transcoding * stuff. * * Revision 1.4 2000/03/02 19:53:49 roddey * This checkin includes many changes done while waiting for the * 1.1.0 code to be finished. I can't list them all here, but a list is * available elsewhere. * * Revision 1.3 2000/02/11 03:05:35 abagchi * Removed second parameter from call to StrX constructor * * Revision 1.2 2000/02/06 07:47:24 rahulj * Year 2K copyright swat. * * Revision 1.1.1.1 1999/11/09 01:09:29 twl * Initial checkin * * Revision 1.11 1999/11/08 20:43:42 rahul * Swat for adding in Product name and CVS comment log variable. * */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <util/XMLUni.hpp> #include <sax/AttributeList.hpp> #include "SAXPrint.hpp" // --------------------------------------------------------------------------- // Local const data // // Note: This is the 'safe' way to do these strings. If you compiler supports // L"" style strings, and portability is not a concern, you can use // those types constants directly. // --------------------------------------------------------------------------- static const XMLCh gEndElement[] = { chOpenAngle, chForwardSlash, chNull }; static const XMLCh gEndPI[] = { chQuestion, chCloseAngle, chSpace }; static const XMLCh gStartPI[] = { chOpenAngle, chQuestion, chSpace }; static const XMLCh gXMLDecl1[] = { chOpenAngle, chQuestion, chLatin_x, chLatin_m, chLatin_l , chSpace, chLatin_v, chLatin_e, chLatin_r, chLatin_s, chLatin_i , chLatin_o, chLatin_n, chEqual, chDoubleQuote, chDigit_1, chPeriod , chDigit_0, chDoubleQuote, chSpace, chLatin_e, chLatin_n, chLatin_c , chLatin_o, chLatin_d, chLatin_i, chLatin_n, chLatin_g, chEqual , chDoubleQuote, chNull }; static const XMLCh gXMLDecl2[] = { chDoubleQuote, chSpace, chQuestion, chCloseAngle , chCR, chLF, chNull }; // --------------------------------------------------------------------------- // SAXPrintHandlers: Constructors and Destructor // --------------------------------------------------------------------------- SAXPrintHandlers::SAXPrintHandlers( const char* const encodingName , const XMLFormatter::UnRepFlags unRepFlags) : fFormatter ( encodingName , this , XMLFormatter::NoEscapes , unRepFlags ) { // // Go ahead and output an XML Decl with our known encoding. This // is not the best answer, but its the best we can do until we // have SAX2 support. // fFormatter << gXMLDecl1 << fFormatter.getEncodingName() << gXMLDecl2; } SAXPrintHandlers::~SAXPrintHandlers() { } // --------------------------------------------------------------------------- // SAXPrintHandlers: Overrides of the output formatter target interface // --------------------------------------------------------------------------- void SAXPrintHandlers::writeChars(const XMLByte* const toWrite) { // For this one, just dump them to the standard output cout << toWrite; } // --------------------------------------------------------------------------- // SAXPrintHandlers: Overrides of the SAX ErrorHandler interface // --------------------------------------------------------------------------- void SAXPrintHandlers::error(const SAXParseException& e) { cerr << "\nError at file " << StrX(e.getSystemId()) << ", line " << e.getLineNumber() << ", char " << e.getColumnNumber() << "\n Message: " << StrX(e.getMessage()) << endl; } void SAXPrintHandlers::fatalError(const SAXParseException& e) { cerr << "\nFatal Error at file " << StrX(e.getSystemId()) << ", line " << e.getLineNumber() << ", char " << e.getColumnNumber() << "\n Message: " << StrX(e.getMessage()) << endl; } void SAXPrintHandlers::warning(const SAXParseException& e) { cerr << "\nWarning at file " << StrX(e.getSystemId()) << ", line " << e.getLineNumber() << ", char " << e.getColumnNumber() << "\n Message: " << StrX(e.getMessage()) << endl; } // --------------------------------------------------------------------------- // SAXPrintHandlers: Overrides of the SAX DTDHandler interface // --------------------------------------------------------------------------- void SAXPrintHandlers::unparsedEntityDecl(const XMLCh* const name , const XMLCh* const publicId , const XMLCh* const systemId , const XMLCh* const notationName) { // Not used at this time } void SAXPrintHandlers::notationDecl(const XMLCh* const name , const XMLCh* const publicId , const XMLCh* const systemId) { // Not used at this time } // --------------------------------------------------------------------------- // SAXPrintHandlers: Overrides of the SAX DocumentHandler interface // --------------------------------------------------------------------------- void SAXPrintHandlers::characters(const XMLCh* const chars , const unsigned int length) { fFormatter.formatBuf(chars, length, XMLFormatter::CharEscapes); } void SAXPrintHandlers::endDocument() { } void SAXPrintHandlers::endElement(const XMLCh* const name) { fFormatter << gEndElement << name << chCloseAngle; } void SAXPrintHandlers::ignorableWhitespace( const XMLCh* const chars ,const unsigned int length) { fFormatter.formatBuf(chars, length); } void SAXPrintHandlers::processingInstruction(const XMLCh* const target , const XMLCh* const data) { fFormatter << gStartPI << target; if (data) fFormatter << chSpace << data; fFormatter << gEndPI; } void SAXPrintHandlers::startDocument() { } void SAXPrintHandlers::startElement(const XMLCh* const name , AttributeList& attributes) { // The name has to be representable without any escapes fFormatter << XMLFormatter::NoEscapes << chOpenAngle << name; unsigned int len = attributes.getLength(); for (unsigned int index = 0; index < len; index++) { // // Again the name has to be completely representable. But the // attribute can have refs and requires the attribute style // escaping. // fFormatter << XMLFormatter::NoEscapes << chSpace << attributes.getName(index) << chEqual << chDoubleQuote << XMLFormatter::AttrEscapes << attributes.getValue(index) << XMLFormatter::NoEscapes << chDoubleQuote; } fFormatter << chCloseAngle; } <commit_msg>A couple more tweaks of the event handler output.<commit_after>/* * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2000 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * $Log$ * Revision 1.8 2000/04/07 23:25:53 roddey * A couple more tweaks of the event handler output. * * Revision 1.7 2000/04/06 19:09:51 roddey * Some more improvements to output formatting. Now it will correctly * handle doing the 'replacement char' style of dealing with chars * that are unrepresentable. * * Revision 1.6 2000/04/05 00:20:32 roddey * More updates for the low level formatted output support * * Revision 1.5 2000/03/28 19:43:11 roddey * Fixes for signed/unsigned warnings. New work for two way transcoding * stuff. * * Revision 1.4 2000/03/02 19:53:49 roddey * This checkin includes many changes done while waiting for the * 1.1.0 code to be finished. I can't list them all here, but a list is * available elsewhere. * * Revision 1.3 2000/02/11 03:05:35 abagchi * Removed second parameter from call to StrX constructor * * Revision 1.2 2000/02/06 07:47:24 rahulj * Year 2K copyright swat. * * Revision 1.1.1.1 1999/11/09 01:09:29 twl * Initial checkin * * Revision 1.11 1999/11/08 20:43:42 rahul * Swat for adding in Product name and CVS comment log variable. * */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <util/XMLUni.hpp> #include <sax/AttributeList.hpp> #include "SAXPrint.hpp" // --------------------------------------------------------------------------- // Local const data // // Note: This is the 'safe' way to do these strings. If you compiler supports // L"" style strings, and portability is not a concern, you can use // those types constants directly. // --------------------------------------------------------------------------- static const XMLCh gEndElement[] = { chOpenAngle, chForwardSlash, chNull }; static const XMLCh gEndPI[] = { chQuestion, chCloseAngle, chSpace }; static const XMLCh gStartPI[] = { chOpenAngle, chQuestion, chSpace }; static const XMLCh gXMLDecl1[] = { chOpenAngle, chQuestion, chLatin_x, chLatin_m, chLatin_l , chSpace, chLatin_v, chLatin_e, chLatin_r, chLatin_s, chLatin_i , chLatin_o, chLatin_n, chEqual, chDoubleQuote, chDigit_1, chPeriod , chDigit_0, chDoubleQuote, chSpace, chLatin_e, chLatin_n, chLatin_c , chLatin_o, chLatin_d, chLatin_i, chLatin_n, chLatin_g, chEqual , chDoubleQuote, chNull }; static const XMLCh gXMLDecl2[] = { chDoubleQuote, chSpace, chQuestion, chCloseAngle , chCR, chLF, chNull }; // --------------------------------------------------------------------------- // SAXPrintHandlers: Constructors and Destructor // --------------------------------------------------------------------------- SAXPrintHandlers::SAXPrintHandlers( const char* const encodingName , const XMLFormatter::UnRepFlags unRepFlags) : fFormatter ( encodingName , this , XMLFormatter::NoEscapes , unRepFlags ) { // // Go ahead and output an XML Decl with our known encoding. This // is not the best answer, but its the best we can do until we // have SAX2 support. // fFormatter << gXMLDecl1 << fFormatter.getEncodingName() << gXMLDecl2; } SAXPrintHandlers::~SAXPrintHandlers() { } // --------------------------------------------------------------------------- // SAXPrintHandlers: Overrides of the output formatter target interface // --------------------------------------------------------------------------- void SAXPrintHandlers::writeChars(const XMLByte* const toWrite) { // For this one, just dump them to the standard output cout << toWrite; } // --------------------------------------------------------------------------- // SAXPrintHandlers: Overrides of the SAX ErrorHandler interface // --------------------------------------------------------------------------- void SAXPrintHandlers::error(const SAXParseException& e) { cerr << "\nError at file " << StrX(e.getSystemId()) << ", line " << e.getLineNumber() << ", char " << e.getColumnNumber() << "\n Message: " << StrX(e.getMessage()) << endl; } void SAXPrintHandlers::fatalError(const SAXParseException& e) { cerr << "\nFatal Error at file " << StrX(e.getSystemId()) << ", line " << e.getLineNumber() << ", char " << e.getColumnNumber() << "\n Message: " << StrX(e.getMessage()) << endl; } void SAXPrintHandlers::warning(const SAXParseException& e) { cerr << "\nWarning at file " << StrX(e.getSystemId()) << ", line " << e.getLineNumber() << ", char " << e.getColumnNumber() << "\n Message: " << StrX(e.getMessage()) << endl; } // --------------------------------------------------------------------------- // SAXPrintHandlers: Overrides of the SAX DTDHandler interface // --------------------------------------------------------------------------- void SAXPrintHandlers::unparsedEntityDecl(const XMLCh* const name , const XMLCh* const publicId , const XMLCh* const systemId , const XMLCh* const notationName) { // Not used at this time } void SAXPrintHandlers::notationDecl(const XMLCh* const name , const XMLCh* const publicId , const XMLCh* const systemId) { // Not used at this time } // --------------------------------------------------------------------------- // SAXPrintHandlers: Overrides of the SAX DocumentHandler interface // --------------------------------------------------------------------------- void SAXPrintHandlers::characters(const XMLCh* const chars , const unsigned int length) { fFormatter.formatBuf(chars, length, XMLFormatter::CharEscapes); } void SAXPrintHandlers::endDocument() { } void SAXPrintHandlers::endElement(const XMLCh* const name) { // No escapes are legal here fFormatter << XMLFormatter::NoEscapes << gEndElement << name << chCloseAngle; } void SAXPrintHandlers::ignorableWhitespace( const XMLCh* const chars ,const unsigned int length) { fFormatter.formatBuf(chars, length, XMLFormatter::NoEscapes); } void SAXPrintHandlers::processingInstruction(const XMLCh* const target , const XMLCh* const data) { fFormatter << XMLFormatter::NoEscapes << gStartPI << target; if (data) fFormatter << chSpace << data; fFormatter << XMLFormatter::NoEscapes << gEndPI; } void SAXPrintHandlers::startDocument() { } void SAXPrintHandlers::startElement(const XMLCh* const name , AttributeList& attributes) { // The name has to be representable without any escapes fFormatter << XMLFormatter::NoEscapes << chOpenAngle << name; unsigned int len = attributes.getLength(); for (unsigned int index = 0; index < len; index++) { // // Again the name has to be completely representable. But the // attribute can have refs and requires the attribute style // escaping. // fFormatter << XMLFormatter::NoEscapes << chSpace << attributes.getName(index) << chEqual << chDoubleQuote << XMLFormatter::AttrEscapes << attributes.getValue(index) << XMLFormatter::NoEscapes << chDoubleQuote; } fFormatter << chCloseAngle; } <|endoftext|>
<commit_before>#include "pqrs/file_path.hpp" #include "pqrs/vector.hpp" #include <iostream> namespace pqrs { namespace file_path { std::string combine(const std::string& path1, const std::string& path2) { return path1 + "/" + path2; } namespace { size_t get_dirname_position(const std::string& path, size_t pos = std::string::npos) { if (path.empty()) return 0; if (pos == std::string::npos) { pos = path.size() - 1; } if (path.size() <= pos) return 0; if (pos == 0) { // We retain the first slash for dirname("/") == "/". if (path[pos] == '/') { return 1; } else { return 0; } } if (path[pos] == '/') { --pos; } size_t i = path.rfind('/', pos); if (i == std::string::npos) { return 0; } if (i == 0) { // path starts with "/". return 1; } return i; } size_t process_dot(const std::string& path, size_t pos) { if (path.empty()) return pos; // foo/bar/./ // ^ // pos // if (pos > 2 && path[pos - 2] == '/' && path[pos - 1] == '.') { return pos - 2; } // ./foo/bar // ^ // pos // if (pos == 1 && path[0] == '.') { return 0; } return pos; } size_t process_dotdot(const std::string& path, size_t pos) { // foo/bar/../ // ^ // pos // if (pos > 2 && path[pos - 3] == '/' && path[pos - 2] == '.' && path[pos - 1] == '.') { pos = get_dirname_position(path, pos - 3); // foo/bar/../ // ^ // pos return pos; } // ../foo/bar // ^ // pos // if (pos == 2 && path[0] == '.' && path[1] == '.') { return 0; } return pos; } } std::string dirname(const std::string& path) { size_t pos = get_dirname_position(path); return path.substr(0, pos); } void normalize(std::string& path) { if (path.empty()) return; size_t end = path.size(); size_t dest = 1; for (size_t src = 1; src < end; ++src) { // skip // if (path[dest - 1] == '/' && path[src] == '/') { continue; } // handling . and .. if (path[src] == '/') { for (int i = 0; i < 2; ++i) { size_t d = dest; switch (i) { case 0: d = process_dot(path, d); break; case 1: d = process_dotdot(path, d); break; } if (dest != d) { dest = d; } } if (dest == 0) { if (path[dest] != '/') { continue; } } else { if (path[dest - 1] == '/') { continue; } } } if (dest != src) { path[dest] = path[src]; } ++dest; } dest = process_dot(path, dest); dest = process_dotdot(path, dest); path.resize(dest); } } } <commit_msg>cleanup<commit_after>#include "pqrs/file_path.hpp" #include "pqrs/vector.hpp" #include <iostream> namespace pqrs { namespace file_path { std::string combine(const std::string& path1, const std::string& path2) { return path1 + "/" + path2; } namespace { size_t get_dirname_position(const std::string& path, size_t pos = std::string::npos) { if (path.empty()) return 0; if (pos == std::string::npos) { pos = path.size() - 1; } if (path.size() <= pos) return 0; if (pos == 0) { // We retain the first slash for dirname("/") == "/". if (path[pos] == '/') { return 1; } else { return 0; } } if (path[pos] == '/') { --pos; } size_t i = path.rfind('/', pos); if (i == std::string::npos) { return 0; } if (i == 0) { // path starts with "/". return 1; } return i; } size_t process_dot(const std::string& path, size_t pos) { if (path.empty()) return pos; // foo/bar/./ // ^ // pos // if (pos > 2 && path[pos - 2] == '/' && path[pos - 1] == '.') { return pos - 2; } // ./foo/bar // ^ // pos // if (pos == 1 && path[0] == '.') { return 0; } return pos; } size_t process_dotdot(const std::string& path, size_t pos) { // foo/bar/../ // ^ // pos // if (pos > 2 && path[pos - 3] == '/' && path[pos - 2] == '.' && path[pos - 1] == '.') { pos = get_dirname_position(path, pos - 3); // foo/bar/../ // ^ // pos return pos; } // ../foo/bar // ^ // pos // if (pos == 2 && path[0] == '.' && path[1] == '.') { return 0; } return pos; } } std::string dirname(const std::string& path) { size_t pos = get_dirname_position(path); return path.substr(0, pos); } void normalize(std::string& path) { if (path.empty()) return; size_t end = path.size(); size_t dest = 1; for (size_t src = 1; src < end; ++src) { // Skip multiple slashes. if (path[dest - 1] == '/' && path[src] == '/') { continue; } // Handling . and .. if (path[src] == '/') { dest = process_dot(path, dest); dest = process_dotdot(path, dest); if (dest == 0) { if (path[0] != '/') { continue; } } else { if (path[dest - 1] == '/') { continue; } } } if (dest != src) { path[dest] = path[src]; } ++dest; } dest = process_dot(path, dest); dest = process_dotdot(path, dest); path.resize(dest); } } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: RenameElemTContext.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2004-07-13 08:58:31 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _XMLOFF_RENAMEELEMTCONTEXT_HXX #define _XMLOFF_RENAMEELEMTCONTEXT_HXX #ifndef _XMLOFF_XMLTOKEN_HXX #include "xmltoken.hxx" #endif #ifndef _XMLOFF_TRANSFORMERCONTEXT_HXX #include "TransformerContext.hxx" #endif class XMLRenameElemTransformerContext : public XMLTransformerContext { ::rtl::OUString m_aElemQName; ::rtl::OUString m_aAttrQName; ::rtl::OUString m_aAttrValue; public: TYPEINFO(); // The following consutructor renames the element names "rQName" // to bPrefix/eToken XMLRenameElemTransformerContext( XMLTransformerBase& rTransformer, const ::rtl::OUString& rQName, sal_uInt16 nPrefix, ::xmloff::token::XMLTokenEnum eToken ); // The following consutructor renames the element names "rQName" // to bPrefix/eToken and adds an attribute nAPrefix/eAToken that has // the value eVToken. XMLRenameElemTransformerContext( XMLTransformerBase& rTransformer, const ::rtl::OUString& rQName, sal_uInt16 nPrefix, ::xmloff::token::XMLTokenEnum eToken, sal_uInt16 nAPrefix, ::xmloff::token::XMLTokenEnum eAToken, ::xmloff::token::XMLTokenEnum eVToken ); // A contexts destructor does anything that is required if an element // ends. By default, nothing is done. // Note that virtual methods cannot be used inside destructors. Use // EndElement instead if this is required. virtual ~XMLRenameElemTransformerContext(); virtual void StartElement( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList ); virtual void EndElement(); }; #endif // _XMLOFF_RENAMEELEMCONTEXT_HXX <commit_msg>INTEGRATION: CWS ooo19126 (1.2.300); FILE MERGED 2005/09/05 14:40:29 rt 1.2.300.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: RenameElemTContext.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-09 15:55:03 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _XMLOFF_RENAMEELEMTCONTEXT_HXX #define _XMLOFF_RENAMEELEMTCONTEXT_HXX #ifndef _XMLOFF_XMLTOKEN_HXX #include "xmltoken.hxx" #endif #ifndef _XMLOFF_TRANSFORMERCONTEXT_HXX #include "TransformerContext.hxx" #endif class XMLRenameElemTransformerContext : public XMLTransformerContext { ::rtl::OUString m_aElemQName; ::rtl::OUString m_aAttrQName; ::rtl::OUString m_aAttrValue; public: TYPEINFO(); // The following consutructor renames the element names "rQName" // to bPrefix/eToken XMLRenameElemTransformerContext( XMLTransformerBase& rTransformer, const ::rtl::OUString& rQName, sal_uInt16 nPrefix, ::xmloff::token::XMLTokenEnum eToken ); // The following consutructor renames the element names "rQName" // to bPrefix/eToken and adds an attribute nAPrefix/eAToken that has // the value eVToken. XMLRenameElemTransformerContext( XMLTransformerBase& rTransformer, const ::rtl::OUString& rQName, sal_uInt16 nPrefix, ::xmloff::token::XMLTokenEnum eToken, sal_uInt16 nAPrefix, ::xmloff::token::XMLTokenEnum eAToken, ::xmloff::token::XMLTokenEnum eVToken ); // A contexts destructor does anything that is required if an element // ends. By default, nothing is done. // Note that virtual methods cannot be used inside destructors. Use // EndElement instead if this is required. virtual ~XMLRenameElemTransformerContext(); virtual void StartElement( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList ); virtual void EndElement(); }; #endif // _XMLOFF_RENAMEELEMCONTEXT_HXX <|endoftext|>
<commit_before> #include "math.h" #include <sstream> #include <limits> #include <stdexcept> #include "glps_parser.h" #include "scsi/config.h" namespace { // Numeric operations int unary_negate(parse_context* ctxt, expr_value_t *R, const expr_t * const *A) { *R = -boost::get<double>(A[0]->value); return 0; } int unary_sin(parse_context* ctxt, expr_value_t *R, const expr_t * const *A) { *R = sin(boost::get<double>(A[0]->value)); return 0; } int unary_cos(parse_context* ctxt, expr_value_t *R, const expr_t * const *A) { *R = cos(boost::get<double>(A[0]->value)); return 0; } int unary_tan(parse_context* ctxt, expr_value_t *R, const expr_t * const *A) { *R = tan(boost::get<double>(A[0]->value)); return 0; } int unary_asin(parse_context* ctxt, expr_value_t *R, const expr_t * const *A) { *R = asin(boost::get<double>(A[0]->value)); return 0; } int unary_acos(parse_context* ctxt, expr_value_t *R, const expr_t * const *A) { *R = acos(boost::get<double>(A[0]->value)); return 0; } int unary_atan(parse_context* ctxt, expr_value_t *R, const expr_t * const *A) { *R = atan(boost::get<double>(A[0]->value)); return 0; } int binary_add(parse_context* ctxt, expr_value_t *R, const expr_t * const *A) { *R = boost::get<double>(A[0]->value)+boost::get<double>(A[1]->value); return 0; } int binary_sub(parse_context* ctxt, expr_value_t *R, const expr_t * const *A) { *R = boost::get<double>(A[0]->value)-boost::get<double>(A[1]->value); return 0; } int binary_mult(parse_context* ctxt, expr_value_t *R, const expr_t * const *A) { *R = boost::get<double>(A[0]->value)*boost::get<double>(A[1]->value); return 0; } int binary_div(parse_context* ctxt, expr_value_t *R, const expr_t * const *A) { double result = boost::get<double>(A[0]->value)/boost::get<double>(A[1]->value); if(!isfinite(result)) { ctxt->last_error = "division results in non-finite value"; return 1; } *R = result; return 0; } // beamline operations int unary_bl_negate(parse_context* ctxt, expr_value_t *R, const expr_t * const *A) { // reverse the order of the beamline const std::vector<std::string>& line = boost::get<std::vector<std::string> >(A[0]->value); std::vector<std::string> ret(line.size()); std::copy(line.rbegin(), line.rend(), ret.begin()); *R = ret; return 0; } template<int MULT, int LINE> int binary_bl_mult(parse_context* ctxt, expr_value_t *R, const expr_t * const *A) { // multiple of scale * beamline repeats the beamline 'scale' times assert(A[MULT]->etype==glps_expr_number); assert(A[LINE]->etype==glps_expr_line); double factor = boost::get<double>(A[MULT]->value); if(factor<0.0 || factor>std::numeric_limits<unsigned>::max()) { ctxt->last_error = "beamline scale by negative value or out of range value"; return 1; } unsigned factori = (unsigned)factor; const std::vector<std::string>& line = boost::get<std::vector<std::string> >(A[LINE]->value); std::vector<std::string> ret(line.size()*factori); if(factori>0) { std::vector<std::string>::iterator outi = ret.begin(); while(factori--) outi = std::copy(line.begin(), line.end(), outi); } *R = ret; return 0; } int unary_parse(parse_context* ctxt, expr_value_t *R, const expr_t * const *A) { assert(A[0]->etype==glps_expr_string); const std::string& name = boost::get<std::string>(A[0]->value); GLPSParser P; P.setPrinter(ctxt->printer); boost::shared_ptr<Config> ret(P.parse_file(name.c_str())); *R = ret; return 0; } int unary_file(parse_context* ctxt, expr_value_t *R, const expr_t * const *A) { using namespace boost::filesystem; const std::string& inp = boost::get<std::string>(A[0]->value); path ret(canonical(inp, ctxt->cwd)); if(!exists(ret)) { std::ostringstream strm; strm<<"\""<<ret<<"\" does not exist"; ctxt->last_error = strm.str(); return 1; } *R = ret.native(); return 0; } int unary_h5file(parse_context* ctxt, expr_value_t *R, const expr_t * const *A) { using namespace boost::filesystem; const std::string& inp = boost::get<std::string>(A[0]->value); /* The provided spec may contain both file path and group(s) * seperated by '/' which is ambigious as the file path * may contain '/' as well... * so do as h5ls does and strip off from the right hand side until * and try to open while '/' remain. */ size_t sep = inp.npos; while(true) { sep = inp.find_last_of('/', sep-1); path fname(absolute(inp.substr(0, sep), ctxt->cwd)); if(exists(fname)) { *R = canonical(fname).native() + inp.substr(sep); return 0; } else if(sep==inp.npos) { break; } } std::ostringstream strm; strm<<"\""<<inp<<"\" does not exist"; ctxt->last_error = strm.str(); return 1; } } // namespace parse_context::parse_context(const char *path) :last_line(0), printer(NULL), error_scratch(300), scanner(NULL) { if(path) cwd = boost::filesystem::canonical(path); else cwd = boost::filesystem::current_path(); addop("-", &unary_negate, glps_expr_number, 1, glps_expr_number); addop("sin", &unary_sin, glps_expr_number, 1, glps_expr_number); addop("cos", &unary_cos, glps_expr_number, 1, glps_expr_number); addop("tan", &unary_tan, glps_expr_number, 1, glps_expr_number); addop("asin",&unary_asin,glps_expr_number, 1, glps_expr_number); addop("acos",&unary_acos,glps_expr_number, 1, glps_expr_number); addop("atan",&unary_atan,glps_expr_number, 1, glps_expr_number); // aliases to capture legacy behavour :P addop("arcsin",&unary_asin,glps_expr_number, 1, glps_expr_number); addop("arccos",&unary_acos,glps_expr_number, 1, glps_expr_number); addop("arctan",&unary_atan,glps_expr_number, 1, glps_expr_number); addop("+", &binary_add, glps_expr_number, 2, glps_expr_number, glps_expr_number); addop("-", &binary_sub, glps_expr_number, 2, glps_expr_number, glps_expr_number); addop("*", &binary_mult,glps_expr_number, 2, glps_expr_number, glps_expr_number); addop("/", &binary_div, glps_expr_number, 2, glps_expr_number, glps_expr_number); addop("-", &unary_bl_negate, glps_expr_line, 1, glps_expr_line); addop("*", &binary_bl_mult<0,1>, glps_expr_line, 2, glps_expr_number, glps_expr_line); addop("*", &binary_bl_mult<1,0>, glps_expr_line, 2, glps_expr_line, glps_expr_number); addop("parse", &unary_parse, glps_expr_config, 1, glps_expr_string); addop("file", &unary_file, glps_expr_string, 1, glps_expr_string); addop("h5file", &unary_h5file, glps_expr_string, 1, glps_expr_string); } parse_context::~parse_context() { } <commit_msg>parse() handle relative path<commit_after> #include "math.h" #include <sstream> #include <limits> #include <stdexcept> #include "glps_parser.h" #include "scsi/config.h" namespace { // Numeric operations int unary_negate(parse_context* ctxt, expr_value_t *R, const expr_t * const *A) { *R = -boost::get<double>(A[0]->value); return 0; } int unary_sin(parse_context* ctxt, expr_value_t *R, const expr_t * const *A) { *R = sin(boost::get<double>(A[0]->value)); return 0; } int unary_cos(parse_context* ctxt, expr_value_t *R, const expr_t * const *A) { *R = cos(boost::get<double>(A[0]->value)); return 0; } int unary_tan(parse_context* ctxt, expr_value_t *R, const expr_t * const *A) { *R = tan(boost::get<double>(A[0]->value)); return 0; } int unary_asin(parse_context* ctxt, expr_value_t *R, const expr_t * const *A) { *R = asin(boost::get<double>(A[0]->value)); return 0; } int unary_acos(parse_context* ctxt, expr_value_t *R, const expr_t * const *A) { *R = acos(boost::get<double>(A[0]->value)); return 0; } int unary_atan(parse_context* ctxt, expr_value_t *R, const expr_t * const *A) { *R = atan(boost::get<double>(A[0]->value)); return 0; } int binary_add(parse_context* ctxt, expr_value_t *R, const expr_t * const *A) { *R = boost::get<double>(A[0]->value)+boost::get<double>(A[1]->value); return 0; } int binary_sub(parse_context* ctxt, expr_value_t *R, const expr_t * const *A) { *R = boost::get<double>(A[0]->value)-boost::get<double>(A[1]->value); return 0; } int binary_mult(parse_context* ctxt, expr_value_t *R, const expr_t * const *A) { *R = boost::get<double>(A[0]->value)*boost::get<double>(A[1]->value); return 0; } int binary_div(parse_context* ctxt, expr_value_t *R, const expr_t * const *A) { double result = boost::get<double>(A[0]->value)/boost::get<double>(A[1]->value); if(!isfinite(result)) { ctxt->last_error = "division results in non-finite value"; return 1; } *R = result; return 0; } // beamline operations int unary_bl_negate(parse_context* ctxt, expr_value_t *R, const expr_t * const *A) { // reverse the order of the beamline const std::vector<std::string>& line = boost::get<std::vector<std::string> >(A[0]->value); std::vector<std::string> ret(line.size()); std::copy(line.rbegin(), line.rend(), ret.begin()); *R = ret; return 0; } template<int MULT, int LINE> int binary_bl_mult(parse_context* ctxt, expr_value_t *R, const expr_t * const *A) { // multiple of scale * beamline repeats the beamline 'scale' times assert(A[MULT]->etype==glps_expr_number); assert(A[LINE]->etype==glps_expr_line); double factor = boost::get<double>(A[MULT]->value); if(factor<0.0 || factor>std::numeric_limits<unsigned>::max()) { ctxt->last_error = "beamline scale by negative value or out of range value"; return 1; } unsigned factori = (unsigned)factor; const std::vector<std::string>& line = boost::get<std::vector<std::string> >(A[LINE]->value); std::vector<std::string> ret(line.size()*factori); if(factori>0) { std::vector<std::string>::iterator outi = ret.begin(); while(factori--) outi = std::copy(line.begin(), line.end(), outi); } *R = ret; return 0; } int unary_parse(parse_context* ctxt, expr_value_t *R, const expr_t * const *A) { using namespace boost::filesystem; assert(A[0]->etype==glps_expr_string); path name(canonical(boost::get<std::string>(A[0]->value), ctxt->cwd)); GLPSParser P; P.setPrinter(ctxt->printer); boost::shared_ptr<Config> ret(P.parse_file(name.native().c_str())); *R = ret; return 0; } int unary_file(parse_context* ctxt, expr_value_t *R, const expr_t * const *A) { using namespace boost::filesystem; const std::string& inp = boost::get<std::string>(A[0]->value); path ret(canonical(inp, ctxt->cwd)); if(!exists(ret)) { std::ostringstream strm; strm<<"\""<<ret<<"\" does not exist"; ctxt->last_error = strm.str(); return 1; } *R = ret.native(); return 0; } int unary_h5file(parse_context* ctxt, expr_value_t *R, const expr_t * const *A) { using namespace boost::filesystem; const std::string& inp = boost::get<std::string>(A[0]->value); /* The provided spec may contain both file path and group(s) * seperated by '/' which is ambigious as the file path * may contain '/' as well... * so do as h5ls does and strip off from the right hand side until * and try to open while '/' remain. */ size_t sep = inp.npos; while(true) { sep = inp.find_last_of('/', sep-1); path fname(absolute(inp.substr(0, sep), ctxt->cwd)); if(exists(fname)) { *R = canonical(fname).native() + inp.substr(sep); return 0; } else if(sep==inp.npos) { break; } } std::ostringstream strm; strm<<"\""<<inp<<"\" does not exist"; ctxt->last_error = strm.str(); return 1; } } // namespace parse_context::parse_context(const char *path) :last_line(0), printer(NULL), error_scratch(300), scanner(NULL) { if(path) cwd = boost::filesystem::canonical(path); else cwd = boost::filesystem::current_path(); addop("-", &unary_negate, glps_expr_number, 1, glps_expr_number); addop("sin", &unary_sin, glps_expr_number, 1, glps_expr_number); addop("cos", &unary_cos, glps_expr_number, 1, glps_expr_number); addop("tan", &unary_tan, glps_expr_number, 1, glps_expr_number); addop("asin",&unary_asin,glps_expr_number, 1, glps_expr_number); addop("acos",&unary_acos,glps_expr_number, 1, glps_expr_number); addop("atan",&unary_atan,glps_expr_number, 1, glps_expr_number); // aliases to capture legacy behavour :P addop("arcsin",&unary_asin,glps_expr_number, 1, glps_expr_number); addop("arccos",&unary_acos,glps_expr_number, 1, glps_expr_number); addop("arctan",&unary_atan,glps_expr_number, 1, glps_expr_number); addop("+", &binary_add, glps_expr_number, 2, glps_expr_number, glps_expr_number); addop("-", &binary_sub, glps_expr_number, 2, glps_expr_number, glps_expr_number); addop("*", &binary_mult,glps_expr_number, 2, glps_expr_number, glps_expr_number); addop("/", &binary_div, glps_expr_number, 2, glps_expr_number, glps_expr_number); addop("-", &unary_bl_negate, glps_expr_line, 1, glps_expr_line); addop("*", &binary_bl_mult<0,1>, glps_expr_line, 2, glps_expr_number, glps_expr_line); addop("*", &binary_bl_mult<1,0>, glps_expr_line, 2, glps_expr_line, glps_expr_number); addop("parse", &unary_parse, glps_expr_config, 1, glps_expr_string); addop("file", &unary_file, glps_expr_string, 1, glps_expr_string); addop("h5file", &unary_h5file, glps_expr_string, 1, glps_expr_string); } parse_context::~parse_context() { } <|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2009, 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 <algorithm> #include <cassert> #include "boost/format.hpp" #include "boost/lexical_cast.hpp" #include "boost/regex.hpp" #include "boost/filesystem/operations.hpp" #include "boost/filesystem/path.hpp" #include "boost/filesystem/convenience.hpp" #include "boost/algorithm/string.hpp" #include "IECore/Exception.h" #include "IECore/FileSequence.h" #include "IECore/FileSequenceFunctions.h" #include "IECore/CompoundFrameList.h" #include "IECore/EmptyFrameList.h" #include "IECore/FrameRange.h" using namespace IECore; void IECore::findSequences( const std::vector< std::string > &names, std::vector< FileSequencePtr > &sequences ) { sequences.clear(); /// this matches names of the form $prefix$frameNumber$suffix /// placing each of those in a group of the resulting match. /// both $prefix and $suffix may be the empty string and $frameNumber /// may be preceded by a minus sign. boost::regex matchExpression( std::string( "^([^#]*?)(-?[0-9]+)([^0-9#]*)$" ) ); /// build a mapping from ($prefix, $suffix) to a list of $frameNumbers typedef std::vector< std::string > Frames; typedef std::map< std::pair< std::string, std::string >, Frames > SequenceMap; SequenceMap sequenceMap; for ( std::vector< std::string >::const_iterator it = names.begin(); it != names.end(); ++it ) { boost::smatch matches; if ( boost::regex_match( *it, matches, matchExpression ) ) { sequenceMap[ SequenceMap::key_type( std::string( matches[1].first, matches[1].second ), std::string( matches[3].first, matches[3].second ) ) ].push_back( std::string( matches[2].first, matches[2].second ) ); } } for ( SequenceMap::const_iterator it = sequenceMap.begin(); it != sequenceMap.end(); ++it ) { const SequenceMap::key_type &fixes = it->first; const Frames &frames = it->second; /// in diabolical cases the elements of frames may not all have the same padding /// so we'll sort them out into padded and unpadded frame sequences here, by creating /// a map of padding->list of frames. unpadded things will be considered to have a padding /// of 1. typedef std::vector< FrameList::Frame > NumericFrames; typedef std::map< unsigned int, NumericFrames > PaddingToFramesMap; PaddingToFramesMap paddingToFrames; for ( Frames::const_iterator fIt = frames.begin(); fIt != frames.end(); ++fIt ) { std::string frame = *fIt; int sign = 1; assert( frame.size() ); if ( *frame.begin() == '-' ) { frame = frame.substr( 1, frame.size() - 1 ); sign = -1; } if ( *frame.begin() == '0' || paddingToFrames.find( frame.size() ) != paddingToFrames.end() ) { paddingToFrames[ frame.size() ].push_back( sign * boost::lexical_cast<FrameList::Frame>( frame ) ); } else { paddingToFrames[ 1 ].push_back( sign * boost::lexical_cast<FrameList::Frame>( frame ) ); } } for ( PaddingToFramesMap::iterator pIt = paddingToFrames.begin(); pIt != paddingToFrames.end(); ++pIt ) { const PaddingToFramesMap::key_type &padding = pIt->first; NumericFrames &numericFrames = pIt->second; std::sort( numericFrames.begin(), numericFrames.end() ); FrameListPtr frameList = frameListFromList( numericFrames ); std::vector< FrameList::Frame > expandedFrameList; frameList->asList( expandedFrameList ); /// remove any sequences with less than two files if ( expandedFrameList.size() >= 2 ) { std::string frameTemplate; for ( PaddingToFramesMap::key_type i = 0; i < padding; i++ ) { frameTemplate += "#"; } sequences.push_back( new FileSequence( fixes.first + frameTemplate + fixes.second, frameList ) ); } } } } void IECore::ls( const std::string &path, std::vector< FileSequencePtr > &sequences ) { sequences.clear(); if ( boost::filesystem::is_directory( path ) ) { boost::filesystem::directory_iterator end; std::vector< std::string > files; for ( boost::filesystem::directory_iterator it( path ); it != end; ++it ) { files.push_back( it->leaf() ); } findSequences( files, sequences ); } } void IECore::ls( const std::string &sequencePath, FileSequencePtr &sequence ) { sequence = 0; boost::smatch matches; bool m = boost::regex_match( sequencePath, matches, FileSequence::fileNameValidator() ); if ( !m ) { return; } const std::string paddingStr( matches[2].first, matches[2].second ); const unsigned padding = paddingStr.size(); std::vector< std::string > files; boost::filesystem::path dir = boost::filesystem::path( sequencePath ).parent_path(); std::string baseSequencePath = boost::filesystem::path( sequencePath ).filename(); const std::string::size_type first = baseSequencePath.find_first_of( '#' ); assert( first != std::string::npos ); const std::string prefix = baseSequencePath.substr( 0, first ); const std::string::size_type last = baseSequencePath.find_last_of( '#' ); assert( last != std::string::npos ); const std::string suffix = baseSequencePath.substr( last + 1, baseSequencePath.size() - last - 1 ); boost::filesystem::path dirToCheck( dir ); if ( dirToCheck.string() == "" ) { dirToCheck = "."; } boost::filesystem::directory_iterator end; for ( boost::filesystem::directory_iterator it( dirToCheck ); it != end; ++it ) { const std::string &fileName = it->leaf(); if ( fileName.substr( 0, prefix.size() ) == prefix && fileName.substr( fileName.size() - suffix.size(), suffix.size() ) == suffix ) { files.push_back( ( dir / fileName ).string() ); } } std::vector< FileSequencePtr > sequences; findSequences( files, sequences ); for ( std::vector< FileSequencePtr >::iterator it = sequences.begin(); it != sequences.end() ; ++it ) { if ( (*it)->getPadding() == padding ) { sequence = *it; return; } } } FrameListPtr IECore::frameListFromList( const std::vector< FrameList::Frame > &frames ) { if ( frames.size() == 0 ) { return new EmptyFrameList(); } else if ( frames.size() == 1 ) { return new FrameRange( frames[0], frames[0] ); } std::vector< FrameListPtr > frameLists; FrameList::Frame rangeStart = 0; FrameList::Frame rangeEnd = 1; FrameList::Frame rangeStep = frames[ rangeEnd ] - frames[ rangeStart ]; assert( rangeStep > 0 ); while ( rangeEnd <= frames.size() ) { if ( rangeEnd == frames.size() || frames[ rangeEnd ] - frames[ rangeEnd -1 ] != rangeStep ) { /// we've come to the end of a run if ( rangeEnd - 1 == rangeStart ) { frameLists.push_back( new FrameRange( frames[ rangeStart ], frames[ rangeStart ] ) ); } else { frameLists.push_back( new FrameRange( frames[ rangeStart ], frames[ rangeEnd -1 ], rangeStep ) ); } rangeStart = rangeEnd; rangeEnd = rangeStart + 1; if ( rangeEnd < frames.size() ) { rangeStep = frames[ rangeEnd ] - frames[ rangeStart ]; } } else { rangeEnd ++; } } if ( frameLists.size() == 1 ) { return frameLists[0]; } else { return new CompoundFrameList( frameLists ); } } <commit_msg>Fixed 64-bit warnings<commit_after>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2009, 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 <algorithm> #include <cassert> #include "boost/format.hpp" #include "boost/lexical_cast.hpp" #include "boost/regex.hpp" #include "boost/filesystem/operations.hpp" #include "boost/filesystem/path.hpp" #include "boost/filesystem/convenience.hpp" #include "boost/algorithm/string.hpp" #include "IECore/Exception.h" #include "IECore/FileSequence.h" #include "IECore/FileSequenceFunctions.h" #include "IECore/CompoundFrameList.h" #include "IECore/EmptyFrameList.h" #include "IECore/FrameRange.h" using namespace IECore; void IECore::findSequences( const std::vector< std::string > &names, std::vector< FileSequencePtr > &sequences ) { sequences.clear(); /// this matches names of the form $prefix$frameNumber$suffix /// placing each of those in a group of the resulting match. /// both $prefix and $suffix may be the empty string and $frameNumber /// may be preceded by a minus sign. boost::regex matchExpression( std::string( "^([^#]*?)(-?[0-9]+)([^0-9#]*)$" ) ); /// build a mapping from ($prefix, $suffix) to a list of $frameNumbers typedef std::vector< std::string > Frames; typedef std::map< std::pair< std::string, std::string >, Frames > SequenceMap; SequenceMap sequenceMap; for ( std::vector< std::string >::const_iterator it = names.begin(); it != names.end(); ++it ) { boost::smatch matches; if ( boost::regex_match( *it, matches, matchExpression ) ) { sequenceMap[ SequenceMap::key_type( std::string( matches[1].first, matches[1].second ), std::string( matches[3].first, matches[3].second ) ) ].push_back( std::string( matches[2].first, matches[2].second ) ); } } for ( SequenceMap::const_iterator it = sequenceMap.begin(); it != sequenceMap.end(); ++it ) { const SequenceMap::key_type &fixes = it->first; const Frames &frames = it->second; /// in diabolical cases the elements of frames may not all have the same padding /// so we'll sort them out into padded and unpadded frame sequences here, by creating /// a map of padding->list of frames. unpadded things will be considered to have a padding /// of 1. typedef std::vector< FrameList::Frame > NumericFrames; typedef std::map< unsigned int, NumericFrames > PaddingToFramesMap; PaddingToFramesMap paddingToFrames; for ( Frames::const_iterator fIt = frames.begin(); fIt != frames.end(); ++fIt ) { std::string frame = *fIt; int sign = 1; assert( frame.size() ); if ( *frame.begin() == '-' ) { frame = frame.substr( 1, frame.size() - 1 ); sign = -1; } if ( *frame.begin() == '0' || paddingToFrames.find( frame.size() ) != paddingToFrames.end() ) { paddingToFrames[ frame.size() ].push_back( sign * boost::lexical_cast<FrameList::Frame>( frame ) ); } else { paddingToFrames[ 1 ].push_back( sign * boost::lexical_cast<FrameList::Frame>( frame ) ); } } for ( PaddingToFramesMap::iterator pIt = paddingToFrames.begin(); pIt != paddingToFrames.end(); ++pIt ) { const PaddingToFramesMap::key_type &padding = pIt->first; NumericFrames &numericFrames = pIt->second; std::sort( numericFrames.begin(), numericFrames.end() ); FrameListPtr frameList = frameListFromList( numericFrames ); std::vector< FrameList::Frame > expandedFrameList; frameList->asList( expandedFrameList ); /// remove any sequences with less than two files if ( expandedFrameList.size() >= 2 ) { std::string frameTemplate; for ( PaddingToFramesMap::key_type i = 0; i < padding; i++ ) { frameTemplate += "#"; } sequences.push_back( new FileSequence( fixes.first + frameTemplate + fixes.second, frameList ) ); } } } } void IECore::ls( const std::string &path, std::vector< FileSequencePtr > &sequences ) { sequences.clear(); if ( boost::filesystem::is_directory( path ) ) { boost::filesystem::directory_iterator end; std::vector< std::string > files; for ( boost::filesystem::directory_iterator it( path ); it != end; ++it ) { files.push_back( it->leaf() ); } findSequences( files, sequences ); } } void IECore::ls( const std::string &sequencePath, FileSequencePtr &sequence ) { sequence = 0; boost::smatch matches; bool m = boost::regex_match( sequencePath, matches, FileSequence::fileNameValidator() ); if ( !m ) { return; } const std::string paddingStr( matches[2].first, matches[2].second ); const unsigned padding = paddingStr.size(); std::vector< std::string > files; boost::filesystem::path dir = boost::filesystem::path( sequencePath ).parent_path(); std::string baseSequencePath = boost::filesystem::path( sequencePath ).filename(); const std::string::size_type first = baseSequencePath.find_first_of( '#' ); assert( first != std::string::npos ); const std::string prefix = baseSequencePath.substr( 0, first ); const std::string::size_type last = baseSequencePath.find_last_of( '#' ); assert( last != std::string::npos ); const std::string suffix = baseSequencePath.substr( last + 1, baseSequencePath.size() - last - 1 ); boost::filesystem::path dirToCheck( dir ); if ( dirToCheck.string() == "" ) { dirToCheck = "."; } boost::filesystem::directory_iterator end; for ( boost::filesystem::directory_iterator it( dirToCheck ); it != end; ++it ) { const std::string &fileName = it->leaf(); if ( fileName.substr( 0, prefix.size() ) == prefix && fileName.substr( fileName.size() - suffix.size(), suffix.size() ) == suffix ) { files.push_back( ( dir / fileName ).string() ); } } std::vector< FileSequencePtr > sequences; findSequences( files, sequences ); for ( std::vector< FileSequencePtr >::iterator it = sequences.begin(); it != sequences.end() ; ++it ) { if ( (*it)->getPadding() == padding ) { sequence = *it; return; } } } FrameListPtr IECore::frameListFromList( const std::vector< FrameList::Frame > &frames ) { if ( frames.size() == 0 ) { return new EmptyFrameList(); } else if ( frames.size() == 1 ) { return new FrameRange( frames[0], frames[0] ); } std::vector< FrameListPtr > frameLists; FrameList::Frame rangeStart = 0; FrameList::Frame rangeEnd = 1; FrameList::Frame rangeStep = frames[ rangeEnd ] - frames[ rangeStart ]; assert( rangeStep > 0 ); while ( rangeEnd <= (FrameList::Frame)frames.size() ) { if ( rangeEnd == (FrameList::Frame)frames.size() || frames[ rangeEnd ] - frames[ rangeEnd -1 ] != rangeStep ) { /// we've come to the end of a run if ( rangeEnd - 1 == rangeStart ) { frameLists.push_back( new FrameRange( frames[ rangeStart ], frames[ rangeStart ] ) ); } else { frameLists.push_back( new FrameRange( frames[ rangeStart ], frames[ rangeEnd -1 ], rangeStep ) ); } rangeStart = rangeEnd; rangeEnd = rangeStart + 1; if ( rangeEnd < (FrameList::Frame)frames.size() ) { rangeStep = frames[ rangeEnd ] - frames[ rangeStart ]; } } else { rangeEnd ++; } } if ( frameLists.size() == 1 ) { return frameLists[0]; } else { return new CompoundFrameList( frameLists ); } } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * 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/. */ #include <sal/config.h> #include <unotest/filters-test.hxx> #include <test/bootstrapfixture.hxx> #include <rtl/strbuf.hxx> #include <osl/file.hxx> #include <sfx2/app.hxx> #include <sfx2/docfilt.hxx> #include <sfx2/docfile.hxx> #include <sfx2/frame.hxx> #include <sfx2/sfxmodelfactory.hxx> #include <svl/stritem.hxx> #include <unotools/tempfile.hxx> #include <comphelper/storagehelper.hxx> #define CALC_DEBUG_OUTPUT 0 #define TEST_BUG_FILES 0 #include "helper/qahelper.hxx" #include "docsh.hxx" #include "postit.hxx" #include "patattr.hxx" #include "scitems.hxx" #include "document.hxx" #include "cellform.hxx" #define ODS_FORMAT_TYPE 50331943 #define XLS_FORMAT_TYPE 318767171 #define XLSX_FORMAT_TYPE 268959811 #define LOTUS123_FORMAT_TYPE 268435649 #define ODS 0 #define XLS 1 #define XLSX 2 #define LOTUS123 3 using namespace ::com::sun::star; using namespace ::com::sun::star::uno; namespace { struct FileFormat { const char* pName; const char* pFilterName; const char* pTypeName; unsigned int nFormatType; }; FileFormat aFileFormats[] = { { "ods" , "calc8", "", ODS_FORMAT_TYPE }, { "xls" , "MS Excel 97", "calc_MS_EXCEL_97", XLS_FORMAT_TYPE }, { "xlsx", "Calc MS Excel 2007 XML" , "MS Excel 2007 XML", XLSX_FORMAT_TYPE }, { "123" , "Lotus", "calc_Lotus", LOTUS123_FORMAT_TYPE } }; } class ScExportTest : public test::BootstrapFixture { public: ScExportTest(); virtual void setUp(); virtual void tearDown(); ScDocShellRef saveAndReload( ScDocShell*, const rtl::OUString&, const rtl::OUString&, const rtl::OUString&, sal_uLong ); ScDocShellRef saveAndReloadPassword( ScDocShell*, const rtl::OUString&, const rtl::OUString&, const rtl::OUString&, sal_uLong ); void test(); void testPasswordExport(); CPPUNIT_TEST_SUITE(ScExportTest); CPPUNIT_TEST(test); #if !defined(MACOSX) && !defined(DRAGONFLY) && !defined(WNT) CPPUNIT_TEST(testPasswordExport); #endif CPPUNIT_TEST_SUITE_END(); private: rtl::OUString m_aBaseString; uno::Reference<uno::XInterface> m_xCalcComponent; ScDocShellRef saveAndReload( ScDocShell* pShell, sal_Int32 nFormat ); }; /* void ScFiltersTest::createFileURL(const rtl::OUString& aFileBase, const rtl::OUString& aFileExtension, rtl::OUString& rFilePath) { rtl::OUString aSep(RTL_CONSTASCII_USTRINGPARAM("/")); rtl::OUStringBuffer aBuffer( getSrcRootURL() ); aBuffer.append(m_aBaseString).append(aSep).append(aFileExtension); aBuffer.append(aSep).append(aFileBase).append(aFileExtension); rFilePath = aBuffer.makeStringAndClear(); } */ ScDocShellRef ScExportTest::saveAndReloadPassword(ScDocShell* pShell, const rtl::OUString &rFilter, const rtl::OUString &rUserData, const rtl::OUString& rTypeName, sal_uLong nFormatType) { utl::TempFile aTempFile; aTempFile.EnableKillingFile(); SfxMedium aStoreMedium( aTempFile.GetURL(), STREAM_STD_WRITE ); sal_uInt32 nExportFormat = 0; if (nFormatType) nExportFormat = SFX_FILTER_EXPORT | SFX_FILTER_USESOPTIONS; SfxFilter* pExportFilter = new SfxFilter( rFilter, rtl::OUString(), nFormatType, nExportFormat, rTypeName, 0, rtl::OUString(), rUserData, rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("private:factory/scalc*")) ); pExportFilter->SetVersion(SOFFICE_FILEFORMAT_CURRENT); aStoreMedium.SetFilter(pExportFilter); SfxItemSet* pExportSet = aStoreMedium.GetItemSet(); uno::Sequence< beans::NamedValue > aEncryptionData = comphelper::OStorageHelper::CreatePackageEncryptionData( rtl::OUString("test") ); uno::Any xEncryptionData; xEncryptionData <<= aEncryptionData; pExportSet->Put(SfxUnoAnyItem(SID_ENCRYPTIONDATA, xEncryptionData)); uno::Reference< embed::XStorage > xMedStorage = aStoreMedium.GetStorage(); ::comphelper::OStorageHelper::SetCommonStorageEncryptionData( xMedStorage, aEncryptionData ); pShell->DoSaveAs( aStoreMedium ); pShell->DoClose(); //std::cout << "File: " << aTempFile.GetURL() << std::endl; sal_uInt32 nFormat = 0; if (nFormatType) nFormat = SFX_FILTER_IMPORT | SFX_FILTER_USESOPTIONS; SfxFilter* pFilter = new SfxFilter( rFilter, rtl::OUString(), nFormatType, nFormat, rTypeName, 0, rtl::OUString(), rUserData, rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("private:factory/scalc*")) ); pFilter->SetVersion(SOFFICE_FILEFORMAT_CURRENT); ScDocShellRef xDocShRef = new ScDocShell; SfxMedium* pSrcMed = new SfxMedium(aTempFile.GetURL(), STREAM_STD_READ); SfxItemSet* pSet = pSrcMed->GetItemSet(); pSet->Put(SfxStringItem(SID_PASSWORD, rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("test")))); pSrcMed->SetFilter(pFilter); if (!xDocShRef->DoLoad(pSrcMed)) { xDocShRef->DoClose(); // load failed. xDocShRef.Clear(); } return xDocShRef; } ScDocShellRef ScExportTest::saveAndReload(ScDocShell* pShell, const rtl::OUString &rFilter, const rtl::OUString &rUserData, const rtl::OUString& rTypeName, sal_uLong nFormatType) { utl::TempFile aTempFile; aTempFile.EnableKillingFile(); SfxMedium aStoreMedium( aTempFile.GetURL(), STREAM_STD_WRITE ); sal_uInt32 nExportFormat = 0; if (nFormatType) nExportFormat = SFX_FILTER_EXPORT | SFX_FILTER_USESOPTIONS; SfxFilter* pExportFilter = new SfxFilter( rFilter, rtl::OUString(), nFormatType, nExportFormat, rTypeName, 0, rtl::OUString(), rUserData, rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("private:factory/scalc*")) ); pExportFilter->SetVersion(SOFFICE_FILEFORMAT_CURRENT); aStoreMedium.SetFilter(pExportFilter); pShell->DoSaveAs( aStoreMedium ); pShell->DoClose(); //std::cout << "File: " << aTempFile.GetURL() << std::endl; sal_uInt32 nFormat = 0; if (nFormatType) nFormat = SFX_FILTER_IMPORT | SFX_FILTER_USESOPTIONS; SfxFilter* pFilter = new SfxFilter( rFilter, rtl::OUString(), nFormatType, nFormat, rTypeName, 0, rtl::OUString(), rUserData, rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("private:factory/scalc*")) ); pFilter->SetVersion(SOFFICE_FILEFORMAT_CURRENT); ScDocShellRef xDocShRef = new ScDocShell; SfxMedium* pSrcMed = new SfxMedium(aTempFile.GetURL(), STREAM_STD_READ); pSrcMed->SetFilter(pFilter); if (!xDocShRef->DoLoad(pSrcMed)) { xDocShRef->DoClose(); // load failed. xDocShRef.Clear(); } return xDocShRef; } ScDocShellRef ScExportTest::saveAndReload( ScDocShell* pShell, sal_Int32 nFormat ) { rtl::OUString aFileExtension(aFileFormats[nFormat].pName, strlen(aFileFormats[nFormat].pName), RTL_TEXTENCODING_UTF8 ); rtl::OUString aFilterName(aFileFormats[nFormat].pFilterName, strlen(aFileFormats[nFormat].pFilterName), RTL_TEXTENCODING_UTF8) ; rtl::OUString aFilterType(aFileFormats[nFormat].pTypeName, strlen(aFileFormats[nFormat].pTypeName), RTL_TEXTENCODING_UTF8); ScDocShellRef xDocSh = saveAndReload(pShell, aFilterName, rtl::OUString(), aFilterType, aFileFormats[nFormat].nFormatType); CPPUNIT_ASSERT(xDocSh.Is()); return xDocSh; } void ScExportTest::test() { ScDocShell* pShell = new ScDocShell( SFXMODEL_STANDARD | SFXMODEL_DISABLE_EMBEDDED_SCRIPTS | SFXMODEL_DISABLE_DOCUMENT_RECOVERY); pShell->DoInitNew(); ScDocument* pDoc = pShell->GetDocument(); pDoc->SetValue(0,0,0, 1.0); CPPUNIT_ASSERT(pDoc); ScDocShellRef xDocSh = saveAndReload( pShell, ODS ); CPPUNIT_ASSERT(xDocSh.Is()); ScDocument* pLoadedDoc = xDocSh->GetDocument(); double aVal = pLoadedDoc->GetValue(0,0,0); CPPUNIT_ASSERT_DOUBLES_EQUAL(aVal, 1.0, 1e-8); } void ScExportTest::testPasswordExport() { ScDocShell* pShell = new ScDocShell( SFXMODEL_STANDARD | SFXMODEL_DISABLE_EMBEDDED_SCRIPTS | SFXMODEL_DISABLE_DOCUMENT_RECOVERY); pShell->DoInitNew(); ScDocument* pDoc = pShell->GetDocument(); pDoc->SetValue(0,0,0, 1.0); CPPUNIT_ASSERT(pDoc); sal_Int32 nFormat = ODS; rtl::OUString aFileExtension(aFileFormats[nFormat].pName, strlen(aFileFormats[nFormat].pName), RTL_TEXTENCODING_UTF8 ); rtl::OUString aFilterName(aFileFormats[nFormat].pFilterName, strlen(aFileFormats[nFormat].pFilterName), RTL_TEXTENCODING_UTF8) ; rtl::OUString aFilterType(aFileFormats[nFormat].pTypeName, strlen(aFileFormats[nFormat].pTypeName), RTL_TEXTENCODING_UTF8); ScDocShellRef xDocSh = saveAndReloadPassword(pShell, aFilterName, rtl::OUString(), aFilterType, aFileFormats[nFormat].nFormatType); CPPUNIT_ASSERT(xDocSh.Is()); ScDocument* pLoadedDoc = xDocSh->GetDocument(); double aVal = pLoadedDoc->GetValue(0,0,0); CPPUNIT_ASSERT_DOUBLES_EQUAL(aVal, 1.0, 1e-8); } ScExportTest::ScExportTest() : m_aBaseString(RTL_CONSTASCII_USTRINGPARAM("/sc/qa/unit/data")) { } void ScExportTest::setUp() { test::BootstrapFixture::setUp(); // This is a bit of a fudge, we do this to ensure that ScGlobals::ensure, // which is a private symbol to us, gets called m_xCalcComponent = getMultiServiceFactory()->createInstance(rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.comp.Calc.SpreadsheetDocument"))); CPPUNIT_ASSERT_MESSAGE("no calc component!", m_xCalcComponent.is()); } void ScExportTest::tearDown() { uno::Reference< lang::XComponent >( m_xCalcComponent, UNO_QUERY_THROW )->dispose(); test::BootstrapFixture::tearDown(); } CPPUNIT_TEST_SUITE_REGISTRATION(ScExportTest); CPPUNIT_PLUGIN_IMPLEMENT(); /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>add initial xlsx cond format export test<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * 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/. */ #include <sal/config.h> #include <unotest/filters-test.hxx> #include <test/bootstrapfixture.hxx> #include <rtl/strbuf.hxx> #include <osl/file.hxx> #include <sfx2/app.hxx> #include <sfx2/docfilt.hxx> #include <sfx2/docfile.hxx> #include <sfx2/frame.hxx> #include <sfx2/sfxmodelfactory.hxx> #include <svl/stritem.hxx> #include <unotools/tempfile.hxx> #include <comphelper/storagehelper.hxx> #define CALC_DEBUG_OUTPUT 0 #define TEST_BUG_FILES 0 #include "helper/qahelper.hxx" #include "docsh.hxx" #include "postit.hxx" #include "patattr.hxx" #include "scitems.hxx" #include "document.hxx" #include "cellform.hxx" #define ODS_FORMAT_TYPE 50331943 #define XLS_FORMAT_TYPE 318767171 #define XLSX_FORMAT_TYPE 268959811 #define LOTUS123_FORMAT_TYPE 268435649 #define ODS 0 #define XLS 1 #define XLSX 2 #define LOTUS123 3 using namespace ::com::sun::star; using namespace ::com::sun::star::uno; namespace { struct FileFormat { const char* pName; const char* pFilterName; const char* pTypeName; unsigned int nFormatType; }; FileFormat aFileFormats[] = { { "ods" , "calc8", "", ODS_FORMAT_TYPE }, { "xls" , "MS Excel 97", "calc_MS_EXCEL_97", XLS_FORMAT_TYPE }, { "xlsx", "Calc MS Excel 2007 XML" , "MS Excel 2007 XML", XLSX_FORMAT_TYPE }, { "123" , "Lotus", "calc_Lotus", LOTUS123_FORMAT_TYPE } }; } class ScExportTest : public test::BootstrapFixture { public: ScExportTest(); virtual void setUp(); virtual void tearDown(); ScDocShellRef saveAndReload( ScDocShell*, const rtl::OUString&, const rtl::OUString&, const rtl::OUString&, sal_uLong ); ScDocShellRef saveAndReloadPassword( ScDocShell*, const rtl::OUString&, const rtl::OUString&, const rtl::OUString&, sal_uLong ); void test(); void testPasswordExport(); void testConditionalFormatExportXLSX(); CPPUNIT_TEST_SUITE(ScExportTest); CPPUNIT_TEST(test); #if !defined(MACOSX) && !defined(DRAGONFLY) && !defined(WNT) CPPUNIT_TEST(testPasswordExport); #endif CPPUNIT_TEST(testConditionalFormatExportXLSX); CPPUNIT_TEST_SUITE_END(); private: rtl::OUString m_aBaseString; uno::Reference<uno::XInterface> m_xCalcComponent; ScDocShellRef saveAndReload( ScDocShell* pShell, sal_Int32 nFormat ); ScDocShellRef loadDocument( const rtl::OUString& rFileNameBase, sal_Int32 nFormat ); void createFileURL( const rtl::OUString& aFileBase, const rtl::OUString& rFileExtension, rtl::OUString& rFilePath); void createCSVPath(const rtl::OUString& rFileBase, rtl::OUString& rCSVPath); }; void ScExportTest::createFileURL(const rtl::OUString& aFileBase, const rtl::OUString& aFileExtension, rtl::OUString& rFilePath) { rtl::OUString aSep("/"); rtl::OUStringBuffer aBuffer( getSrcRootURL() ); aBuffer.append(m_aBaseString).append(aSep).append(aFileExtension); aBuffer.append(aSep).append(aFileBase).append(aFileExtension); rFilePath = aBuffer.makeStringAndClear(); } void ScExportTest::createCSVPath(const rtl::OUString& aFileBase, rtl::OUString& rCSVPath) { rtl::OUStringBuffer aBuffer(getSrcRootPath()); aBuffer.append(m_aBaseString).append(rtl::OUString("/contentCSV/")); aBuffer.append(aFileBase).append(rtl::OUString("csv")); rCSVPath = aBuffer.makeStringAndClear(); } ScDocShellRef ScExportTest::saveAndReloadPassword(ScDocShell* pShell, const rtl::OUString &rFilter, const rtl::OUString &rUserData, const rtl::OUString& rTypeName, sal_uLong nFormatType) { utl::TempFile aTempFile; aTempFile.EnableKillingFile(); SfxMedium aStoreMedium( aTempFile.GetURL(), STREAM_STD_WRITE ); sal_uInt32 nExportFormat = 0; if (nFormatType) nExportFormat = SFX_FILTER_EXPORT | SFX_FILTER_USESOPTIONS; SfxFilter* pExportFilter = new SfxFilter( rFilter, rtl::OUString(), nFormatType, nExportFormat, rTypeName, 0, rtl::OUString(), rUserData, rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("private:factory/scalc*")) ); pExportFilter->SetVersion(SOFFICE_FILEFORMAT_CURRENT); aStoreMedium.SetFilter(pExportFilter); SfxItemSet* pExportSet = aStoreMedium.GetItemSet(); uno::Sequence< beans::NamedValue > aEncryptionData = comphelper::OStorageHelper::CreatePackageEncryptionData( rtl::OUString("test") ); uno::Any xEncryptionData; xEncryptionData <<= aEncryptionData; pExportSet->Put(SfxUnoAnyItem(SID_ENCRYPTIONDATA, xEncryptionData)); uno::Reference< embed::XStorage > xMedStorage = aStoreMedium.GetStorage(); ::comphelper::OStorageHelper::SetCommonStorageEncryptionData( xMedStorage, aEncryptionData ); pShell->DoSaveAs( aStoreMedium ); pShell->DoClose(); //std::cout << "File: " << aTempFile.GetURL() << std::endl; sal_uInt32 nFormat = 0; if (nFormatType) nFormat = SFX_FILTER_IMPORT | SFX_FILTER_USESOPTIONS; SfxFilter* pFilter = new SfxFilter( rFilter, rtl::OUString(), nFormatType, nFormat, rTypeName, 0, rtl::OUString(), rUserData, rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("private:factory/scalc*")) ); pFilter->SetVersion(SOFFICE_FILEFORMAT_CURRENT); ScDocShellRef xDocShRef = new ScDocShell; SfxMedium* pSrcMed = new SfxMedium(aTempFile.GetURL(), STREAM_STD_READ); SfxItemSet* pSet = pSrcMed->GetItemSet(); pSet->Put(SfxStringItem(SID_PASSWORD, rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("test")))); pSrcMed->SetFilter(pFilter); if (!xDocShRef->DoLoad(pSrcMed)) { xDocShRef->DoClose(); // load failed. xDocShRef.Clear(); } return xDocShRef; } ScDocShellRef ScExportTest::saveAndReload(ScDocShell* pShell, const rtl::OUString &rFilter, const rtl::OUString &rUserData, const rtl::OUString& rTypeName, sal_uLong nFormatType) { utl::TempFile aTempFile; aTempFile.EnableKillingFile(); SfxMedium aStoreMedium( aTempFile.GetURL(), STREAM_STD_WRITE ); sal_uInt32 nExportFormat = 0; if (nFormatType) nExportFormat = SFX_FILTER_EXPORT | SFX_FILTER_USESOPTIONS; SfxFilter* pExportFilter = new SfxFilter( rFilter, rtl::OUString(), nFormatType, nExportFormat, rTypeName, 0, rtl::OUString(), rUserData, rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("private:factory/scalc*")) ); pExportFilter->SetVersion(SOFFICE_FILEFORMAT_CURRENT); aStoreMedium.SetFilter(pExportFilter); pShell->DoSaveAs( aStoreMedium ); pShell->DoClose(); //std::cout << "File: " << aTempFile.GetURL() << std::endl; sal_uInt32 nFormat = 0; if (nFormatType) nFormat = SFX_FILTER_IMPORT | SFX_FILTER_USESOPTIONS; SfxFilter* pFilter = new SfxFilter( rFilter, rtl::OUString(), nFormatType, nFormat, rTypeName, 0, rtl::OUString(), rUserData, rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("private:factory/scalc*")) ); pFilter->SetVersion(SOFFICE_FILEFORMAT_CURRENT); ScDocShellRef xDocShRef = new ScDocShell; SfxMedium* pSrcMed = new SfxMedium(aTempFile.GetURL(), STREAM_STD_READ); pSrcMed->SetFilter(pFilter); if (!xDocShRef->DoLoad(pSrcMed)) { xDocShRef->DoClose(); // load failed. xDocShRef.Clear(); } return xDocShRef; } ScDocShellRef ScExportTest::saveAndReload( ScDocShell* pShell, sal_Int32 nFormat ) { rtl::OUString aFileExtension(aFileFormats[nFormat].pName, strlen(aFileFormats[nFormat].pName), RTL_TEXTENCODING_UTF8 ); rtl::OUString aFilterName(aFileFormats[nFormat].pFilterName, strlen(aFileFormats[nFormat].pFilterName), RTL_TEXTENCODING_UTF8) ; rtl::OUString aFilterType(aFileFormats[nFormat].pTypeName, strlen(aFileFormats[nFormat].pTypeName), RTL_TEXTENCODING_UTF8); ScDocShellRef xDocSh = saveAndReload(pShell, aFilterName, rtl::OUString(), aFilterType, aFileFormats[nFormat].nFormatType); CPPUNIT_ASSERT(xDocSh.Is()); return xDocSh; } ScDocShellRef ScExportTest::loadDocument(const rtl::OUString& rFileName, sal_Int32 nFormat) { rtl::OUString aFileExtension(aFileFormats[nFormat].pName, strlen(aFileFormats[nFormat].pName), RTL_TEXTENCODING_UTF8 ); rtl::OUString aFilterName(aFileFormats[nFormat].pFilterName, strlen(aFileFormats[nFormat].pFilterName), RTL_TEXTENCODING_UTF8) ; rtl::OUString aFileName; createFileURL( rFileName, aFileExtension, aFileName ); rtl::OUString aFilterType(aFileFormats[nFormat].pTypeName, strlen(aFileFormats[nFormat].pTypeName), RTL_TEXTENCODING_UTF8); unsigned int nFormatType = aFileFormats[nFormat].nFormatType; unsigned int nClipboardId = nFormatType ? SFX_FILTER_IMPORT | SFX_FILTER_USESOPTIONS : 0; SfxFilter* pFilter = new SfxFilter( aFilterName, rtl::OUString(), nFormatType, nClipboardId, aFilterType, 0, rtl::OUString(), rtl::OUString(), rtl::OUString("private:factory/scalc*") ); pFilter->SetVersion(SOFFICE_FILEFORMAT_CURRENT); ScDocShellRef xDocShRef = new ScDocShell; SfxMedium* pSrcMed = new SfxMedium(aFileName, STREAM_STD_READ); pSrcMed->SetFilter(pFilter); if (!xDocShRef->DoLoad(pSrcMed)) { xDocShRef->DoClose(); // load failed. xDocShRef.Clear(); } return xDocShRef; } void ScExportTest::test() { ScDocShell* pShell = new ScDocShell( SFXMODEL_STANDARD | SFXMODEL_DISABLE_EMBEDDED_SCRIPTS | SFXMODEL_DISABLE_DOCUMENT_RECOVERY); pShell->DoInitNew(); ScDocument* pDoc = pShell->GetDocument(); pDoc->SetValue(0,0,0, 1.0); CPPUNIT_ASSERT(pDoc); ScDocShellRef xDocSh = saveAndReload( pShell, ODS ); CPPUNIT_ASSERT(xDocSh.Is()); ScDocument* pLoadedDoc = xDocSh->GetDocument(); double aVal = pLoadedDoc->GetValue(0,0,0); CPPUNIT_ASSERT_DOUBLES_EQUAL(aVal, 1.0, 1e-8); } void ScExportTest::testPasswordExport() { ScDocShell* pShell = new ScDocShell( SFXMODEL_STANDARD | SFXMODEL_DISABLE_EMBEDDED_SCRIPTS | SFXMODEL_DISABLE_DOCUMENT_RECOVERY); pShell->DoInitNew(); ScDocument* pDoc = pShell->GetDocument(); pDoc->SetValue(0,0,0, 1.0); CPPUNIT_ASSERT(pDoc); sal_Int32 nFormat = ODS; rtl::OUString aFileExtension(aFileFormats[nFormat].pName, strlen(aFileFormats[nFormat].pName), RTL_TEXTENCODING_UTF8 ); rtl::OUString aFilterName(aFileFormats[nFormat].pFilterName, strlen(aFileFormats[nFormat].pFilterName), RTL_TEXTENCODING_UTF8) ; rtl::OUString aFilterType(aFileFormats[nFormat].pTypeName, strlen(aFileFormats[nFormat].pTypeName), RTL_TEXTENCODING_UTF8); ScDocShellRef xDocSh = saveAndReloadPassword(pShell, aFilterName, rtl::OUString(), aFilterType, aFileFormats[nFormat].nFormatType); CPPUNIT_ASSERT(xDocSh.Is()); ScDocument* pLoadedDoc = xDocSh->GetDocument(); double aVal = pLoadedDoc->GetValue(0,0,0); CPPUNIT_ASSERT_DOUBLES_EQUAL(aVal, 1.0, 1e-8); } void ScExportTest::testConditionalFormatExportXLSX() { ScDocShellRef xShell = loadDocument("new_cond_format_test.", XLSX); CPPUNIT_ASSERT(xShell.Is()); ScDocShellRef xDocSh = saveAndReload(&(*xShell), XLSX); CPPUNIT_ASSERT(xDocSh.Is()); ScDocument* pDoc = xDocSh->GetDocument(); rtl::OUString aCSVFile("new_cond_format_test."); rtl::OUString aCSVPath; createCSVPath( aCSVFile, aCSVPath ); testCondFile(aCSVPath, pDoc, 0); } ScExportTest::ScExportTest() : m_aBaseString(RTL_CONSTASCII_USTRINGPARAM("/sc/qa/unit/data")) { } void ScExportTest::setUp() { test::BootstrapFixture::setUp(); // This is a bit of a fudge, we do this to ensure that ScGlobals::ensure, // which is a private symbol to us, gets called m_xCalcComponent = getMultiServiceFactory()->createInstance(rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.comp.Calc.SpreadsheetDocument"))); CPPUNIT_ASSERT_MESSAGE("no calc component!", m_xCalcComponent.is()); } void ScExportTest::tearDown() { uno::Reference< lang::XComponent >( m_xCalcComponent, UNO_QUERY_THROW )->dispose(); test::BootstrapFixture::tearDown(); } CPPUNIT_TEST_SUITE_REGISTRATION(ScExportTest); CPPUNIT_PLUGIN_IMPLEMENT(); /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>#include "gtest/gtest.h" #include "gmock/gmock.h" #include <Arduino.h> #include <Wire.h> #include <functional> #define MOCK_GLOBAL_METHOD(RETURN_TYPE, FUNCTION_NAME) \ template< typename... Args>\ RETURN_TYPE FUNCTION_NAME (Args... args)\ {\ return mockPointer->FUNCTION_NAME(args...);\ }\ #define REAL_MOCK_IMPLEMENTATION(MockName)\ struct MockName##_Implementation\ REAL_MOCK_IMPLEMENTATION(Serial) { MOCK_METHOD0(foo, int() ); MOCK_METHOD1(foo, int(int) ); MOCK_METHOD2(foo, int(int, int) ); MOCK_METHOD0(boo, int() ); MOCK_METHOD1(boo, int(int) ); MOCK_METHOD2(boo, int(int, int) ); }; #define GLOBAL_MOCK_IMPLEMENTATION(MockName)\ struct MockName##_PointerClass\ {\ MockName##_Implementation* mockPointer = nullptr;\ };\ struct MockName##_GlobalObjectMethodImplementation : public MockName##_PointerClass\ GLOBAL_MOCK_IMPLEMENTATION(Serial) { MOCK_GLOBAL_METHOD(int, foo) MOCK_GLOBAL_METHOD(int, boo) }; //#define GLOBAL_MOCK_DEFINISIONS(MockName) class MockGlobalObject : public Serial_GlobalObjectMethodImplementation { MockGlobalObject& operator=(const MockGlobalObject& other) = delete; MockGlobalObject(const MockGlobalObject& other) = delete; public: MockGlobalObject(){} static MockGlobalObject& getGlobalInstanceReference() { static MockGlobalObject globalInstance; return globalInstance; } }; class MockLocalObject : public Serial_Implementation { MockGlobalObject& globalObj = MockGlobalObject::getGlobalInstanceReference(); public: MockLocalObject() { EXPECT_EQ(nullptr, globalObj.mockPointer) << "Are you trying to instantiate multiple local mock objects in one scope?"; globalObj.mockPointer = this; } ~MockLocalObject() { EXPECT_NE(nullptr, globalObj.mockPointer); globalObj.mockPointer = nullptr; } }; using ::testing::Return; using ::testing::_; auto& globalObj = MockGlobalObject::getGlobalInstanceReference(); TEST(SomeMock, FirstTest) { MockLocalObject obj; EXPECT_CALL(obj, foo()).WillOnce(Return(1) ); EXPECT_CALL(obj, foo(2)).WillOnce(Return(2) ); EXPECT_CALL(obj, foo(3, 3)).WillOnce(Return(3) ); EXPECT_CALL(obj, boo(3, 3)).WillOnce(Return(4) ); EXPECT_EQ(1, globalObj.foo()); EXPECT_EQ(2, globalObj.foo(2)); EXPECT_EQ(3, globalObj.foo(3, 3)); EXPECT_EQ(4, globalObj.boo(3, 3)); } TEST(SomeMock, SecondTest) { MockLocalObject obj; EXPECT_CALL(obj, foo()).WillOnce(Return(1) ); EXPECT_CALL(obj, foo(2)).WillOnce(Return(2) ); EXPECT_CALL(obj, foo(3, 3)).WillOnce(Return(3) ); EXPECT_EQ(1, globalObj.foo()); EXPECT_EQ(2, globalObj.foo(2)); EXPECT_EQ(3, globalObj.foo(3, 3)); } <commit_msg>Refactoring, got working with some defines<commit_after>#include "gtest/gtest.h" #include "gmock/gmock.h" #include <Arduino.h> #include <Wire.h> #include <functional> #define MOCK_GLOBAL_METHOD(RETURN_TYPE, FUNCTION_NAME) \ template< typename... Args>\ RETURN_TYPE FUNCTION_NAME (Args... args)\ {\ return mockPointer->FUNCTION_NAME(args...);\ }\ #define REAL_MOCK_IMPLEMENTATION(MockName)\ struct MockName##_Implementation\ REAL_MOCK_IMPLEMENTATION(Serial) { MOCK_METHOD0(foo, int() ); MOCK_METHOD1(foo, int(int) ); MOCK_METHOD2(foo, int(int, int) ); MOCK_METHOD0(boo, int() ); MOCK_METHOD1(boo, int(int) ); MOCK_METHOD2(boo, int(int, int) ); }; #define GLOBAL_MOCK_IMPLEMENTATION(MockName)\ struct MockName##_PointerClass\ {\ MockName##_Implementation* mockPointer = nullptr;\ };\ struct MockName##_GlobalObjectMethodImplementation : public MockName##_PointerClass\ GLOBAL_MOCK_IMPLEMENTATION(Serial) { MOCK_GLOBAL_METHOD(int, foo) MOCK_GLOBAL_METHOD(int, boo) }; #define GLOBAL_MOCK_DEFINISIONS(MockName)\ class MockName##_GlobalObject : public Serial_GlobalObjectMethodImplementation\ {\ MockName##_GlobalObject& operator=(const MockName##_GlobalObject& other) = delete;\ MockName##_GlobalObject(const MockName##_GlobalObject& other) = delete;\ \ public:\ MockName##_GlobalObject(){}\ \ static MockName##_GlobalObject& getGlobalInstanceReference()\ {\ static MockName##_GlobalObject globalInstance;\ return globalInstance;\ }\ };\ class MockName##_LocalObject : public Serial_Implementation\ {\ MockName##_GlobalObject& globalObj = MockName##_GlobalObject::getGlobalInstanceReference();\ \ public:\ MockName##_LocalObject()\ {\ EXPECT_EQ(nullptr, globalObj.mockPointer)\ << "Are you trying to instantiate multiple local mock objects in one scope?";\ globalObj.mockPointer = this;\ }\ \ ~MockName##_LocalObject()\ {\ EXPECT_NE(nullptr, globalObj.mockPointer);\ globalObj.mockPointer = nullptr;\ }\ };\ auto& MockName = MockName##_GlobalObject::getGlobalInstanceReference()\ GLOBAL_MOCK_DEFINISIONS(Serial); using ::testing::Return; using ::testing::_; TEST(SomeMock, FirstTest) { Serial_LocalObject obj; EXPECT_CALL(obj, foo()).WillOnce(Return(1) ); EXPECT_CALL(obj, foo(2)).WillOnce(Return(2) ); EXPECT_CALL(obj, foo(3, 3)).WillOnce(Return(3) ); EXPECT_CALL(obj, boo(3, 3)).WillOnce(Return(4) ); EXPECT_EQ(1, Serial.foo()); EXPECT_EQ(2, Serial.foo(2)); EXPECT_EQ(3, Serial.foo(3, 3)); EXPECT_EQ(4, Serial.boo(3, 3)); } TEST(SomeMock, SecondTest) { Serial_LocalObject obj; EXPECT_CALL(obj, foo()).WillOnce(Return(1) ); EXPECT_CALL(obj, foo(2)).WillOnce(Return(2) ); EXPECT_CALL(obj, foo(3, 3)).WillOnce(Return(3) ); EXPECT_EQ(1, Serial.foo()); EXPECT_EQ(2, Serial.foo(2)); EXPECT_EQ(3, Serial.foo(3, 3)); } <|endoftext|>
<commit_before>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2014 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #include "OgreGLES2FrameBufferObject.h" #include "OgreGLES2HardwarePixelBuffer.h" #include "OgreGLES2FBORenderTexture.h" #include "OgreGLES2DepthBuffer.h" #include "OgreGLUtil.h" #include "OgreRoot.h" #include "OgreGLES2RenderSystem.h" #include "OgreGLES2Support.h" namespace Ogre { //----------------------------------------------------------------------------- GLES2FrameBufferObject::GLES2FrameBufferObject(GLES2FBOManager *manager, uint fsaa): mManager(manager), mNumSamples(fsaa) { // Generate framebuffer object OGRE_CHECK_GL_ERROR(glGenFramebuffers(1, &mFB)); if(Root::getSingleton().getRenderSystem()->getCapabilities()->hasCapability(RSC_DEBUG)) { OGRE_CHECK_GL_ERROR(glLabelObjectEXT(GL_FRAMEBUFFER, mFB, 0, ("FBO #" + StringConverter::toString(mFB)).c_str())); } mNumSamples = std::min(mNumSamples, manager->getMaxFSAASamples()); // Will we need a second FBO to do multisampling? if (mNumSamples) { OGRE_CHECK_GL_ERROR(glGenFramebuffers(1, &mMultisampleFB)); if(Root::getSingleton().getRenderSystem()->getCapabilities()->hasCapability(RSC_DEBUG)) { OGRE_CHECK_GL_ERROR(glLabelObjectEXT(GL_FRAMEBUFFER, mMultisampleFB, 0, ("MSAA FBO #" + StringConverter::toString(mMultisampleFB)).c_str())); } } else { mMultisampleFB = 0; } // Initialise state mDepth.buffer = 0; mStencil.buffer = 0; for(size_t x = 0; x < OGRE_MAX_MULTIPLE_RENDER_TARGETS; ++x) { mColour[x].buffer=0; } } GLES2FrameBufferObject::~GLES2FrameBufferObject() { mManager->releaseRenderBuffer(mDepth); mManager->releaseRenderBuffer(mStencil); mManager->releaseRenderBuffer(mMultisampleColourBuffer); // Delete framebuffer object OGRE_CHECK_GL_ERROR(glDeleteFramebuffers(1, &mFB)); if (mMultisampleFB) OGRE_CHECK_GL_ERROR(glDeleteFramebuffers(1, &mMultisampleFB)); } #if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID || OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN void GLES2FrameBufferObject::notifyOnContextLost() { mManager->releaseRenderBuffer(mDepth); mManager->releaseRenderBuffer(mStencil); mManager->releaseRenderBuffer(mMultisampleColourBuffer); OGRE_CHECK_GL_ERROR(glDeleteFramebuffers(1, &mFB)); if (mMultisampleFB) OGRE_CHECK_GL_ERROR(glDeleteFramebuffers(1, &mMultisampleFB)); } void GLES2FrameBufferObject::notifyOnContextReset(const GLES2SurfaceDesc &target) { // Generate framebuffer object OGRE_CHECK_GL_ERROR(glGenFramebuffers(1, &mFB)); OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, mFB)); // Bind target to surface 0 and initialise bindSurface(0, target); } #endif void GLES2FrameBufferObject::bindSurface(size_t attachment, const GLES2SurfaceDesc &target) { assert(attachment < OGRE_MAX_MULTIPLE_RENDER_TARGETS); mColour[attachment] = target; // Re-initialise if(mColour[0].buffer) initialise(); } void GLES2FrameBufferObject::unbindSurface(size_t attachment) { assert(attachment < OGRE_MAX_MULTIPLE_RENDER_TARGETS); mColour[attachment].buffer = 0; // Re-initialise if buffer 0 still bound if(mColour[0].buffer) initialise(); } void GLES2FrameBufferObject::initialise() { // Release depth and stencil, if they were bound mManager->releaseRenderBuffer(mDepth); mManager->releaseRenderBuffer(mStencil); mManager->releaseRenderBuffer(mMultisampleColourBuffer); // First buffer must be bound if(!mColour[0].buffer) { OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Attachment 0 must have surface attached", "GLES2FrameBufferObject::initialise"); } // If we're doing multisampling, then we need another FBO which contains a // renderbuffer which is set up to multisample, and we'll blit it to the final // FBO afterwards to perform the multisample resolve. In that case, the // mMultisampleFB is bound during rendering and is the one with a depth/stencil // Store basic stats uint32 width = mColour[0].buffer->getWidth(); uint32 height = mColour[0].buffer->getHeight(); GLuint format = mColour[0].buffer->getGLFormat(); ushort maxSupportedMRTs = Root::getSingleton().getRenderSystem()->getCapabilities()->getNumMultiRenderTargets(); // Bind simple buffer to add colour attachments OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, mFB)); // Bind all attachment points to frame buffer for(unsigned int x = 0; x < maxSupportedMRTs; ++x) { if(mColour[x].buffer) { if(mColour[x].buffer->getWidth() != width || mColour[x].buffer->getHeight() != height) { StringStream ss; ss << "Attachment " << x << " has incompatible size "; ss << mColour[x].buffer->getWidth() << "x" << mColour[x].buffer->getHeight(); ss << ". It must be of the same as the size of surface 0, "; ss << width << "x" << height; ss << "."; OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, ss.str(), "GLES2FrameBufferObject::initialise"); } if(mColour[x].buffer->getGLFormat() != format) { StringStream ss; ss << "Attachment " << x << " has incompatible format."; OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, ss.str(), "GLES2FrameBufferObject::initialise"); } if(getFormat() == PF_DEPTH) mColour[x].buffer->bindToFramebuffer(GL_DEPTH_ATTACHMENT, mColour[x].zoffset); else mColour[x].buffer->bindToFramebuffer(GL_COLOR_ATTACHMENT0+x, mColour[x].zoffset); } else { // Detach OGRE_CHECK_GL_ERROR(glFramebufferRenderbuffer(GL_FRAMEBUFFER, static_cast<GLenum>(GL_COLOR_ATTACHMENT0+x), GL_RENDERBUFFER, 0)); } } // Now deal with depth / stencil if (mMultisampleFB) { // Bind multisample buffer OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, mMultisampleFB)); // Create AA render buffer (colour) // note, this can be shared too because we blit it to the final FBO // right after the render is finished mMultisampleColourBuffer = mManager->requestRenderBuffer(format, width, height, mNumSamples); // Attach it, because we won't be attaching below and non-multisample has // actually been attached to other FBO mMultisampleColourBuffer.buffer->bindToFramebuffer(GL_COLOR_ATTACHMENT0, mMultisampleColourBuffer.zoffset); // depth & stencil will be dealt with below } // Depth buffer is not handled here anymore. // See GLES2FrameBufferObject::attachDepthBuffer() & RenderSystem::setDepthBufferFor() #if OGRE_NO_GLES3_SUPPORT == 0 GLenum bufs[OGRE_MAX_MULTIPLE_RENDER_TARGETS]; GLsizei n=0; for(unsigned int x=0; x<maxSupportedMRTs; ++x) { // Fill attached colour buffers if(mColour[x].buffer) { if(getFormat() == PF_DEPTH) bufs[x] = GL_DEPTH_ATTACHMENT; else bufs[x] = GL_COLOR_ATTACHMENT0 + x; // Keep highest used buffer + 1 n = x+1; } else { bufs[x] = GL_NONE; } } // Drawbuffer extension supported, use it if(getFormat() != PF_DEPTH) OGRE_CHECK_GL_ERROR(glDrawBuffers(n, bufs)); if (mMultisampleFB) { // we need a read buffer because we'll be blitting to mFB OGRE_CHECK_GL_ERROR(glReadBuffer(bufs[0])); } else { // No read buffer, by default, if we want to read anyway we must not forget to set this. OGRE_CHECK_GL_ERROR(glReadBuffer(GL_NONE)); } #endif // Check status GLuint status; OGRE_CHECK_GL_ERROR(status = glCheckFramebufferStatus(GL_FRAMEBUFFER)); // Bind main buffer #if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS // The screen buffer is 1 on iOS OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, 1)); #else OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, 0)); #endif switch(status) { case GL_FRAMEBUFFER_COMPLETE: // All is good break; case GL_FRAMEBUFFER_UNSUPPORTED: OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "All framebuffer formats with this texture internal format unsupported", "GLES2FrameBufferObject::initialise"); default: OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Framebuffer incomplete or other FBO status error", "GLES2FrameBufferObject::initialise"); } } void GLES2FrameBufferObject::bind() { // Bind it to FBO const GLuint fb = mMultisampleFB ? mMultisampleFB : mFB; OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, fb)); } void GLES2FrameBufferObject::swapBuffers() { if (mMultisampleFB) { #if OGRE_NO_GLES3_SUPPORT == 0 GLint oldfb = 0; OGRE_CHECK_GL_ERROR(glGetIntegerv(GL_FRAMEBUFFER_BINDING, &oldfb)); // Blit from multisample buffer to final buffer, triggers resolve uint32 width = mColour[0].buffer->getWidth(); uint32 height = mColour[0].buffer->getHeight(); OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_READ_FRAMEBUFFER, mMultisampleFB)); OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, mFB)); OGRE_CHECK_GL_ERROR(glBlitFramebuffer(0, 0, width, height, 0, 0, width, height, GL_COLOR_BUFFER_BIT, GL_NEAREST)); // Unbind OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, oldfb)); #endif } } void GLES2FrameBufferObject::attachDepthBuffer( DepthBuffer *depthBuffer ) { GLES2DepthBuffer *glDepthBuffer = static_cast<GLES2DepthBuffer*>(depthBuffer); OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, mMultisampleFB ? mMultisampleFB : mFB )); if( glDepthBuffer ) { GLES2RenderBuffer *depthBuf = glDepthBuffer->getDepthBuffer(); GLES2RenderBuffer *stencilBuf = glDepthBuffer->getStencilBuffer(); //Attach depth buffer, if it has one. if( depthBuf ) depthBuf->bindToFramebuffer( GL_DEPTH_ATTACHMENT, 0 ); //Attach stencil buffer, if it has one. if( stencilBuf ) stencilBuf->bindToFramebuffer( GL_STENCIL_ATTACHMENT, 0 ); } else { OGRE_CHECK_GL_ERROR(glFramebufferRenderbuffer( GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, 0)); OGRE_CHECK_GL_ERROR(glFramebufferRenderbuffer( GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, 0)); } } //----------------------------------------------------------------------------- void GLES2FrameBufferObject::detachDepthBuffer() { OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, mMultisampleFB ? mMultisampleFB : mFB )); OGRE_CHECK_GL_ERROR(glFramebufferRenderbuffer( GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, 0 )); OGRE_CHECK_GL_ERROR(glFramebufferRenderbuffer( GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, 0 )); } uint32 GLES2FrameBufferObject::getWidth() { assert(mColour[0].buffer); return mColour[0].buffer->getWidth(); } uint32 GLES2FrameBufferObject::getHeight() { assert(mColour[0].buffer); return mColour[0].buffer->getHeight(); } PixelFormat GLES2FrameBufferObject::getFormat() { assert(mColour[0].buffer); return mColour[0].buffer->getFormat(); } GLsizei GLES2FrameBufferObject::getFSAA() { return mNumSamples; } //----------------------------------------------------------------------------- } <commit_msg>[GLES2] Call glLabelObjectEXT after binding to avoid GL_INVALID_OPERATION on iOS<commit_after>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2014 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #include "OgreGLES2FrameBufferObject.h" #include "OgreGLES2HardwarePixelBuffer.h" #include "OgreGLES2FBORenderTexture.h" #include "OgreGLES2DepthBuffer.h" #include "OgreGLUtil.h" #include "OgreRoot.h" #include "OgreGLES2RenderSystem.h" #include "OgreGLES2Support.h" namespace Ogre { //----------------------------------------------------------------------------- GLES2FrameBufferObject::GLES2FrameBufferObject(GLES2FBOManager *manager, uint fsaa): mManager(manager), mNumSamples(fsaa) { #if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS GLint oldfb = 0; OGRE_CHECK_GL_ERROR(glGetIntegerv(GL_FRAMEBUFFER_BINDING, &oldfb)); #endif // Generate framebuffer object OGRE_CHECK_GL_ERROR(glGenFramebuffers(1, &mFB)); if(Root::getSingleton().getRenderSystem()->getCapabilities()->hasCapability(RSC_DEBUG)) { #if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, mFB)); // to avoid GL_INVALID_OPERATION in glLabelObjectEXT(GL_FRAMEBUFFER,...) on iOS #endif OGRE_CHECK_GL_ERROR(glLabelObjectEXT(GL_FRAMEBUFFER, mFB, 0, ("FBO #" + StringConverter::toString(mFB)).c_str())); } mNumSamples = std::min(mNumSamples, manager->getMaxFSAASamples()); // Will we need a second FBO to do multisampling? if (mNumSamples) { OGRE_CHECK_GL_ERROR(glGenFramebuffers(1, &mMultisampleFB)); if(Root::getSingleton().getRenderSystem()->getCapabilities()->hasCapability(RSC_DEBUG)) { #if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, mMultisampleFB)); // to avoid GL_INVALID_OPERATION in glLabelObjectEXT(GL_FRAMEBUFFER,...) on iOS #endif OGRE_CHECK_GL_ERROR(glLabelObjectEXT(GL_FRAMEBUFFER, mMultisampleFB, 0, ("MSAA FBO #" + StringConverter::toString(mMultisampleFB)).c_str())); } } else { mMultisampleFB = 0; } #if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, oldfb)); #endif // Initialise state mDepth.buffer = 0; mStencil.buffer = 0; for(size_t x = 0; x < OGRE_MAX_MULTIPLE_RENDER_TARGETS; ++x) { mColour[x].buffer=0; } } GLES2FrameBufferObject::~GLES2FrameBufferObject() { mManager->releaseRenderBuffer(mDepth); mManager->releaseRenderBuffer(mStencil); mManager->releaseRenderBuffer(mMultisampleColourBuffer); // Delete framebuffer object OGRE_CHECK_GL_ERROR(glDeleteFramebuffers(1, &mFB)); if (mMultisampleFB) OGRE_CHECK_GL_ERROR(glDeleteFramebuffers(1, &mMultisampleFB)); } #if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID || OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN void GLES2FrameBufferObject::notifyOnContextLost() { mManager->releaseRenderBuffer(mDepth); mManager->releaseRenderBuffer(mStencil); mManager->releaseRenderBuffer(mMultisampleColourBuffer); OGRE_CHECK_GL_ERROR(glDeleteFramebuffers(1, &mFB)); if (mMultisampleFB) OGRE_CHECK_GL_ERROR(glDeleteFramebuffers(1, &mMultisampleFB)); } void GLES2FrameBufferObject::notifyOnContextReset(const GLES2SurfaceDesc &target) { // Generate framebuffer object OGRE_CHECK_GL_ERROR(glGenFramebuffers(1, &mFB)); OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, mFB)); // Bind target to surface 0 and initialise bindSurface(0, target); } #endif void GLES2FrameBufferObject::bindSurface(size_t attachment, const GLES2SurfaceDesc &target) { assert(attachment < OGRE_MAX_MULTIPLE_RENDER_TARGETS); mColour[attachment] = target; // Re-initialise if(mColour[0].buffer) initialise(); } void GLES2FrameBufferObject::unbindSurface(size_t attachment) { assert(attachment < OGRE_MAX_MULTIPLE_RENDER_TARGETS); mColour[attachment].buffer = 0; // Re-initialise if buffer 0 still bound if(mColour[0].buffer) initialise(); } void GLES2FrameBufferObject::initialise() { // Release depth and stencil, if they were bound mManager->releaseRenderBuffer(mDepth); mManager->releaseRenderBuffer(mStencil); mManager->releaseRenderBuffer(mMultisampleColourBuffer); // First buffer must be bound if(!mColour[0].buffer) { OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Attachment 0 must have surface attached", "GLES2FrameBufferObject::initialise"); } // If we're doing multisampling, then we need another FBO which contains a // renderbuffer which is set up to multisample, and we'll blit it to the final // FBO afterwards to perform the multisample resolve. In that case, the // mMultisampleFB is bound during rendering and is the one with a depth/stencil // Store basic stats uint32 width = mColour[0].buffer->getWidth(); uint32 height = mColour[0].buffer->getHeight(); GLuint format = mColour[0].buffer->getGLFormat(); ushort maxSupportedMRTs = Root::getSingleton().getRenderSystem()->getCapabilities()->getNumMultiRenderTargets(); // Bind simple buffer to add colour attachments OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, mFB)); // Bind all attachment points to frame buffer for(unsigned int x = 0; x < maxSupportedMRTs; ++x) { if(mColour[x].buffer) { if(mColour[x].buffer->getWidth() != width || mColour[x].buffer->getHeight() != height) { StringStream ss; ss << "Attachment " << x << " has incompatible size "; ss << mColour[x].buffer->getWidth() << "x" << mColour[x].buffer->getHeight(); ss << ". It must be of the same as the size of surface 0, "; ss << width << "x" << height; ss << "."; OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, ss.str(), "GLES2FrameBufferObject::initialise"); } if(mColour[x].buffer->getGLFormat() != format) { StringStream ss; ss << "Attachment " << x << " has incompatible format."; OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, ss.str(), "GLES2FrameBufferObject::initialise"); } if(getFormat() == PF_DEPTH) mColour[x].buffer->bindToFramebuffer(GL_DEPTH_ATTACHMENT, mColour[x].zoffset); else mColour[x].buffer->bindToFramebuffer(GL_COLOR_ATTACHMENT0+x, mColour[x].zoffset); } else { // Detach OGRE_CHECK_GL_ERROR(glFramebufferRenderbuffer(GL_FRAMEBUFFER, static_cast<GLenum>(GL_COLOR_ATTACHMENT0+x), GL_RENDERBUFFER, 0)); } } // Now deal with depth / stencil if (mMultisampleFB) { // Bind multisample buffer OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, mMultisampleFB)); // Create AA render buffer (colour) // note, this can be shared too because we blit it to the final FBO // right after the render is finished mMultisampleColourBuffer = mManager->requestRenderBuffer(format, width, height, mNumSamples); // Attach it, because we won't be attaching below and non-multisample has // actually been attached to other FBO mMultisampleColourBuffer.buffer->bindToFramebuffer(GL_COLOR_ATTACHMENT0, mMultisampleColourBuffer.zoffset); // depth & stencil will be dealt with below } // Depth buffer is not handled here anymore. // See GLES2FrameBufferObject::attachDepthBuffer() & RenderSystem::setDepthBufferFor() #if OGRE_NO_GLES3_SUPPORT == 0 GLenum bufs[OGRE_MAX_MULTIPLE_RENDER_TARGETS]; GLsizei n=0; for(unsigned int x=0; x<maxSupportedMRTs; ++x) { // Fill attached colour buffers if(mColour[x].buffer) { if(getFormat() == PF_DEPTH) bufs[x] = GL_DEPTH_ATTACHMENT; else bufs[x] = GL_COLOR_ATTACHMENT0 + x; // Keep highest used buffer + 1 n = x+1; } else { bufs[x] = GL_NONE; } } // Drawbuffer extension supported, use it if(getFormat() != PF_DEPTH) OGRE_CHECK_GL_ERROR(glDrawBuffers(n, bufs)); if (mMultisampleFB) { // we need a read buffer because we'll be blitting to mFB OGRE_CHECK_GL_ERROR(glReadBuffer(bufs[0])); } else { // No read buffer, by default, if we want to read anyway we must not forget to set this. OGRE_CHECK_GL_ERROR(glReadBuffer(GL_NONE)); } #endif // Check status GLuint status; OGRE_CHECK_GL_ERROR(status = glCheckFramebufferStatus(GL_FRAMEBUFFER)); // Bind main buffer #if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS // The screen buffer is 1 on iOS OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, 1)); #else OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, 0)); #endif switch(status) { case GL_FRAMEBUFFER_COMPLETE: // All is good break; case GL_FRAMEBUFFER_UNSUPPORTED: OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "All framebuffer formats with this texture internal format unsupported", "GLES2FrameBufferObject::initialise"); default: OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Framebuffer incomplete or other FBO status error", "GLES2FrameBufferObject::initialise"); } } void GLES2FrameBufferObject::bind() { // Bind it to FBO const GLuint fb = mMultisampleFB ? mMultisampleFB : mFB; OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, fb)); } void GLES2FrameBufferObject::swapBuffers() { if (mMultisampleFB) { #if OGRE_NO_GLES3_SUPPORT == 0 GLint oldfb = 0; OGRE_CHECK_GL_ERROR(glGetIntegerv(GL_FRAMEBUFFER_BINDING, &oldfb)); // Blit from multisample buffer to final buffer, triggers resolve uint32 width = mColour[0].buffer->getWidth(); uint32 height = mColour[0].buffer->getHeight(); OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_READ_FRAMEBUFFER, mMultisampleFB)); OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, mFB)); OGRE_CHECK_GL_ERROR(glBlitFramebuffer(0, 0, width, height, 0, 0, width, height, GL_COLOR_BUFFER_BIT, GL_NEAREST)); // Unbind OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, oldfb)); #endif } } void GLES2FrameBufferObject::attachDepthBuffer( DepthBuffer *depthBuffer ) { GLES2DepthBuffer *glDepthBuffer = static_cast<GLES2DepthBuffer*>(depthBuffer); OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, mMultisampleFB ? mMultisampleFB : mFB )); if( glDepthBuffer ) { GLES2RenderBuffer *depthBuf = glDepthBuffer->getDepthBuffer(); GLES2RenderBuffer *stencilBuf = glDepthBuffer->getStencilBuffer(); //Attach depth buffer, if it has one. if( depthBuf ) depthBuf->bindToFramebuffer( GL_DEPTH_ATTACHMENT, 0 ); //Attach stencil buffer, if it has one. if( stencilBuf ) stencilBuf->bindToFramebuffer( GL_STENCIL_ATTACHMENT, 0 ); } else { OGRE_CHECK_GL_ERROR(glFramebufferRenderbuffer( GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, 0)); OGRE_CHECK_GL_ERROR(glFramebufferRenderbuffer( GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, 0)); } } //----------------------------------------------------------------------------- void GLES2FrameBufferObject::detachDepthBuffer() { OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, mMultisampleFB ? mMultisampleFB : mFB )); OGRE_CHECK_GL_ERROR(glFramebufferRenderbuffer( GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, 0 )); OGRE_CHECK_GL_ERROR(glFramebufferRenderbuffer( GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, 0 )); } uint32 GLES2FrameBufferObject::getWidth() { assert(mColour[0].buffer); return mColour[0].buffer->getWidth(); } uint32 GLES2FrameBufferObject::getHeight() { assert(mColour[0].buffer); return mColour[0].buffer->getHeight(); } PixelFormat GLES2FrameBufferObject::getFormat() { assert(mColour[0].buffer); return mColour[0].buffer->getFormat(); } GLsizei GLES2FrameBufferObject::getFSAA() { return mNumSamples; } //----------------------------------------------------------------------------- } <|endoftext|>
<commit_before><?hh // strict /** * @copyright 2010-2015, The Titon Project * @license http://opensource.org/licenses/bsd-license.php * @link http://titon.io */ namespace Titon\Kernel; use Titon\Event\EmitsEvents; use Titon\Event\Subject; use Titon\Kernel\Event\ShutdownEvent; use Titon\Kernel\Event\StartupEvent; use Titon\Kernel\Event\TerminateEvent; use Titon\Kernel\Middleware\Pipeline; /** * The AbstractKernel is the base kernel implementation that handles the middleware pipeline process. * All child kernels must implement the `handle()` method to customize the input and output handling process. * * @package Titon\Kernel */ abstract class AbstractKernel<Ta as Application, Ti as Input, To as Output> implements Kernel<Ta, Ti, To>, Subject { use EmitsEvents; /** * The current application. * * @var \Titon\Kernel\Application */ protected Ta $app; /** * The CLI exit code to terminate with. * * @var int */ protected int $exitCode = 0; /** * The contextual input object. * * @var \Titon\Kernel\Input */ protected ?Ti $input; /** * The contextual output object. * * @var \Titon\Kernel\Output */ protected ?To $output; /** * Pipeline to manage middleware. * * @var \Titon\Kernel\Middleware\Pipeline */ protected Pipeline<Ti, To> $pipeline; /** * The time the execution started. * * @var float */ protected float $startTime; /** * Instantiate a new application and pipeline. * * @param \Titon\Kernel\Application $app * @param \Titon\Kernel\Middleware\Pipeline $pipeline */ public function __construct(Ta $app, Pipeline<Ti, To> $pipeline) { $this->app = $app; $this->pipeline = $pipeline; $this->startTime = microtime(true); } /** * {@inheritdoc} */ public function getApplication(): Ta { return $this->app; } /** * Return the total time it took to execute up to this point. * * @return float */ public function getExecutionTime(): float { return microtime(true) - $this->getStartTime(); } /** * {@inheritdoc} */ public function getInput(): ?Ti { return $this->input; } /** * {@inheritdoc} */ public function getOutput(): ?To { return $this->output; } /** * Return the execution start time. * * @return float */ public function getStartTime(): float { return $this->startTime; } /** * {@inheritdoc} */ public function pipe(Middleware<Ti, To> $middleware): this { $this->pipeline->through($middleware); return $this; } /** * {@inheritdoc} */ final public function run(Ti $input, To $output): To { $this->input = $input; $this->output = $output; // Emit startup events $this->startup(); // Since the kernel itself is middleware, add the kernel as the last item in the pipeline. // This allows the `handle()` method to be ran after all other middleware. $this->pipe($this); // Handle the middleware pipeline stack $this->output = $output = $this->pipeline->handle($input, $output); // Emit shutdown events $this->shutdown(); return $output; } /** * {@inheritdoc} */ public function terminate(): void { $input = $this->getInput(); $output = $this->getOutput(); invariant($input !== null && $output !== null, 'Input and Output must not be null.'); $this->emit(new TerminateEvent($this, $input, $output)); exit($this->exitCode); } /** * Triggered after the pipeline is handled but before the output is sent. */ protected function shutdown(): void { $input = $this->getInput(); $output = $this->getOutput(); invariant($input !== null && $output !== null, 'Input and Output must not be null.'); $this->emit(new ShutdownEvent($this, $input, $output)); } /** * Triggered before the pipeline is handled. */ protected function startup(): void { $input = $this->getInput(); $output = $this->getOutput(); invariant($input !== null && $output !== null, 'Input and Output must not be null.'); $this->emit(new StartupEvent($this, $input, $output)); } } <commit_msg>Made the kernel pipeline optional.<commit_after><?hh // strict /** * @copyright 2010-2015, The Titon Project * @license http://opensource.org/licenses/bsd-license.php * @link http://titon.io */ namespace Titon\Kernel; use Titon\Event\EmitsEvents; use Titon\Event\Subject; use Titon\Kernel\Event\ShutdownEvent; use Titon\Kernel\Event\StartupEvent; use Titon\Kernel\Event\TerminateEvent; use Titon\Kernel\Middleware\Pipeline; /** * The AbstractKernel is the base kernel implementation that handles the middleware pipeline process. * All child kernels must implement the `handle()` method to customize the input and output handling process. * * @package Titon\Kernel */ abstract class AbstractKernel<Ta as Application, Ti as Input, To as Output> implements Kernel<Ta, Ti, To>, Subject { use EmitsEvents; /** * The current application. * * @var \Titon\Kernel\Application */ protected Ta $app; /** * The CLI exit code to terminate with. * * @var int */ protected int $exitCode = 0; /** * The contextual input object. * * @var \Titon\Kernel\Input */ protected ?Ti $input; /** * The contextual output object. * * @var \Titon\Kernel\Output */ protected ?To $output; /** * Pipeline to manage middleware. * * @var \Titon\Kernel\Middleware\Pipeline */ protected Pipeline<Ti, To> $pipeline; /** * The time the execution started. * * @var float */ protected float $startTime; /** * Instantiate a new application and pipeline. * * @param \Titon\Kernel\Application $app * @param \Titon\Kernel\Middleware\Pipeline $pipeline */ public function __construct(Ta $app, Pipeline<Ti, To> $pipeline = null) { if ($pipeline === null) { $pipeline = new Pipeline(); } $this->app = $app; $this->pipeline = $pipeline; $this->startTime = microtime(true); } /** * {@inheritdoc} */ public function getApplication(): Ta { return $this->app; } /** * Return the total time it took to execute up to this point. * * @return float */ public function getExecutionTime(): float { return microtime(true) - $this->getStartTime(); } /** * {@inheritdoc} */ public function getInput(): ?Ti { return $this->input; } /** * {@inheritdoc} */ public function getOutput(): ?To { return $this->output; } /** * Return the execution start time. * * @return float */ public function getStartTime(): float { return $this->startTime; } /** * {@inheritdoc} */ public function pipe(Middleware<Ti, To> $middleware): this { $this->pipeline->through($middleware); return $this; } /** * {@inheritdoc} */ final public function run(Ti $input, To $output): To { $this->input = $input; $this->output = $output; // Emit startup events $this->startup(); // Since the kernel itself is middleware, add the kernel as the last item in the pipeline. // This allows the `handle()` method to be ran after all other middleware. $this->pipe($this); // Handle the middleware pipeline stack $this->output = $output = $this->pipeline->handle($input, $output); // Emit shutdown events $this->shutdown(); return $output; } /** * {@inheritdoc} */ public function terminate(): void { $input = $this->getInput(); $output = $this->getOutput(); invariant($input !== null && $output !== null, 'Input and Output must not be null.'); $this->emit(new TerminateEvent($this, $input, $output)); exit($this->exitCode); } /** * Triggered after the pipeline is handled but before the output is sent. */ protected function shutdown(): void { $input = $this->getInput(); $output = $this->getOutput(); invariant($input !== null && $output !== null, 'Input and Output must not be null.'); $this->emit(new ShutdownEvent($this, $input, $output)); } /** * Triggered before the pipeline is handled. */ protected function startup(): void { $input = $this->getInput(); $output = $this->getOutput(); invariant($input !== null && $output !== null, 'Input and Output must not be null.'); $this->emit(new StartupEvent($this, $input, $output)); } } <|endoftext|>
<commit_before>// // CACheckbox.cpp // CrossApp // // Created by Li Yuanfeng on 14-3-23. // Copyright (c) 2014 http://9miao.com All rights reserved. // #include "CACheckbox.h" #include "view/CAScale9ImageView.h" #include "view/CAView.h" #include "view/CAScrollView.h" #include "dispatcher/CATouch.h" #include "basics/CAPointExtension.h" #include "cocoa/CCSet.h" #include "view/CALabel.h" #include "basics/CAApplication.h" #include "basics/CAScheduler.h" #include "animation/CAViewAnimation.h" #include "support/CAThemeManager.h" #include "support/ccUtils.h" NS_CC_BEGIN CACheckbox::CACheckbox() :m_pImageView(nullptr) ,m_pLabel(nullptr) ,m_sTitleFontName("") ,m_fTitleFontSize(0) ,m_bTitleBold(false) ,m_pTitleLabelSize(DSizeZero) ,m_bDefineTitleLabelSize(false) ,m_pImageSize(DSizeZero) ,m_bDefineImageSize(false) ,m_pTitleOffset(DSizeZero) ,m_bDefineTitleOffset(false) ,m_pImageOffset(DSizeZero) ,m_bDefineImageOffset(false) ,m_pImageNormal(nullptr) ,m_pImageSelected(nullptr) ,m_cImageColorNormal(CAColor_white) ,m_cImageColorSelected(CAColor_white) ,m_cTitleColorNormal(CAColor_white) ,m_cTitleColorSelected(CAColor_white) ,m_bIsOn(false) { m_pImageView = new CAImageView(); m_pImageView->init(); this->insertSubview(m_pImageView, 1); m_pLabel = new CALabel(); m_pLabel->init(); m_pLabel->setTextAlignment(CATextAlignment::Left); m_pLabel->setVerticalTextAlignmet(CAVerticalTextAlignment::Center); m_pLabel->setNumberOfLine(1); this->insertSubview(m_pLabel, 1); } CACheckbox::~CACheckbox(void) { CC_SAFE_RELEASE_NULL(m_pImageView); CC_SAFE_RELEASE_NULL(m_pLabel); CC_SAFE_RELEASE_NULL(m_pImageNormal); CC_SAFE_RELEASE_NULL(m_pImageSelected); } CACheckbox* CACheckbox::create() { CACheckbox* btn = new CACheckbox(); if (btn && btn->init()) { btn->autorelease(); return btn; } CC_SAFE_DELETE(btn); return NULL; } CACheckbox* CACheckbox::createWithFrame(const DRect& rect) { CACheckbox* btn = new CACheckbox(); if (btn && btn->initWithFrame(rect)) { btn->autorelease(); return btn; } CC_SAFE_DELETE(btn); return NULL; } CACheckbox* CACheckbox::createWithCenter(const DRect& rect) { CACheckbox* btn = new CACheckbox(); if (btn && btn->initWithCenter(rect)) { btn->autorelease(); return btn; } CC_SAFE_DELETE(btn); return NULL; } CACheckbox* CACheckbox::createWithLayout(const CrossApp::DLayout &layout) { CACheckbox* btn = new CACheckbox(); if (btn && btn->initWithLayout(layout)) { btn->autorelease(); return btn; } CC_SAFE_DELETE(btn); return NULL; } bool CACheckbox::init() { if (!CAControl::init()) { return false; } return true; } void CACheckbox::onExitTransitionDidStart() { CAControl::onExitTransitionDidStart(); } void CACheckbox::onEnterTransitionDidFinish() { CAControl::onEnterTransitionDidFinish(); this->updateCheckboxState(); } void CACheckbox::setImageStateNormal(CAImage* var) { CC_SAFE_RETAIN(var); CC_SAFE_RETAIN(m_pImageNormal); m_pImageNormal = var; this->updateCheckboxState(); } CAImage* CACheckbox::getImageStateNormal() { return m_pImageNormal; } void CACheckbox::setImageStateSelected(CAImage* var) { CC_SAFE_RETAIN(var); CC_SAFE_RETAIN(m_pImageSelected); m_pImageSelected = var; this->updateCheckboxState(); } CAImage* CACheckbox::getImageStateSelected() { return m_pImageSelected; } void CACheckbox::setTitleStateNormal(const std::string& var) { m_sTitleNormal = var; this->updateCheckboxState(); } const std::string& CACheckbox::getTitleStateNormal() { return m_sTitleNormal; } void CACheckbox::setTitleStateSelected(const std::string& var) { m_sTitleSelected = var; this->updateCheckboxState(); } const std::string& CACheckbox::getTitleStateSelected() { return m_sTitleSelected; } void CACheckbox::setImageColorStateNormal(const CAColor4B& var) { m_cImageColorNormal = var; this->updateCheckboxState(); } void CACheckbox::setImageColorStateSelected(const CAColor4B& var) { m_cImageColorSelected = var; this->updateCheckboxState(); } void CACheckbox::setTitleColorStateNormal(const CAColor4B& var) { m_cTitleColorNormal = var; this->updateCheckboxState(); } void CACheckbox::setTitleColorStateSelected(const CAColor4B& var) { m_cTitleColorSelected = var; this->updateCheckboxState(); } void CACheckbox::setTitleFontName(const std::string& var) { if (m_sTitleFontName.compare(var)) { m_sTitleFontName = var; m_pLabel->setFontName(m_sTitleFontName.c_str()); this->updateCheckboxState(); } } void CACheckbox::setImageOffset(const DSize& offset) { m_bDefineImageOffset = true; m_pImageOffset = offset; DRect rect = m_pImageView->getCenter(); rect.origin = m_obContentSize/2; rect.origin.x += offset.width; rect.origin.y += offset.height; m_pImageView->setCenter(rect); } void CACheckbox::setImageSize(const DSize& size) { m_bDefineImageSize = true; m_pImageSize = size; DRect rect = m_pImageView->getCenter(); rect.size = m_pImageSize; m_pImageView->setCenter(rect); } void CACheckbox::setTitleOffset(const DSize& offset) { m_bDefineTitleOffset = true; m_pTitleOffset = offset; DRect rect = m_pLabel->getCenter(); rect.origin = m_obContentSize/2; rect.origin.x += offset.width; rect.origin.y += offset.height; m_pLabel->setCenter(rect); } void CACheckbox::setTitleLabelSize(const DSize& size) { m_bDefineTitleLabelSize= true; m_pTitleLabelSize = size; DRect rect = m_pLabel->getCenter(); rect.size = m_pTitleLabelSize; m_pLabel->setCenter(rect); } void CACheckbox::setTitleFontSize(float fontSize) { m_fTitleFontSize = fontSize; m_pLabel->setFontSize(m_fTitleFontSize); } void CACheckbox::setTitleBold(bool bold) { m_bTitleBold = bold; m_pLabel->setBold(bold); } void CACheckbox::setTitleTextAlignment(const CATextAlignment& var) { m_pLabel->setTextAlignment(var); } void CACheckbox::setTarget(const std::function<void(bool on)>& function) { m_function = function; } void CACheckbox::setIsOn(bool on) { if (m_bIsOn != on) { m_bIsOn = on; this->updateCheckboxState(); } } bool CACheckbox::isOn() { return m_bIsOn; } void CACheckbox::updateWithPreferredSize() { if (m_fTitleFontSize < FLT_EPSILON) { m_pLabel->setFontSize(this->getBounds().size.height * 0.667f); } } bool CACheckbox::ccTouchBegan(CrossApp::CATouch *pTouch, CrossApp::CAEvent *pEvent) { DPoint point = pTouch->getLocation(); point = this->convertToNodeSpace(point); this->setHighlightedState(true); return true; } void CACheckbox::ccTouchMoved(CrossApp::CATouch *pTouch, CrossApp::CAEvent *pEvent) { DPoint point = pTouch->getLocation(); point = this->convertToNodeSpace(point); if (getBounds().containsPoint(point)) { this->setHighlightedState(true); } else { this->setHighlightedState(false); } } void CACheckbox::ccTouchEnded(CrossApp::CATouch *pTouch, CrossApp::CAEvent *pEvent) { DPoint point = pTouch->getLocation(); point = this->convertToNodeSpace(point); this->setHighlightedState(false); bool on = !m_bIsOn; if (getBounds().containsPoint(point)) { on = !m_bIsOn; } else { on = m_bIsOn; } if (on != m_bIsOn) { this->setIsOn(on); if (m_function) { m_function(m_bIsOn); } } } void CACheckbox::ccTouchCancelled(CrossApp::CATouch *pTouch, CrossApp::CAEvent *pEvent) { this->setHighlightedState(false); } void CACheckbox::setHighlightedState(bool var) { CAColor4B imageColor = m_bIsOn ? m_cImageColorSelected : m_cImageColorNormal; CAColor4B titleColor = m_bIsOn ? m_cTitleColorSelected : m_cTitleColorNormal; if (var) { imageColor = ccc4Mult(imageColor, 0.9f); titleColor = ccc4Mult(titleColor, 0.9f); } m_pImageView->setColor(imageColor); m_pLabel->setColor(titleColor); } void CACheckbox::updateCheckboxState() { CC_RETURN_IF(!m_bRunning); DRect imageViewCenter = DRectZero; DRect rect = DRectZero; DRect labelCenter = this->getBounds(); float labelSize = 0; CAImage* image = (m_bIsOn && m_pImageSelected) ? m_pImageSelected : m_pImageNormal; const std::string& title = (m_bIsOn && !m_sTitleSelected.empty()) ? m_sTitleSelected : m_sTitleNormal; if (image && title.length() == 0) { DSize size = this->getBounds().size; DSize iSize = image->getContentSize(); float scaleX = size.width / iSize.width * 0.8f; float scaleY = size.height / iSize.height * 0.8f; float scale = MIN(scaleX, scaleY); iSize = ccpMult(iSize, scale); imageViewCenter.origin = size / 2; imageViewCenter.size = iSize; } else if (!image && title.length() > 0) { labelSize = m_obContentSize.height * 0.8f; labelCenter.size = m_obContentSize; labelCenter.origin.x = m_obContentSize.width * 0.5f; labelCenter.origin.y = m_obContentSize.height * 0.425f; } else if (image && title.length() > 0) { DSize size = m_obContentSize; DSize iSize = image->getContentSize(); float scaleX = size.width / iSize.width * 0.8f; float scaleY = size.height / iSize.height * 0.8f; float scale = MIN(scaleX, scaleY); iSize = ccpMult(iSize, scale); imageViewCenter.size = iSize; imageViewCenter.origin.x = iSize.width * 0.5f + 10; imageViewCenter.origin.y = size.height * 0.5f; labelSize = size.height * 0.8f; labelCenter.size.width = m_obContentSize.width - iSize.width - 30; labelCenter.size.height = m_obContentSize.height; labelCenter.origin.x = iSize.width + 20 + labelCenter.size.width /2; labelCenter.origin.y = size.height * 0.425f; } if (!title.empty()) { if (m_bDefineTitleLabelSize) { labelCenter.size = m_pTitleLabelSize; } if(m_bDefineTitleOffset) { labelCenter.origin = ccpMult(m_obContentSize, 0.5f); labelCenter.origin = ccpAdd(labelCenter.origin, m_pTitleOffset); } m_pLabel->setCenter(labelCenter); if(m_fTitleFontSize == 0) { m_fTitleFontSize = labelSize; } m_pLabel->setFontSize(m_fTitleFontSize); m_pLabel->setColor(m_bIsOn ? m_cTitleColorSelected : m_cTitleColorNormal); } if (strcmp(title.c_str(), m_pLabel->getText().c_str())) { m_pLabel->setText(title.c_str()); } if (image) { m_pImageView->setColor(m_bIsOn ? m_cImageColorSelected : m_cImageColorNormal); if (m_bDefineImageSize) { imageViewCenter.size = m_pImageSize; } if (m_bDefineImageOffset) { imageViewCenter.origin = ccpMult(m_obContentSize, 0.5f); imageViewCenter.origin = ccpAdd(imageViewCenter.origin, m_pImageOffset); } m_pImageView->setCenter(imageViewCenter); } if (image != m_pImageView->getImage()) { m_pImageView->setImage(image); } } void CACheckbox::setContentSize(const DSize & var) { DSize size = var; // if (m_bRecSpe) // { // const CAThemeManager::stringMap& map = CAApplication::getApplication()->getThemeManager()->getThemeMap(""); // int h = atoi(map.at("height").c_str()); // size.height = (h == 0) ? size.height : h; // } CAView::setContentSize(size); this->updateWithPreferredSize(); this->updateCheckboxState(); } NS_CC_END <commit_msg>no message<commit_after>// // CACheckbox.cpp // CrossApp // // Created by Li Yuanfeng on 14-3-23. // Copyright (c) 2014 http://9miao.com All rights reserved. // #include "CACheckbox.h" #include "view/CAScale9ImageView.h" #include "view/CAView.h" #include "view/CAScrollView.h" #include "dispatcher/CATouch.h" #include "basics/CAPointExtension.h" #include "cocoa/CCSet.h" #include "view/CALabel.h" #include "basics/CAApplication.h" #include "basics/CAScheduler.h" #include "animation/CAViewAnimation.h" #include "support/CAThemeManager.h" #include "support/ccUtils.h" NS_CC_BEGIN CACheckbox::CACheckbox() :m_pImageView(nullptr) ,m_pLabel(nullptr) ,m_sTitleFontName("") ,m_fTitleFontSize(0) ,m_bTitleBold(false) ,m_pTitleLabelSize(DSizeZero) ,m_bDefineTitleLabelSize(false) ,m_pImageSize(DSizeZero) ,m_bDefineImageSize(false) ,m_pTitleOffset(DSizeZero) ,m_bDefineTitleOffset(false) ,m_pImageOffset(DSizeZero) ,m_bDefineImageOffset(false) ,m_pImageNormal(nullptr) ,m_pImageSelected(nullptr) ,m_cImageColorNormal(CAColor_white) ,m_cImageColorSelected(CAColor_white) ,m_cTitleColorNormal(CAColor_white) ,m_cTitleColorSelected(CAColor_white) ,m_bIsOn(false) { m_pImageView = new CAImageView(); m_pImageView->init(); this->insertSubview(m_pImageView, 1); m_pLabel = new CALabel(); m_pLabel->init(); m_pLabel->setTextAlignment(CATextAlignment::Left); m_pLabel->setVerticalTextAlignmet(CAVerticalTextAlignment::Center); m_pLabel->setNumberOfLine(1); this->insertSubview(m_pLabel, 1); const CAThemeManager::stringMap& map = CAApplication::getApplication()->getThemeManager()->getThemeMap("CACheckbox"); this->setImageStateNormal(CAImage::create(map.at("checkbox_image_normal"))); this->setImageStateSelected(CAImage::create(map.at("checkbox_image_selected"))); } CACheckbox::~CACheckbox(void) { CC_SAFE_RELEASE_NULL(m_pImageView); CC_SAFE_RELEASE_NULL(m_pLabel); CC_SAFE_RELEASE_NULL(m_pImageNormal); CC_SAFE_RELEASE_NULL(m_pImageSelected); } CACheckbox* CACheckbox::create() { CACheckbox* btn = new CACheckbox(); if (btn && btn->init()) { btn->autorelease(); return btn; } CC_SAFE_DELETE(btn); return NULL; } CACheckbox* CACheckbox::createWithFrame(const DRect& rect) { CACheckbox* btn = new CACheckbox(); if (btn && btn->initWithFrame(rect)) { btn->autorelease(); return btn; } CC_SAFE_DELETE(btn); return NULL; } CACheckbox* CACheckbox::createWithCenter(const DRect& rect) { CACheckbox* btn = new CACheckbox(); if (btn && btn->initWithCenter(rect)) { btn->autorelease(); return btn; } CC_SAFE_DELETE(btn); return NULL; } CACheckbox* CACheckbox::createWithLayout(const CrossApp::DLayout &layout) { CACheckbox* btn = new CACheckbox(); if (btn && btn->initWithLayout(layout)) { btn->autorelease(); return btn; } CC_SAFE_DELETE(btn); return NULL; } bool CACheckbox::init() { if (!CAControl::init()) { return false; } return true; } void CACheckbox::onExitTransitionDidStart() { CAControl::onExitTransitionDidStart(); } void CACheckbox::onEnterTransitionDidFinish() { CAControl::onEnterTransitionDidFinish(); this->updateCheckboxState(); } void CACheckbox::setImageStateNormal(CAImage* var) { CC_SAFE_RETAIN(var); CC_SAFE_RETAIN(m_pImageNormal); m_pImageNormal = var; this->updateCheckboxState(); } CAImage* CACheckbox::getImageStateNormal() { return m_pImageNormal; } void CACheckbox::setImageStateSelected(CAImage* var) { CC_SAFE_RETAIN(var); CC_SAFE_RETAIN(m_pImageSelected); m_pImageSelected = var; this->updateCheckboxState(); } CAImage* CACheckbox::getImageStateSelected() { return m_pImageSelected; } void CACheckbox::setTitleStateNormal(const std::string& var) { m_sTitleNormal = var; this->updateCheckboxState(); } const std::string& CACheckbox::getTitleStateNormal() { return m_sTitleNormal; } void CACheckbox::setTitleStateSelected(const std::string& var) { m_sTitleSelected = var; this->updateCheckboxState(); } const std::string& CACheckbox::getTitleStateSelected() { return m_sTitleSelected; } void CACheckbox::setImageColorStateNormal(const CAColor4B& var) { m_cImageColorNormal = var; this->updateCheckboxState(); } void CACheckbox::setImageColorStateSelected(const CAColor4B& var) { m_cImageColorSelected = var; this->updateCheckboxState(); } void CACheckbox::setTitleColorStateNormal(const CAColor4B& var) { m_cTitleColorNormal = var; this->updateCheckboxState(); } void CACheckbox::setTitleColorStateSelected(const CAColor4B& var) { m_cTitleColorSelected = var; this->updateCheckboxState(); } void CACheckbox::setTitleFontName(const std::string& var) { if (m_sTitleFontName.compare(var)) { m_sTitleFontName = var; m_pLabel->setFontName(m_sTitleFontName.c_str()); this->updateCheckboxState(); } } void CACheckbox::setImageOffset(const DSize& offset) { m_bDefineImageOffset = true; m_pImageOffset = offset; DRect rect = m_pImageView->getCenter(); rect.origin = m_obContentSize/2; rect.origin.x += offset.width; rect.origin.y += offset.height; m_pImageView->setCenter(rect); } void CACheckbox::setImageSize(const DSize& size) { m_bDefineImageSize = true; m_pImageSize = size; DRect rect = m_pImageView->getCenter(); rect.size = m_pImageSize; m_pImageView->setCenter(rect); } void CACheckbox::setTitleOffset(const DSize& offset) { m_bDefineTitleOffset = true; m_pTitleOffset = offset; DRect rect = m_pLabel->getCenter(); rect.origin = m_obContentSize/2; rect.origin.x += offset.width; rect.origin.y += offset.height; m_pLabel->setCenter(rect); } void CACheckbox::setTitleLabelSize(const DSize& size) { m_bDefineTitleLabelSize= true; m_pTitleLabelSize = size; DRect rect = m_pLabel->getCenter(); rect.size = m_pTitleLabelSize; m_pLabel->setCenter(rect); } void CACheckbox::setTitleFontSize(float fontSize) { m_fTitleFontSize = fontSize; m_pLabel->setFontSize(m_fTitleFontSize); } void CACheckbox::setTitleBold(bool bold) { m_bTitleBold = bold; m_pLabel->setBold(bold); } void CACheckbox::setTitleTextAlignment(const CATextAlignment& var) { m_pLabel->setTextAlignment(var); } void CACheckbox::setTarget(const std::function<void(bool on)>& function) { m_function = function; } void CACheckbox::setIsOn(bool on) { if (m_bIsOn != on) { m_bIsOn = on; this->updateCheckboxState(); } } bool CACheckbox::isOn() { return m_bIsOn; } void CACheckbox::updateWithPreferredSize() { if (m_fTitleFontSize < FLT_EPSILON) { m_pLabel->setFontSize(this->getBounds().size.height * 0.667f); } } bool CACheckbox::ccTouchBegan(CrossApp::CATouch *pTouch, CrossApp::CAEvent *pEvent) { DPoint point = pTouch->getLocation(); point = this->convertToNodeSpace(point); this->setHighlightedState(true); return true; } void CACheckbox::ccTouchMoved(CrossApp::CATouch *pTouch, CrossApp::CAEvent *pEvent) { DPoint point = pTouch->getLocation(); point = this->convertToNodeSpace(point); if (getBounds().containsPoint(point)) { this->setHighlightedState(true); } else { this->setHighlightedState(false); } } void CACheckbox::ccTouchEnded(CrossApp::CATouch *pTouch, CrossApp::CAEvent *pEvent) { DPoint point = pTouch->getLocation(); point = this->convertToNodeSpace(point); this->setHighlightedState(false); bool on = !m_bIsOn; if (getBounds().containsPoint(point)) { on = !m_bIsOn; } else { on = m_bIsOn; } if (on != m_bIsOn) { this->setIsOn(on); if (m_function) { m_function(m_bIsOn); } } } void CACheckbox::ccTouchCancelled(CrossApp::CATouch *pTouch, CrossApp::CAEvent *pEvent) { this->setHighlightedState(false); } void CACheckbox::setHighlightedState(bool var) { CAColor4B imageColor = m_bIsOn ? m_cImageColorSelected : m_cImageColorNormal; CAColor4B titleColor = m_bIsOn ? m_cTitleColorSelected : m_cTitleColorNormal; if (var) { imageColor = ccc4Mult(imageColor, 0.9f); titleColor = ccc4Mult(titleColor, 0.9f); } m_pImageView->setColor(imageColor); m_pLabel->setColor(titleColor); } void CACheckbox::updateCheckboxState() { CC_RETURN_IF(!m_bRunning); DRect imageViewCenter = DRectZero; DRect rect = DRectZero; DRect labelCenter = this->getBounds(); float labelSize = 0; CAImage* image = (m_bIsOn && m_pImageSelected) ? m_pImageSelected : m_pImageNormal; const std::string& title = (m_bIsOn && !m_sTitleSelected.empty()) ? m_sTitleSelected : m_sTitleNormal; if (image && title.length() == 0) { DSize size = this->getBounds().size; DSize iSize = image->getContentSize(); float scaleX = size.width / iSize.width * 0.8f; float scaleY = size.height / iSize.height * 0.8f; float scale = MIN(scaleX, scaleY); iSize = ccpMult(iSize, scale); imageViewCenter.origin = size / 2; imageViewCenter.size = iSize; } else if (!image && title.length() > 0) { labelSize = m_obContentSize.height * 0.8f; labelCenter.size = m_obContentSize; labelCenter.origin.x = m_obContentSize.width * 0.5f; labelCenter.origin.y = m_obContentSize.height * 0.425f; } else if (image && title.length() > 0) { DSize size = m_obContentSize; DSize iSize = image->getContentSize(); float scaleX = size.width / iSize.width * 0.8f; float scaleY = size.height / iSize.height * 0.8f; float scale = MIN(scaleX, scaleY); iSize = ccpMult(iSize, scale); imageViewCenter.size = iSize; imageViewCenter.origin.x = iSize.width * 0.5f + 10; imageViewCenter.origin.y = size.height * 0.5f; labelSize = size.height * 0.8f; labelCenter.size.width = m_obContentSize.width - iSize.width - 30; labelCenter.size.height = m_obContentSize.height; labelCenter.origin.x = iSize.width + 20 + labelCenter.size.width /2; labelCenter.origin.y = size.height * 0.425f; } if (!title.empty()) { if (m_bDefineTitleLabelSize) { labelCenter.size = m_pTitleLabelSize; } if(m_bDefineTitleOffset) { labelCenter.origin = ccpMult(m_obContentSize, 0.5f); labelCenter.origin = ccpAdd(labelCenter.origin, m_pTitleOffset); } m_pLabel->setCenter(labelCenter); if(m_fTitleFontSize == 0) { m_fTitleFontSize = labelSize; } m_pLabel->setFontSize(m_fTitleFontSize); m_pLabel->setColor(m_bIsOn ? m_cTitleColorSelected : m_cTitleColorNormal); } if (strcmp(title.c_str(), m_pLabel->getText().c_str())) { m_pLabel->setText(title.c_str()); } if (image) { m_pImageView->setColor(m_bIsOn ? m_cImageColorSelected : m_cImageColorNormal); if (m_bDefineImageSize) { imageViewCenter.size = m_pImageSize; } if (m_bDefineImageOffset) { imageViewCenter.origin = ccpMult(m_obContentSize, 0.5f); imageViewCenter.origin = ccpAdd(imageViewCenter.origin, m_pImageOffset); } m_pImageView->setCenter(imageViewCenter); } if (image != m_pImageView->getImage()) { m_pImageView->setImage(image); } } void CACheckbox::setContentSize(const DSize & var) { DSize size = var; // if (m_bRecSpe) // { // const CAThemeManager::stringMap& map = CAApplication::getApplication()->getThemeManager()->getThemeMap(""); // int h = atoi(map.at("height").c_str()); // size.height = (h == 0) ? size.height : h; // } CAView::setContentSize(size); this->updateWithPreferredSize(); this->updateCheckboxState(); } NS_CC_END <|endoftext|>
<commit_before>// Copyright (c) 2011 Zeex // // 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 <algorithm> #include <functional> #include <iomanip> #include <iostream> #include <iterator> #include <sstream> #include <string> #include <vector> #include "amxcallstack.h" #include "amxdebuginfo.h" #include "amx/amx.h" #include "amx/amxdbg.h" static bool IsFunctionArgument(const AMXDebugInfo::Symbol &symbol, ucell functionAddress) { return symbol.IsLocal() && symbol.GetCodeStartAddress() == functionAddress; } class IsArgumentOf : public std::unary_function<AMXDebugInfo::Symbol, bool> { public: IsArgumentOf(ucell function) : function_(function) {} bool operator()(AMXDebugInfo::Symbol symbol) const { return symbol.IsLocal() && symbol.GetCodeStartAddress() == function_; } private: ucell function_; }; static inline bool CompareArguments(const AMXDebugInfo::Symbol &left, const AMXDebugInfo::Symbol &right) { return left.GetAddress() < right.GetAddress(); } class IsFunctionAt : public std::unary_function<const AMXDebugInfo::Symbol&, bool> { public: IsFunctionAt(ucell address) : address_(address) {} bool operator()(const AMXDebugInfo::Symbol &symbol) const { return symbol.IsFunction() && symbol.GetAddress() == address_; } private: ucell address_; }; static inline const char *GetPublicFunctionName(AMX *amx, ucell address) { AMX_HEADER *hdr = reinterpret_cast<AMX_HEADER*>(amx->base); AMX_FUNCSTUBNT *publics = reinterpret_cast<AMX_FUNCSTUBNT*>(amx->base + hdr->publics); AMX_FUNCSTUBNT *natives = reinterpret_cast<AMX_FUNCSTUBNT*>(amx->base + hdr->natives); for (AMX_FUNCSTUBNT *p = publics; p < natives; ++p) { if (p->address == address) { return reinterpret_cast<const char*>(p->nameofs + amx->base); } } return 0; } static inline bool IsPublicFunction(AMX *amx, ucell address) { return GetPublicFunctionName(amx, address) != 0; } AMXStackFrame::AMXStackFrame(AMX *amx, ucell frameAddress, const AMXDebugInfo &debugInfo) : isPublic_(false) , frameAddress_(frameAddress) , callAddress_(0) , functionAddress_(0) { if (IsOnStack(frameAddress_, amx)) { AMX_HEADER *hdr = reinterpret_cast<AMX_HEADER*>(amx->base); ucell data = reinterpret_cast<ucell>(amx->base + hdr->dat); ucell code = reinterpret_cast<ucell>(amx->base) + hdr->cod; callAddress_ = *(reinterpret_cast<ucell*>(data + frameAddress_) + 1) - 2*sizeof(cell); if (callAddress_ >= 0 && callAddress_ < static_cast<ucell>(hdr->dat - hdr->cod)) { functionAddress_ = *reinterpret_cast<ucell*>(callAddress_ + sizeof(cell) + code) - code; Init(amx, debugInfo); } else { callAddress_ = 0; } } } AMXStackFrame::AMXStackFrame(AMX *amx, ucell frameAddress, ucell callAddress, ucell functionAddress, const AMXDebugInfo &debugInfo) : isPublic_(false) , frameAddress_(frameAddress) , callAddress_(callAddress) , functionAddress_(functionAddress) { Init(amx, debugInfo); } void AMXStackFrame::Init(AMX *amx, const AMXDebugInfo &debugInfo) { isPublic_ = IsPublicFunction(amx, functionAddress_); if (debugInfo.IsLoaded()) { if (callAddress_ != 0) { fileName_ = debugInfo.GetFileName(callAddress_); lineNumber_ = debugInfo.GetLineNumber(callAddress_); } else { // Entry point fileName_ = debugInfo.GetFileName(functionAddress_); lineNumber_ = debugInfo.GetLineNumber(functionAddress_); } // Get function return value tag AMXDebugInfo::SymbolTable::const_iterator it = std::find_if( debugInfo.GetSymbols().begin(), debugInfo.GetSymbols().end(), IsFunctionAt(functionAddress_) ); if (it != debugInfo.GetSymbols().end()) { functionResultTag_ = debugInfo.GetTagName((*it).GetTag()) + ":"; if (functionResultTag_ == "_:") { functionResultTag_.clear(); } } // Get function name functionName_ = debugInfo.GetFunctionName(functionAddress_); // Get parameters std::remove_copy_if( debugInfo.GetSymbols().begin(), debugInfo.GetSymbols().end(), std::back_inserter(arguments_), std::not1(IsArgumentOf(functionAddress_)) ); // Order them by address std::sort(arguments_.begin(), arguments_.end(), CompareArguments); // Build a comma-separated list of arguments and their values std::stringstream argStream; for (std::vector<AMXDebugInfo::Symbol>::const_iterator arg = arguments_.begin(); arg != arguments_.end(); ++arg) { if (arg != arguments_.begin()) { argStream << ", "; } // For reference parameters, print the '&' sign in front of their tag if (arg->IsReference()) { argStream << "&"; } // Get parameter's tag std::string tag = debugInfo.GetTag(arg->GetTag()).GetName() + ":"; if (tag != "_:") { argStream << tag; } // Get parameter name argStream << arg->GetName(); cell value = arg->GetValue(amx); if (arg->IsVariable()) { if (tag == "bool:") { argStream << "=" << value ? "true" : "false"; } else if (tag == "Float:") { argStream << "=" << std::fixed << std::setprecision(5) << amx_ctof(value); } else { argStream << "=" << value; } } else { if (arg->IsArray() || arg->IsArrayRef()) { // Get array dimensions std::vector<AMXDebugInfo::SymbolDim> dims = arg->GetDims(); for (std::size_t i = 0; i < dims.size(); ++i) { if (dims[i].GetSize() == 0) { argStream << "[]"; } else { std::string tag = debugInfo.GetTagName(dims[i].GetTag()) + ":"; if (tag == "_:") tag.clear(); argStream << "[" << tag << dims[i].GetSize() << "]"; } } } argStream << "=@0x" << std::hex << value << std::dec; } } // The function prototype is of the following form: // [public ][tag:]name([arg1=value1[, arg2=value2, [...]]]) if (IsPublic()) { functionPrototype_.append("public "); } functionPrototype_ .append(functionResultTag_) .append(functionName_) .append("(") .append(argStream.str()) .append(")"); } else { // No debug info available... const char *name = GetPublicFunctionName(amx, functionAddress_); if (name != 0) { functionName_.assign(name); } } } AMXCallStack::AMXCallStack(AMX *amx, const AMXDebugInfo &debugInfo, ucell topFrame) { AMX_HEADER *hdr = reinterpret_cast<AMX_HEADER*>(amx->base); ucell data = reinterpret_cast<ucell>(amx->base + hdr->dat); ucell frm = topFrame; if (frm == 0) { frm = amx->frm; } while (frm > static_cast<ucell>(amx->stk)) { AMXStackFrame frame(amx, frm, debugInfo); frames_.push_back(frame); if (frame.GetFunctionAddress() == 0) { // Invalid frame address break; } frm = *reinterpret_cast<ucell*>(data + frm); } // Correct entry point address (it's not on the stack) if (debugInfo.IsLoaded()) { if (frames_.size() > 1) { ucell epAddr = debugInfo.GetFunctionStartAddress(frames_[frames_.size() - 2].GetCallAddress()); frames_.back() = AMXStackFrame(amx, frames_.back().GetFrameAddress(), 0, epAddr, debugInfo); } else if (frames_.size() != 0) { ucell epAddr = debugInfo.GetFunctionStartAddress(amx->cip); frames_.back() = AMXStackFrame(amx, frames_.back().GetFrameAddress(), 0, epAddr, debugInfo); } } else { // Can't fetch the address frames_.back() = AMXStackFrame(amx, 0, 0, 0); } } <commit_msg>AMXCallStack: Make array address fixed width (8 characters)<commit_after>// Copyright (c) 2011 Zeex // // 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 <algorithm> #include <functional> #include <iomanip> #include <iostream> #include <iterator> #include <sstream> #include <string> #include <vector> #include "amxcallstack.h" #include "amxdebuginfo.h" #include "amx/amx.h" #include "amx/amxdbg.h" static bool IsFunctionArgument(const AMXDebugInfo::Symbol &symbol, ucell functionAddress) { return symbol.IsLocal() && symbol.GetCodeStartAddress() == functionAddress; } class IsArgumentOf : public std::unary_function<AMXDebugInfo::Symbol, bool> { public: IsArgumentOf(ucell function) : function_(function) {} bool operator()(AMXDebugInfo::Symbol symbol) const { return symbol.IsLocal() && symbol.GetCodeStartAddress() == function_; } private: ucell function_; }; static inline bool CompareArguments(const AMXDebugInfo::Symbol &left, const AMXDebugInfo::Symbol &right) { return left.GetAddress() < right.GetAddress(); } class IsFunctionAt : public std::unary_function<const AMXDebugInfo::Symbol&, bool> { public: IsFunctionAt(ucell address) : address_(address) {} bool operator()(const AMXDebugInfo::Symbol &symbol) const { return symbol.IsFunction() && symbol.GetAddress() == address_; } private: ucell address_; }; static inline const char *GetPublicFunctionName(AMX *amx, ucell address) { AMX_HEADER *hdr = reinterpret_cast<AMX_HEADER*>(amx->base); AMX_FUNCSTUBNT *publics = reinterpret_cast<AMX_FUNCSTUBNT*>(amx->base + hdr->publics); AMX_FUNCSTUBNT *natives = reinterpret_cast<AMX_FUNCSTUBNT*>(amx->base + hdr->natives); for (AMX_FUNCSTUBNT *p = publics; p < natives; ++p) { if (p->address == address) { return reinterpret_cast<const char*>(p->nameofs + amx->base); } } return 0; } static inline bool IsPublicFunction(AMX *amx, ucell address) { return GetPublicFunctionName(amx, address) != 0; } AMXStackFrame::AMXStackFrame(AMX *amx, ucell frameAddress, const AMXDebugInfo &debugInfo) : isPublic_(false) , frameAddress_(frameAddress) , callAddress_(0) , functionAddress_(0) { if (IsOnStack(frameAddress_, amx)) { AMX_HEADER *hdr = reinterpret_cast<AMX_HEADER*>(amx->base); ucell data = reinterpret_cast<ucell>(amx->base + hdr->dat); ucell code = reinterpret_cast<ucell>(amx->base) + hdr->cod; callAddress_ = *(reinterpret_cast<ucell*>(data + frameAddress_) + 1) - 2*sizeof(cell); if (callAddress_ >= 0 && callAddress_ < static_cast<ucell>(hdr->dat - hdr->cod)) { functionAddress_ = *reinterpret_cast<ucell*>(callAddress_ + sizeof(cell) + code) - code; Init(amx, debugInfo); } else { callAddress_ = 0; } } } AMXStackFrame::AMXStackFrame(AMX *amx, ucell frameAddress, ucell callAddress, ucell functionAddress, const AMXDebugInfo &debugInfo) : isPublic_(false) , frameAddress_(frameAddress) , callAddress_(callAddress) , functionAddress_(functionAddress) { Init(amx, debugInfo); } void AMXStackFrame::Init(AMX *amx, const AMXDebugInfo &debugInfo) { isPublic_ = IsPublicFunction(amx, functionAddress_); if (debugInfo.IsLoaded()) { if (callAddress_ != 0) { fileName_ = debugInfo.GetFileName(callAddress_); lineNumber_ = debugInfo.GetLineNumber(callAddress_); } else { // Entry point fileName_ = debugInfo.GetFileName(functionAddress_); lineNumber_ = debugInfo.GetLineNumber(functionAddress_); } // Get function return value tag AMXDebugInfo::SymbolTable::const_iterator it = std::find_if( debugInfo.GetSymbols().begin(), debugInfo.GetSymbols().end(), IsFunctionAt(functionAddress_) ); if (it != debugInfo.GetSymbols().end()) { functionResultTag_ = debugInfo.GetTagName((*it).GetTag()) + ":"; if (functionResultTag_ == "_:") { functionResultTag_.clear(); } } // Get function name functionName_ = debugInfo.GetFunctionName(functionAddress_); // Get parameters std::remove_copy_if( debugInfo.GetSymbols().begin(), debugInfo.GetSymbols().end(), std::back_inserter(arguments_), std::not1(IsArgumentOf(functionAddress_)) ); // Order them by address std::sort(arguments_.begin(), arguments_.end(), CompareArguments); // Build a comma-separated list of arguments and their values std::stringstream argStream; for (std::vector<AMXDebugInfo::Symbol>::const_iterator arg = arguments_.begin(); arg != arguments_.end(); ++arg) { if (arg != arguments_.begin()) { argStream << ", "; } // For reference parameters, print the '&' sign in front of their tag if (arg->IsReference()) { argStream << "&"; } // Get parameter's tag std::string tag = debugInfo.GetTag(arg->GetTag()).GetName() + ":"; if (tag != "_:") { argStream << tag; } // Get parameter name argStream << arg->GetName(); cell value = arg->GetValue(amx); if (arg->IsVariable()) { if (tag == "bool:") { argStream << "=" << value ? "true" : "false"; } else if (tag == "Float:") { argStream << "=" << std::fixed << std::setprecision(5) << amx_ctof(value); } else { argStream << "=" << value; } } else { if (arg->IsArray() || arg->IsArrayRef()) { // Get array dimensions std::vector<AMXDebugInfo::SymbolDim> dims = arg->GetDims(); for (std::size_t i = 0; i < dims.size(); ++i) { if (dims[i].GetSize() == 0) { argStream << "[]"; } else { std::string tag = debugInfo.GetTagName(dims[i].GetTag()) + ":"; if (tag == "_:") tag.clear(); argStream << "[" << tag << dims[i].GetSize() << "]"; } } } argStream << "=@0x" << std::hex << std::setw(8) << std::setfill('0') << value << std::dec; } } // The function prototype is of the following form: // [public ][tag:]name([arg1=value1[, arg2=value2, [...]]]) if (IsPublic()) { functionPrototype_.append("public "); } functionPrototype_ .append(functionResultTag_) .append(functionName_) .append("(") .append(argStream.str()) .append(")"); } else { // No debug info available... const char *name = GetPublicFunctionName(amx, functionAddress_); if (name != 0) { functionName_.assign(name); } } } AMXCallStack::AMXCallStack(AMX *amx, const AMXDebugInfo &debugInfo, ucell topFrame) { AMX_HEADER *hdr = reinterpret_cast<AMX_HEADER*>(amx->base); ucell data = reinterpret_cast<ucell>(amx->base + hdr->dat); ucell frm = topFrame; if (frm == 0) { frm = amx->frm; } while (frm > static_cast<ucell>(amx->stk)) { AMXStackFrame frame(amx, frm, debugInfo); frames_.push_back(frame); if (frame.GetFunctionAddress() == 0) { // Invalid frame address break; } frm = *reinterpret_cast<ucell*>(data + frm); } // Correct entry point address (it's not on the stack) if (debugInfo.IsLoaded()) { if (frames_.size() > 1) { ucell epAddr = debugInfo.GetFunctionStartAddress(frames_[frames_.size() - 2].GetCallAddress()); frames_.back() = AMXStackFrame(amx, frames_.back().GetFrameAddress(), 0, epAddr, debugInfo); } else if (frames_.size() != 0) { ucell epAddr = debugInfo.GetFunctionStartAddress(amx->cip); frames_.back() = AMXStackFrame(amx, frames_.back().GetFrameAddress(), 0, epAddr, debugInfo); } } else { // Can't fetch the address frames_.back() = AMXStackFrame(amx, 0, 0, 0); } } <|endoftext|>
<commit_before>/**************************************************************************** * * Copyright (c) 2016 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /** * @file df_imu.cpp * Lightweight driver to access IMU driver of DriverFramework. * * @author Julian Oes <julian@oes.ch> */ #include <px4_config.h> #include <sys/types.h> #include <sys/stat.h> #include <stdint.h> #include <stddef.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <unistd.h> #include <px4_getopt.h> #include <errno.h> #include <systemlib/perf_counter.h> #include <systemlib/err.h> #include <drivers/drv_accel.h> #include <board_config.h> //#include <mathlib/math/filter/LowPassFilter2p.hpp> //#include <lib/conversion/rotation.h> // #include <mpu9250/MPU9250.hpp> #include <DevMgr.hpp> #include <VirtDevObj.hpp> #define ACCELSIM_DEVICE_PATH_ACCEL "/dev/df_accel" extern "C" { __EXPORT int df_imu_main(int argc, char *argv[]); } using namespace DriverFramework; class DfImu : public MPU9250 { public: DfImu(/*enum Rotation rotation*/); ~DfImu(); //enum Rotation _rotation; /** * Start automatic measurement. * * @return 0 on success */ int start(); /** * Stop automatic measurement. * * @return 0 on success */ int stop(); private: virtual int _publish_callback(struct imu_sensor_data &data); orb_advert_t _accel_topic; int _accel_orb_class_instance; perf_counter_t _accel_sample_perf; }; DfImu::DfImu(/*enum Rotation rotation*/) : MPU9250(IMU_DEVICE_PATH), _accel_topic(nullptr), _accel_orb_class_instance(-1), _accel_sample_perf(perf_alloc(PC_ELAPSED, "df_accel_read")) /*_rotation(rotation)*/ { m_id.dev_id_s.bus = 1; m_id.dev_id_s.devtype = DRV_ACC_DEVTYPE_MPU9250; } DfImu::~DfImu() { } int DfImu::start() { struct accel_report arp = {}; arp.timestamp = 1234; /* measurement will have generated a report, publish */ _accel_topic = orb_advertise_multi(ORB_ID(sensor_accel), &arp, &_accel_orb_class_instance, ORB_PRIO_DEFAULT); if (_accel_topic == nullptr) { PX4_WARN("ADVERT ERR"); return -1; } /* init device and start sensor */ int ret = init(); if (ret != 0) { PX4_ERR("MPU9250 init fail: %d", ret); return ret; } ret = MPU9250::start(); if (ret != 0) { PX4_ERR("MPU9250 start fail: %d", ret); return ret; } return 0; } int DfImu::stop() { /* stop sensor */ return 0; } int DfImu::_publish_callback(struct imu_sensor_data &data) { accel_report accel_report = {}; accel_report.timestamp = data.last_read_time_usec; // TODO: remove these (or get the values) accel_report.x_raw = NAN; accel_report.y_raw = NAN; accel_report.z_raw = NAN; accel_report.x = data.accel_m_s2_x; accel_report.y = data.accel_m_s2_y; accel_report.z = data.accel_m_s2_z; // TODO: get these right accel_report.scaling = -1.0f; accel_report.range_m_s2 = -1.0f; if (!(m_pub_blocked)) { /* publish it */ if (_accel_topic != nullptr) { orb_publish(ORB_ID(sensor_accel), _accel_topic, &accel_report); } } /* notify anyone waiting for data */ DevMgr::updateNotify(*this); return 0; }; namespace df_imu { DfImu *g_dev = nullptr; int start(/* enum Rotation rotation */); int stop(); int info(); void usage(); int start(/*enum Rotation rotation*/) { g_dev = new DfImu(/*rotation*/); if (g_dev == nullptr) { PX4_ERR("failed instantiating DfImu object"); return -1; } int ret = g_dev->start(); if (ret != 0) { PX4_ERR("DfImu start failed"); return ret; } // Open the IMU sensor DevHandle h; DevMgr::getHandle(IMU_DEVICE_PATH, h); if (!h.isValid()) { DF_LOG_INFO("Error: unable to obtain a valid handle for the receiver at: %s (%d)", IMU_DEVICE_PATH, h.getError()); return -1; } DevMgr::releaseHandle(h); return 0; } int stop() { if (g_dev == nullptr) { PX4_ERR("driver not running"); return 1; } int ret = g_dev->stop(); if (ret != 0) { PX4_ERR("driver could not be stopped"); return ret; } delete g_dev; g_dev = nullptr; return 0; } /** * Print a little info about the driver. */ int info() { if (g_dev == nullptr) { PX4_ERR("driver not running"); return 1; } PX4_DEBUG("state @ %p", g_dev); return 0; } void usage() { PX4_WARN("Usage: df_imu 'start', 'info', 'stop'"); PX4_WARN("options:"); //PX4_WARN(" -R rotation"); } } // namespace int df_imu_main(int argc, char *argv[]) { int ch; // enum Rotation rotation = ROTATION_NONE; int ret = 0; int myoptind = 1; const char *myoptarg = NULL; /* jump over start/off/etc and look at options first */ while ((ch = px4_getopt(argc, argv, "R:", &myoptind, &myoptarg)) != EOF) { switch (ch) { //case 'R': // rotation = (enum Rotation)atoi(myoptarg); // break; default: df_imu::usage(); return 0; } } if (argc <= 1) { df_imu::usage(); return 1; } const char *verb = argv[myoptind]; if (!strcmp(verb, "start")) { ret = df_imu::start(/*rotation*/); } else if (!strcmp(verb, "stop")) { ret = df_imu::stop(); } else if (!strcmp(verb, "info")) { ret = df_imu::info(); } else { df_imu::usage(); return 1; } return ret; } <commit_msg>df_imu: remove debug relict<commit_after>/**************************************************************************** * * Copyright (c) 2016 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /** * @file df_imu.cpp * Lightweight driver to access IMU driver of DriverFramework. * * @author Julian Oes <julian@oes.ch> */ #include <px4_config.h> #include <sys/types.h> #include <sys/stat.h> #include <stdint.h> #include <stddef.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <unistd.h> #include <px4_getopt.h> #include <errno.h> #include <systemlib/perf_counter.h> #include <systemlib/err.h> #include <drivers/drv_accel.h> #include <board_config.h> //#include <mathlib/math/filter/LowPassFilter2p.hpp> //#include <lib/conversion/rotation.h> // #include <mpu9250/MPU9250.hpp> #include <DevMgr.hpp> #include <VirtDevObj.hpp> #define ACCELSIM_DEVICE_PATH_ACCEL "/dev/df_accel" extern "C" { __EXPORT int df_imu_main(int argc, char *argv[]); } using namespace DriverFramework; class DfImu : public MPU9250 { public: DfImu(/*enum Rotation rotation*/); ~DfImu(); //enum Rotation _rotation; /** * Start automatic measurement. * * @return 0 on success */ int start(); /** * Stop automatic measurement. * * @return 0 on success */ int stop(); private: virtual int _publish_callback(struct imu_sensor_data &data); orb_advert_t _accel_topic; int _accel_orb_class_instance; perf_counter_t _accel_sample_perf; }; DfImu::DfImu(/*enum Rotation rotation*/) : MPU9250(IMU_DEVICE_PATH), _accel_topic(nullptr), _accel_orb_class_instance(-1), _accel_sample_perf(perf_alloc(PC_ELAPSED, "df_accel_read")) /*_rotation(rotation)*/ { m_id.dev_id_s.bus = 1; m_id.dev_id_s.devtype = DRV_ACC_DEVTYPE_MPU9250; } DfImu::~DfImu() { } int DfImu::start() { struct accel_report arp = {}; /* measurement will have generated a report, publish */ _accel_topic = orb_advertise_multi(ORB_ID(sensor_accel), &arp, &_accel_orb_class_instance, ORB_PRIO_DEFAULT); if (_accel_topic == nullptr) { PX4_WARN("ADVERT ERR"); return -1; } /* init device and start sensor */ int ret = init(); if (ret != 0) { PX4_ERR("MPU9250 init fail: %d", ret); return ret; } ret = MPU9250::start(); if (ret != 0) { PX4_ERR("MPU9250 start fail: %d", ret); return ret; } return 0; } int DfImu::stop() { /* stop sensor */ return 0; } int DfImu::_publish_callback(struct imu_sensor_data &data) { accel_report accel_report = {}; accel_report.timestamp = data.last_read_time_usec; // TODO: remove these (or get the values) accel_report.x_raw = NAN; accel_report.y_raw = NAN; accel_report.z_raw = NAN; accel_report.x = data.accel_m_s2_x; accel_report.y = data.accel_m_s2_y; accel_report.z = data.accel_m_s2_z; // TODO: get these right accel_report.scaling = -1.0f; accel_report.range_m_s2 = -1.0f; if (!(m_pub_blocked)) { /* publish it */ if (_accel_topic != nullptr) { orb_publish(ORB_ID(sensor_accel), _accel_topic, &accel_report); } } /* notify anyone waiting for data */ DevMgr::updateNotify(*this); return 0; }; namespace df_imu { DfImu *g_dev = nullptr; int start(/* enum Rotation rotation */); int stop(); int info(); void usage(); int start(/*enum Rotation rotation*/) { g_dev = new DfImu(/*rotation*/); if (g_dev == nullptr) { PX4_ERR("failed instantiating DfImu object"); return -1; } int ret = g_dev->start(); if (ret != 0) { PX4_ERR("DfImu start failed"); return ret; } // Open the IMU sensor DevHandle h; DevMgr::getHandle(IMU_DEVICE_PATH, h); if (!h.isValid()) { DF_LOG_INFO("Error: unable to obtain a valid handle for the receiver at: %s (%d)", IMU_DEVICE_PATH, h.getError()); return -1; } DevMgr::releaseHandle(h); return 0; } int stop() { if (g_dev == nullptr) { PX4_ERR("driver not running"); return 1; } int ret = g_dev->stop(); if (ret != 0) { PX4_ERR("driver could not be stopped"); return ret; } delete g_dev; g_dev = nullptr; return 0; } /** * Print a little info about the driver. */ int info() { if (g_dev == nullptr) { PX4_ERR("driver not running"); return 1; } PX4_DEBUG("state @ %p", g_dev); return 0; } void usage() { PX4_WARN("Usage: df_imu 'start', 'info', 'stop'"); PX4_WARN("options:"); //PX4_WARN(" -R rotation"); } } // namespace int df_imu_main(int argc, char *argv[]) { int ch; // enum Rotation rotation = ROTATION_NONE; int ret = 0; int myoptind = 1; const char *myoptarg = NULL; /* jump over start/off/etc and look at options first */ while ((ch = px4_getopt(argc, argv, "R:", &myoptind, &myoptarg)) != EOF) { switch (ch) { //case 'R': // rotation = (enum Rotation)atoi(myoptarg); // break; default: df_imu::usage(); return 0; } } if (argc <= 1) { df_imu::usage(); return 1; } const char *verb = argv[myoptind]; if (!strcmp(verb, "start")) { ret = df_imu::start(/*rotation*/); } else if (!strcmp(verb, "stop")) { ret = df_imu::stop(); } else if (!strcmp(verb, "info")) { ret = df_imu::info(); } else { df_imu::usage(); return 1; } return ret; } <|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 "qgeoroutesegment.h" #include "qgeoroutesegment_p.h" #include "qgeocoordinate.h" #include <QDateTime> QTM_BEGIN_NAMESPACE /*! \class QGeoRouteSegment \brief The QGeoRouteSegment class represents a segment of a route. \inmodule QtLocation \ingroup maps-routing A QGeoRouteSegment instance has information about the physcial layout of the route segment, the length of the route and estimated time required to traverse the route segment and an optional QGeoManeuver associated with the end of the route segment. QGeoRouteSegment instances can be thought of as edges on a routing graph, with QGeoManeuver instances as optional labels attached to the vertices of the graph. */ /*! Constructs an invalid route segment object. The route segment will remain invalid until one of setNextRouteSegment(), setTravelTime(), setDistance(), setPath() or setManeuver() is called. */ QGeoRouteSegment::QGeoRouteSegment() : d_ptr(new QGeoRouteSegmentPrivate()) {} /*! Constructs a route segment object from the contents of \a other. */ QGeoRouteSegment::QGeoRouteSegment(const QGeoRouteSegment &other) : d_ptr(other.d_ptr) {} /*! \internal */ QGeoRouteSegment::QGeoRouteSegment(QExplicitlySharedDataPointer<QGeoRouteSegmentPrivate> &d_ptr) : d_ptr(d_ptr) {} /*! Destroys this route segment object. */ QGeoRouteSegment::~QGeoRouteSegment() {} /*! Assigns \a other to this route segment object and then returns a reference to this route segment object. */ QGeoRouteSegment& QGeoRouteSegment::operator= (const QGeoRouteSegment & other) { d_ptr = other.d_ptr; return *this; } /*! Returns whether this route segment and \a other are equal. The value of nextRouteSegment() is not considered in the comparison. */ bool QGeoRouteSegment::operator ==(const QGeoRouteSegment &other) const { return (d_ptr.constData() == other.d_ptr.constData()); } /*! Returns whether this route segment and \a other are not equal. The value of nextRouteSegment() is not considered in the comparison. */ bool QGeoRouteSegment::operator !=(const QGeoRouteSegment &other) const { return !(operator==(other)); } /*! Returns whether this route segment is valid or not. If nextRouteSegment() is called on the last route segment of a route, the returned value will be an invalid route segment. */ bool QGeoRouteSegment::isValid() const { return d_ptr->valid; } /*! Sets the next route segment in the route to \a routeSegment. */ void QGeoRouteSegment::setNextRouteSegment(const QGeoRouteSegment &routeSegment) { d_ptr->valid = true; d_ptr->nextSegment = routeSegment.d_ptr; } /*! Returns the next route segment in the route. Will return an invalid route segment if this is the last route segment in the route. */ QGeoRouteSegment QGeoRouteSegment::nextRouteSegment() const { if (d_ptr->valid && d_ptr->nextSegment) return QGeoRouteSegment(d_ptr->nextSegment); QGeoRouteSegment segment; segment.d_ptr->valid = false; return segment; } /*! Sets the estimated amount of time it will take to traverse this segment of the route, in seconds, to \a secs. */ void QGeoRouteSegment::setTravelTime(int secs) { d_ptr->valid = true; d_ptr->travelTime = secs; } /*! Returns the estimated amount of time it will take to traverse this segment of the route, in seconds. */ int QGeoRouteSegment::travelTime() const { return d_ptr->travelTime; } /*! Sets the distance covered by this segment of the route, in metres, to \a distance. */ void QGeoRouteSegment::setDistance(qreal distance) { d_ptr->valid = true; d_ptr->distance = distance; } /*! Returns the distance covered by this segment of the route, in metres. */ qreal QGeoRouteSegment::distance() const { return d_ptr->distance; } /*! Sets the geometric shape of this segment of the route to \a path. The coordinates in \a path should be listed in the order in which they would be traversed by someone traveling along this segment of the route. */ void QGeoRouteSegment::setPath(const QList<QGeoCoordinate> &path) { d_ptr->valid = true; d_ptr->path = path; } /*! Returns the geometric shape of this route segment of the route. The coordinates should be listed in the order in which they would be traversed by someone traveling along this segment of the route. */ QList<QGeoCoordinate> QGeoRouteSegment::path() const { return d_ptr->path; } /*! Sets the maneuver for this route segement to \a maneuver. */ void QGeoRouteSegment::setManeuver(const QGeoManeuver &maneuver) { d_ptr->valid = true; d_ptr->maneuver = maneuver; } /*! Returns the manevuer for this route segment. Will return an invalid QGeoManeuver if no information has been attached to the endpoint of this route segment. */ QGeoManeuver QGeoRouteSegment::maneuver() const { return d_ptr->maneuver; } /******************************************************************************* *******************************************************************************/ QGeoRouteSegmentPrivate::QGeoRouteSegmentPrivate() : valid(true), travelTime(0), distance(0.0) {} QGeoRouteSegmentPrivate::QGeoRouteSegmentPrivate(const QGeoRouteSegmentPrivate &other) : QSharedData(other), valid(other.valid), travelTime(other.travelTime), distance(other.distance), path(other.path), maneuver(other.maneuver), nextSegment(other.nextSegment) {} QGeoRouteSegmentPrivate::~QGeoRouteSegmentPrivate() { nextSegment.reset(); } bool QGeoRouteSegmentPrivate::operator ==(const QGeoRouteSegmentPrivate &other) const { return ((valid == other.valid) && (travelTime == other.travelTime) && (distance == other.distance) && (path == other.path) && (maneuver == other.maneuver)); } /******************************************************************************* *******************************************************************************/ QTM_END_NAMESPACE <commit_msg>Fixed faulty default value of QGeoRouteSegmentPrivate::valid<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 "qgeoroutesegment.h" #include "qgeoroutesegment_p.h" #include "qgeocoordinate.h" #include <QDateTime> QTM_BEGIN_NAMESPACE /*! \class QGeoRouteSegment \brief The QGeoRouteSegment class represents a segment of a route. \inmodule QtLocation \ingroup maps-routing A QGeoRouteSegment instance has information about the physcial layout of the route segment, the length of the route and estimated time required to traverse the route segment and an optional QGeoManeuver associated with the end of the route segment. QGeoRouteSegment instances can be thought of as edges on a routing graph, with QGeoManeuver instances as optional labels attached to the vertices of the graph. */ /*! Constructs an invalid route segment object. The route segment will remain invalid until one of setNextRouteSegment(), setTravelTime(), setDistance(), setPath() or setManeuver() is called. */ QGeoRouteSegment::QGeoRouteSegment() : d_ptr(new QGeoRouteSegmentPrivate()) {} /*! Constructs a route segment object from the contents of \a other. */ QGeoRouteSegment::QGeoRouteSegment(const QGeoRouteSegment &other) : d_ptr(other.d_ptr) {} /*! \internal */ QGeoRouteSegment::QGeoRouteSegment(QExplicitlySharedDataPointer<QGeoRouteSegmentPrivate> &d_ptr) : d_ptr(d_ptr) {} /*! Destroys this route segment object. */ QGeoRouteSegment::~QGeoRouteSegment() {} /*! Assigns \a other to this route segment object and then returns a reference to this route segment object. */ QGeoRouteSegment& QGeoRouteSegment::operator= (const QGeoRouteSegment & other) { d_ptr = other.d_ptr; return *this; } /*! Returns whether this route segment and \a other are equal. The value of nextRouteSegment() is not considered in the comparison. */ bool QGeoRouteSegment::operator ==(const QGeoRouteSegment &other) const { return (d_ptr.constData() == other.d_ptr.constData()); } /*! Returns whether this route segment and \a other are not equal. The value of nextRouteSegment() is not considered in the comparison. */ bool QGeoRouteSegment::operator !=(const QGeoRouteSegment &other) const { return !(operator==(other)); } /*! Returns whether this route segment is valid or not. If nextRouteSegment() is called on the last route segment of a route, the returned value will be an invalid route segment. */ bool QGeoRouteSegment::isValid() const { return d_ptr->valid; } /*! Sets the next route segment in the route to \a routeSegment. */ void QGeoRouteSegment::setNextRouteSegment(const QGeoRouteSegment &routeSegment) { d_ptr->valid = true; d_ptr->nextSegment = routeSegment.d_ptr; } /*! Returns the next route segment in the route. Will return an invalid route segment if this is the last route segment in the route. */ QGeoRouteSegment QGeoRouteSegment::nextRouteSegment() const { if (d_ptr->valid && d_ptr->nextSegment) return QGeoRouteSegment(d_ptr->nextSegment); QGeoRouteSegment segment; segment.d_ptr->valid = false; return segment; } /*! Sets the estimated amount of time it will take to traverse this segment of the route, in seconds, to \a secs. */ void QGeoRouteSegment::setTravelTime(int secs) { d_ptr->valid = true; d_ptr->travelTime = secs; } /*! Returns the estimated amount of time it will take to traverse this segment of the route, in seconds. */ int QGeoRouteSegment::travelTime() const { return d_ptr->travelTime; } /*! Sets the distance covered by this segment of the route, in metres, to \a distance. */ void QGeoRouteSegment::setDistance(qreal distance) { d_ptr->valid = true; d_ptr->distance = distance; } /*! Returns the distance covered by this segment of the route, in metres. */ qreal QGeoRouteSegment::distance() const { return d_ptr->distance; } /*! Sets the geometric shape of this segment of the route to \a path. The coordinates in \a path should be listed in the order in which they would be traversed by someone traveling along this segment of the route. */ void QGeoRouteSegment::setPath(const QList<QGeoCoordinate> &path) { d_ptr->valid = true; d_ptr->path = path; } /*! Returns the geometric shape of this route segment of the route. The coordinates should be listed in the order in which they would be traversed by someone traveling along this segment of the route. */ QList<QGeoCoordinate> QGeoRouteSegment::path() const { return d_ptr->path; } /*! Sets the maneuver for this route segement to \a maneuver. */ void QGeoRouteSegment::setManeuver(const QGeoManeuver &maneuver) { d_ptr->valid = true; d_ptr->maneuver = maneuver; } /*! Returns the manevuer for this route segment. Will return an invalid QGeoManeuver if no information has been attached to the endpoint of this route segment. */ QGeoManeuver QGeoRouteSegment::maneuver() const { return d_ptr->maneuver; } /******************************************************************************* *******************************************************************************/ QGeoRouteSegmentPrivate::QGeoRouteSegmentPrivate() : valid(false), travelTime(0), distance(0.0) {} QGeoRouteSegmentPrivate::QGeoRouteSegmentPrivate(const QGeoRouteSegmentPrivate &other) : QSharedData(other), valid(other.valid), travelTime(other.travelTime), distance(other.distance), path(other.path), maneuver(other.maneuver), nextSegment(other.nextSegment) {} QGeoRouteSegmentPrivate::~QGeoRouteSegmentPrivate() { nextSegment.reset(); } bool QGeoRouteSegmentPrivate::operator ==(const QGeoRouteSegmentPrivate &other) const { return ((valid == other.valid) && (travelTime == other.travelTime) && (distance == other.distance) && (path == other.path) && (maneuver == other.maneuver)); } /******************************************************************************* *******************************************************************************/ QTM_END_NAMESPACE <|endoftext|>
<commit_before>#include <stdio.h> #include <sys/sysinfo.h> #include <sys/statfs.h> #include <sys/vfs.h> #include <stdlib.h> #include <string.h> #include <string> #include <sys/ioctl.h> #include <netinet/tcp.h> #include <arpa/inet.h> #include <net/if.h> #include "event/event.h" #include "event/bufferevent.h" #include "event/buffer.h" #include "event/thread.h" #include "Config.h" #include "json/json.h" #include "Protocol.h" using namespace std; #define CONFIG_PATH "/etc/smart_car_device.conf" typedef void (*cfunc)(struct bufferevent *,Json::Value&); string network_card_name; string device_name; string api_host; int api_port; struct event_base* baseEvent; map<string,cfunc> client_api_list; //获取基本信息 void handlerGetDeviceBaseInfo(struct bufferevent * bufEvent,Json::Value &data){ //获取内存大小 struct sysinfo memInfo; sysinfo(&memInfo); double totalMemSize = (double)memInfo.totalram/(1024.0*1024.0); double usedMemSize = (double)(memInfo.totalram-memInfo.freeram)/(1024.0*1024.0); //获取磁盘大小 struct statfs diskInfo; statfs("/", &diskInfo); double totalDiskSize = (double)(diskInfo.f_bsize*diskInfo.f_blocks)/(1024.0*1024.0); double usedDiskSize = (double)(diskInfo.f_bsize*diskInfo.f_blocks-diskInfo.f_bsize*diskInfo.f_bfree)/(1024.0*1024.0); printf("mem total:%.2fMB,mem used:%.2fMB,disk total:%.2fMB,disk used:%.2fMB\n",totalMemSize,usedMemSize,totalDiskSize,usedDiskSize ); Json::Value root; Json::Value re_data; root["is_app"] = false; root["protocol"] = API_DEVICE_BASE_INFO; root["data"] = re_data; bufferevent_write(bufEvent, root.toStyledString().c_str(), root.toStyledString().length()); } //键盘按下 void handlerKeyDown(struct bufferevent * bufEvent,Json::Value &data){ printf("key down:%s\n", data["data"].toStyledString().c_str()); } //获取MAC地址 string getMacAddress(){ FILE *fstream = NULL; char buff[32]; memset (buff ,'\0', sizeof(buff)); string cmd = "ip addr |grep -A 2 "+network_card_name+" | awk 'NR>1'|awk 'NR<2'|awk '{print $2}'" // 通过管道来回去系统命令返回的值 if(NULL == (fstream = popen (cmd.c_str (), "r"))) { perror("popen"); exit(0); } if(NULL == fgets (buff, sizeof(buff), fstream)){ printf("not find mac address !!!\n"); exit(0); } pclose(fstream); return string(buff); } //调用方法 void callFunc(struct bufferevent * bufEvent,Json::Value &request_data,const string func){ if(func.length() == 0){ return; } if (client_api_list.count(func)) { (*(client_api_list[func]))(bufEvent,request_data); } } void sendDeviceInfo(struct bufferevent * bufEvent){ Json::Value root; Json::Value data; //获取MAC地址 data["mac"] = getMacAddress(); data["name"] = device_name; root["protocol"] = API_DEVICE_INFO; root["is_app"] = false; root["data"] = data; string json = root.toStyledString(); bufferevent_write(bufEvent, json.c_str(), json.length()); } //读操作 void ReadEventCb(struct bufferevent *bufEvent, void *args){ Json::Reader reader; Json::Value data; //获取输入缓存 struct evbuffer * pInput = bufferevent_get_input(bufEvent); //获取输入缓存数据的长度 int len = evbuffer_get_length(pInput); //获取数据 char* body = new char[len+1]; memset(body,0,sizeof(char)*(len+1)); evbuffer_remove(pInput, body, len); if(reader.parse(body, data)){ string func = data["protocol"].asString(); callFunc(bufEvent,data,func); } delete[] body; return ; } //写操作 void WriteEventCb(struct bufferevent *bufEvent, void *args){ } //关闭 void SignalEventCb(struct bufferevent * bufEvent, short sEvent, void * args){ //请求的连接过程已经完成 if(BEV_EVENT_CONNECTED == sEvent){ bufferevent_enable(bufEvent, EV_READ); //设置读超时时间 10s struct timeval tTimeout = {10, 0}; bufferevent_set_timeouts( bufEvent, &tTimeout, NULL); string mac = getMacAddress(); if(mac.length() == 0){ printf("MAC地址获取错误请检查网卡配置\n"); event_base_loopexit(baseEvent, NULL); exit(0); } //发送基本信息 sendDeviceInfo(bufEvent); } //写操作发生事件 if(BEV_EVENT_WRITING & sEvent){} //操作时发生错误 if (sEvent & BEV_EVENT_ERROR){ perror("event"); event_base_loopexit(baseEvent, NULL); } //结束指示 if (sEvent & BEV_EVENT_EOF){ perror("event"); event_base_loopexit(baseEvent, NULL); } //读取发生事件或者超时处理 if(0 != (sEvent & (BEV_EVENT_TIMEOUT|BEV_EVENT_READING)) ){ //发送心跳包 // //重新注册可读事件 bufferevent_enable(bufEvent, EV_READ); } return ; } void setConfig(const char* config_path){ Config config; //检测配置文件是否存在 if(!config.FileExist(config_path)){ printf("config: not find config file\n"); exit(0); } //读取配置 config.ReadFile(config_path); api_host = config.Read("SERVER_HOST", api_host); api_port = config.Read("API_PORT", api_port); network_card_name = config.Read("NETWORK_CARD", network_card_name); device_name = config.Read("DEVICE_NAME", device_name); } void startRun(const char* ip,int port){ //创建事件驱动句柄 baseEvent = event_base_new(); //创建socket类型的bufferevent struct bufferevent* bufferEvent = bufferevent_socket_new(baseEvent, -1, 0); //构造服务器地址 struct sockaddr_in sin; memset(&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; sin.sin_addr.s_addr = inet_addr(api_host.c_str()); sin.sin_port = htons(api_port); //连接服务器 if( bufferevent_socket_connect(bufferEvent, (struct sockaddr*)&sin, sizeof(sin)) < 0){ perror("socket"); return; } //设置回调函数, 及回调函数的参数 bufferevent_setcb(bufferEvent, ReadEventCb, WriteEventCb, SignalEventCb,NULL); //开始事件循环 event_base_dispatch(baseEvent); //事件循环结束 资源清理 bufferevent_free(bufferEvent); event_base_free(baseEvent); } //初始化API列表 void initApiList() { client_api_list[API_DEVICE_BASE_INFO] = &handlerGetDeviceBaseInfo; client_api_list[API_DEVICE_KEY_DOWN] = &handlerKeyDown; } int main(){ //加载API列表 initApiList(); //加载配置文件 setConfig(CONFIG_PATH); //启动sockt startRun(api_host.c_str(),api_port); return 0; } <commit_msg>printf wanl0<commit_after>#include <stdio.h> #include <sys/sysinfo.h> #include <sys/statfs.h> #include <sys/vfs.h> #include <stdlib.h> #include <string.h> #include <string> #include <sys/ioctl.h> #include <netinet/tcp.h> #include <arpa/inet.h> #include <net/if.h> #include "event/event.h" #include "event/bufferevent.h" #include "event/buffer.h" #include "event/thread.h" #include "Config.h" #include "json/json.h" #include "Protocol.h" using namespace std; #define CONFIG_PATH "/etc/smart_car_device.conf" typedef void (*cfunc)(struct bufferevent *,Json::Value&); string network_card_name; string device_name; string api_host; int api_port; struct event_base* baseEvent; map<string,cfunc> client_api_list; //获取基本信息 void handlerGetDeviceBaseInfo(struct bufferevent * bufEvent,Json::Value &data){ //获取内存大小 struct sysinfo memInfo; sysinfo(&memInfo); double totalMemSize = (double)memInfo.totalram/(1024.0*1024.0); double usedMemSize = (double)(memInfo.totalram-memInfo.freeram)/(1024.0*1024.0); //获取磁盘大小 struct statfs diskInfo; statfs("/", &diskInfo); double totalDiskSize = (double)(diskInfo.f_bsize*diskInfo.f_blocks)/(1024.0*1024.0); double usedDiskSize = (double)(diskInfo.f_bsize*diskInfo.f_blocks-diskInfo.f_bsize*diskInfo.f_bfree)/(1024.0*1024.0); printf("mem total:%.2fMB,mem used:%.2fMB,disk total:%.2fMB,disk used:%.2fMB\n",totalMemSize,usedMemSize,totalDiskSize,usedDiskSize ); Json::Value root; Json::Value re_data; root["is_app"] = false; root["protocol"] = API_DEVICE_BASE_INFO; root["data"] = re_data; bufferevent_write(bufEvent, root.toStyledString().c_str(), root.toStyledString().length()); } //键盘按下 void handlerKeyDown(struct bufferevent * bufEvent,Json::Value &data){ printf("key down:%s\n", data["data"].toStyledString().c_str()); } //获取MAC地址 string getMacAddress(){ char buff[32]; memset (buff ,'\0', sizeof(buff)); string cmd = "ip addr |grep -A 2 "+network_card_name+" | awk 'NR>1'|awk 'NR<2'|awk '{print $2}'" // 通过管道来回去系统命令返回的值 FILE *fstream = popen(cmd.c_str (), "r"); if(fstream == NULL) { perror("popen"); exit(0); } if(NULL == fgets (buff, sizeof(buff), fstream)){ printf("not find mac address !!!\n"); exit(0); } pclose(fstream); return string(buff); } //调用方法 void callFunc(struct bufferevent * bufEvent,Json::Value &request_data,const string func){ if(func.length() == 0){ return; } if (client_api_list.count(func)) { (*(client_api_list[func]))(bufEvent,request_data); } } void sendDeviceInfo(struct bufferevent * bufEvent){ Json::Value root; Json::Value data; //获取MAC地址 data["mac"] = getMacAddress(); data["name"] = device_name; root["protocol"] = API_DEVICE_INFO; root["is_app"] = false; root["data"] = data; string json = root.toStyledString(); bufferevent_write(bufEvent, json.c_str(), json.length()); } //读操作 void ReadEventCb(struct bufferevent *bufEvent, void *args){ Json::Reader reader; Json::Value data; //获取输入缓存 struct evbuffer * pInput = bufferevent_get_input(bufEvent); //获取输入缓存数据的长度 int len = evbuffer_get_length(pInput); //获取数据 char* body = new char[len+1]; memset(body,0,sizeof(char)*(len+1)); evbuffer_remove(pInput, body, len); if(reader.parse(body, data)){ string func = data["protocol"].asString(); callFunc(bufEvent,data,func); } delete[] body; return ; } //写操作 void WriteEventCb(struct bufferevent *bufEvent, void *args){ } //关闭 void SignalEventCb(struct bufferevent * bufEvent, short sEvent, void * args){ //请求的连接过程已经完成 if(BEV_EVENT_CONNECTED == sEvent){ bufferevent_enable(bufEvent, EV_READ); //设置读超时时间 10s struct timeval tTimeout = {10, 0}; bufferevent_set_timeouts( bufEvent, &tTimeout, NULL); string mac = getMacAddress(); if(mac.length() == 0){ printf("MAC地址获取错误请检查网卡配置\n"); event_base_loopexit(baseEvent, NULL); exit(0); } //发送基本信息 sendDeviceInfo(bufEvent); } //写操作发生事件 if(BEV_EVENT_WRITING & sEvent){} //操作时发生错误 if (sEvent & BEV_EVENT_ERROR){ perror("event"); event_base_loopexit(baseEvent, NULL); } //结束指示 if (sEvent & BEV_EVENT_EOF){ perror("event"); event_base_loopexit(baseEvent, NULL); } //读取发生事件或者超时处理 if(0 != (sEvent & (BEV_EVENT_TIMEOUT|BEV_EVENT_READING)) ){ //发送心跳包 // //重新注册可读事件 bufferevent_enable(bufEvent, EV_READ); } return ; } void setConfig(const char* config_path){ Config config; //检测配置文件是否存在 if(!config.FileExist(config_path)){ printf("config: not find config file\n"); exit(0); } //读取配置 config.ReadFile(config_path); api_host = config.Read("SERVER_HOST", api_host); api_port = config.Read("API_PORT", api_port); network_card_name = config.Read("NETWORK_CARD", network_card_name); device_name = config.Read("DEVICE_NAME", device_name); } void startRun(const char* ip,int port){ //创建事件驱动句柄 baseEvent = event_base_new(); //创建socket类型的bufferevent struct bufferevent* bufferEvent = bufferevent_socket_new(baseEvent, -1, 0); //构造服务器地址 struct sockaddr_in sin; memset(&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; sin.sin_addr.s_addr = inet_addr(api_host.c_str()); sin.sin_port = htons(api_port); //连接服务器 if( bufferevent_socket_connect(bufferEvent, (struct sockaddr*)&sin, sizeof(sin)) < 0){ perror("socket"); return; } //设置回调函数, 及回调函数的参数 bufferevent_setcb(bufferEvent, ReadEventCb, WriteEventCb, SignalEventCb,NULL); //开始事件循环 event_base_dispatch(baseEvent); //事件循环结束 资源清理 bufferevent_free(bufferEvent); event_base_free(baseEvent); } //初始化API列表 void initApiList() { client_api_list[API_DEVICE_BASE_INFO] = &handlerGetDeviceBaseInfo; client_api_list[API_DEVICE_KEY_DOWN] = &handlerKeyDown; } int main(){ //加载API列表 initApiList(); //加载配置文件 setConfig(CONFIG_PATH); //启动sockt startRun(api_host.c_str(),api_port); return 0; } <|endoftext|>
<commit_before>/*===========================================================================*\ * * * OpenMesh * * Copyright (C) 2001-2011 by Computer Graphics Group, RWTH Aachen * * www.openmesh.org * * * *---------------------------------------------------------------------------* * This file is part of OpenMesh. * * * * OpenMesh 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 3 of * * the License, or (at your option) any later version with the * * following exceptions: * * * * If other files instantiate templates or use macros * * or inline functions from this file, or you compile this file and * * link it with other files to produce an executable, this file does * * not by itself cause the resulting executable to be covered by the * * GNU Lesser General Public License. This exception does not however * * invalidate any other reasons why the executable file might be * * covered by the GNU Lesser General Public License. * * * * OpenMesh 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 LesserGeneral Public * * License along with OpenMesh. If not, * * see <http://www.gnu.org/licenses/>. * * * \*===========================================================================*/ /*===========================================================================*\ * * * $Revision$ * * $Date$ * * * \*===========================================================================*/ //============================================================================= // // CLASS PolyMeshT - IMPLEMENTATION // //============================================================================= #define OPENMESH_POLYMESH_C //== INCLUDES ================================================================= #include <OpenMesh/Core/Mesh/PolyMeshT.hh> #include <OpenMesh/Core/Geometry/LoopSchemeMaskT.hh> #include <OpenMesh/Core/Utils/vector_cast.hh> #include <OpenMesh/Core/System/omstream.hh> #include <vector> //== NAMESPACES =============================================================== namespace OpenMesh { //== IMPLEMENTATION ========================================================== template <class Kernel> uint PolyMeshT<Kernel>::find_feature_edges(Scalar _angle_tresh) { assert(Kernel::has_edge_status());//this function needs edge status property uint n_feature_edges = 0; for (EdgeIter e_it = Kernel::edges_begin(); e_it != Kernel::edges_end(); ++e_it) { if (fabs(calc_dihedral_angle(e_it)) > _angle_tresh) {//note: could be optimized by comparing cos(dih_angle) vs. cos(_angle_tresh) status(e_it).set_feature(true); n_feature_edges++; } else { status(e_it).set_feature(false); } } return n_feature_edges; } //----------------------------------------------------------------------------- template <class Kernel> typename PolyMeshT<Kernel>::Normal PolyMeshT<Kernel>:: calc_face_normal(FaceHandle _fh) const { assert(this->halfedge_handle(_fh).is_valid()); ConstFaceVertexIter fv_it(this->cfv_iter(_fh)); Point p0 = this->point(fv_it); Point p0i = p0; //save point of vertex 0 ++fv_it; Point p1 = this->point(fv_it); Point p1i = p1; //save point of vertex 1 ++fv_it; Point p2; //calculate area-weighted average normal of polygon's ears Normal n(0,0,0); for(; fv_it; ++fv_it) { p2 = this->point(fv_it); n += vector_cast<Normal>(calc_face_normal(p0, p1, p2)); p0 = p1; p1 = p2; } //two additional steps since we started at vertex 2, not 0 n += vector_cast<Normal>(calc_face_normal(p0i, p0, p1)); n += vector_cast<Normal>(calc_face_normal(p1i, p0i, p1)); typename Normal::value_type norm = n.length(); // The expression ((n *= (1.0/norm)),n) is used because the OpenSG // vector class does not return self after component-wise // self-multiplication with a scalar!!! return (norm != typename Normal::value_type(0)) ? ((n *= (typename Normal::value_type(1)/norm)),n) : Normal(0,0,0); } //----------------------------------------------------------------------------- template <class Kernel> typename PolyMeshT<Kernel>::Normal PolyMeshT<Kernel>:: calc_face_normal(const Point& _p0, const Point& _p1, const Point& _p2) const { #if 1 // The OpenSG <Vector>::operator -= () does not support the type Point // as rhs. Therefore use vector_cast at this point!!! // Note! OpenSG distinguishes between Normal and Point!!! Normal p1p0(vector_cast<Normal>(_p0)); p1p0 -= vector_cast<Normal>(_p1); Normal p1p2(vector_cast<Normal>(_p2)); p1p2 -= vector_cast<Normal>(_p1); Normal n = cross(p1p2, p1p0); typename Normal::value_type norm = n.length(); // The expression ((n *= (1.0/norm)),n) is used because the OpenSG // vector class does not return self after component-wise // self-multiplication with a scalar!!! return (norm != typename Normal::value_type(0)) ? ((n *= (typename Normal::value_type(1)/norm)),n) : Normal(0,0,0); #else Point p1p0 = _p0; p1p0 -= _p1; Point p1p2 = _p2; p1p2 -= _p1; Normal n = vector_cast<Normal>(cross(p1p2, p1p0)); typename Normal::value_type norm = n.length(); return (norm != 0.0) ? n *= (1.0/norm) : Normal(0,0,0); #endif } //----------------------------------------------------------------------------- template <class Kernel> void PolyMeshT<Kernel>:: calc_face_centroid(FaceHandle _fh, Point& _pt) const { _pt.vectorize(0); Scalar valence = 0.0; for (ConstFaceVertexIter cfv_it = this->cfv_iter(_fh); cfv_it; ++cfv_it, valence += 1.0) { _pt += this->point(cfv_it); } _pt /= valence; } //----------------------------------------------------------------------------- template <class Kernel> void PolyMeshT<Kernel>:: update_normals() { // Face normals are required to compute the vertex and the halfedge normals if (Kernel::has_face_normals() ) { update_face_normals(); if (Kernel::has_vertex_normals() ) update_vertex_normals(); if (Kernel::has_halfedge_normals()) update_halfedge_normals(); } } //----------------------------------------------------------------------------- template <class Kernel> void PolyMeshT<Kernel>:: update_face_normals() { FaceIter f_it(Kernel::faces_begin()), f_end(Kernel::faces_end()); for (; f_it != f_end; ++f_it) this->set_normal(f_it.handle(), calc_face_normal(f_it.handle())); } //----------------------------------------------------------------------------- template <class Kernel> void PolyMeshT<Kernel>:: update_halfedge_normals(const double _feature_angle) { HalfedgeIter h_it(Kernel::halfedges_begin()), h_end(Kernel::halfedges_end()); for (; h_it != h_end; ++h_it) this->set_normal(h_it.handle(), calc_halfedge_normal(h_it.handle(), _feature_angle)); } //----------------------------------------------------------------------------- template <class Kernel> typename PolyMeshT<Kernel>::Normal PolyMeshT<Kernel>:: calc_halfedge_normal(HalfedgeHandle _heh, const double _feature_angle) const { if(Kernel::is_boundary(_heh)) return Normal(0,0,0); else { std::vector<FaceHandle> fhs; fhs.reserve(10); HalfedgeHandle heh = _heh; // collect CW face-handles do { fhs.push_back(Kernel::face_handle(heh)); heh = Kernel::next_halfedge_handle(heh); heh = Kernel::opposite_halfedge_handle(heh); } while(heh != _heh && !Kernel::is_boundary(heh) && !is_estimated_feature_edge(heh, _feature_angle)); // collect CCW face-handles if(heh != _heh && !is_estimated_feature_edge(_heh, _feature_angle)) { heh = Kernel::opposite_halfedge_handle(_heh); if ( !Kernel::is_boundary(heh) ) { do { fhs.push_back(Kernel::face_handle(heh)); heh = Kernel::prev_halfedge_handle(heh); heh = Kernel::opposite_halfedge_handle(heh); } while(!Kernel::is_boundary(heh) && !is_estimated_feature_edge(heh, _feature_angle)); } } Normal n(0,0,0); for(unsigned int i=0; i<fhs.size(); ++i) n += Kernel::normal(fhs[i]); return n.normalize(); } } //----------------------------------------------------------------------------- template <class Kernel> bool PolyMeshT<Kernel>:: is_estimated_feature_edge(HalfedgeHandle _heh, const double _feature_angle) const { EdgeHandle eh = Kernel::edge_handle(_heh); if(Kernel::has_edge_status()) { if(Kernel::status(eh).feature()) return true; } if(Kernel::is_boundary(eh)) return false; // compute angle between faces FaceHandle fh0 = Kernel::face_handle(_heh); FaceHandle fh1 = Kernel::face_handle(Kernel::opposite_halfedge_handle(_heh)); Normal fn0 = Kernel::normal(fh0); Normal fn1 = Kernel::normal(fh1); // dihedral angle above angle threshold return ( dot(fn0,fn1) < cos(_feature_angle) ); } //----------------------------------------------------------------------------- template <class Kernel> typename PolyMeshT<Kernel>::Normal PolyMeshT<Kernel>:: calc_vertex_normal(VertexHandle _vh) const { Normal n; calc_vertex_normal_fast(_vh,n); Scalar norm = n.length(); if (norm != 0.0) n *= (1.0/norm); return n; } //----------------------------------------------------------------------------- template <class Kernel> void PolyMeshT<Kernel>:: calc_vertex_normal_fast(VertexHandle _vh, Normal& _n) const { _n.vectorize(0.0); for (ConstVertexFaceIter vf_it=this->cvf_iter(_vh); vf_it; ++vf_it) _n += this->normal(vf_it.handle()); } //----------------------------------------------------------------------------- template <class Kernel> void PolyMeshT<Kernel>:: calc_vertex_normal_correct(VertexHandle _vh, Normal& _n) const { _n.vectorize(0.0); ConstVertexIHalfedgeIter cvih_it = cvih_iter(_vh); if (!cvih_it) {//don't crash on isolated vertices return; } Normal in_he_vec; calc_edge_vector(cvih_it, in_he_vec); for ( ; cvih_it; ++cvih_it) {//calculates the sector normal defined by cvih_it and adds it to _n if (is_boundary(cvih_it)) { continue; } HalfedgeHandle out_heh(next_halfedge_handle(cvih_it)); Normal out_he_vec; calc_edge_vector(out_heh, out_he_vec); _n += cross(in_he_vec, out_he_vec);//sector area is taken into account in_he_vec = out_he_vec; in_he_vec *= -1;//change the orientation } } //----------------------------------------------------------------------------- template <class Kernel> void PolyMeshT<Kernel>:: calc_vertex_normal_loop(VertexHandle _vh, Normal& _n) const { static const LoopSchemeMaskDouble& loop_scheme_mask__ = LoopSchemeMaskDoubleSingleton::Instance(); Normal t_v(0.0,0.0,0.0), t_w(0.0,0.0,0.0); unsigned int vh_val = valence(_vh); unsigned int i = 0; for (ConstVertexOHalfedgeIter cvoh_it = cvoh_iter(_vh); cvoh_it; ++cvoh_it, ++i) { VertexHandle r1_v(to_vertex_handle(cvoh_it)); t_v += (typename Point::value_type)(loop_scheme_mask__.tang0_weight(vh_val, i))*this->point(r1_v); t_w += (typename Point::value_type)(loop_scheme_mask__.tang1_weight(vh_val, i))*this->point(r1_v); } _n = cross(t_w, t_v);//hack: should be cross(t_v, t_w), but then the normals are reversed? } //----------------------------------------------------------------------------- template <class Kernel> void PolyMeshT<Kernel>:: update_vertex_normals() { VertexIter v_it(Kernel::vertices_begin()), v_end(Kernel::vertices_end()); for (; v_it!=v_end; ++v_it) this->set_normal(v_it.handle(), calc_vertex_normal(v_it.handle())); } //============================================================================= } // namespace OpenMesh //============================================================================= <commit_msg>Fixed the usage of vector traits such that the traits are used and not the vector types value_type. (Thanks to Mario Deuss for the patch)<commit_after>/*===========================================================================*\ * * * OpenMesh * * Copyright (C) 2001-2011 by Computer Graphics Group, RWTH Aachen * * www.openmesh.org * * * *---------------------------------------------------------------------------* * This file is part of OpenMesh. * * * * OpenMesh 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 3 of * * the License, or (at your option) any later version with the * * following exceptions: * * * * If other files instantiate templates or use macros * * or inline functions from this file, or you compile this file and * * link it with other files to produce an executable, this file does * * not by itself cause the resulting executable to be covered by the * * GNU Lesser General Public License. This exception does not however * * invalidate any other reasons why the executable file might be * * covered by the GNU Lesser General Public License. * * * * OpenMesh 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 LesserGeneral Public * * License along with OpenMesh. If not, * * see <http://www.gnu.org/licenses/>. * * * \*===========================================================================*/ /*===========================================================================*\ * * * $Revision$ * * $Date$ * * * \*===========================================================================*/ //============================================================================= // // CLASS PolyMeshT - IMPLEMENTATION // //============================================================================= #define OPENMESH_POLYMESH_C //== INCLUDES ================================================================= #include <OpenMesh/Core/Mesh/PolyMeshT.hh> #include <OpenMesh/Core/Geometry/LoopSchemeMaskT.hh> #include <OpenMesh/Core/Utils/vector_cast.hh> #include <OpenMesh/Core/System/omstream.hh> #include <vector> //== NAMESPACES =============================================================== namespace OpenMesh { //== IMPLEMENTATION ========================================================== template <class Kernel> uint PolyMeshT<Kernel>::find_feature_edges(Scalar _angle_tresh) { assert(Kernel::has_edge_status());//this function needs edge status property uint n_feature_edges = 0; for (EdgeIter e_it = Kernel::edges_begin(); e_it != Kernel::edges_end(); ++e_it) { if (fabs(calc_dihedral_angle(e_it)) > _angle_tresh) {//note: could be optimized by comparing cos(dih_angle) vs. cos(_angle_tresh) status(e_it).set_feature(true); n_feature_edges++; } else { status(e_it).set_feature(false); } } return n_feature_edges; } //----------------------------------------------------------------------------- template <class Kernel> typename PolyMeshT<Kernel>::Normal PolyMeshT<Kernel>:: calc_face_normal(FaceHandle _fh) const { assert(this->halfedge_handle(_fh).is_valid()); ConstFaceVertexIter fv_it(this->cfv_iter(_fh)); Point p0 = this->point(fv_it); Point p0i = p0; //save point of vertex 0 ++fv_it; Point p1 = this->point(fv_it); Point p1i = p1; //save point of vertex 1 ++fv_it; Point p2; //calculate area-weighted average normal of polygon's ears Normal n(0,0,0); for(; fv_it; ++fv_it) { p2 = this->point(fv_it); n += vector_cast<Normal>(calc_face_normal(p0, p1, p2)); p0 = p1; p1 = p2; } //two additional steps since we started at vertex 2, not 0 n += vector_cast<Normal>(calc_face_normal(p0i, p0, p1)); n += vector_cast<Normal>(calc_face_normal(p1i, p0i, p1)); typename vector_traits<Normal>::value_type norm = n.length(); // The expression ((n *= (1.0/norm)),n) is used because the OpenSG // vector class does not return self after component-wise // self-multiplication with a scalar!!! return (norm != typename vector_traits<Normal>::value_type(0)) ? ((n *= (typename vector_traits<Normal>::value_type(1)/norm)),n) : Normal(0,0,0); } //----------------------------------------------------------------------------- template <class Kernel> typename PolyMeshT<Kernel>::Normal PolyMeshT<Kernel>:: calc_face_normal(const Point& _p0, const Point& _p1, const Point& _p2) const { #if 1 // The OpenSG <Vector>::operator -= () does not support the type Point // as rhs. Therefore use vector_cast at this point!!! // Note! OpenSG distinguishes between Normal and Point!!! Normal p1p0(vector_cast<Normal>(_p0)); p1p0 -= vector_cast<Normal>(_p1); Normal p1p2(vector_cast<Normal>(_p2)); p1p2 -= vector_cast<Normal>(_p1); Normal n = cross(p1p2, p1p0); typename vector_traits<Normal>::value_type norm = n.length(); // The expression ((n *= (1.0/norm)),n) is used because the OpenSG // vector class does not return self after component-wise // self-multiplication with a scalar!!! return (norm != typename vector_traits<Normal>::value_type(0)) ? ((n *= (typename vector_traits<Normal>::value_type(1)/norm)),n) : Normal(0,0,0); #else Point p1p0 = _p0; p1p0 -= _p1; Point p1p2 = _p2; p1p2 -= _p1; Normal n = vector_cast<Normal>(cross(p1p2, p1p0)); typename vector_traits<Normal>::value_type norm = n.length(); return (norm != 0.0) ? n *= (1.0/norm) : Normal(0,0,0); #endif } //----------------------------------------------------------------------------- template <class Kernel> void PolyMeshT<Kernel>:: calc_face_centroid(FaceHandle _fh, Point& _pt) const { _pt.vectorize(0); Scalar valence = 0.0; for (ConstFaceVertexIter cfv_it = this->cfv_iter(_fh); cfv_it; ++cfv_it, valence += 1.0) { _pt += this->point(cfv_it); } _pt /= valence; } //----------------------------------------------------------------------------- template <class Kernel> void PolyMeshT<Kernel>:: update_normals() { // Face normals are required to compute the vertex and the halfedge normals if (Kernel::has_face_normals() ) { update_face_normals(); if (Kernel::has_vertex_normals() ) update_vertex_normals(); if (Kernel::has_halfedge_normals()) update_halfedge_normals(); } } //----------------------------------------------------------------------------- template <class Kernel> void PolyMeshT<Kernel>:: update_face_normals() { FaceIter f_it(Kernel::faces_begin()), f_end(Kernel::faces_end()); for (; f_it != f_end; ++f_it) this->set_normal(f_it.handle(), calc_face_normal(f_it.handle())); } //----------------------------------------------------------------------------- template <class Kernel> void PolyMeshT<Kernel>:: update_halfedge_normals(const double _feature_angle) { HalfedgeIter h_it(Kernel::halfedges_begin()), h_end(Kernel::halfedges_end()); for (; h_it != h_end; ++h_it) this->set_normal(h_it.handle(), calc_halfedge_normal(h_it.handle(), _feature_angle)); } //----------------------------------------------------------------------------- template <class Kernel> typename PolyMeshT<Kernel>::Normal PolyMeshT<Kernel>:: calc_halfedge_normal(HalfedgeHandle _heh, const double _feature_angle) const { if(Kernel::is_boundary(_heh)) return Normal(0,0,0); else { std::vector<FaceHandle> fhs; fhs.reserve(10); HalfedgeHandle heh = _heh; // collect CW face-handles do { fhs.push_back(Kernel::face_handle(heh)); heh = Kernel::next_halfedge_handle(heh); heh = Kernel::opposite_halfedge_handle(heh); } while(heh != _heh && !Kernel::is_boundary(heh) && !is_estimated_feature_edge(heh, _feature_angle)); // collect CCW face-handles if(heh != _heh && !is_estimated_feature_edge(_heh, _feature_angle)) { heh = Kernel::opposite_halfedge_handle(_heh); if ( !Kernel::is_boundary(heh) ) { do { fhs.push_back(Kernel::face_handle(heh)); heh = Kernel::prev_halfedge_handle(heh); heh = Kernel::opposite_halfedge_handle(heh); } while(!Kernel::is_boundary(heh) && !is_estimated_feature_edge(heh, _feature_angle)); } } Normal n(0,0,0); for(unsigned int i=0; i<fhs.size(); ++i) n += Kernel::normal(fhs[i]); return n.normalize(); } } //----------------------------------------------------------------------------- template <class Kernel> bool PolyMeshT<Kernel>:: is_estimated_feature_edge(HalfedgeHandle _heh, const double _feature_angle) const { EdgeHandle eh = Kernel::edge_handle(_heh); if(Kernel::has_edge_status()) { if(Kernel::status(eh).feature()) return true; } if(Kernel::is_boundary(eh)) return false; // compute angle between faces FaceHandle fh0 = Kernel::face_handle(_heh); FaceHandle fh1 = Kernel::face_handle(Kernel::opposite_halfedge_handle(_heh)); Normal fn0 = Kernel::normal(fh0); Normal fn1 = Kernel::normal(fh1); // dihedral angle above angle threshold return ( dot(fn0,fn1) < cos(_feature_angle) ); } //----------------------------------------------------------------------------- template <class Kernel> typename PolyMeshT<Kernel>::Normal PolyMeshT<Kernel>:: calc_vertex_normal(VertexHandle _vh) const { Normal n; calc_vertex_normal_fast(_vh,n); Scalar norm = n.length(); if (norm != 0.0) n *= (1.0/norm); return n; } //----------------------------------------------------------------------------- template <class Kernel> void PolyMeshT<Kernel>:: calc_vertex_normal_fast(VertexHandle _vh, Normal& _n) const { _n.vectorize(0.0); for (ConstVertexFaceIter vf_it=this->cvf_iter(_vh); vf_it; ++vf_it) _n += this->normal(vf_it.handle()); } //----------------------------------------------------------------------------- template <class Kernel> void PolyMeshT<Kernel>:: calc_vertex_normal_correct(VertexHandle _vh, Normal& _n) const { _n.vectorize(0.0); ConstVertexIHalfedgeIter cvih_it = cvih_iter(_vh); if (!cvih_it) {//don't crash on isolated vertices return; } Normal in_he_vec; calc_edge_vector(cvih_it, in_he_vec); for ( ; cvih_it; ++cvih_it) {//calculates the sector normal defined by cvih_it and adds it to _n if (is_boundary(cvih_it)) { continue; } HalfedgeHandle out_heh(next_halfedge_handle(cvih_it)); Normal out_he_vec; calc_edge_vector(out_heh, out_he_vec); _n += cross(in_he_vec, out_he_vec);//sector area is taken into account in_he_vec = out_he_vec; in_he_vec *= -1;//change the orientation } } //----------------------------------------------------------------------------- template <class Kernel> void PolyMeshT<Kernel>:: calc_vertex_normal_loop(VertexHandle _vh, Normal& _n) const { static const LoopSchemeMaskDouble& loop_scheme_mask__ = LoopSchemeMaskDoubleSingleton::Instance(); Normal t_v(0.0,0.0,0.0), t_w(0.0,0.0,0.0); unsigned int vh_val = valence(_vh); unsigned int i = 0; for (ConstVertexOHalfedgeIter cvoh_it = cvoh_iter(_vh); cvoh_it; ++cvoh_it, ++i) { VertexHandle r1_v(to_vertex_handle(cvoh_it)); t_v += (typename vector_traits<Point>::value_type)(loop_scheme_mask__.tang0_weight(vh_val, i))*this->point(r1_v); t_w += (typename vector_traits<Point>::value_type)(loop_scheme_mask__.tang1_weight(vh_val, i))*this->point(r1_v); } _n = cross(t_w, t_v);//hack: should be cross(t_v, t_w), but then the normals are reversed? } //----------------------------------------------------------------------------- template <class Kernel> void PolyMeshT<Kernel>:: update_vertex_normals() { VertexIter v_it(Kernel::vertices_begin()), v_end(Kernel::vertices_end()); for (; v_it!=v_end; ++v_it) this->set_normal(v_it.handle(), calc_vertex_normal(v_it.handle())); } //============================================================================= } // namespace OpenMesh //============================================================================= <|endoftext|>
<commit_before>#pragma once #include <agency/detail/config.hpp> #include <thrust/system_error.h> #include <thrust/system/cuda/error.h> #include <cuda_runtime.h> namespace agency { namespace cuda { namespace detail { template<class T> class managed_allocator { public: using value_type = T; value_type* allocate(size_t n) { value_type* result = nullptr; cudaError_t error = cudaMallocManaged(&result, n * sizeof(T), cudaMemAttachGlobal); if(error != cudaSuccess) { throw thrust::system_error(error, thrust::cuda_category(), "managed_allocator::allocate(): cudaMallocManaged"); } return result; } void deallocate(value_type* ptr, size_t) { cudaError_t error = cudaFree(ptr); if(error != cudaSuccess) { throw thrust::system_error(error, thrust::cuda_category(), "managed_allocator::deallocate(): cudaFree"); } } template<class U, class... Args> void construct(U* ptr, Args&&... args) { cudaError_t error = cudaDeviceSynchronize(); if(error != cudaSuccess) { throw thrust::system_error(error, thrust::cuda_category(), "managed_allocator::allocate(): cudaDeviceSynchronize"); } new(ptr) T(std::forward<Args>(args)...); } }; } // end detail } // end cuda } // end agency <commit_msg>Associate a device with managed_allocator Synchronize the entire system within managed_allocator::construct()<commit_after>#pragma once #include <agency/detail/config.hpp> #include <agency/cuda/device.hpp> #include <thrust/system_error.h> #include <thrust/system/cuda/error.h> #include <cuda_runtime.h> namespace agency { namespace cuda { namespace detail { template<class T> class managed_allocator { private: device_id device_; const device_id& device() const { return device_; } public: using value_type = T; managed_allocator() : device_() { auto devices = all_devices(); if(!devices.empty()) { device_ = devices[0]; } } value_type* allocate(size_t n) { // switch to our device scoped_current_device set_current_device(device()); value_type* result = nullptr; cudaError_t error = cudaMallocManaged(&result, n * sizeof(T), cudaMemAttachGlobal); if(error != cudaSuccess) { throw thrust::system_error(error, thrust::cuda_category(), "managed_allocator::allocate(): cudaMallocManaged"); } return result; } void deallocate(value_type* ptr, size_t) { // switch to our device scoped_current_device set_current_device(device()); cudaError_t error = cudaFree(ptr); if(error != cudaSuccess) { throw thrust::system_error(error, thrust::cuda_category(), "managed_allocator::deallocate(): cudaFree"); } } template<class U, class... Args> void construct(U* ptr, Args&&... args) { // we need to synchronize with all devices before touching the ptr detail::wait(all_devices()); new(ptr) T(std::forward<Args>(args)...); } }; } // end detail } // end cuda } // end agency <|endoftext|>
<commit_before><commit_msg>[PartDesign] Remove 'Set tip' from Body contextual menu ; fixes #4304<commit_after><|endoftext|>
<commit_before>/** * Copyright (C) 2016 3D Repo Ltd * * 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/>. */ #include "repo_maker_selection_tree.h" #include "../../core/model/bson/repo_node_reference.h" #include "../modeloptimizer/repo_optimizer_ifc.h" using namespace repo::manipulator::modelutility; const static std::string REPO_LABEL_VISIBILITY_STATE = "toggleState"; const static std::string REPO_VISIBILITY_STATE_SHOW = "visible"; const static std::string REPO_VISIBILITY_STATE_HIDDEN = "invisible"; const static std::string REPO_VISIBILITY_STATE_HALF_HIDDEN = "parentOfInvisible"; SelectionTreeMaker::SelectionTreeMaker( const repo::core::model::RepoScene *scene) : scene(scene) { } repo::lib::PropertyTree SelectionTreeMaker::generatePTree( const repo::core::model::RepoNode *currentNode, std::unordered_map < std::string, std::pair < std::string, std::string >> &idMaps, const std::string &currentPath, bool &hiddenOnDefault, std::vector<std::string> &hiddenNode) const { repo::lib::PropertyTree tree; if (currentNode) { std::string idString = currentNode->getUniqueID().toString(); repo::lib::RepoUUID sharedID = currentNode->getSharedID(); std::string childPath = currentPath.empty() ? idString : currentPath + "__" + idString; auto children = scene->getChildrenAsNodes(repo::core::model::RepoScene::GraphType::DEFAULT, sharedID); std::vector<repo::lib::PropertyTree> childrenTrees; std::vector<repo::core::model::RepoNode*> childrenTypes[2]; std::vector<repo::lib::RepoUUID> metaIDs; for (const auto &child : children) { //Ensure IFC Space (if any) are put into the tree first. if (child->getName().find(IFC_TYPE_SPACE_LABEL) != std::string::npos) childrenTypes[0].push_back(child); else if (child->getTypeAsEnum() == repo::core::model::NodeType::METADATA) { metaIDs.push_back(child->getUniqueID()); } else childrenTypes[1].push_back(child); } bool hasHiddenChildren = false; for (const auto childrenSet : childrenTypes) { for (const auto &child : childrenSet) { if (child) { switch (child->getTypeAsEnum()) { case repo::core::model::NodeType::MESH: case repo::core::model::NodeType::TRANSFORMATION: case repo::core::model::NodeType::CAMERA: case repo::core::model::NodeType::REFERENCE: { bool hiddenChild = false; childrenTrees.push_back(generatePTree(child, idMaps, childPath, hiddenChild, hiddenNode)); hasHiddenChildren = hasHiddenChildren || hiddenChild; } } } else { repoDebug << "Null pointer for child node at generatePTree, current path : " << currentPath; repoError << "Unexpected error at selection tree generation, the tree may not be complete."; } } } std::string name = currentNode->getName(); if (repo::core::model::NodeType::REFERENCE == currentNode->getTypeAsEnum()) { if (auto refNode = dynamic_cast<const repo::core::model::ReferenceNode*>(currentNode)) { auto refDb = refNode->getDatabaseName(); name = (scene->getDatabaseName() == refDb ? "" : (refDb + "/")) + refNode->getProjectName(); } } tree.addToTree("account", scene->getDatabaseName()); tree.addToTree("project", scene->getProjectName()); if (!name.empty()) tree.addToTree("name", name); tree.addToTree("path", childPath); tree.addToTree("_id", idString); tree.addToTree("shared_id", sharedID.toString()); tree.addToTree("children", childrenTrees); tree.addToTree("meta", metaIDs); if (name.find(IFC_TYPE_SPACE_LABEL) != std::string::npos && currentNode->getTypeAsEnum() == repo::core::model::NodeType::MESH) { tree.addToTree(REPO_LABEL_VISIBILITY_STATE, REPO_VISIBILITY_STATE_HIDDEN); hiddenOnDefault = true; hiddenNode.push_back(idString); } else if (hiddenOnDefault = hiddenOnDefault || hasHiddenChildren) { tree.addToTree(REPO_LABEL_VISIBILITY_STATE, REPO_VISIBILITY_STATE_HALF_HIDDEN); } else { tree.addToTree(REPO_LABEL_VISIBILITY_STATE, REPO_VISIBILITY_STATE_SHOW); } idMaps[idString] = { name, childPath }; } else { repoDebug << "Null pointer at generatePTree, current path : " << currentPath; repoError << "Unexpected error at selection tree generation, the tree may not be complete."; } return tree; } std::map<std::string, std::vector<uint8_t>> SelectionTreeMaker::getSelectionTreeAsBuffer() const { auto trees = getSelectionTreeAsPropertyTree(); std::map<std::string, std::vector<uint8_t>> buffer; for (const auto &tree : trees) { std::stringstream ss; tree.second.write_json(ss); std::string jsonString = ss.str(); if (!jsonString.empty()) { size_t byteLength = jsonString.size() * sizeof(*jsonString.data()); buffer[tree.first] = std::vector<uint8_t>(); buffer[tree.first].resize(byteLength); memcpy(buffer[tree.first].data(), jsonString.data(), byteLength); } else { repoError << "Failed to write selection tree into the buffer: JSON string is empty."; } } return buffer; } std::map<std::string, repo::lib::PropertyTree> SelectionTreeMaker::getSelectionTreeAsPropertyTree() const { std::map<std::string, repo::lib::PropertyTree> trees; repo::core::model::RepoNode *root; if (scene && (root = scene->getRoot(repo::core::model::RepoScene::GraphType::DEFAULT))) { std::unordered_map< std::string, std::pair<std::string, std::string>> map; std::vector<std::string> hiddenNodes; bool dummy; repo::lib::PropertyTree tree, settingsTree; tree.mergeSubTree("nodes", generatePTree(root, map, "", dummy, hiddenNodes)); for (const auto pair : map) { //if there's an entry in maps it must have an entry in paths tree.addToTree("idToName." + pair.first, pair.second.first); tree.addToTree("idToPath." + pair.first, pair.second.second); } trees["fulltree.json"] = tree; if (hiddenNodes.size()) { settingsTree.addToTree("hiddenNodes", hiddenNodes); trees["modelProperties.json"] = settingsTree; } } else { repoError << "Failed to generate selection tree: scene is empty or default scene is not loaded"; } return trees; } SelectionTreeMaker::~SelectionTreeMaker() { }<commit_msg>#165 do not create a meta field if there are no metadata IDs to print<commit_after>/** * Copyright (C) 2016 3D Repo Ltd * * 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/>. */ #include "repo_maker_selection_tree.h" #include "../../core/model/bson/repo_node_reference.h" #include "../modeloptimizer/repo_optimizer_ifc.h" using namespace repo::manipulator::modelutility; const static std::string REPO_LABEL_VISIBILITY_STATE = "toggleState"; const static std::string REPO_VISIBILITY_STATE_SHOW = "visible"; const static std::string REPO_VISIBILITY_STATE_HIDDEN = "invisible"; const static std::string REPO_VISIBILITY_STATE_HALF_HIDDEN = "parentOfInvisible"; SelectionTreeMaker::SelectionTreeMaker( const repo::core::model::RepoScene *scene) : scene(scene) { } repo::lib::PropertyTree SelectionTreeMaker::generatePTree( const repo::core::model::RepoNode *currentNode, std::unordered_map < std::string, std::pair < std::string, std::string >> &idMaps, const std::string &currentPath, bool &hiddenOnDefault, std::vector<std::string> &hiddenNode) const { repo::lib::PropertyTree tree; if (currentNode) { std::string idString = currentNode->getUniqueID().toString(); repo::lib::RepoUUID sharedID = currentNode->getSharedID(); std::string childPath = currentPath.empty() ? idString : currentPath + "__" + idString; auto children = scene->getChildrenAsNodes(repo::core::model::RepoScene::GraphType::DEFAULT, sharedID); std::vector<repo::lib::PropertyTree> childrenTrees; std::vector<repo::core::model::RepoNode*> childrenTypes[2]; std::vector<repo::lib::RepoUUID> metaIDs; for (const auto &child : children) { //Ensure IFC Space (if any) are put into the tree first. if (child->getName().find(IFC_TYPE_SPACE_LABEL) != std::string::npos) childrenTypes[0].push_back(child); else if (child->getTypeAsEnum() == repo::core::model::NodeType::METADATA) { metaIDs.push_back(child->getUniqueID()); } else childrenTypes[1].push_back(child); } bool hasHiddenChildren = false; for (const auto childrenSet : childrenTypes) { for (const auto &child : childrenSet) { if (child) { switch (child->getTypeAsEnum()) { case repo::core::model::NodeType::MESH: case repo::core::model::NodeType::TRANSFORMATION: case repo::core::model::NodeType::CAMERA: case repo::core::model::NodeType::REFERENCE: { bool hiddenChild = false; childrenTrees.push_back(generatePTree(child, idMaps, childPath, hiddenChild, hiddenNode)); hasHiddenChildren = hasHiddenChildren || hiddenChild; } } } else { repoDebug << "Null pointer for child node at generatePTree, current path : " << currentPath; repoError << "Unexpected error at selection tree generation, the tree may not be complete."; } } } std::string name = currentNode->getName(); if (repo::core::model::NodeType::REFERENCE == currentNode->getTypeAsEnum()) { if (auto refNode = dynamic_cast<const repo::core::model::ReferenceNode*>(currentNode)) { auto refDb = refNode->getDatabaseName(); name = (scene->getDatabaseName() == refDb ? "" : (refDb + "/")) + refNode->getProjectName(); } } tree.addToTree("account", scene->getDatabaseName()); tree.addToTree("project", scene->getProjectName()); if (!name.empty()) tree.addToTree("name", name); tree.addToTree("path", childPath); tree.addToTree("_id", idString); tree.addToTree("shared_id", sharedID.toString()); tree.addToTree("children", childrenTrees); if (metaIDs.size()) tree.addToTree("meta", metaIDs); if (name.find(IFC_TYPE_SPACE_LABEL) != std::string::npos && currentNode->getTypeAsEnum() == repo::core::model::NodeType::MESH) { tree.addToTree(REPO_LABEL_VISIBILITY_STATE, REPO_VISIBILITY_STATE_HIDDEN); hiddenOnDefault = true; hiddenNode.push_back(idString); } else if (hiddenOnDefault = hiddenOnDefault || hasHiddenChildren) { tree.addToTree(REPO_LABEL_VISIBILITY_STATE, REPO_VISIBILITY_STATE_HALF_HIDDEN); } else { tree.addToTree(REPO_LABEL_VISIBILITY_STATE, REPO_VISIBILITY_STATE_SHOW); } idMaps[idString] = { name, childPath }; } else { repoDebug << "Null pointer at generatePTree, current path : " << currentPath; repoError << "Unexpected error at selection tree generation, the tree may not be complete."; } return tree; } std::map<std::string, std::vector<uint8_t>> SelectionTreeMaker::getSelectionTreeAsBuffer() const { auto trees = getSelectionTreeAsPropertyTree(); std::map<std::string, std::vector<uint8_t>> buffer; for (const auto &tree : trees) { std::stringstream ss; tree.second.write_json(ss); std::string jsonString = ss.str(); if (!jsonString.empty()) { size_t byteLength = jsonString.size() * sizeof(*jsonString.data()); buffer[tree.first] = std::vector<uint8_t>(); buffer[tree.first].resize(byteLength); memcpy(buffer[tree.first].data(), jsonString.data(), byteLength); } else { repoError << "Failed to write selection tree into the buffer: JSON string is empty."; } } return buffer; } std::map<std::string, repo::lib::PropertyTree> SelectionTreeMaker::getSelectionTreeAsPropertyTree() const { std::map<std::string, repo::lib::PropertyTree> trees; repo::core::model::RepoNode *root; if (scene && (root = scene->getRoot(repo::core::model::RepoScene::GraphType::DEFAULT))) { std::unordered_map< std::string, std::pair<std::string, std::string>> map; std::vector<std::string> hiddenNodes; bool dummy; repo::lib::PropertyTree tree, settingsTree; tree.mergeSubTree("nodes", generatePTree(root, map, "", dummy, hiddenNodes)); for (const auto pair : map) { //if there's an entry in maps it must have an entry in paths tree.addToTree("idToName." + pair.first, pair.second.first); tree.addToTree("idToPath." + pair.first, pair.second.second); } trees["fulltree.json"] = tree; if (hiddenNodes.size()) { settingsTree.addToTree("hiddenNodes", hiddenNodes); trees["modelProperties.json"] = settingsTree; } } else { repoError << "Failed to generate selection tree: scene is empty or default scene is not loaded"; } return trees; } SelectionTreeMaker::~SelectionTreeMaker() { }<|endoftext|>
<commit_before>#ifndef GNR_INVOKE_HPP # define GNR_INVOKE_HPP # pragma once #include <functional> #include <tuple> namespace gnr { namespace detail::invoke { template <typename> struct is_tuple : std::false_type {}; template <typename ...T> struct is_tuple<std::tuple<T...>> : std::true_type {}; template <typename T> static constexpr bool is_tuple_v(is_tuple<std::remove_cvref_t<T>>{}); template <std::size_t N> constexpr auto split(auto&& t) noexcept requires(bool(N)) { constexpr auto n(std::tuple_size_v<std::remove_cvref_t<decltype(t)>>); static_assert(n && !(n % N)); return [&]<auto ...I>(std::index_sequence<I...>) noexcept { return std::make_tuple( [&]<auto ...J>(std::index_sequence<J...>) noexcept { constexpr auto K(N * I); return std::forward_as_tuple( std::get<K + J>(std::forward<decltype(t)>(t))...); }(std::make_index_sequence<N + I - I>())... ); }(std::make_index_sequence<n / N>()); } template <typename F, typename T> constexpr bool is_noexcept_invocable() noexcept { auto const f(static_cast<std::remove_reference_t<F>*>(nullptr)); auto const t(static_cast<std::remove_reference_t<T>*>(nullptr)); return noexcept( [&]<auto ...I>(std::index_sequence<I...>) { return (std::invoke(F(*f), std::get<I>(T(*t))...)); }(std::make_index_sequence< std::tuple_size_v<std::remove_cvref_t<T>> >() ) ); } } constexpr decltype(auto) apply(auto&& f, auto&& t) noexcept( detail::invoke::is_noexcept_invocable<decltype(f), decltype(t)>() ) { return [&]<auto ...I>(std::index_sequence<I...>) noexcept(noexcept( std::invoke( std::forward<decltype(f)>(f), std::get<I>(std::forward<decltype(t)>(t))... ) ) ) { return std::invoke( std::forward<decltype(f)>(f), std::get<I>(std::forward<decltype(t)>(t))... ); }(std::make_index_sequence< std::tuple_size_v<std::remove_cvref_t<decltype(t)>> >() ); } constexpr auto invoke_all(auto f, auto&& ...a) noexcept(noexcept((f(std::forward<decltype(a)>(a)), ...))) { return (f(std::forward<decltype(a)>(a)), ...); } constexpr auto invoke_cond(auto f, auto&& ...a) noexcept(noexcept((f(std::forward<decltype(a)>(a)), ...))) { return (f(std::forward<decltype(a)>(a)) || ...); } namespace detail::invoke { template <std::size_t N, typename F, typename ...A> constexpr bool is_noexcept_split_invocable() noexcept { auto const f(static_cast<std::remove_reference_t<F>*>(nullptr)); return noexcept( ::gnr::apply([&](auto&& ...t) noexcept(noexcept( (::gnr::apply(F(*f), std::forward<decltype(t)>(t)), ...))) { (::gnr::apply(F(*f), std::forward<decltype(t)>(t)), ...); }, detail::invoke::split<N>( std::forward_as_tuple( A(*static_cast<std::remove_reference_t<A>*>(nullptr))... ) ) ) ); } } template <std::size_t N> constexpr void invoke_split(auto&& f, auto&& ...a) noexcept( detail::invoke::is_noexcept_split_invocable<N, decltype(f), decltype(a)...>() ) { ::gnr::apply( [&](auto&& ...t) noexcept(noexcept( (::gnr::apply(f, std::forward<decltype(t)>(t)), ...)) ) { (::gnr::apply(f, std::forward<decltype(t)>(t)), ...); }, detail::invoke::split<N>(std::forward_as_tuple(a...)) ); } template <std::size_t N> constexpr void invoke_split_cond(auto&& f, auto&& ...a) noexcept( detail::invoke::is_noexcept_split_invocable< N, decltype(f), decltype(a)... >() ) { ::gnr::apply( [&](auto&& ...t) noexcept(noexcept( (::gnr::apply(f, std::forward<decltype(t)>(t)), ...) ) ) { (::gnr::apply(f, std::forward<decltype(t)>(t)) || ...); }, detail::invoke::split<N>(std::forward_as_tuple(a...)) ); } constexpr auto chain_apply(auto&& t, auto&& f, auto&& ...fs) noexcept(noexcept( ::gnr::apply( std::forward<decltype(f)>(f), std::forward<decltype(t)>(t) ) ) ) requires(detail::invoke::is_tuple_v<decltype(t)>) { if constexpr(sizeof...(fs)) { using R = decltype( ::gnr::apply( std::forward<decltype(f)>(f), std::forward<decltype(t)>(t) ) ); if constexpr(gnr::detail::invoke::is_tuple_v<R>) { return chain_apply( ::gnr::apply( std::forward<decltype(f)>(f), std::forward<decltype(t)>(t) ), std::forward<decltype(fs)>(fs)... ); } else if constexpr(std::is_void_v<R>) { ::gnr::apply( std::forward<decltype(f)>(f), std::forward<decltype(t)>(t) ); return chain_apply( std::tuple(), std::forward<decltype(fs)>(fs)... ); } else { return chain_apply( std::forward_as_tuple( ::gnr::apply( std::forward<decltype(f)>(f), std::forward<decltype(t)>(t) ) ), std::forward<decltype(fs)>(fs)... ); } } else { return ::gnr::apply( std::forward<decltype(f)>(f), std::forward<decltype(t)>(t) ); } } constexpr auto chain_apply(auto&& a, auto&& ...f) noexcept(noexcept( chain_apply( std::forward_as_tuple(a), std::forward<decltype(f)>(f)... ) ) ) requires(!detail::invoke::is_tuple_v<decltype(a)>) { return chain_apply( std::forward_as_tuple(a), std::forward<decltype(f)>(f)... ); } } #endif // GNR_INVOKE_HPP <commit_msg>some fixes<commit_after>#ifndef GNR_INVOKE_HPP # define GNR_INVOKE_HPP # pragma once #include <functional> #include <tuple> namespace gnr { namespace detail::invoke { template <typename> struct is_tuple : std::false_type {}; template <typename ...T> struct is_tuple<std::tuple<T...>> : std::true_type {}; template <typename T> static constexpr bool is_tuple_v(is_tuple<std::remove_cvref_t<T>>{}); template <std::size_t N> constexpr auto split(auto&& t) noexcept requires(bool(N)) { constexpr auto n(std::tuple_size_v<std::remove_cvref_t<decltype(t)>>); static_assert(n && !(n % N)); return [&]<auto ...I>(std::index_sequence<I...>) noexcept { return std::make_tuple( [&]<auto ...J>(std::index_sequence<J...>) noexcept { constexpr auto K(N * I); return std::forward_as_tuple( std::get<K + J>(std::forward<decltype(t)>(t))...); }(std::make_index_sequence<N + I - I>())... ); }(std::make_index_sequence<n / N>()); } template <typename F, typename T> constexpr bool is_noexcept_invocable() noexcept { auto const f(static_cast<std::remove_reference_t<F>*>(nullptr)); auto const t(static_cast<std::remove_reference_t<T>*>(nullptr)); return noexcept( [&]<auto ...I>(std::index_sequence<I...>) { return (std::invoke(F(*f), std::get<I>(T(*t))...)); }(std::make_index_sequence< std::tuple_size_v<std::remove_cvref_t<T>> >() ) ); } } constexpr decltype(auto) apply(auto&& f, auto&& t) noexcept( detail::invoke::is_noexcept_invocable<decltype(f), decltype(t)>() ) { return [&]<auto ...I>(std::index_sequence<I...>) noexcept(noexcept( std::invoke( std::forward<decltype(f)>(f), std::get<I>(std::forward<decltype(t)>(t))... ) ) ) { return std::invoke( std::forward<decltype(f)>(f), std::get<I>(std::forward<decltype(t)>(t))... ); }(std::make_index_sequence< std::tuple_size_v<std::remove_cvref_t<decltype(t)>> >() ); } constexpr auto invoke_all(auto f, auto&& ...a) noexcept(noexcept((f(std::forward<decltype(a)>(a)), ...))) { return (f(std::forward<decltype(a)>(a)), ...); } constexpr auto invoke_cond(auto f, auto&& ...a) noexcept(noexcept((f(std::forward<decltype(a)>(a)), ...))) { return (f(std::forward<decltype(a)>(a)) || ...); } namespace detail::invoke { template <std::size_t N, typename F, typename ...A> constexpr bool is_noexcept_split_invocable() noexcept { auto const f(static_cast<std::remove_reference_t<F>*>(nullptr)); return noexcept( ::gnr::apply([&](auto&& ...t) noexcept(noexcept( (::gnr::apply(F(*f), std::forward<decltype(t)>(t)), ...))) { (::gnr::apply(F(*f), std::forward<decltype(t)>(t)), ...); }, detail::invoke::split<N>( std::forward_as_tuple( A(*static_cast<std::remove_reference_t<A>*>(nullptr))... ) ) ) ); } } template <std::size_t N> constexpr void invoke_split(auto&& f, auto&& ...a) noexcept( detail::invoke::is_noexcept_split_invocable<N, decltype(f), decltype(a)...>() ) { ::gnr::apply( [&](auto&& ...t) noexcept(noexcept( (::gnr::apply(f, std::forward<decltype(t)>(t)), ...)) ) { (::gnr::apply(f, std::forward<decltype(t)>(t)), ...); }, detail::invoke::split<N>(std::forward_as_tuple(a...)) ); } template <std::size_t N> constexpr bool invoke_split_cond(auto&& f, auto&& ...a) noexcept( detail::invoke::is_noexcept_split_invocable< N, decltype(f), decltype(a)... >() ) { return ::gnr::apply( [&](auto&& ...t) noexcept(noexcept( (::gnr::apply(f, std::forward<decltype(t)>(t)), ...) ) ) { return (::gnr::apply(f, std::forward<decltype(t)>(t)) || ...); }, detail::invoke::split<N>(std::forward_as_tuple(a...)) ); } constexpr auto chain_apply(auto&& t, auto&& f, auto&& ...fs) noexcept(noexcept( ::gnr::apply( std::forward<decltype(f)>(f), std::forward<decltype(t)>(t) ) ) ) requires(detail::invoke::is_tuple_v<decltype(t)>) { if constexpr(sizeof...(fs)) { using R = decltype( ::gnr::apply( std::forward<decltype(f)>(f), std::forward<decltype(t)>(t) ) ); if constexpr(gnr::detail::invoke::is_tuple_v<R>) { return chain_apply( ::gnr::apply( std::forward<decltype(f)>(f), std::forward<decltype(t)>(t) ), std::forward<decltype(fs)>(fs)... ); } else if constexpr(std::is_void_v<R>) { ::gnr::apply( std::forward<decltype(f)>(f), std::forward<decltype(t)>(t) ); return chain_apply( std::tuple(), std::forward<decltype(fs)>(fs)... ); } else { return chain_apply( std::forward_as_tuple( ::gnr::apply( std::forward<decltype(f)>(f), std::forward<decltype(t)>(t) ) ), std::forward<decltype(fs)>(fs)... ); } } else { return ::gnr::apply( std::forward<decltype(f)>(f), std::forward<decltype(t)>(t) ); } } constexpr auto chain_apply(auto&& a, auto&& ...f) noexcept(noexcept( chain_apply( std::forward_as_tuple(a), std::forward<decltype(f)>(f)... ) ) ) requires(!detail::invoke::is_tuple_v<decltype(a)>) { return chain_apply( std::forward_as_tuple(a), std::forward<decltype(f)>(f)... ); } } #endif // GNR_INVOKE_HPP <|endoftext|>
<commit_before>/** * \file * \brief threadTestCases object definition * * \author Copyright (C) 2014 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \date 2014-08-24 */ #include "threadTestCases.hpp" #include "ThreadPriorityTestCase.hpp" namespace distortos { namespace test { namespace { /*---------------------------------------------------------------------------------------------------------------------+ | local objects +---------------------------------------------------------------------------------------------------------------------*/ /// ThreadPriorityTestCase instance const ThreadPriorityTestCase priorityTestCase; /// array with references to TestCase objects related to threads const TestCaseRange::value_type threadTestCases_[] { priorityTestCase, }; } // namespace /*---------------------------------------------------------------------------------------------------------------------+ | global objects +---------------------------------------------------------------------------------------------------------------------*/ const TestCaseRange threadTestCases {threadTestCases_}; } // namespace test } // namespace distortos <commit_msg>test: add ThreadFunctionTypesTestCase to list of executed testcases<commit_after>/** * \file * \brief threadTestCases object definition * * \author Copyright (C) 2014 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \date 2014-08-28 */ #include "threadTestCases.hpp" #include "ThreadPriorityTestCase.hpp" #include "ThreadFunctionTypesTestCase.hpp" namespace distortos { namespace test { namespace { /*---------------------------------------------------------------------------------------------------------------------+ | local objects +---------------------------------------------------------------------------------------------------------------------*/ /// ThreadPriorityTestCase instance const ThreadPriorityTestCase priorityTestCase; /// ThreadFunctionTypesTestCase instance const ThreadFunctionTypesTestCase functionTypesTestCase; /// array with references to TestCase objects related to threads const TestCaseRange::value_type threadTestCases_[] { priorityTestCase, functionTypesTestCase, }; } // namespace /*---------------------------------------------------------------------------------------------------------------------+ | global objects +---------------------------------------------------------------------------------------------------------------------*/ const TestCaseRange threadTestCases {threadTestCases_}; } // namespace test } // namespace distortos <|endoftext|>
<commit_before>/* Carloop mileage reminder app * Copyright 2016 1000 Tools, Inc. * * Accumulates miles in a counter stored in EEPROM. * When the limit is reached, set a flag in EEPROM that an event should * be published to the Particle Cloud. * In the cloud, set the event to send an SMS to the driver. */ #include "application.h" #include "carloop/carloop.h" #include "storage.h" // Function declarations void publishEvent(); void setupCloud(); int resetIntervalCounter(String); int changeIntervalLimit(String arg); void updateSpeed(); void requestVehicleSpeed(); void waitForVehicleSpeedResponse(); // Don't block the main program while connecting to WiFi/cellular. // This way the main program runs on the Carloop even outside of WiFi range. SYSTEM_THREAD(ENABLED); // Tell the program which revision of Carloop you are using. Carloop<CarloopRevision2> carloop; // The data that is stored and loaded in permanent storage (EEPROM) // including the current interval count and limit Data data; // The class that will read and write the data to EEPROM Storage storage; // OBD constants for CAN // CAN IDs for OBD messages const auto OBD_CAN_REQUEST_ID = 0x7E0; const auto OBD_CAN_REPLY_ID_MIN = 0x7E8; // Modes (aka services) for OBD const auto OBD_MODE_CURRENT_DATA = 0x01; // OBD signals (aka PID) that can be requested const auto OBD_PID_VEHICLE_SPEED = 0x0d; // Time to wait for a reply for an OBD request const auto OBD_TIMEOUT_MS = 10; uint8_t vehicleSpeedKmh = 0; void setup() { setupCloud(); storage.load(data); // Configure the CAN bus speed for 500 kbps, the standard speed for the OBD-II port. // Other common speeds are 250 kbps and 1 Mbps. carloop.setCANSpeed(500000); // Connect to the CAN bus carloop.begin(); } void setupCloud() { Particle.function("reset", resetIntervalCounter); Particle.function("limit", changeIntervalLimit); Particle.variable("count", data.intervalCounter); } int resetIntervalCounter(String) { data.intervalCounter = 0; data.intervalReached = 0; storage.store(data); return 0; } int changeIntervalLimit(String arg) { long newLimit = arg.toInt(); if (newLimit <= 0) { return -1; } data.intervalLimit = newLimit; while (data.intervalCounter >= data.intervalLimit) { data.intervalCounter -= data.intervalLimit; data.intervalReached = 1; } storage.store(data); return 0; } void loop() { updateSpeed(); publishEvent(); } void updateSpeed() { requestVehicleSpeed(); waitForVehicleSpeedResponse(); } void requestVehicleSpeed() { CANMessage message; // A CAN message to request the vehicle speed message.id = OBD_CAN_REQUEST_ID; message.len = 8; // Data is an OBD request: get current value of the vehicle speed PID message.data[0] = 2; // 2 byte request message.data[1] = OBD_MODE_CURRENT_DATA; message.data[2] = OBD_PID_VEHICLE_SPEED; // Send the message on the bus! carloop.can().transmit(message); } void waitForVehicleSpeedResponse() { uint32_t start = millis(); bool received = false; while (millis() - start < OBD_TIMEOUT_MS) { } } // If we reached the limit and we're connected to the cloud through WiFi // or cellular, publish the event void publishEvent() { if (data.intervalReached && Particle.connected()) { // Publish the event interval with the value set to the mileage that was reached Particle.publish("interval", String::format("%.0f", data.intervalLimit), PRIVATE); data.intervalReached = 0; storage.store(data); } } <commit_msg>First compiling version<commit_after>/* Carloop mileage reminder app * Copyright 2016 1000 Tools, Inc. * * Accumulates miles in a counter stored in EEPROM. * When the limit is reached, set a flag in EEPROM that an event should * be published to the Particle Cloud. * In the cloud, set the event to send an SMS to the driver. */ #include "application.h" #include "carloop/carloop.h" #include "storage.h" // Function declarations void publishEvent(); void setupCloud(); int resetIntervalCounter(String); int changeIntervalLimit(String arg); void updateSpeed(); void requestVehicleSpeed(); void waitForVehicleSpeedResponse(); void updateMileage(uint8_t newVehicleSpeedKhm); double computeDeltaMileage(uint8_t newVehicleSpeedKhm); void checkIntervalLimit(); void storeMileage(); // Don't block the main program while connecting to WiFi/cellular. // This way the main program runs on the Carloop even outside of WiFi range. SYSTEM_THREAD(ENABLED); // Tell the program which revision of Carloop you are using. Carloop<CarloopRevision2> carloop; // The data that is stored and loaded in permanent storage (EEPROM) // including the current interval count and limit Data data; // The class that will read and write the data to EEPROM Storage storage; // Only store to EEPROM every so often const auto STORAGE_PERIOD = 60 * 1000; /* every minute */ uint32_t lastStorageTime = 0; // OBD constants for CAN // CAN IDs for OBD messages const auto OBD_CAN_REQUEST_ID = 0x7E0; const auto OBD_CAN_REPLY_ID = 0x7E8; // Modes (aka services) for OBD const auto OBD_MODE_CURRENT_DATA = 0x01; // OBD signals (aka PID) that can be requested const auto OBD_PID_VEHICLE_SPEED = 0x0d; // Time to wait for a reply for an OBD request const auto OBD_TIMEOUT_MS = 10; uint8_t vehicleSpeedKmh = 0; uint32_t lastVehicleSpeedUpdateTime = 0; // Called at boot // Sets up the CAN bus and cloud functions void setup() { setupCloud(); storage.load(data); // Configure the CAN bus speed for 500 kbps, the standard speed for the OBD-II port. // Other common speeds are 250 kbps and 1 Mbps. carloop.setCANSpeed(500000); // Connect to the CAN bus carloop.begin(); } // Allow interacting with the Carloop remotely void setupCloud() { Particle.function("reset", resetIntervalCounter); Particle.function("limit", changeIntervalLimit); Particle.variable("count", data.intervalCounter); } // Reset the interval counter and store the zero value in EEPROM int resetIntervalCounter(String) { data.intervalCounter = 0; data.intervalReached = 0; storage.store(data); return 0; } // Set the interval upper limit and make sure the current value is below // that. Store the values value in EEPROM int changeIntervalLimit(String arg) { long newLimit = arg.toInt(); if (newLimit <= 0) { return -1; } data.intervalLimit = newLimit; checkIntervalLimit(); storage.store(data); return 0; } // Called over and over // Process new CAN messages here to update the vehicle speed, update // the mileage and update the interval counter void loop() { updateSpeed(); storeMileage(); publishEvent(); delay(100); } void updateSpeed() { requestVehicleSpeed(); waitForVehicleSpeedResponse(); } void requestVehicleSpeed() { CANMessage message; // A CAN message to request the vehicle speed message.id = OBD_CAN_REQUEST_ID; message.len = 8; // Data is an OBD request: get current value of the vehicle speed PID message.data[0] = 2; // 2 byte request message.data[1] = OBD_MODE_CURRENT_DATA; message.data[2] = OBD_PID_VEHICLE_SPEED; // Send the message on the bus! carloop.can().transmit(message); } void waitForVehicleSpeedResponse() { uint32_t start = millis(); bool received = false; while (millis() - start < OBD_TIMEOUT_MS) { CANMessage message; if (carloop.can().receive(message)) { if (message.id == OBD_CAN_REPLY_ID && message.data[2] == OBD_PID_VEHICLE_SPEED) { received = true; uint8_t newVehicleSpeedKhm = message.data[3]; updateMileage(newVehicleSpeedKhm); } } } if (!received) { updateMileage(0); } } void updateMileage(uint8_t newVehicleSpeedKhm) { double deltaMileage = computeDeltaMileage(newVehicleSpeedKhm); data.intervalCounter += deltaMileage; checkIntervalLimit(); } double computeDeltaMileage(uint8_t newVehicleSpeedKhm) { uint32_t now = millis(); double deltaMileage = 0.0; // If the speed was previously 0 or newly 0, or timed out because the // car was off, just save the new speed value if (vehicleSpeedKmh > 0 && newVehicleSpeedKhm > 0) { // The car was previously driving and is still driving // Figure out the distance driven using the trapezoidal rule uint32_t msDiff = now - lastVehicleSpeedUpdateTime; // Calculate only if the difference is plausible if (msDiff < 1000) { // distance in km/h * ms uint32_t deltaDistance = msDiff * (vehicleSpeedKmh + newVehicleSpeedKhm) / 2; // Convert to miles // 1 kilometer per hour * ms = 1.72603109 × 10^-7 miles // km/h * ms * (1 h / 3600 s) * (0.621371 mi / 1 km) * (1 s / 1000 ms) deltaMileage = deltaDistance * 1.72603109e-7; } } vehicleSpeedKmh = newVehicleSpeedKhm; lastVehicleSpeedUpdateTime = now; return deltaMileage; } // If the interval limit is reached, mark it so we can publish an event // when we come back to network range void checkIntervalLimit() { while (data.intervalCounter >= data.intervalLimit) { data.intervalCounter -= data.intervalLimit; data.intervalReached = 1; } } // Store data to EEPROM every so often void storeMileage() { if (millis() - lastStorageTime > STORAGE_PERIOD) { storage.store(data); lastStorageTime = millis(); } } // If we reached the limit and we're connected to the cloud through WiFi // or cellular, publish the event void publishEvent() { if (data.intervalReached && Particle.connected()) { // Publish the event interval with the value set to the mileage that was reached Particle.publish("interval", String::format("%.0f", data.intervalLimit), PRIVATE); // Clear the flag avoid publishing the same event twice data.intervalReached = 0; storage.store(data); } } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * 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/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #ifndef INCLUDED_VCL_INC_GENERIC_GLYPHCACHE_HXX #define INCLUDED_VCL_INC_GENERIC_GLYPHCACHE_HXX #include <config_graphite.h> #include <ft2build.h> #include FT_FREETYPE_H #include FT_GLYPH_H #include <boost/shared_ptr.hpp> #include <basebmp/bitmapdevice.hxx> #include <com/sun/star/i18n/XBreakIterator.hpp> #include <tools/gen.hxx> #include <vcl/dllapi.h> #include <vcl/metric.hxx> #include <outfont.hxx> #include <sallayout.hxx> #include <unordered_map> class FtFontInfo; class GlyphCachePeer; class GlyphData; class GraphiteFaceWrapper; class ImplFontOptions; class PhysicalFontCollection; class RawBitmap; class ServerFont; class ServerFontLayout; class ServerFontLayoutEngine; namespace basegfx { class B2DPolyPolygon; } namespace vcl { struct FontCapabilities; } class VCL_DLLPUBLIC GlyphCache { public: explicit GlyphCache( GlyphCachePeer& ); ~GlyphCache(); static GlyphCache& GetInstance(); void AddFontFile( const OString& rNormalizedName, int nFaceNum, sal_IntPtr nFontId, const ImplDevFontAttributes&); void AnnounceFonts( PhysicalFontCollection* ) const; ServerFont* CacheFont( const FontSelectPattern& ); void UncacheFont( ServerFont& ); void ClearFontCache(); void InvalidateAllGlyphs(); protected: GlyphCachePeer& mrPeer; private: friend class ServerFont; // used by ServerFont class only void AddedGlyph( ServerFont&, GlyphData& ); void RemovingGlyph( GlyphData& ); void UsingGlyph( ServerFont&, GlyphData& ); void GrowNotify(); private: void GarbageCollect(); // the GlyphCache's FontList matches a font request to a serverfont instance // the FontList key's mpFontData member is reinterpreted as integer font id struct IFSD_Equal{ bool operator()( const FontSelectPattern&, const FontSelectPattern& ) const; }; struct IFSD_Hash{ size_t operator()( const FontSelectPattern& ) const; }; typedef std::unordered_map<FontSelectPattern,ServerFont*,IFSD_Hash,IFSD_Equal > FontList; FontList maFontList; sal_uLong mnMaxSize; // max overall cache size in bytes mutable sal_uLong mnBytesUsed; mutable long mnLruIndex; mutable int mnGlyphCount; ServerFont* mpCurrentGCFont; class FreetypeManager* mpFtManager; }; class GlyphMetric { public: GlyphMetric() : mnAdvanceWidth(0) {} Point GetOffset() const { return maOffset; } Point GetDelta() const { return maDelta; } Size GetSize() const { return maSize; } long GetCharWidth() const { return mnAdvanceWidth; } protected: friend class GlyphData; void SetOffset( int nX, int nY ) { maOffset = Point( nX, nY); } void SetDelta( int nX, int nY ) { maDelta = Point( nX, nY); } void SetSize( const Size& s ) { maSize = s; } void SetCharWidth( long nW ) { mnAdvanceWidth = nW; } private: long mnAdvanceWidth; Point maDelta; Point maOffset; Size maSize; }; // the glyph specific data needed by a GlyphCachePeer is usually trivial, // not attaching it to the corresponding GlyphData would be overkill; // this is currently only used by the headless (aka svp) plugin, where meInfo is // basebmp::Format and mpData is SvpGcpHelper* struct ExtGlyphData { int meInfo; void* mpData; ExtGlyphData() : meInfo(0), mpData(NULL) {} }; class GlyphData { public: GlyphData() : mnLruValue(0) {} const GlyphMetric& GetMetric() const { return maMetric; } Size GetSize() const { return maMetric.GetSize(); } void SetSize( const Size& s) { maMetric.SetSize( s ); } void SetOffset( int nX, int nY ) { maMetric.SetOffset( nX, nY ); } void SetDelta( int nX, int nY ) { maMetric.SetDelta( nX, nY ); } void SetCharWidth( long nW ) { maMetric.SetCharWidth( nW ); } void SetLruValue( int n ) const { mnLruValue = n; } long GetLruValue() const { return mnLruValue;} ExtGlyphData& ExtDataRef() { return maExtData; } const ExtGlyphData& ExtDataRef() const { return maExtData; } private: GlyphMetric maMetric; ExtGlyphData maExtData; // used by GlyphCache for cache LRU algorithm mutable long mnLruValue; }; class VCL_DLLPUBLIC ServerFont { public: ServerFont( const FontSelectPattern&, FtFontInfo* ); virtual ~ServerFont(); const OString& GetFontFileName() const; bool TestFont() const { return mbFaceOk;} FT_Face GetFtFace() const; int GetLoadFlags() const { return (mnLoadFlags & ~FT_LOAD_IGNORE_TRANSFORM); } void SetFontOptions( boost::shared_ptr<ImplFontOptions> ); boost::shared_ptr<ImplFontOptions> GetFontOptions() const; bool NeedsArtificialBold() const { return mbArtBold; } bool NeedsArtificialItalic() const { return mbArtItalic; } const FontSelectPattern& GetFontSelData() const { return maFontSelData; } void FetchFontMetric( ImplFontMetricData&, long& rFactor ) const; const unsigned char* GetTable( const char* pName, sal_uLong* pLength ); int GetEmUnits() const { return maFaceFT->units_per_EM;} const FT_Size_Metrics& GetMetricsFT() const { return maSizeFT->metrics; } const FontCharMapPtr GetFontCharMap() const; bool GetFontCapabilities(vcl::FontCapabilities &) const; GlyphData& GetGlyphData( sal_GlyphId ); const GlyphMetric& GetGlyphMetric( sal_GlyphId aGlyphId ) { return GetGlyphData( aGlyphId ).GetMetric(); } #if ENABLE_GRAPHITE virtual GraphiteFaceWrapper* GetGraphiteFace() const; #endif sal_GlyphId GetGlyphIndex( sal_UCS4 ) const; sal_GlyphId GetRawGlyphIndex( sal_UCS4, sal_UCS4 = 0 ) const; sal_GlyphId FixupGlyphIndex( sal_GlyphId aGlyphId, sal_UCS4 ) const; bool GetGlyphOutline( sal_GlyphId aGlyphId, ::basegfx::B2DPolyPolygon& ) const; bool GetAntialiasAdvice( void ) const; bool GetGlyphBitmap1( sal_GlyphId aGlyphId, RawBitmap& ) const; bool GetGlyphBitmap8( sal_GlyphId aGlyphId, RawBitmap& ) const; private: friend class GlyphCache; friend class ServerFontLayout; friend class ImplServerFontEntry; friend class X11SalGraphics; friend class CairoTextRender; void AddRef() const { ++mnRefCount; } long GetRefCount() const { return mnRefCount; } long Release() const; sal_uLong GetByteCount() const { return mnBytesUsed; } void InitGlyphData( sal_GlyphId, GlyphData& ) const; void GarbageCollect( long ); void ReleaseFromGarbageCollect(); int ApplyGlyphTransform( int nGlyphFlags, FT_GlyphRec_*, bool ) const; bool ApplyGSUB( const FontSelectPattern& ); ServerFontLayoutEngine* GetLayoutEngine(); typedef std::unordered_map<int,GlyphData> GlyphList; mutable GlyphList maGlyphList; const FontSelectPattern maFontSelData; // used by GlyphCache for cache LRU algorithm mutable long mnRefCount; mutable sal_uLong mnBytesUsed; ServerFont* mpPrevGCFont; ServerFont* mpNextGCFont; // 16.16 fixed point values used for a rotated font long mnCos; long mnSin; bool mbCollectedZW; int mnWidth; int mnPrioEmbedded; int mnPrioAntiAlias; int mnPrioAutoHint; FtFontInfo* mpFontInfo; FT_Int mnLoadFlags; double mfStretch; FT_FaceRec_* maFaceFT; FT_SizeRec_* maSizeFT; boost::shared_ptr<ImplFontOptions> mpFontOptions; bool mbFaceOk; bool mbArtItalic; bool mbArtBold; bool mbUseGamma; typedef std::unordered_map<int,int> GlyphSubstitution; GlyphSubstitution maGlyphSubstitution; ServerFontLayoutEngine* mpLayoutEngine; }; // a class for cache entries for physical font instances that are based on serverfonts class VCL_DLLPUBLIC ImplServerFontEntry : public ImplFontEntry { private: ServerFont* mpServerFont; boost::shared_ptr<ImplFontOptions> mpFontOptions; bool mbGotFontOptions; public: ImplServerFontEntry( FontSelectPattern& ); virtual ~ImplServerFontEntry(); void SetServerFont(ServerFont* p); void HandleFontOptions(); }; class VCL_DLLPUBLIC ServerFontLayout : public GenericSalLayout { private: ServerFont& mrServerFont; com::sun::star::uno::Reference<com::sun::star::i18n::XBreakIterator> mxBreak; // enforce proper copy semantic SAL_DLLPRIVATE ServerFontLayout( const ServerFontLayout& ); SAL_DLLPRIVATE ServerFontLayout& operator=( const ServerFontLayout& ); public: ServerFontLayout( ServerFont& ); virtual bool LayoutText( ImplLayoutArgs& ) SAL_OVERRIDE; virtual void AdjustLayout( ImplLayoutArgs& ) SAL_OVERRIDE; virtual void DrawText( SalGraphics& ) const SAL_OVERRIDE; void setNeedFallback(ImplLayoutArgs& rArgs, sal_Int32 nIndex, bool bRightToLeft); ServerFont& GetServerFont() const { return mrServerFont; } }; class ServerFontLayoutEngine { public: virtual ~ServerFontLayoutEngine() {} virtual bool layout(ServerFontLayout&, ImplLayoutArgs&) = 0; }; class GlyphCachePeer { protected: GlyphCachePeer() : mnBytesUsed(0) {} virtual ~GlyphCachePeer() {} public: sal_Int32 GetByteCount() const { return mnBytesUsed; } virtual void RemovingFont( ServerFont& ) {} virtual void RemovingGlyph( GlyphData& ) {} protected: sal_Int32 mnBytesUsed; }; class VCL_DLLPUBLIC RawBitmap { public: RawBitmap(); ~RawBitmap(); bool Rotate( int nAngle ); public: basebmp::RawMemorySharedArray mpBits; sal_uLong mnAllocated; sal_uLong mnWidth; sal_uLong mnHeight; sal_uLong mnScanlineSize; sal_uLong mnBitCount; int mnXOffset; int mnYOffset; }; #endif // INCLUDED_VCL_INC_GENERIC_GLYPHCACHE_HXX /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>vcl: whitespace cleanup on GlyphCache class definition<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * 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/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #ifndef INCLUDED_VCL_INC_GENERIC_GLYPHCACHE_HXX #define INCLUDED_VCL_INC_GENERIC_GLYPHCACHE_HXX #include <config_graphite.h> #include <ft2build.h> #include FT_FREETYPE_H #include FT_GLYPH_H #include <boost/shared_ptr.hpp> #include <basebmp/bitmapdevice.hxx> #include <com/sun/star/i18n/XBreakIterator.hpp> #include <tools/gen.hxx> #include <vcl/dllapi.h> #include <vcl/metric.hxx> #include <outfont.hxx> #include <sallayout.hxx> #include <unordered_map> class FtFontInfo; class GlyphCachePeer; class GlyphData; class GraphiteFaceWrapper; class ImplFontOptions; class PhysicalFontCollection; class RawBitmap; class ServerFont; class ServerFontLayout; class ServerFontLayoutEngine; namespace basegfx { class B2DPolyPolygon; } namespace vcl { struct FontCapabilities; } class VCL_DLLPUBLIC GlyphCache { public: explicit GlyphCache( GlyphCachePeer& ); ~GlyphCache(); static GlyphCache& GetInstance(); void AddFontFile( const OString& rNormalizedName, int nFaceNum, sal_IntPtr nFontId, const ImplDevFontAttributes&); void AnnounceFonts( PhysicalFontCollection* ) const; ServerFont* CacheFont( const FontSelectPattern& ); void UncacheFont( ServerFont& ); void ClearFontCache(); void InvalidateAllGlyphs(); protected: GlyphCachePeer& mrPeer; private: friend class ServerFont; // used by ServerFont class only void AddedGlyph( ServerFont&, GlyphData& ); void RemovingGlyph( GlyphData& ); void UsingGlyph( ServerFont&, GlyphData& ); void GrowNotify(); private: void GarbageCollect(); // the GlyphCache's FontList matches a font request to a serverfont instance // the FontList key's mpFontData member is reinterpreted as integer font id struct IFSD_Equal{ bool operator()( const FontSelectPattern&, const FontSelectPattern& ) const; }; struct IFSD_Hash{ size_t operator()( const FontSelectPattern& ) const; }; typedef std::unordered_map<FontSelectPattern,ServerFont*,IFSD_Hash,IFSD_Equal > FontList; FontList maFontList; sal_uLong mnMaxSize; // max overall cache size in bytes mutable sal_uLong mnBytesUsed; mutable long mnLruIndex; mutable int mnGlyphCount; ServerFont* mpCurrentGCFont; class FreetypeManager* mpFtManager; }; class GlyphMetric { public: GlyphMetric() : mnAdvanceWidth(0) {} Point GetOffset() const { return maOffset; } Point GetDelta() const { return maDelta; } Size GetSize() const { return maSize; } long GetCharWidth() const { return mnAdvanceWidth; } protected: friend class GlyphData; void SetOffset( int nX, int nY ) { maOffset = Point( nX, nY); } void SetDelta( int nX, int nY ) { maDelta = Point( nX, nY); } void SetSize( const Size& s ) { maSize = s; } void SetCharWidth( long nW ) { mnAdvanceWidth = nW; } private: long mnAdvanceWidth; Point maDelta; Point maOffset; Size maSize; }; // the glyph specific data needed by a GlyphCachePeer is usually trivial, // not attaching it to the corresponding GlyphData would be overkill; // this is currently only used by the headless (aka svp) plugin, where meInfo is // basebmp::Format and mpData is SvpGcpHelper* struct ExtGlyphData { int meInfo; void* mpData; ExtGlyphData() : meInfo(0), mpData(NULL) {} }; class GlyphData { public: GlyphData() : mnLruValue(0) {} const GlyphMetric& GetMetric() const { return maMetric; } Size GetSize() const { return maMetric.GetSize(); } void SetSize( const Size& s) { maMetric.SetSize( s ); } void SetOffset( int nX, int nY ) { maMetric.SetOffset( nX, nY ); } void SetDelta( int nX, int nY ) { maMetric.SetDelta( nX, nY ); } void SetCharWidth( long nW ) { maMetric.SetCharWidth( nW ); } void SetLruValue( int n ) const { mnLruValue = n; } long GetLruValue() const { return mnLruValue;} ExtGlyphData& ExtDataRef() { return maExtData; } const ExtGlyphData& ExtDataRef() const { return maExtData; } private: GlyphMetric maMetric; ExtGlyphData maExtData; // used by GlyphCache for cache LRU algorithm mutable long mnLruValue; }; class VCL_DLLPUBLIC ServerFont { public: ServerFont( const FontSelectPattern&, FtFontInfo* ); virtual ~ServerFont(); const OString& GetFontFileName() const; bool TestFont() const { return mbFaceOk;} FT_Face GetFtFace() const; int GetLoadFlags() const { return (mnLoadFlags & ~FT_LOAD_IGNORE_TRANSFORM); } void SetFontOptions( boost::shared_ptr<ImplFontOptions> ); boost::shared_ptr<ImplFontOptions> GetFontOptions() const; bool NeedsArtificialBold() const { return mbArtBold; } bool NeedsArtificialItalic() const { return mbArtItalic; } const FontSelectPattern& GetFontSelData() const { return maFontSelData; } void FetchFontMetric( ImplFontMetricData&, long& rFactor ) const; const unsigned char* GetTable( const char* pName, sal_uLong* pLength ); int GetEmUnits() const { return maFaceFT->units_per_EM;} const FT_Size_Metrics& GetMetricsFT() const { return maSizeFT->metrics; } const FontCharMapPtr GetFontCharMap() const; bool GetFontCapabilities(vcl::FontCapabilities &) const; GlyphData& GetGlyphData( sal_GlyphId ); const GlyphMetric& GetGlyphMetric( sal_GlyphId aGlyphId ) { return GetGlyphData( aGlyphId ).GetMetric(); } #if ENABLE_GRAPHITE virtual GraphiteFaceWrapper* GetGraphiteFace() const; #endif sal_GlyphId GetGlyphIndex( sal_UCS4 ) const; sal_GlyphId GetRawGlyphIndex( sal_UCS4, sal_UCS4 = 0 ) const; sal_GlyphId FixupGlyphIndex( sal_GlyphId aGlyphId, sal_UCS4 ) const; bool GetGlyphOutline( sal_GlyphId aGlyphId, ::basegfx::B2DPolyPolygon& ) const; bool GetAntialiasAdvice( void ) const; bool GetGlyphBitmap1( sal_GlyphId aGlyphId, RawBitmap& ) const; bool GetGlyphBitmap8( sal_GlyphId aGlyphId, RawBitmap& ) const; private: friend class GlyphCache; friend class ServerFontLayout; friend class ImplServerFontEntry; friend class X11SalGraphics; friend class CairoTextRender; void AddRef() const { ++mnRefCount; } long GetRefCount() const { return mnRefCount; } long Release() const; sal_uLong GetByteCount() const { return mnBytesUsed; } void InitGlyphData( sal_GlyphId, GlyphData& ) const; void GarbageCollect( long ); void ReleaseFromGarbageCollect(); int ApplyGlyphTransform( int nGlyphFlags, FT_GlyphRec_*, bool ) const; bool ApplyGSUB( const FontSelectPattern& ); ServerFontLayoutEngine* GetLayoutEngine(); typedef std::unordered_map<int,GlyphData> GlyphList; mutable GlyphList maGlyphList; const FontSelectPattern maFontSelData; // used by GlyphCache for cache LRU algorithm mutable long mnRefCount; mutable sal_uLong mnBytesUsed; ServerFont* mpPrevGCFont; ServerFont* mpNextGCFont; // 16.16 fixed point values used for a rotated font long mnCos; long mnSin; bool mbCollectedZW; int mnWidth; int mnPrioEmbedded; int mnPrioAntiAlias; int mnPrioAutoHint; FtFontInfo* mpFontInfo; FT_Int mnLoadFlags; double mfStretch; FT_FaceRec_* maFaceFT; FT_SizeRec_* maSizeFT; boost::shared_ptr<ImplFontOptions> mpFontOptions; bool mbFaceOk; bool mbArtItalic; bool mbArtBold; bool mbUseGamma; typedef std::unordered_map<int,int> GlyphSubstitution; GlyphSubstitution maGlyphSubstitution; ServerFontLayoutEngine* mpLayoutEngine; }; // a class for cache entries for physical font instances that are based on serverfonts class VCL_DLLPUBLIC ImplServerFontEntry : public ImplFontEntry { private: ServerFont* mpServerFont; boost::shared_ptr<ImplFontOptions> mpFontOptions; bool mbGotFontOptions; public: ImplServerFontEntry( FontSelectPattern& ); virtual ~ImplServerFontEntry(); void SetServerFont(ServerFont* p); void HandleFontOptions(); }; class VCL_DLLPUBLIC ServerFontLayout : public GenericSalLayout { private: ServerFont& mrServerFont; com::sun::star::uno::Reference<com::sun::star::i18n::XBreakIterator> mxBreak; // enforce proper copy semantic SAL_DLLPRIVATE ServerFontLayout( const ServerFontLayout& ); SAL_DLLPRIVATE ServerFontLayout& operator=( const ServerFontLayout& ); public: ServerFontLayout( ServerFont& ); virtual bool LayoutText( ImplLayoutArgs& ) SAL_OVERRIDE; virtual void AdjustLayout( ImplLayoutArgs& ) SAL_OVERRIDE; virtual void DrawText( SalGraphics& ) const SAL_OVERRIDE; void setNeedFallback(ImplLayoutArgs& rArgs, sal_Int32 nIndex, bool bRightToLeft); ServerFont& GetServerFont() const { return mrServerFont; } }; class ServerFontLayoutEngine { public: virtual ~ServerFontLayoutEngine() {} virtual bool layout(ServerFontLayout&, ImplLayoutArgs&) = 0; }; class GlyphCachePeer { protected: GlyphCachePeer() : mnBytesUsed(0) {} virtual ~GlyphCachePeer() {} public: sal_Int32 GetByteCount() const { return mnBytesUsed; } virtual void RemovingFont( ServerFont& ) {} virtual void RemovingGlyph( GlyphData& ) {} protected: sal_Int32 mnBytesUsed; }; class VCL_DLLPUBLIC RawBitmap { public: RawBitmap(); ~RawBitmap(); bool Rotate( int nAngle ); public: basebmp::RawMemorySharedArray mpBits; sal_uLong mnAllocated; sal_uLong mnWidth; sal_uLong mnHeight; sal_uLong mnScanlineSize; sal_uLong mnBitCount; int mnXOffset; int mnYOffset; }; #endif // INCLUDED_VCL_INC_GENERIC_GLYPHCACHE_HXX /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>#include <stdio.h> int main(int argc, char* argv[]) { freopen("game.in", "r", stdin); freopen("game.out", "w+", stdout); int n, o, i, p; scanf("%i", &n); for(i = 1; i <= n; i++) { long long a, b; o = 0, p = 0; scanf("%lli %lli", &a, &b); while(a > b) { p++; a -= a / 2; if(!(a % 2)) a++; } printf("Case %i: %i", i, p); } return 0; } <commit_msg>commit via s script<commit_after>#include <stdio.h> int main(int argc, char* argv[]) { freopen("game.in", "r", stdin); freopen("game.out", "w+", stdout); int n, o, i, p; scanf("%i", &n); for(i = 1; i <= n; i++) { long long a, b; o = 0, p = 0; scanf("%lli %lli", &a, &b); while(a > b) { p++; a -= a / 2; if(!(a % 2)) a++; } // ܳ˻Уȫ printf("Case %i: %i\n", i, p); } return 0; } <|endoftext|>
<commit_before>#include "common/grpc/common.h" #include "common/http/headers.h" #include "test/mocks/upstream/mocks.h" #include "test/proto/helloworld.pb.h" #include "test/test_common/utility.h" #include "gtest/gtest.h" namespace Envoy { namespace Grpc { TEST(GrpcCommonTest, GetGrpcStatus) { Http::TestHeaderMapImpl ok_trailers{{"grpc-status", "0"}}; EXPECT_EQ(Status::Ok, Common::getGrpcStatus(ok_trailers).value()); Http::TestHeaderMapImpl no_status_trailers{{"foo", "bar"}}; EXPECT_FALSE(Common::getGrpcStatus(no_status_trailers).valid()); Http::TestHeaderMapImpl aborted_trailers{{"grpc-status", "10"}}; EXPECT_EQ(Status::Aborted, Common::getGrpcStatus(aborted_trailers).value()); Http::TestHeaderMapImpl unauth_trailers{{"grpc-status", "16"}}; EXPECT_EQ(Status::Unauthenticated, Common::getGrpcStatus(unauth_trailers).value()); Http::TestHeaderMapImpl invalid_trailers{{"grpc-status", "-1"}}; EXPECT_EQ(Status::InvalidCode, Common::getGrpcStatus(invalid_trailers).value()); } TEST(GrpcCommonTest, GetGrpcMessage) { Http::TestHeaderMapImpl empty_trailers; EXPECT_EQ("", Common::getGrpcMessage(empty_trailers)); Http::TestHeaderMapImpl error_trailers{{"grpc-message", "Some error"}}; EXPECT_EQ("Some error", Common::getGrpcMessage(error_trailers)); Http::TestHeaderMapImpl empty_error_trailers{{"grpc-message", ""}}; EXPECT_EQ("", Common::getGrpcMessage(empty_error_trailers)); } TEST(GrpcCommonTest, ChargeStats) { NiceMock<Upstream::MockClusterInfo> cluster; Common::chargeStat(cluster, "service", "method", true); EXPECT_EQ(1U, cluster.stats_store_.counter("grpc.service.method.success").value()); EXPECT_EQ(0U, cluster.stats_store_.counter("grpc.service.method.failure").value()); EXPECT_EQ(1U, cluster.stats_store_.counter("grpc.service.method.total").value()); Common::chargeStat(cluster, "service", "method", false); EXPECT_EQ(1U, cluster.stats_store_.counter("grpc.service.method.success").value()); EXPECT_EQ(1U, cluster.stats_store_.counter("grpc.service.method.failure").value()); EXPECT_EQ(2U, cluster.stats_store_.counter("grpc.service.method.total").value()); Http::TestHeaderMapImpl trailers; Http::HeaderEntry& status = trailers.insertGrpcStatus(); status.value("0", 1); Common::chargeStat(cluster, "grpc", "service", "method", &status); EXPECT_EQ(1U, cluster.stats_store_.counter("grpc.service.method.0").value()); EXPECT_EQ(2U, cluster.stats_store_.counter("grpc.service.method.success").value()); EXPECT_EQ(1U, cluster.stats_store_.counter("grpc.service.method.failure").value()); EXPECT_EQ(3U, cluster.stats_store_.counter("grpc.service.method.total").value()); status.value("1", 1); Common::chargeStat(cluster, "grpc", "service", "method", &status); EXPECT_EQ(1U, cluster.stats_store_.counter("grpc.service.method.0").value()); EXPECT_EQ(1U, cluster.stats_store_.counter("grpc.service.method.1").value()); EXPECT_EQ(2U, cluster.stats_store_.counter("grpc.service.method.success").value()); EXPECT_EQ(2U, cluster.stats_store_.counter("grpc.service.method.failure").value()); EXPECT_EQ(4U, cluster.stats_store_.counter("grpc.service.method.total").value()); } TEST(GrpcCommonTest, PrepareHeaders) { Http::MessagePtr message = Common::prepareHeaders("cluster", "service_name", "method_name"); EXPECT_STREQ("POST", message->headers().Method()->value().c_str()); EXPECT_STREQ("/service_name/method_name", message->headers().Path()->value().c_str()); EXPECT_STREQ("cluster", message->headers().Host()->value().c_str()); EXPECT_STREQ("application/grpc", message->headers().ContentType()->value().c_str()); } TEST(GrpcCommonTest, ResolveServiceAndMethod) { std::string service; std::string method; Http::HeaderMapImpl headers; Http::HeaderEntry& path = headers.insertPath(); path.value(std::string("/service_name/method_name")); EXPECT_TRUE(Common::resolveServiceAndMethod(&path, &service, &method)); EXPECT_EQ("service_name", service); EXPECT_EQ("method_name", method); path.value(std::string("")); EXPECT_FALSE(Common::resolveServiceAndMethod(&path, &service, &method)); path.value(std::string("/")); EXPECT_FALSE(Common::resolveServiceAndMethod(&path, &service, &method)); path.value(std::string("//")); EXPECT_FALSE(Common::resolveServiceAndMethod(&path, &service, &method)); path.value(std::string("/service_name")); EXPECT_FALSE(Common::resolveServiceAndMethod(&path, &service, &method)); path.value(std::string("/service_name/")); EXPECT_FALSE(Common::resolveServiceAndMethod(&path, &service, &method)); } TEST(GrpcCommonTest, GrpcToHttpStatus) { const std::vector<std::pair<Status::GrpcStatus, uint64_t>> test_set = { {Status::GrpcStatus::Ok, 200}, {Status::GrpcStatus::Canceled, 499}, {Status::GrpcStatus::Unknown, 500}, {Status::GrpcStatus::InvalidArgument, 400}, {Status::GrpcStatus::DeadlineExceeded, 504}, {Status::GrpcStatus::NotFound, 404}, {Status::GrpcStatus::AlreadyExists, 409}, {Status::GrpcStatus::PermissionDenied, 403}, {Status::GrpcStatus::ResourceExhausted, 429}, {Status::GrpcStatus::FailedPrecondition, 400}, {Status::GrpcStatus::Aborted, 409}, {Status::GrpcStatus::OutOfRange, 400}, {Status::GrpcStatus::Unimplemented, 501}, {Status::GrpcStatus::Internal, 500}, {Status::GrpcStatus::Unavailable, 503}, {Status::GrpcStatus::DataLoss, 500}, {Status::GrpcStatus::Unauthenticated, 401}, {Status::GrpcStatus::InvalidCode, 500}, }; for (const auto& test_case : test_set) { EXPECT_EQ(test_case.second, Common::grpcToHttpStatus(test_case.first)); } } TEST(GrpcCommonTest, HasGrpcContentType) { { Http::TestHeaderMapImpl headers{}; EXPECT_FALSE(Common::hasGrpcContentType(headers)); } auto isGrpcContentType = [](const std::string& s) { Http::TestHeaderMapImpl headers{{"content-type", s}}; return Common::hasGrpcContentType(headers); }; EXPECT_FALSE(isGrpcContentType("")); EXPECT_FALSE(isGrpcContentType("application/text")); EXPECT_TRUE(isGrpcContentType("application/grpc")); EXPECT_TRUE(isGrpcContentType("application/grpc+")); EXPECT_TRUE(isGrpcContentType("application/grpc+foo")); EXPECT_FALSE(isGrpcContentType("application/grpc-")); EXPECT_FALSE(isGrpcContentType("application/grpc-web")); EXPECT_FALSE(isGrpcContentType("application/grpc-web+foo")); } TEST(GrpcCommonTest, IsGrpcResponseHeader) { Http::TestHeaderMapImpl grpc_status_only{{":status", "500"}, {"grpc-status", "14"}}; EXPECT_TRUE(Common::isGrpcResponseHeader(grpc_status_only, true)); EXPECT_FALSE(Common::isGrpcResponseHeader(grpc_status_only, false)); Http::TestHeaderMapImpl grpc_response_header{{":status", "200"}, {"content-type", "application/grpc"}}; EXPECT_FALSE(Common::isGrpcResponseHeader(grpc_response_header, true)); EXPECT_TRUE(Common::isGrpcResponseHeader(grpc_response_header, false)); Http::TestHeaderMapImpl json_response_header{{":status", "200"}, {"content-type", "application/json"}}; EXPECT_FALSE(Common::isGrpcResponseHeader(json_response_header, true)); EXPECT_FALSE(Common::isGrpcResponseHeader(json_response_header, false)); } } // namespace Grpc } // namespace Envoy <commit_msg>Improve Grpc::Common test coverage (#2494)<commit_after>#include "common/grpc/common.h" #include "common/http/headers.h" #include "common/http/message_impl.h" #include "test/mocks/upstream/mocks.h" #include "test/proto/helloworld.pb.h" #include "test/test_common/utility.h" #include "gtest/gtest.h" namespace Envoy { namespace Grpc { TEST(GrpcCommonTest, GetGrpcStatus) { Http::TestHeaderMapImpl ok_trailers{{"grpc-status", "0"}}; EXPECT_EQ(Status::Ok, Common::getGrpcStatus(ok_trailers).value()); Http::TestHeaderMapImpl no_status_trailers{{"foo", "bar"}}; EXPECT_FALSE(Common::getGrpcStatus(no_status_trailers).valid()); Http::TestHeaderMapImpl aborted_trailers{{"grpc-status", "10"}}; EXPECT_EQ(Status::Aborted, Common::getGrpcStatus(aborted_trailers).value()); Http::TestHeaderMapImpl unauth_trailers{{"grpc-status", "16"}}; EXPECT_EQ(Status::Unauthenticated, Common::getGrpcStatus(unauth_trailers).value()); Http::TestHeaderMapImpl invalid_trailers{{"grpc-status", "-1"}}; EXPECT_EQ(Status::InvalidCode, Common::getGrpcStatus(invalid_trailers).value()); } TEST(GrpcCommonTest, GetGrpcMessage) { Http::TestHeaderMapImpl empty_trailers; EXPECT_EQ("", Common::getGrpcMessage(empty_trailers)); Http::TestHeaderMapImpl error_trailers{{"grpc-message", "Some error"}}; EXPECT_EQ("Some error", Common::getGrpcMessage(error_trailers)); Http::TestHeaderMapImpl empty_error_trailers{{"grpc-message", ""}}; EXPECT_EQ("", Common::getGrpcMessage(empty_error_trailers)); } TEST(GrpcCommonTest, ChargeStats) { NiceMock<Upstream::MockClusterInfo> cluster; Common::chargeStat(cluster, "service", "method", true); EXPECT_EQ(1U, cluster.stats_store_.counter("grpc.service.method.success").value()); EXPECT_EQ(0U, cluster.stats_store_.counter("grpc.service.method.failure").value()); EXPECT_EQ(1U, cluster.stats_store_.counter("grpc.service.method.total").value()); Common::chargeStat(cluster, "service", "method", false); EXPECT_EQ(1U, cluster.stats_store_.counter("grpc.service.method.success").value()); EXPECT_EQ(1U, cluster.stats_store_.counter("grpc.service.method.failure").value()); EXPECT_EQ(2U, cluster.stats_store_.counter("grpc.service.method.total").value()); Http::TestHeaderMapImpl trailers; Http::HeaderEntry& status = trailers.insertGrpcStatus(); status.value("0", 1); Common::chargeStat(cluster, "grpc", "service", "method", &status); EXPECT_EQ(1U, cluster.stats_store_.counter("grpc.service.method.0").value()); EXPECT_EQ(2U, cluster.stats_store_.counter("grpc.service.method.success").value()); EXPECT_EQ(1U, cluster.stats_store_.counter("grpc.service.method.failure").value()); EXPECT_EQ(3U, cluster.stats_store_.counter("grpc.service.method.total").value()); status.value("1", 1); Common::chargeStat(cluster, "grpc", "service", "method", &status); EXPECT_EQ(1U, cluster.stats_store_.counter("grpc.service.method.0").value()); EXPECT_EQ(1U, cluster.stats_store_.counter("grpc.service.method.1").value()); EXPECT_EQ(2U, cluster.stats_store_.counter("grpc.service.method.success").value()); EXPECT_EQ(2U, cluster.stats_store_.counter("grpc.service.method.failure").value()); EXPECT_EQ(4U, cluster.stats_store_.counter("grpc.service.method.total").value()); } TEST(GrpcCommonTest, PrepareHeaders) { Http::MessagePtr message = Common::prepareHeaders("cluster", "service_name", "method_name"); EXPECT_STREQ("POST", message->headers().Method()->value().c_str()); EXPECT_STREQ("/service_name/method_name", message->headers().Path()->value().c_str()); EXPECT_STREQ("cluster", message->headers().Host()->value().c_str()); EXPECT_STREQ("application/grpc", message->headers().ContentType()->value().c_str()); } TEST(GrpcCommonTest, ResolveServiceAndMethod) { std::string service; std::string method; Http::HeaderMapImpl headers; Http::HeaderEntry& path = headers.insertPath(); path.value(std::string("/service_name/method_name")); EXPECT_TRUE(Common::resolveServiceAndMethod(&path, &service, &method)); EXPECT_EQ("service_name", service); EXPECT_EQ("method_name", method); path.value(std::string("")); EXPECT_FALSE(Common::resolveServiceAndMethod(&path, &service, &method)); path.value(std::string("/")); EXPECT_FALSE(Common::resolveServiceAndMethod(&path, &service, &method)); path.value(std::string("//")); EXPECT_FALSE(Common::resolveServiceAndMethod(&path, &service, &method)); path.value(std::string("/service_name")); EXPECT_FALSE(Common::resolveServiceAndMethod(&path, &service, &method)); path.value(std::string("/service_name/")); EXPECT_FALSE(Common::resolveServiceAndMethod(&path, &service, &method)); } TEST(GrpcCommonTest, GrpcToHttpStatus) { const std::vector<std::pair<Status::GrpcStatus, uint64_t>> test_set = { {Status::GrpcStatus::Ok, 200}, {Status::GrpcStatus::Canceled, 499}, {Status::GrpcStatus::Unknown, 500}, {Status::GrpcStatus::InvalidArgument, 400}, {Status::GrpcStatus::DeadlineExceeded, 504}, {Status::GrpcStatus::NotFound, 404}, {Status::GrpcStatus::AlreadyExists, 409}, {Status::GrpcStatus::PermissionDenied, 403}, {Status::GrpcStatus::ResourceExhausted, 429}, {Status::GrpcStatus::FailedPrecondition, 400}, {Status::GrpcStatus::Aborted, 409}, {Status::GrpcStatus::OutOfRange, 400}, {Status::GrpcStatus::Unimplemented, 501}, {Status::GrpcStatus::Internal, 500}, {Status::GrpcStatus::Unavailable, 503}, {Status::GrpcStatus::DataLoss, 500}, {Status::GrpcStatus::Unauthenticated, 401}, {Status::GrpcStatus::InvalidCode, 500}, }; for (const auto& test_case : test_set) { EXPECT_EQ(test_case.second, Common::grpcToHttpStatus(test_case.first)); } } TEST(GrpcCommonTest, HttpToGrpcStatus) { const std::vector<std::pair<uint64_t, Status::GrpcStatus>> test_set = { {400, Status::GrpcStatus::Internal}, {401, Status::GrpcStatus::Unauthenticated}, {403, Status::GrpcStatus::PermissionDenied}, {404, Status::GrpcStatus::Unimplemented}, {429, Status::GrpcStatus::Unavailable}, {502, Status::GrpcStatus::Unavailable}, {503, Status::GrpcStatus::Unavailable}, {504, Status::GrpcStatus::Unavailable}, {500, Status::GrpcStatus::Unknown}, }; for (const auto& test_case : test_set) { EXPECT_EQ(test_case.second, Common::httpToGrpcStatus(test_case.first)); } } TEST(GrpcCommonTest, HasGrpcContentType) { { Http::TestHeaderMapImpl headers{}; EXPECT_FALSE(Common::hasGrpcContentType(headers)); } auto isGrpcContentType = [](const std::string& s) { Http::TestHeaderMapImpl headers{{"content-type", s}}; return Common::hasGrpcContentType(headers); }; EXPECT_FALSE(isGrpcContentType("")); EXPECT_FALSE(isGrpcContentType("application/text")); EXPECT_TRUE(isGrpcContentType("application/grpc")); EXPECT_TRUE(isGrpcContentType("application/grpc+")); EXPECT_TRUE(isGrpcContentType("application/grpc+foo")); EXPECT_FALSE(isGrpcContentType("application/grpc-")); EXPECT_FALSE(isGrpcContentType("application/grpc-web")); EXPECT_FALSE(isGrpcContentType("application/grpc-web+foo")); } TEST(GrpcCommonTest, IsGrpcResponseHeader) { Http::TestHeaderMapImpl grpc_status_only{{":status", "500"}, {"grpc-status", "14"}}; EXPECT_TRUE(Common::isGrpcResponseHeader(grpc_status_only, true)); EXPECT_FALSE(Common::isGrpcResponseHeader(grpc_status_only, false)); Http::TestHeaderMapImpl grpc_response_header{{":status", "200"}, {"content-type", "application/grpc"}}; EXPECT_FALSE(Common::isGrpcResponseHeader(grpc_response_header, true)); EXPECT_TRUE(Common::isGrpcResponseHeader(grpc_response_header, false)); Http::TestHeaderMapImpl json_response_header{{":status", "200"}, {"content-type", "application/json"}}; EXPECT_FALSE(Common::isGrpcResponseHeader(json_response_header, true)); EXPECT_FALSE(Common::isGrpcResponseHeader(json_response_header, false)); } TEST(GrpcCommonTest, ValidateResponse) { { Http::ResponseMessageImpl response( Http::HeaderMapPtr{new Http::TestHeaderMapImpl{{":status", "200"}}}); response.trailers(Http::HeaderMapPtr{new Http::TestHeaderMapImpl{{"grpc-status", "0"}}}); EXPECT_NO_THROW(Common::validateResponse(response)); } { Http::ResponseMessageImpl response( Http::HeaderMapPtr{new Http::TestHeaderMapImpl{{":status", "503"}}}); EXPECT_THROW_WITH_MESSAGE(Common::validateResponse(response), Exception, "non-200 response code"); } { Http::ResponseMessageImpl response( Http::HeaderMapPtr{new Http::TestHeaderMapImpl{{":status", "200"}}}); response.trailers(Http::HeaderMapPtr{new Http::TestHeaderMapImpl{{"grpc-status", "100"}}}); EXPECT_THROW_WITH_MESSAGE(Common::validateResponse(response), Exception, "bad grpc-status trailer"); } { Http::ResponseMessageImpl response( Http::HeaderMapPtr{new Http::TestHeaderMapImpl{{":status", "200"}}}); response.trailers(Http::HeaderMapPtr{new Http::TestHeaderMapImpl{{"grpc-status", "4"}}}); EXPECT_THROW_WITH_MESSAGE(Common::validateResponse(response), Exception, ""); } { Http::ResponseMessageImpl response( Http::HeaderMapPtr{new Http::TestHeaderMapImpl{{":status", "200"}}}); response.trailers(Http::HeaderMapPtr{ new Http::TestHeaderMapImpl{{"grpc-status", "4"}, {"grpc-message", "custom error"}}}); EXPECT_THROW_WITH_MESSAGE(Common::validateResponse(response), Exception, "custom error"); } { Http::ResponseMessageImpl response(Http::HeaderMapPtr{ new Http::TestHeaderMapImpl{{":status", "200"}, {"grpc-status", "100"}}}); EXPECT_THROW_WITH_MESSAGE(Common::validateResponse(response), Exception, "bad grpc-status header"); } { Http::ResponseMessageImpl response( Http::HeaderMapPtr{new Http::TestHeaderMapImpl{{":status", "200"}, {"grpc-status", "4"}}}); EXPECT_THROW_WITH_MESSAGE(Common::validateResponse(response), Exception, ""); } { Http::ResponseMessageImpl response(Http::HeaderMapPtr{new Http::TestHeaderMapImpl{ {":status", "200"}, {"grpc-status", "4"}, {"grpc-message", "custom error"}}}); EXPECT_THROW_WITH_MESSAGE(Common::validateResponse(response), Exception, "custom error"); } } } // namespace Grpc } // namespace Envoy <|endoftext|>
<commit_before>/* * Copyright (c) 2016 tildearrow * * 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. */ #ifdef _WIN32 #define FONT "C:\\Windows\\Fonts\\segoeui.ttf" #elif __APPLE__ #define FONT "/System/Library/Fonts/SFNSDisplay-Regular.otf" #elif __linux__ #define FONT "/usr/share/fonts/TTF/Ubuntu-R.ttf" #else #warning "really? please tell me if you are compiling on this OS" #endif #include "includes.h" #include "font.h" #include "ui.h" #include "gfxeditor.h" SDL_Window* mainWindow; SDL_Renderer* mainRenderer; SDL_Event* event; int mouseX; int mouseY; unsigned int mouseB; unsigned int mouseBold; SDL_Color color[16]; bool willquit; uisystem* ui; gfxeditor* geditor; font* mainFont; int curview; int cureditid, curedittype; const char* viewname[9]={"Graphics","Audio","Entity Types","Scenes","Functions","ShouldNotAppear","ShouldNotAppear","ShouldNotAppear","ShouldNotAppear"}; struct graphic { string name; int id; int width; int height; int originX, originY; int subgraphics; bool background; std::vector<unsigned char*> data; int colmode; unsigned char** colmask; }; struct audio { string name; int id; int size; float* data; int finaltype; }; struct etype { string name; int id; int initialgraphic; int initialsubgraphic; int parent; int category; std::vector<string> eventcode; string headercode; }; struct viewport { SDL_Rect view, port; float viewangle, portangle; }; struct scene { string name; int id; int width; int height; bool freeze; std::vector<viewport> viewports; }; struct function { string name; int id; string code; }; std::vector<graphic> graphics; std::vector<audio> sounds; std::vector<etype> etypes; std::vector<scene> scenes; std::vector<function> functions; void doNothing(){ printf("hello world!\n"); } void drawScreen() { SDL_RenderDrawLine(mainRenderer,0,32,1024,32); if (curview<5) { SDL_RenderDrawLine(mainRenderer,256,32,256,600); SDL_RenderDrawLine(mainRenderer,0,53,256,53); mainFont->drawf(128,41,color[0],1,1,"%s List",viewname[curview]); switch (curview) { case 0: for (int i=0; i<graphics.size(); i++) { mainFont->draw(0,64+(i*20),((cureditid==i && curedittype==0)?(color[1]):(color[0])),0,0,false,graphics[i].name); } // also draw graphic editor geditor->draw(); break; case 1: for (int i=0; i<sounds.size(); i++) { mainFont->draw(0,64+(i*20),((cureditid==i && curedittype==1)?(color[1]):(color[0])),0,0,false,sounds[i].name); } break; case 2: for (int i=0; i<etypes.size(); i++) { mainFont->draw(0,64+(i*20),((cureditid==i && curedittype==2)?(color[1]):(color[0])),0,0,false,etypes[i].name); } break; case 3: for (int i=0; i<scenes.size(); i++) { mainFont->draw(0,64+(i*20),((cureditid==i && curedittype==3)?(color[1]):(color[0])),0,0,false,scenes[i].name); } break; case 4: for (int i=0; i<functions.size(); i++) { mainFont->draw(0,64+(i*20),((cureditid==i && curedittype==4)?(color[1]):(color[0])),0,0,false, functions[i].name); } break; } } } void goGraphicsView() { curview=0; } void goAudioView() { curview=1; } void goETypesView() { curview=2; } void goScenesView() { curview=3; } void goFunctionsView() { curview=4; } void goProjectView() { curview=5; } void goSettingsView() { curview=6; } void goHelpView() { curview=7; } void goAboutView() { curview=8; } void handleMouse() { if ((mouseB&1)>(mouseBold&1)) { // checks for mouse left pressed if (mouseX<256 && mouseY>64) { cureditid=(mouseY-64)/20; curedittype=curview; switch (curview) { case 0: geditor->setdata(graphics[cureditid].data[0], graphics[cureditid].width, graphics[cureditid].height); break; } } } } void makeNewResource() { // make new resource int formersize; switch (curview) { case 0: formersize=graphics.size(); graphics.resize(formersize+1); graphics[formersize].id=formersize; graphics[formersize].name="graphic"; graphics[formersize].name+=std::to_string(formersize); // create pre-defined graphic graphics[formersize].subgraphics=1; graphics[formersize].width=32; graphics[formersize].height=32; graphics[formersize].data.resize(1); graphics[formersize].data[0]=new unsigned char[4096]; break; case 1: formersize=sounds.size(); sounds.resize(formersize+1); sounds[formersize].id=formersize; sounds[formersize].name="sound"; sounds[formersize].name+=std::to_string(formersize); break; case 2: formersize=etypes.size(); etypes.resize(formersize+1); etypes[formersize].id=formersize; etypes[formersize].name="type"; etypes[formersize].name+=std::to_string(formersize); break; case 3: formersize=scenes.size(); scenes.resize(formersize+1); scenes[formersize].id=formersize; scenes[formersize].name="scene"; scenes[formersize].name+=std::to_string(formersize); break; case 4: formersize=functions.size(); functions.resize(formersize+1); functions[formersize].id=formersize; functions[formersize].name="func"; functions[formersize].name+=std::to_string(formersize); break; } } int main() { willquit=false; // init everything SDL_Init(SDL_INIT_VIDEO); TTF_Init(); ui=new uisystem; event=new SDL_Event; string title; title="LowerTriad"; mainWindow=SDL_CreateWindow(title.c_str(),0,0,1024,600,SDL_WINDOW_RESIZABLE); if (!mainWindow) { printf("i'm sorry, but window can't be created: %s\n",SDL_GetError()); return 1; } mainRenderer=SDL_CreateRenderer(mainWindow,-1,SDL_RENDERER_ACCELERATED|SDL_RENDERER_PRESENTVSYNC); // initialize UI mainFont=new font; mainFont->setrenderer(mainRenderer); if (!mainFont->load(FONT,14)) { printf("can't load font, which means this application is going to crash now...\n"); } ui->setrenderer(mainRenderer); color[0].r=192; color[0].g=192; color[0].b=192; color[0].a=255; // main color[1].r=255; color[1].g=255; color[1].b=255; color[1].a=255; // alternate color[2].r=0; color[2].g=255; color[2].b=0; color[2].a=255; // success color[3].r=255; color[3].g=255; color[3].b=0; color[3].a=255; // ongoing color[4].r=255; color[4].g=0; color[4].b=0; color[4].a=255; // failure ui->setfont(mainFont); ui->addbutton(0,0,48,22,"Prepare","Prepare CMake project",color[0],color[0],doNothing); ui->addbutton(48,0,40,22,"Build","Build game",color[0],color[0],doNothing); ui->addbutton(100,0,32,22,"Run","Run compiled game",color[0],color[0],doNothing); ui->addbutton(132,0,56,22,"Package","Create package",color[0],color[0],doNothing); ui->addbutton(200,0,64,22,"Graphics","",color[0],color[0],goGraphicsView); ui->addbutton(264,0,50,22,"Audio","Sound/Music",color[0],color[0],goAudioView); ui->addbutton(314,0,80,22,"EntityTypes","",color[0],color[0],goETypesView); ui->addbutton(394,0,50,22,"Scenes","",color[0],color[0],goScenesView); ui->addbutton(444,0,72,22,"Functions","",color[0],color[0],goFunctionsView); ui->addbutton(516,0,60,22,"Project","",color[0],color[0],goProjectView); ui->addbutton(1024-160,0,60,22,"Settings","",color[0],color[0],goSettingsView); ui->addbutton(1024-100,0,50,22,"Help","",color[0],color[0],goHelpView); ui->addbutton(1024-50,0,50,22,"About","",color[0],color[0],goAboutView); ui->addbutton(225,32,32,22,"Add","Add a new resource",color[0],color[0],makeNewResource); ui->setmouse(&mouseX,&mouseY,&mouseB,&mouseBold); // initialize graphic editor geditor=new gfxeditor; geditor->setfont(mainFont); // initialize IDE variables cureditid=-1; curedittype=0; curview=0; while (1) { // check events while (SDL_PollEvent(event)) { if (event->type==SDL_QUIT) { willquit=true; } } SDL_SetRenderDrawColor(mainRenderer,0,0,0,0); SDL_RenderClear(mainRenderer); SDL_SetRenderDrawColor(mainRenderer,color[0].r,color[0].g,color[0].b,color[0].a); mouseBold=mouseB; mouseB=SDL_GetMouseState(&mouseX, &mouseY); handleMouse(); drawScreen(); ui->drawall(); SDL_RenderPresent(mainRenderer); if (willquit) { break; } } return 0; } <commit_msg>so it is fixed now<commit_after>/* * Copyright (c) 2016 tildearrow * * 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. */ #ifdef _WIN32 #define FONT "C:\\Windows\\Fonts\\segoeui.ttf" #elif __APPLE__ #define FONT "/System/Library/Fonts/SFNSDisplay-Regular.otf" #elif __linux__ #define FONT "/usr/share/fonts/TTF/Ubuntu-R.ttf" #else #warning "really? please tell me if you are compiling on this OS" #endif #include "includes.h" #include "font.h" #include "ui.h" #include "gfxeditor.h" SDL_Window* mainWindow; SDL_Renderer* mainRenderer; SDL_Event* event; int mouseX; int mouseY; unsigned int mouseB; unsigned int mouseBold; SDL_Color color[16]; bool willquit; uisystem* ui; gfxeditor* geditor; font* mainFont; int curview; int cureditid, curedittype; const char* viewname[9]={"Graphics","Audio","Entity Types","Scenes","Functions","ShouldNotAppear","ShouldNotAppear","ShouldNotAppear","ShouldNotAppear"}; struct graphic { string name; int id; int width; int height; int originX, originY; int subgraphics; bool background; std::vector<unsigned char*> data; int colmode; unsigned char** colmask; }; struct audio { string name; int id; int size; float* data; int finaltype; }; struct etype { string name; int id; int initialgraphic; int initialsubgraphic; int parent; int category; std::vector<string> eventcode; string headercode; }; struct viewport { SDL_Rect view, port; float viewangle, portangle; }; struct scene { string name; int id; int width; int height; bool freeze; std::vector<viewport> viewports; }; struct function { string name; int id; string code; }; std::vector<graphic> graphics; std::vector<audio> sounds; std::vector<etype> etypes; std::vector<scene> scenes; std::vector<function> functions; void doNothing(){ printf("hello world!\n"); } void drawScreen() { SDL_RenderDrawLine(mainRenderer,0,32,1024,32); if (curview<5) { SDL_RenderDrawLine(mainRenderer,256,32,256,600); SDL_RenderDrawLine(mainRenderer,0,53,256,53); mainFont->drawf(128,41,color[0],1,1,"%s List",viewname[curview]); switch (curview) { case 0: for (int i=0; i<graphics.size(); i++) { mainFont->draw(0,64+(i*20),((cureditid==i && curedittype==0)?(color[1]):(color[0])),0,0,false,graphics[i].name); } // also draw graphic editor geditor->draw(); break; case 1: for (int i=0; i<sounds.size(); i++) { mainFont->draw(0,64+(i*20),((cureditid==i && curedittype==1)?(color[1]):(color[0])),0,0,false,sounds[i].name); } break; case 2: for (int i=0; i<etypes.size(); i++) { mainFont->draw(0,64+(i*20),((cureditid==i && curedittype==2)?(color[1]):(color[0])),0,0,false,etypes[i].name); } break; case 3: for (int i=0; i<scenes.size(); i++) { mainFont->draw(0,64+(i*20),((cureditid==i && curedittype==3)?(color[1]):(color[0])),0,0,false,scenes[i].name); } break; case 4: for (int i=0; i<functions.size(); i++) { mainFont->draw(0,64+(i*20),((cureditid==i && curedittype==4)?(color[1]):(color[0])),0,0,false, functions[i].name); } break; } } } void goGraphicsView() { curview=0; } void goAudioView() { curview=1; } void goETypesView() { curview=2; } void goScenesView() { curview=3; } void goFunctionsView() { curview=4; } void goProjectView() { curview=5; } void goSettingsView() { curview=6; } void goHelpView() { curview=7; } void goAboutView() { curview=8; } void handleMouse() { if ((mouseB&1)>(mouseBold&1)) { // checks for mouse left pressed if (mouseX<256 && mouseY>64) { curedittype=curview; switch (curview) { case 0: cureditid=(mouseY-64)/20; if (cureditid>=graphics.size()) { cureditid=-1; } if (cureditid!=-1) { geditor->setdata(graphics[cureditid].data[0], graphics[cureditid].width, graphics[cureditid].height); } break; } } } } void makeNewResource() { // make new resource int formersize; switch (curview) { case 0: formersize=graphics.size(); graphics.resize(formersize+1); graphics[formersize].id=formersize; graphics[formersize].name="graphic"; graphics[formersize].name+=std::to_string(formersize); // create pre-defined graphic graphics[formersize].subgraphics=1; graphics[formersize].width=32; graphics[formersize].height=32; graphics[formersize].data.resize(1); graphics[formersize].data[0]=new unsigned char[4096]; break; case 1: formersize=sounds.size(); sounds.resize(formersize+1); sounds[formersize].id=formersize; sounds[formersize].name="sound"; sounds[formersize].name+=std::to_string(formersize); break; case 2: formersize=etypes.size(); etypes.resize(formersize+1); etypes[formersize].id=formersize; etypes[formersize].name="type"; etypes[formersize].name+=std::to_string(formersize); break; case 3: formersize=scenes.size(); scenes.resize(formersize+1); scenes[formersize].id=formersize; scenes[formersize].name="scene"; scenes[formersize].name+=std::to_string(formersize); break; case 4: formersize=functions.size(); functions.resize(formersize+1); functions[formersize].id=formersize; functions[formersize].name="func"; functions[formersize].name+=std::to_string(formersize); break; } } int main() { willquit=false; // init everything SDL_Init(SDL_INIT_VIDEO); TTF_Init(); ui=new uisystem; event=new SDL_Event; string title; title="LowerTriad"; mainWindow=SDL_CreateWindow(title.c_str(),0,0,1024,600,SDL_WINDOW_RESIZABLE); if (!mainWindow) { printf("i'm sorry, but window can't be created: %s\n",SDL_GetError()); return 1; } mainRenderer=SDL_CreateRenderer(mainWindow,-1,SDL_RENDERER_ACCELERATED|SDL_RENDERER_PRESENTVSYNC); // initialize UI mainFont=new font; mainFont->setrenderer(mainRenderer); if (!mainFont->load(FONT,14)) { printf("can't load font, which means this application is going to crash now...\n"); } ui->setrenderer(mainRenderer); color[0].r=192; color[0].g=192; color[0].b=192; color[0].a=255; // main color[1].r=255; color[1].g=255; color[1].b=255; color[1].a=255; // alternate color[2].r=0; color[2].g=255; color[2].b=0; color[2].a=255; // success color[3].r=255; color[3].g=255; color[3].b=0; color[3].a=255; // ongoing color[4].r=255; color[4].g=0; color[4].b=0; color[4].a=255; // failure ui->setfont(mainFont); ui->addbutton(0,0,48,22,"Prepare","Prepare CMake project",color[0],color[0],doNothing); ui->addbutton(48,0,40,22,"Build","Build game",color[0],color[0],doNothing); ui->addbutton(100,0,32,22,"Run","Run compiled game",color[0],color[0],doNothing); ui->addbutton(132,0,56,22,"Package","Create package",color[0],color[0],doNothing); ui->addbutton(200,0,64,22,"Graphics","",color[0],color[0],goGraphicsView); ui->addbutton(264,0,50,22,"Audio","Sound/Music",color[0],color[0],goAudioView); ui->addbutton(314,0,80,22,"EntityTypes","",color[0],color[0],goETypesView); ui->addbutton(394,0,50,22,"Scenes","",color[0],color[0],goScenesView); ui->addbutton(444,0,72,22,"Functions","",color[0],color[0],goFunctionsView); ui->addbutton(516,0,60,22,"Project","",color[0],color[0],goProjectView); ui->addbutton(1024-160,0,60,22,"Settings","",color[0],color[0],goSettingsView); ui->addbutton(1024-100,0,50,22,"Help","",color[0],color[0],goHelpView); ui->addbutton(1024-50,0,50,22,"About","",color[0],color[0],goAboutView); ui->addbutton(225,32,32,22,"Add","Add a new resource",color[0],color[0],makeNewResource); ui->setmouse(&mouseX,&mouseY,&mouseB,&mouseBold); // initialize graphic editor geditor=new gfxeditor; geditor->setfont(mainFont); // initialize IDE variables cureditid=-1; curedittype=0; curview=0; while (1) { // check events while (SDL_PollEvent(event)) { if (event->type==SDL_QUIT) { willquit=true; } } SDL_SetRenderDrawColor(mainRenderer,0,0,0,0); SDL_RenderClear(mainRenderer); SDL_SetRenderDrawColor(mainRenderer,color[0].r,color[0].g,color[0].b,color[0].a); mouseBold=mouseB; mouseB=SDL_GetMouseState(&mouseX, &mouseY); handleMouse(); drawScreen(); ui->drawall(); SDL_RenderPresent(mainRenderer); if (willquit) { break; } } return 0; } <|endoftext|>
<commit_before>/* * This file is part of Poedit (http://www.poedit.net) * * Copyright (C) 2008-2013 Vaclav Slavik * * 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 "attentionbar.h" #include <wx/sizer.h> #include <wx/settings.h> #include <wx/artprov.h> #include <wx/bmpbuttn.h> #include <wx/stattext.h> #include <wx/statbmp.h> #include <wx/config.h> #include <wx/dcclient.h> #ifdef __WXMAC__ #include "osx_helpers.h" #endif #if defined(__WXMSW__) #define USE_SLIDE_EFFECT #endif #ifdef __WXMAC__ #define SMALL_BORDER 5 #define BUTTONS_SPACE 10 #else #define SMALL_BORDER 3 #define BUTTONS_SPACE 3 #endif BEGIN_EVENT_TABLE(AttentionBar, wxPanel) EVT_BUTTON(wxID_CLOSE, AttentionBar::OnClose) EVT_BUTTON(wxID_ANY, AttentionBar::OnAction) END_EVENT_TABLE() AttentionBar::AttentionBar(wxWindow *parent) : wxPanel(parent, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL | wxBORDER_NONE) { #ifdef __WXMSW__ wxColour bg("#FFF499"); // match Visual Studio 2012+'s aesthetics #else wxColour bg = wxSystemSettings::GetColour(wxSYS_COLOUR_INFOBK); #endif SetBackgroundColour(bg); SetForegroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_INFOTEXT)); m_icon = new wxStaticBitmap(this, wxID_ANY, wxNullBitmap); m_label = new wxStaticText(this, wxID_ANY, wxEmptyString); m_buttons = new wxBoxSizer(wxHORIZONTAL); wxButton *btnClose = new wxBitmapButton ( this, wxID_CLOSE, wxArtProvider::GetBitmap("window-close", wxART_MENU), wxDefaultPosition, wxDefaultSize, wxNO_BORDER ); btnClose->SetToolTip(_("Hide this notification message")); #ifdef __WXMSW__ btnClose->SetBackgroundColour(bg); #endif #ifdef __WXMAC__ SetWindowVariant(wxWINDOW_VARIANT_SMALL); #endif #if defined(__WXMAC__) || defined(__WXMSW__) Bind(wxEVT_PAINT, &AttentionBar::OnPaint, this); wxFont boldFont = wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT); boldFont.SetWeight(wxFONTWEIGHT_BOLD); m_label->SetFont(boldFont); #endif // wxSizer *sizer = new wxBoxSizer(wxHORIZONTAL); sizer->AddSpacer(wxSizerFlags::GetDefaultBorder()); sizer->Add(m_icon, wxSizerFlags().Center().Border(wxRIGHT, SMALL_BORDER)); sizer->Add(m_label, wxSizerFlags(1).Center().Border(wxALL, SMALL_BORDER)); sizer->Add(m_buttons, wxSizerFlags().Center().Border(wxALL, SMALL_BORDER)); sizer->Add(btnClose, wxSizerFlags().Center().Border(wxALL, SMALL_BORDER)); SetSizer(sizer); // the bar should be initially hidden Show(false); } #ifdef __WXMAC__ void AttentionBar::OnPaint(wxPaintEvent&) { wxPaintDC dc(this); wxRect rect(dc.GetSize()); dc.SetPen(wxColour(254,230,93)); dc.DrawLine(rect.GetTopLeft(), rect.GetTopRight()); dc.SetPen(wxColour(176,120,7)); dc.DrawLine(rect.GetBottomLeft(), rect.GetBottomRight()); rect.Deflate(0,1); dc.GradientFillLinear ( rect, wxColour(254,220,48), wxColour(253,188,11), wxDOWN ); } #endif // __WXMAC__ #ifdef __WXMSW__ void AttentionBar::OnPaint(wxPaintEvent&) { wxPaintDC dc(this); wxRect rect(dc.GetSize()); dc.SetBrush(*wxTRANSPARENT_BRUSH); dc.SetPen(wxColour("#e5dd8c")); dc.DrawRoundedRectangle(rect, 1); } #endif // __WXMSW__ void AttentionBar::ShowMessage(const AttentionMessage& msg) { if ( msg.IsBlacklisted() ) return; wxString iconName; switch ( msg.m_kind ) { case AttentionMessage::Info: iconName = wxART_INFORMATION; break; case AttentionMessage::Warning: iconName = wxART_WARNING; break; case AttentionMessage::Error: iconName = wxART_ERROR; break; } m_icon->SetBitmap(wxArtProvider::GetBitmap(iconName, wxART_MENU, wxSize(16, 16))); m_label->SetLabelText(msg.m_text); m_buttons->Clear(true/*delete_windows*/); m_actions.clear(); for ( AttentionMessage::Actions::const_iterator i = msg.m_actions.begin(); i != msg.m_actions.end(); ++i ) { wxButton *b = new wxButton(this, wxID_ANY, i->first); #ifdef __WXMAC__ MakeButtonRounded(b->GetHandle()); #endif m_buttons->Add(b, wxSizerFlags().Center().Border(wxRIGHT, BUTTONS_SPACE)); m_actions[b] = i->second; } // we need to size the control correctly _and_ lay out the controls if this // is the first time it's being shown, otherwise we can get garbled look: SetSize(GetParent()->GetClientSize().x, GetBestSize().y); Layout(); #ifdef USE_SLIDE_EFFECT ShowWithEffect(wxSHOW_EFFECT_SLIDE_TO_BOTTOM); #else Show(); #endif GetParent()->Layout(); } void AttentionBar::HideMessage() { #ifdef USE_SLIDE_EFFECT HideWithEffect(wxSHOW_EFFECT_SLIDE_TO_TOP); #else Hide(); #endif GetParent()->Layout(); } void AttentionBar::OnClose(wxCommandEvent& WXUNUSED(event)) { HideMessage(); } void AttentionBar::OnAction(wxCommandEvent& event) { ActionsMap::const_iterator i = m_actions.find(event.GetEventObject()); if ( i == m_actions.end() ) { event.Skip(); return; } HideMessage(); i->second(); } /* static */ void AttentionMessage::AddToBlacklist(const wxString& id) { wxConfig::Get()->Write ( wxString::Format("/messages/dont_show/%s", id.c_str()), (long)true ); } /* static */ bool AttentionMessage::IsBlacklisted(const wxString& id) { return wxConfig::Get()->ReadBool ( wxString::Format("/messages/dont_show/%s", id.c_str()), false ); } void AttentionMessage::AddDontShowAgain() { AddAction(_("Don't show again"), std::bind(&AttentionMessage::AddToBlacklist, m_id)); } <commit_msg>AttentionBar: don't use ShowWithEffect even on Windows.<commit_after>/* * This file is part of Poedit (http://www.poedit.net) * * Copyright (C) 2008-2013 Vaclav Slavik * * 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 "attentionbar.h" #include <wx/sizer.h> #include <wx/settings.h> #include <wx/artprov.h> #include <wx/bmpbuttn.h> #include <wx/stattext.h> #include <wx/statbmp.h> #include <wx/config.h> #include <wx/dcclient.h> #ifdef __WXMAC__ #include "osx_helpers.h" #endif #ifdef __WXMAC__ #define SMALL_BORDER 5 #define BUTTONS_SPACE 10 #else #define SMALL_BORDER 3 #define BUTTONS_SPACE 3 #endif BEGIN_EVENT_TABLE(AttentionBar, wxPanel) EVT_BUTTON(wxID_CLOSE, AttentionBar::OnClose) EVT_BUTTON(wxID_ANY, AttentionBar::OnAction) END_EVENT_TABLE() AttentionBar::AttentionBar(wxWindow *parent) : wxPanel(parent, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL | wxBORDER_NONE) { #ifdef __WXMSW__ wxColour bg("#FFF499"); // match Visual Studio 2012+'s aesthetics #else wxColour bg = wxSystemSettings::GetColour(wxSYS_COLOUR_INFOBK); #endif SetBackgroundColour(bg); SetForegroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_INFOTEXT)); m_icon = new wxStaticBitmap(this, wxID_ANY, wxNullBitmap); m_label = new wxStaticText(this, wxID_ANY, wxEmptyString); m_buttons = new wxBoxSizer(wxHORIZONTAL); wxButton *btnClose = new wxBitmapButton ( this, wxID_CLOSE, wxArtProvider::GetBitmap("window-close", wxART_MENU), wxDefaultPosition, wxDefaultSize, wxNO_BORDER ); btnClose->SetToolTip(_("Hide this notification message")); #ifdef __WXMSW__ btnClose->SetBackgroundColour(bg); #endif #ifdef __WXMAC__ SetWindowVariant(wxWINDOW_VARIANT_SMALL); #endif #if defined(__WXMAC__) || defined(__WXMSW__) Bind(wxEVT_PAINT, &AttentionBar::OnPaint, this); wxFont boldFont = wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT); boldFont.SetWeight(wxFONTWEIGHT_BOLD); m_label->SetFont(boldFont); #endif // wxSizer *sizer = new wxBoxSizer(wxHORIZONTAL); sizer->AddSpacer(wxSizerFlags::GetDefaultBorder()); sizer->Add(m_icon, wxSizerFlags().Center().Border(wxRIGHT, SMALL_BORDER)); sizer->Add(m_label, wxSizerFlags(1).Center().Border(wxALL, SMALL_BORDER)); sizer->Add(m_buttons, wxSizerFlags().Center().Border(wxALL, SMALL_BORDER)); sizer->Add(btnClose, wxSizerFlags().Center().Border(wxALL, SMALL_BORDER)); SetSizer(sizer); // the bar should be initially hidden Show(false); } #ifdef __WXMAC__ void AttentionBar::OnPaint(wxPaintEvent&) { wxPaintDC dc(this); wxRect rect(dc.GetSize()); dc.SetPen(wxColour(254,230,93)); dc.DrawLine(rect.GetTopLeft(), rect.GetTopRight()); dc.SetPen(wxColour(176,120,7)); dc.DrawLine(rect.GetBottomLeft(), rect.GetBottomRight()); rect.Deflate(0,1); dc.GradientFillLinear ( rect, wxColour(254,220,48), wxColour(253,188,11), wxDOWN ); } #endif // __WXMAC__ #ifdef __WXMSW__ void AttentionBar::OnPaint(wxPaintEvent&) { wxPaintDC dc(this); wxRect rect(dc.GetSize()); dc.SetBrush(*wxTRANSPARENT_BRUSH); dc.SetPen(wxColour("#e5dd8c")); dc.DrawRoundedRectangle(rect, 1); } #endif // __WXMSW__ void AttentionBar::ShowMessage(const AttentionMessage& msg) { if ( msg.IsBlacklisted() ) return; wxString iconName; switch ( msg.m_kind ) { case AttentionMessage::Info: iconName = wxART_INFORMATION; break; case AttentionMessage::Warning: iconName = wxART_WARNING; break; case AttentionMessage::Error: iconName = wxART_ERROR; break; } m_icon->SetBitmap(wxArtProvider::GetBitmap(iconName, wxART_MENU, wxSize(16, 16))); m_label->SetLabelText(msg.m_text); m_buttons->Clear(true/*delete_windows*/); m_actions.clear(); for ( AttentionMessage::Actions::const_iterator i = msg.m_actions.begin(); i != msg.m_actions.end(); ++i ) { wxButton *b = new wxButton(this, wxID_ANY, i->first); #ifdef __WXMAC__ MakeButtonRounded(b->GetHandle()); #endif m_buttons->Add(b, wxSizerFlags().Center().Border(wxRIGHT, BUTTONS_SPACE)); m_actions[b] = i->second; } // we need to size the control correctly _and_ lay out the controls if this // is the first time it's being shown, otherwise we can get garbled look: SetSize(GetParent()->GetClientSize().x, GetBestSize().y); Layout(); Show(); GetParent()->Layout(); } void AttentionBar::HideMessage() { Hide(); GetParent()->Layout(); } void AttentionBar::OnClose(wxCommandEvent& WXUNUSED(event)) { HideMessage(); } void AttentionBar::OnAction(wxCommandEvent& event) { ActionsMap::const_iterator i = m_actions.find(event.GetEventObject()); if ( i == m_actions.end() ) { event.Skip(); return; } HideMessage(); i->second(); } /* static */ void AttentionMessage::AddToBlacklist(const wxString& id) { wxConfig::Get()->Write ( wxString::Format("/messages/dont_show/%s", id.c_str()), (long)true ); } /* static */ bool AttentionMessage::IsBlacklisted(const wxString& id) { return wxConfig::Get()->ReadBool ( wxString::Format("/messages/dont_show/%s", id.c_str()), false ); } void AttentionMessage::AddDontShowAgain() { AddAction(_("Don't show again"), std::bind(&AttentionMessage::AddToBlacklist, m_id)); } <|endoftext|>
<commit_before>#include "StructuredDomain.h" #include <cassert> using namespace std; Skeleton::Skeleton(Domain domain): _norient(numOrientations(domain)) { assert(_norient > 0); _orientations = new DPAG[_norient]; _top_orders = new (vector<int>)[_orient]; } Skeleton::~Skeleton() { delete[] _orientations; delete[] _top_orders; } <commit_msg>Initial support for factory method.<commit_after>#include "Instance.h" #include <cassert> using namespace std; // factory method Instance* Instance::factory(Enum d, Transduction t, std::istream& is) throw(BadInstanceCreation) { if(type == SEQUENCE) { return new Sequence(d, t, is); } } Instance::Skeleton::Skeleton(Domain domain): _i(-1), _o(-1), _norient(num_orientations(domain)) { assert(_norient > 0); _orientations = new (DPAG*)[_norient]; _top_orders = new (vector<int>)[_norient]; } Instance::Skeleton::~Skeleton() { for(int i=0; i<_norient; ++i) delete _orientations[i]; delete[] _orientations; delete[] _top_orders; } <|endoftext|>
<commit_before>/* * author: Max Kellermann <mk@cm4all.com> */ #include "Client.hxx" #include "event/Duration.hxx" #include "net/SocketAddress.hxx" #include "net/Interface.hxx" #include <daemon/log.h> #include <avahi-common/error.h> #include <avahi-common/malloc.h> #include <avahi-common/alternative.h> MyAvahiClient::MyAvahiClient(EventLoop &event_loop, const char *_name) :name(_name), reconnect_timer(event_loop, BIND_THIS_METHOD(OnReconnectTimer)), poll(event_loop) { } MyAvahiClient::~MyAvahiClient() { Close(); } void MyAvahiClient::AddService(AvahiIfIndex interface, AvahiProtocol protocol, const char *type, uint16_t port) { /* cannot register any more services after initial connect */ assert(client == nullptr); if (services.empty()) /* initiate the connection */ reconnect_timer.Add(EventDuration<0, 10000>::value); services.emplace_front(interface, protocol, type, port); } void MyAvahiClient::AddService(const char *type, SocketAddress address) { unsigned port = address.GetPort(); if (port == 0) return; unsigned i = FindNetworkInterface(address); AvahiIfIndex ii = i > 0 ? AvahiIfIndex(i) : AVAHI_IF_UNSPEC; AvahiProtocol protocol = AVAHI_PROTO_UNSPEC; switch (address.GetFamily()) { case AF_INET: protocol = AVAHI_PROTO_INET; break; case AF_INET6: protocol = AVAHI_PROTO_INET6; break; } AddService(ii, protocol, type, port); } void MyAvahiClient::Close() { if (group != nullptr) { avahi_entry_group_free(group); group = nullptr; } if (client != nullptr) avahi_client_free(client); } void MyAvahiClient::GroupCallback(AvahiEntryGroup *g, AvahiEntryGroupState state) { switch (state) { case AVAHI_ENTRY_GROUP_ESTABLISHED: break; case AVAHI_ENTRY_GROUP_COLLISION: /* pick a new name */ { char *new_name = avahi_alternative_service_name(name.c_str()); name = new_name; avahi_free(new_name); } /* And recreate the services */ RegisterServices(avahi_entry_group_get_client(g)); break; case AVAHI_ENTRY_GROUP_FAILURE: daemon_log(3, "Avahi service group failure: %s", avahi_strerror(avahi_client_errno(avahi_entry_group_get_client(g)))); break; case AVAHI_ENTRY_GROUP_UNCOMMITED: case AVAHI_ENTRY_GROUP_REGISTERING: break; } } void MyAvahiClient::GroupCallback(AvahiEntryGroup *g, AvahiEntryGroupState state, void *userdata) { auto &client = *(MyAvahiClient *)userdata; client.GroupCallback(g, state); } void MyAvahiClient::RegisterServices(AvahiClient *c) { if (group == nullptr) { group = avahi_entry_group_new(c, GroupCallback, this); if (group == nullptr) { daemon_log(3, "Failed to create Avahi service group: %s", avahi_strerror(avahi_client_errno(c))); return; } } for (const auto &i : services) { int error = avahi_entry_group_add_service(group, AVAHI_IF_UNSPEC, AVAHI_PROTO_UNSPEC, AvahiPublishFlags(0), name.c_str(), i.type.c_str(), nullptr, nullptr, i.port, nullptr); if (error < 0) { daemon_log(3, "Failed to add Avahi service %s: %s", i.type.c_str(), avahi_strerror(error)); return; } } int result = avahi_entry_group_commit(group); if (result < 0) { daemon_log(3, "Failed to commit Avahi service group: %s", avahi_strerror(result)); return; } } void MyAvahiClient::ClientCallback(AvahiClient *c, AvahiClientState state) { int error; switch (state) { case AVAHI_CLIENT_S_RUNNING: if (group == nullptr) RegisterServices(c); break; case AVAHI_CLIENT_FAILURE: error = avahi_client_errno(c); if (error == AVAHI_ERR_DISCONNECTED) { Close(); reconnect_timer.Add(EventDuration<10, 0>::value); } else { daemon_log(3, "Avahi client failed: %s", avahi_strerror(error)); reconnect_timer.Add(EventDuration<60, 0>::value); } break; case AVAHI_CLIENT_S_COLLISION: case AVAHI_CLIENT_S_REGISTERING: if (group != nullptr) avahi_entry_group_reset(group); break; case AVAHI_CLIENT_CONNECTING: break; } } void MyAvahiClient::ClientCallback(AvahiClient *c, AvahiClientState state, void *userdata) { auto &client = *(MyAvahiClient *)userdata; client.ClientCallback(c, state); } void MyAvahiClient::OnReconnectTimer() { int error; client = avahi_client_new(&poll, AVAHI_CLIENT_NO_FAIL, ClientCallback, this, &error); if (client == nullptr) { daemon_log(3, "Failed to create avahi client: %s", avahi_strerror(error)); reconnect_timer.Add(EventDuration<60, 0>::value); return; } } <commit_msg>avahi/Client: add missing newlines to log messages<commit_after>/* * author: Max Kellermann <mk@cm4all.com> */ #include "Client.hxx" #include "event/Duration.hxx" #include "net/SocketAddress.hxx" #include "net/Interface.hxx" #include <daemon/log.h> #include <avahi-common/error.h> #include <avahi-common/malloc.h> #include <avahi-common/alternative.h> MyAvahiClient::MyAvahiClient(EventLoop &event_loop, const char *_name) :name(_name), reconnect_timer(event_loop, BIND_THIS_METHOD(OnReconnectTimer)), poll(event_loop) { } MyAvahiClient::~MyAvahiClient() { Close(); } void MyAvahiClient::AddService(AvahiIfIndex interface, AvahiProtocol protocol, const char *type, uint16_t port) { /* cannot register any more services after initial connect */ assert(client == nullptr); if (services.empty()) /* initiate the connection */ reconnect_timer.Add(EventDuration<0, 10000>::value); services.emplace_front(interface, protocol, type, port); } void MyAvahiClient::AddService(const char *type, SocketAddress address) { unsigned port = address.GetPort(); if (port == 0) return; unsigned i = FindNetworkInterface(address); AvahiIfIndex ii = i > 0 ? AvahiIfIndex(i) : AVAHI_IF_UNSPEC; AvahiProtocol protocol = AVAHI_PROTO_UNSPEC; switch (address.GetFamily()) { case AF_INET: protocol = AVAHI_PROTO_INET; break; case AF_INET6: protocol = AVAHI_PROTO_INET6; break; } AddService(ii, protocol, type, port); } void MyAvahiClient::Close() { if (group != nullptr) { avahi_entry_group_free(group); group = nullptr; } if (client != nullptr) avahi_client_free(client); } void MyAvahiClient::GroupCallback(AvahiEntryGroup *g, AvahiEntryGroupState state) { switch (state) { case AVAHI_ENTRY_GROUP_ESTABLISHED: break; case AVAHI_ENTRY_GROUP_COLLISION: /* pick a new name */ { char *new_name = avahi_alternative_service_name(name.c_str()); name = new_name; avahi_free(new_name); } /* And recreate the services */ RegisterServices(avahi_entry_group_get_client(g)); break; case AVAHI_ENTRY_GROUP_FAILURE: daemon_log(3, "Avahi service group failure: %s\n", avahi_strerror(avahi_client_errno(avahi_entry_group_get_client(g)))); break; case AVAHI_ENTRY_GROUP_UNCOMMITED: case AVAHI_ENTRY_GROUP_REGISTERING: break; } } void MyAvahiClient::GroupCallback(AvahiEntryGroup *g, AvahiEntryGroupState state, void *userdata) { auto &client = *(MyAvahiClient *)userdata; client.GroupCallback(g, state); } void MyAvahiClient::RegisterServices(AvahiClient *c) { if (group == nullptr) { group = avahi_entry_group_new(c, GroupCallback, this); if (group == nullptr) { daemon_log(3, "Failed to create Avahi service group: %s\n", avahi_strerror(avahi_client_errno(c))); return; } } for (const auto &i : services) { int error = avahi_entry_group_add_service(group, AVAHI_IF_UNSPEC, AVAHI_PROTO_UNSPEC, AvahiPublishFlags(0), name.c_str(), i.type.c_str(), nullptr, nullptr, i.port, nullptr); if (error < 0) { daemon_log(3, "Failed to add Avahi service %s: %s\n", i.type.c_str(), avahi_strerror(error)); return; } } int result = avahi_entry_group_commit(group); if (result < 0) { daemon_log(3, "Failed to commit Avahi service group: %s\n", avahi_strerror(result)); return; } } void MyAvahiClient::ClientCallback(AvahiClient *c, AvahiClientState state) { int error; switch (state) { case AVAHI_CLIENT_S_RUNNING: if (group == nullptr) RegisterServices(c); break; case AVAHI_CLIENT_FAILURE: error = avahi_client_errno(c); if (error == AVAHI_ERR_DISCONNECTED) { Close(); reconnect_timer.Add(EventDuration<10, 0>::value); } else { daemon_log(3, "Avahi client failed: %s\n", avahi_strerror(error)); reconnect_timer.Add(EventDuration<60, 0>::value); } break; case AVAHI_CLIENT_S_COLLISION: case AVAHI_CLIENT_S_REGISTERING: if (group != nullptr) avahi_entry_group_reset(group); break; case AVAHI_CLIENT_CONNECTING: break; } } void MyAvahiClient::ClientCallback(AvahiClient *c, AvahiClientState state, void *userdata) { auto &client = *(MyAvahiClient *)userdata; client.ClientCallback(c, state); } void MyAvahiClient::OnReconnectTimer() { int error; client = avahi_client_new(&poll, AVAHI_CLIENT_NO_FAIL, ClientCallback, this, &error); if (client == nullptr) { daemon_log(3, "Failed to create avahi client: %s\n", avahi_strerror(error)); reconnect_timer.Add(EventDuration<60, 0>::value); return; } } <|endoftext|>
<commit_before>#include "cosmology.hpp" #include <math.h> #include <gsl/gsl_integration.h> #include <gsl/gsl_odeiv2.h> #include <gsl/gsl_errno.h> #include "physconst.h" #include <valarray> #include <cassert> /**This file contains code to compute the Hubble function at arbitrary redshift. Most of the code integrates * Omega_Nu for massive neutrinos, taken from the Gadget-3 patches..**/ /* We need to include radiation to get the early-time growth factor right, * which comes into the Zel'dovich approximation.*/ /* Omega_g = 4 \sigma_B T_{CMB}^4 8 \pi G / (3 c^3 H^2)*/ #define OMEGAG (4*STEFAN_BOLTZMANN*8*M_PI*GRAVITY/(3*LIGHTCGS*LIGHTCGS*LIGHTCGS*HUBBLE*HUBBLE*HubbleParam*HubbleParam)*pow(T_CMB0,4)) //Neutrino mass splittings #define M21 7.53e-5 //Particle data group 2016: +- 0.18e-5 eV2 #define M32n 2.44e-3 //Particle data group: +- 0.06e-3 eV2 #define M32i 2.51e-3 //Particle data group: +- 0.06e-3 eV2 //(this is different for normal and inverted hierarchy) /* Compute the three neutrino masses, * including the neutrino mass splittings * from oscillation experiments. * mnu is the total neutrino mass in eV. * Hierarchy is -1 for inverted (two heavy), * 1 for normal (two light) and 0 for degenerate.*/ std::valarray<double> NuPartMasses(double mnu, int Hierarchy) { std::valarray<double> numasses(mnu/3.,3); //Hierarchy == 0 is 3 degenerate neutrinos if(Hierarchy == 0) return numasses; const double M32 = Hierarchy > 0 ? M32n : -M32i; //If the total mass is below that allowed by the hierarchy, //assume one active neutrino. if(mnu < ((Hierarchy > 0) ? sqrt(M32n) + sqrt(M21) : 2*sqrt(M32i) -sqrt(M21))) { return std::valarray<double> ({mnu, 0, 0}); } //DD is the summed masses of the two closest neutrinos double DD1 = 4 * mnu/3. - 2/3.*sqrt(mnu*mnu + 3*M32 + 1.5*M21); //Last term was neglected initially. This should be very well converged. double DD = 4 * mnu/3. - 2/3.*sqrt(mnu*mnu + 3*M32 + 1.5*M21 + 0.75*M21*M21/DD1/DD1); assert(std::isfinite(DD)); assert(fabs(DD1/DD -1) < 1e-2); numasses[0] = mnu - DD; numasses[1] = 0.5*(DD + M21/DD); numasses[2] = 0.5*(DD - M21/DD); return numasses; } //Hubble H(z) / H0 in units of 1/T. double Cosmology::Hubble(double a) { //Begin with curvature and lambda. double hubble_a = OmegaMatter(a); //curvature and lambda hubble_a += (1 - Omega - OmegaLambda) / (a * a) + OmegaLambda; //Add the radiation, including neutrinos hubble_a += OmegaR(a); return HUBBLE * sqrt(hubble_a); } /* Return the total matter density in neutrinos. * rho_nu and friends are not externally callable*/ double Cosmology::OmegaNu(double a) { double rhonu = 0; auto numasses = NuPartMasses(MNu, Hierarchy); for(int i=0; i<3;i++){ rhonu += OmegaNu_single(a,numasses[i]); } return rhonu; } double Cosmology::OmegaMatter(double a) { double OmegaM = Omega; /* Do not include neutrinos * in the source term of the growth function * in growth_ode, unless they are already not * free-streaming. This is not right if * our box overlaps with their free-streaming scale. * In that case the growth factor will be scale-dependent. * In practice the box will either be larger * than the horizon, which is not accurate anyway, or the neutrino * mass will be larger than current constraints allow, * so we don't worry about it too much.*/ if(MNu > 0) { OmegaM -= OmegaNu(1); if (!NeutrinosFreeStreaming) OmegaM += OmegaNu(a); } return OmegaM/(a * a * a); } double Cosmology::OmegaR(double a) { if(NoRadiation) return 0; double omr = OMEGAG/(a*a*a*a); //Neutrinos are included in the radiation, //unless they are massive and not free-streaming if(MNu == 0 || NeutrinosFreeStreaming) omr += OmegaNu(a); return omr; } bool Cosmology::SetNeutrinoFreeStream(double box, double v_th, double a) { /*Neutrino free-streaming length from Lesgourgues & Pastor*/ double nufs = 2 * M_PI * sqrt(2/3.) * v_th / Hubble(a)/a; NeutrinosFreeStreaming = nufs > box/4.; if(!NeutrinosFreeStreaming) fprintf(stderr,"WARNING: Neutrino free-streaming at %g boxes. May be inaccurate as scale-dependent growth is not modelled.\n",nufs/box); return NeutrinosFreeStreaming; } /*Note q carries units of eV/c. kT/c has units of eV/c. * M_nu has units of eV Here c=1. */ double rho_nu_int(double q, void * params) { double amnu = *((double *)params); double epsilon = sqrt(q*q+amnu*amnu); double f0 = 1./(exp(q/(BOLEVK*TNU))+1); return q*q*epsilon*f0; } /* Tables for rho_nu: stores precomputed values between * simulation start and a M_nu = 20 kT_nu*/ #define GSL_VAL 200 /*Get the conversion factor to go from (eV/c)^4 to g/cm^3 * for a **single** neutrino species. */ double get_rho_nu_conversion() { /*q has units of eV/c, so rho_nu now has units of (eV/c)^4*/ double convert=4*M_PI*2; /* The factor of two is for antineutrinos*/ /*rho_nu_val now has units of eV^4*/ /*To get units of density, divide by (c*hbar)**3 in eV s and cm/s */ const double chbar=1./(2*M_PI*LIGHTCGS*HBAR); convert*=(chbar*chbar*chbar); /*Now has units of (eV)/(cm^3)*/ /* 1 eV = 1.60217646 × 10-12 g cm^2 s^(-2) */ /* So 1eV/c^2 = 1.7826909604927859e-33 g*/ /*So this is rho_nu_val in g /cm^3*/ convert*=(1.60217646e-12/LIGHTCGS/LIGHTCGS); return convert; } /*Integrated value of rho_nu for regions between relativistic and non-relativistic*/ double integrate_rho_nu(double a,double mnu) { double abserr; double amnu = a*mnu; gsl_function F; gsl_integration_workspace * w = gsl_integration_workspace_alloc (GSL_VAL); F.function = &rho_nu_int; F.params = &amnu; double rhonu; gsl_integration_qag (&F, 0, 500*BOLEVK*TNU,0 , 1e-9,GSL_VAL,6,w,&rhonu, &abserr); rhonu=rhonu/pow(a,4)*get_rho_nu_conversion(); gsl_integration_workspace_free (w); return rhonu; } /* Value of kT/aM_nu on which to switch from the * analytic expansion to the numerical integration*/ #define NU_SW 50 //1.878 82(24) x 10-29 h02 g/cm3 = 1.053 94(13) x 104 h02 eV/cm3 /*Finds the physical density in neutrinos for a single neutrino species*/ double rho_nu(double a,double mnu) { double rho_nu_val; double amnu=a*mnu; const double kT=BOLEVK*TNU; const double kTamnu2=(kT*kT/amnu/amnu); /*Do it analytically if we are in a regime where we can * The next term is 141682 (kT/amnu)^8. * At kT/amnu = 8, higher terms are larger and the series stops converging. * Don't go lower than 50 here. */ if(NU_SW*NU_SW*kTamnu2 < 1){ /*Heavily non-relativistic*/ /*The constants are Riemann zetas: 3,5,7 respectively*/ rho_nu_val=mnu*pow(kT/a,3)*(1.5*1.202056903159594+kTamnu2*45./4.*1.0369277551433704+2835./32.*kTamnu2*kTamnu2*1.0083492773819229+80325/32.*kTamnu2*kTamnu2*kTamnu2*1.0020083928260826)*get_rho_nu_conversion(); } else if(amnu < 1e-6*kT){ /*Heavily relativistic: we could be more accurate here, * but in practice this will only be called for massless neutrinos, so don't bother.*/ rho_nu_val=7*pow(M_PI*kT/a,4)/120.*get_rho_nu_conversion(); } else{ rho_nu_val = integrate_rho_nu(a,mnu); } return rho_nu_val; } /* Return the matter density in a single neutrino species. * Not externally callable*/ double Cosmology::OmegaNu_single(double a,double mnu) { double rhonu; rhonu=rho_nu(a,mnu); rhonu /= (3* HUBBLE* HUBBLE / (8 * M_PI * GRAVITY)); rhonu /= HubbleParam*HubbleParam; return rhonu; } double Cosmology::GrowthFactor(double astart, double aend) { return growth(aend, NULL) / growth(astart, NULL); } int growth_ode(double a, const double yy[], double dyda[], void * param) { Cosmology * d_this = (Cosmology *) param; const double hub = d_this->Hubble(a)/HUBBLE; dyda[0] = yy[1]/pow(a,3)/hub; /*We want neutrinos to be non-relativistic, as only this part gravitates*/ dyda[1] = yy[0] * 1.5 * a * d_this->OmegaMatter(a) / hub; return GSL_SUCCESS; } /** The growth function is given as a 2nd order DE in Peacock 1999, Cosmological Physics. * D'' + a'/a D' - 1.5 * (a'/a)^2 D = 0 * 1/a (a D')' - 1.5 (a'/a)^2 D * where ' is d/d tau = a^2 H d/da * Define F = a^3 H dD/da * and we have: dF/da = 1.5 a H D */ double Cosmology::growth(double a, double * dDda) { gsl_odeiv2_system FF; FF.function = &growth_ode; FF.jacobian = NULL; FF.dimension = 2; //Just pass the whole structure as the params pointer, as GSL won't let us make the integrand a member function FF.params = this; gsl_odeiv2_driver * drive = gsl_odeiv2_driver_alloc_standard_new(&FF,gsl_odeiv2_step_rkf45, 1e-5, 1e-8,1e-8,1,1); /* We start early to avoid lambda.*/ double curtime = 1e-5; /* Initial velocity chosen so that D = Omegar + 3/2 Omega_m a, * the solution for a matter/radiation universe.* * Note the normalisation of D is arbitrary * and never seen outside this function.*/ double yinit[2] = {OmegaR(curtime) + 1.5 * OmegaMatter(curtime)*curtime, pow(curtime,3)*Hubble(curtime)/HUBBLE * 1.5 * OmegaMatter(curtime)}; int stat = gsl_odeiv2_driver_apply(drive, &curtime,a, yinit); if (stat != GSL_SUCCESS) { printf("gsl_odeiv in growth: %d. Result at %g is %g %g\n",stat, curtime, yinit[0], yinit[1]); } gsl_odeiv2_driver_free(drive); /*Store derivative of D if needed.*/ if(dDda) { *dDda = yinit[1]/pow(a,3)/(Hubble(a)/HUBBLE); } return yinit[0]; } /* * This is the Zeldovich approximation prefactor, * f1 = d ln D1 / dlna = a / D (dD/da) */ double Cosmology::F_Omega(double a) { double dD1da=0; double D1 = growth(a, &dD1da); return a / D1 * dD1da; } /* The 2LPT prefactor, f2 = d ln D2/dlna. * This is an approximation rather than the exact result, * and not strictly valid for closed universes. * The approximation should be good enough since * the 2lpt term is generally small. */ double Cosmology::F2_Omega(double a) { double omega_a; omega_a = Omega / (Omega + a * (1 - Omega - OmegaLambda) + a * a * a * OmegaLambda); if (1 - Omega - OmegaLambda < 0) return 2 * pow(omega_a, 4./7.); else return 2 * pow(omega_a, 6./11.); } <commit_msg>Check derived neutrino mass is positive<commit_after>#include "cosmology.hpp" #include <math.h> #include <gsl/gsl_integration.h> #include <gsl/gsl_odeiv2.h> #include <gsl/gsl_errno.h> #include "physconst.h" #include <valarray> #include <cassert> /**This file contains code to compute the Hubble function at arbitrary redshift. Most of the code integrates * Omega_Nu for massive neutrinos, taken from the Gadget-3 patches..**/ /* We need to include radiation to get the early-time growth factor right, * which comes into the Zel'dovich approximation.*/ /* Omega_g = 4 \sigma_B T_{CMB}^4 8 \pi G / (3 c^3 H^2)*/ #define OMEGAG (4*STEFAN_BOLTZMANN*8*M_PI*GRAVITY/(3*LIGHTCGS*LIGHTCGS*LIGHTCGS*HUBBLE*HUBBLE*HubbleParam*HubbleParam)*pow(T_CMB0,4)) //Neutrino mass splittings #define M21 7.53e-5 //Particle data group 2016: +- 0.18e-5 eV2 #define M32n 2.44e-3 //Particle data group: +- 0.06e-3 eV2 #define M32i 2.51e-3 //Particle data group: +- 0.06e-3 eV2 //(this is different for normal and inverted hierarchy) /* Compute the three neutrino masses, * including the neutrino mass splittings * from oscillation experiments. * mnu is the total neutrino mass in eV. * Hierarchy is -1 for inverted (two heavy), * 1 for normal (two light) and 0 for degenerate.*/ std::valarray<double> NuPartMasses(double mnu, int Hierarchy) { std::valarray<double> numasses(mnu/3.,3); //Hierarchy == 0 is 3 degenerate neutrinos if(Hierarchy == 0) return numasses; const double M32 = Hierarchy > 0 ? M32n : -M32i; //If the total mass is below that allowed by the hierarchy, //assume one active neutrino. if(mnu < ((Hierarchy > 0) ? sqrt(M32n) + sqrt(M21) : 2*sqrt(M32i) -sqrt(M21))) { return std::valarray<double> ({mnu, 0, 0}); } //DD is the summed masses of the two closest neutrinos double DD1 = 4 * mnu/3. - 2/3.*sqrt(mnu*mnu + 3*M32 + 1.5*M21); //Last term was neglected initially. This should be very well converged. double DD = 4 * mnu/3. - 2/3.*sqrt(mnu*mnu + 3*M32 + 1.5*M21 + 0.75*M21*M21/DD1/DD1); assert(std::isfinite(DD)); assert(fabs(DD1/DD -1) < 2e-2); numasses[0] = mnu - DD; numasses[1] = 0.5*(DD + M21/DD); numasses[2] = 0.5*(DD - M21/DD); assert(numasses[2] > 0); return numasses; } //Hubble H(z) / H0 in units of 1/T. double Cosmology::Hubble(double a) { //Begin with curvature and lambda. double hubble_a = OmegaMatter(a); //curvature and lambda hubble_a += (1 - Omega - OmegaLambda) / (a * a) + OmegaLambda; //Add the radiation, including neutrinos hubble_a += OmegaR(a); return HUBBLE * sqrt(hubble_a); } /* Return the total matter density in neutrinos. * rho_nu and friends are not externally callable*/ double Cosmology::OmegaNu(double a) { double rhonu = 0; auto numasses = NuPartMasses(MNu, Hierarchy); for(int i=0; i<3;i++){ rhonu += OmegaNu_single(a,numasses[i]); } return rhonu; } double Cosmology::OmegaMatter(double a) { double OmegaM = Omega; /* Do not include neutrinos * in the source term of the growth function * in growth_ode, unless they are already not * free-streaming. This is not right if * our box overlaps with their free-streaming scale. * In that case the growth factor will be scale-dependent. * In practice the box will either be larger * than the horizon, which is not accurate anyway, or the neutrino * mass will be larger than current constraints allow, * so we don't worry about it too much.*/ if(MNu > 0) { OmegaM -= OmegaNu(1); if (!NeutrinosFreeStreaming) OmegaM += OmegaNu(a); } return OmegaM/(a * a * a); } double Cosmology::OmegaR(double a) { if(NoRadiation) return 0; double omr = OMEGAG/(a*a*a*a); //Neutrinos are included in the radiation, //unless they are massive and not free-streaming if(MNu == 0 || NeutrinosFreeStreaming) omr += OmegaNu(a); return omr; } bool Cosmology::SetNeutrinoFreeStream(double box, double v_th, double a) { /*Neutrino free-streaming length from Lesgourgues & Pastor*/ double nufs = 2 * M_PI * sqrt(2/3.) * v_th / Hubble(a)/a; NeutrinosFreeStreaming = nufs > box/4.; if(!NeutrinosFreeStreaming) fprintf(stderr,"WARNING: Neutrino free-streaming at %g boxes. May be inaccurate as scale-dependent growth is not modelled.\n",nufs/box); return NeutrinosFreeStreaming; } /*Note q carries units of eV/c. kT/c has units of eV/c. * M_nu has units of eV Here c=1. */ double rho_nu_int(double q, void * params) { double amnu = *((double *)params); double epsilon = sqrt(q*q+amnu*amnu); double f0 = 1./(exp(q/(BOLEVK*TNU))+1); return q*q*epsilon*f0; } /* Tables for rho_nu: stores precomputed values between * simulation start and a M_nu = 20 kT_nu*/ #define GSL_VAL 200 /*Get the conversion factor to go from (eV/c)^4 to g/cm^3 * for a **single** neutrino species. */ double get_rho_nu_conversion() { /*q has units of eV/c, so rho_nu now has units of (eV/c)^4*/ double convert=4*M_PI*2; /* The factor of two is for antineutrinos*/ /*rho_nu_val now has units of eV^4*/ /*To get units of density, divide by (c*hbar)**3 in eV s and cm/s */ const double chbar=1./(2*M_PI*LIGHTCGS*HBAR); convert*=(chbar*chbar*chbar); /*Now has units of (eV)/(cm^3)*/ /* 1 eV = 1.60217646 × 10-12 g cm^2 s^(-2) */ /* So 1eV/c^2 = 1.7826909604927859e-33 g*/ /*So this is rho_nu_val in g /cm^3*/ convert*=(1.60217646e-12/LIGHTCGS/LIGHTCGS); return convert; } /*Integrated value of rho_nu for regions between relativistic and non-relativistic*/ double integrate_rho_nu(double a,double mnu) { double abserr; double amnu = a*mnu; gsl_function F; gsl_integration_workspace * w = gsl_integration_workspace_alloc (GSL_VAL); F.function = &rho_nu_int; F.params = &amnu; double rhonu; gsl_integration_qag (&F, 0, 500*BOLEVK*TNU,0 , 1e-9,GSL_VAL,6,w,&rhonu, &abserr); rhonu=rhonu/pow(a,4)*get_rho_nu_conversion(); gsl_integration_workspace_free (w); return rhonu; } /* Value of kT/aM_nu on which to switch from the * analytic expansion to the numerical integration*/ #define NU_SW 50 //1.878 82(24) x 10-29 h02 g/cm3 = 1.053 94(13) x 104 h02 eV/cm3 /*Finds the physical density in neutrinos for a single neutrino species*/ double rho_nu(double a,double mnu) { double rho_nu_val; double amnu=a*mnu; const double kT=BOLEVK*TNU; const double kTamnu2=(kT*kT/amnu/amnu); /*Do it analytically if we are in a regime where we can * The next term is 141682 (kT/amnu)^8. * At kT/amnu = 8, higher terms are larger and the series stops converging. * Don't go lower than 50 here. */ if(NU_SW*NU_SW*kTamnu2 < 1){ /*Heavily non-relativistic*/ /*The constants are Riemann zetas: 3,5,7 respectively*/ rho_nu_val=mnu*pow(kT/a,3)*(1.5*1.202056903159594+kTamnu2*45./4.*1.0369277551433704+2835./32.*kTamnu2*kTamnu2*1.0083492773819229+80325/32.*kTamnu2*kTamnu2*kTamnu2*1.0020083928260826)*get_rho_nu_conversion(); } else if(amnu < 1e-6*kT){ /*Heavily relativistic: we could be more accurate here, * but in practice this will only be called for massless neutrinos, so don't bother.*/ rho_nu_val=7*pow(M_PI*kT/a,4)/120.*get_rho_nu_conversion(); } else{ rho_nu_val = integrate_rho_nu(a,mnu); } return rho_nu_val; } /* Return the matter density in a single neutrino species. * Not externally callable*/ double Cosmology::OmegaNu_single(double a,double mnu) { double rhonu; rhonu=rho_nu(a,mnu); rhonu /= (3* HUBBLE* HUBBLE / (8 * M_PI * GRAVITY)); rhonu /= HubbleParam*HubbleParam; return rhonu; } double Cosmology::GrowthFactor(double astart, double aend) { return growth(aend, NULL) / growth(astart, NULL); } int growth_ode(double a, const double yy[], double dyda[], void * param) { Cosmology * d_this = (Cosmology *) param; const double hub = d_this->Hubble(a)/HUBBLE; dyda[0] = yy[1]/pow(a,3)/hub; /*We want neutrinos to be non-relativistic, as only this part gravitates*/ dyda[1] = yy[0] * 1.5 * a * d_this->OmegaMatter(a) / hub; return GSL_SUCCESS; } /** The growth function is given as a 2nd order DE in Peacock 1999, Cosmological Physics. * D'' + a'/a D' - 1.5 * (a'/a)^2 D = 0 * 1/a (a D')' - 1.5 (a'/a)^2 D * where ' is d/d tau = a^2 H d/da * Define F = a^3 H dD/da * and we have: dF/da = 1.5 a H D */ double Cosmology::growth(double a, double * dDda) { gsl_odeiv2_system FF; FF.function = &growth_ode; FF.jacobian = NULL; FF.dimension = 2; //Just pass the whole structure as the params pointer, as GSL won't let us make the integrand a member function FF.params = this; gsl_odeiv2_driver * drive = gsl_odeiv2_driver_alloc_standard_new(&FF,gsl_odeiv2_step_rkf45, 1e-5, 1e-8,1e-8,1,1); /* We start early to avoid lambda.*/ double curtime = 1e-5; /* Initial velocity chosen so that D = Omegar + 3/2 Omega_m a, * the solution for a matter/radiation universe.* * Note the normalisation of D is arbitrary * and never seen outside this function.*/ double yinit[2] = {OmegaR(curtime) + 1.5 * OmegaMatter(curtime)*curtime, pow(curtime,3)*Hubble(curtime)/HUBBLE * 1.5 * OmegaMatter(curtime)}; int stat = gsl_odeiv2_driver_apply(drive, &curtime,a, yinit); if (stat != GSL_SUCCESS) { printf("gsl_odeiv in growth: %d. Result at %g is %g %g\n",stat, curtime, yinit[0], yinit[1]); } gsl_odeiv2_driver_free(drive); /*Store derivative of D if needed.*/ if(dDda) { *dDda = yinit[1]/pow(a,3)/(Hubble(a)/HUBBLE); } return yinit[0]; } /* * This is the Zeldovich approximation prefactor, * f1 = d ln D1 / dlna = a / D (dD/da) */ double Cosmology::F_Omega(double a) { double dD1da=0; double D1 = growth(a, &dD1da); return a / D1 * dD1da; } /* The 2LPT prefactor, f2 = d ln D2/dlna. * This is an approximation rather than the exact result, * and not strictly valid for closed universes. * The approximation should be good enough since * the 2lpt term is generally small. */ double Cosmology::F2_Omega(double a) { double omega_a; omega_a = Omega / (Omega + a * (1 - Omega - OmegaLambda) + a * a * a * OmegaLambda); if (1 - Omega - OmegaLambda < 0) return 2 * pow(omega_a, 4./7.); else return 2 * pow(omega_a, 6./11.); } <|endoftext|>
<commit_before>/* * Class to make list of available lessons. * source available at (Github repo - MIT licence): * http://dstjrd.ir/s/cppx * https://github.com/mohsend/cpp-examples */ // این کلاس فقط برای این ساخته شده که لیستی از دروس ارایه شده را در اختیار کد اصلی بگذارد // در یک مثال واقعی این اطلاعات در دیتابیس ذخیره میشوند و از آنجا لود میشوند. نه از یک فایل هدر #ifndef LIST_OF_LESSONS_HPP #define LIST_OF_LESSONS_HPP 1 #include <string> #include "Clesson.hpp" using namespace std; class listOfLessons { private: // یک آرایه از کلاس درس برای ذخیره واحد های ارایه شده Clesson lessons[14]; public: listOfLessons(); Clesson getLessonByCode(unsigned int); void listAll(); }; // مقدار دهی به اجزای آرایه listOfLessons::listOfLessons() { int index = 0; lessons[index++].setDetails("Persian literature", "Daemi", 2, 0, true); lessons[index++].setDetails("C++ fundamentals", "Pur ganji", 4, 0, true); lessons[index++].setDetails("maths 1", "Reza", 3, 0, true); lessons[index++].setDetails("maths 1", "Zia manesh", 3, 0, true); lessons[index++].setDetails("maths 2", "Reza", 3, 0, true); lessons[index++].setDetails("maths 2", "Zia manesh", 3, 0, true); lessons[index++].setDetails("physics 1", "Ghafari", 3, 0, true); lessons[index++].setDetails("physics 2", "Ghafari", 3, 0, true); lessons[index++].setDetails("phy lab 1", "", 1, 0, false); lessons[index++].setDetails("phy lab 2", "Salehi", 1, 0, false); lessons[index++].setDetails("history", "", 2, 0, true); lessons[index++].setDetails("object oriented programming", "Farhadi", 3, 0, true); } // لیست کردن تمام درس های ارایه شده. void listOfLessons::listAll() { for (unsigned int i = 0; i < 10; i++) { string theory = (lessons[i].getTheory()) ? "Theory" : "Applied"; cout << i + 1 << ") " << lessons[i].getName() << " by Prof. " << lessons[i].getLecturer() << " (" << lessons[i].getUnits() << ' ' << theory << " units)" << endl; } } // متد ای برای گرفتن درس ارایه شده به صورت یک نمونه از کلاس درس با استفاده از کد درس Clesson listOfLessons::getLessonByCode(unsigned int code) { return lessons[(code - 1)]; } #endif <commit_msg>added a variable to keep the size of array (unsigned int index)<commit_after>/* * Class to make list of available lessons. * source available at (Github repo - MIT licence): * http://dstjrd.ir/s/cppx * https://github.com/mohsend/cpp-examples */ // این کلاس فقط برای این ساخته شده که لیستی از دروس ارایه شده را در اختیار کد اصلی بگذارد // در یک مثال واقعی این اطلاعات در دیتابیس ذخیره میشوند و از آنجا لود میشوند. نه از یک فایل هدر #ifndef LIST_OF_LESSONS_HPP #define LIST_OF_LESSONS_HPP 1 #include <string> #include "Clesson.hpp" using namespace std; class listOfLessons { private: // یک آرایه از کلاس درس برای ذخیره واحد های ارایه شده Clesson lessons[14]; unsigned int index; public: listOfLessons(); Clesson getLessonByCode(unsigned int); void listAll(); }; // مقدار دهی به اجزای آرایه listOfLessons::listOfLessons() { index = 0; lessons[index++].setDetails("Persian literature", "Daemi", 2, 0, true); lessons[index++].setDetails("C++ fundamentals", "Pur ganji", 4, 0, true); lessons[index++].setDetails("maths 1", "Reza", 3, 0, true); lessons[index++].setDetails("maths 1", "Zia manesh", 3, 0, true); lessons[index++].setDetails("maths 2", "Reza", 3, 0, true); lessons[index++].setDetails("maths 2", "Zia manesh", 3, 0, true); lessons[index++].setDetails("physics 1", "Ghafari", 3, 0, true); lessons[index++].setDetails("physics 2", "Ghafari", 3, 0, true); lessons[index++].setDetails("phy lab 1", "", 1, 0, false); lessons[index++].setDetails("phy lab 2", "Salehi", 1, 0, false); lessons[index++].setDetails("history", "", 2, 0, true); lessons[index++].setDetails("object oriented programming", "Farhadi", 3, 0, true); } // لیست کردن تمام درس های ارایه شده. void listOfLessons::listAll() { for (unsigned int i = 0; i < index; i++) { string theory = (lessons[i].getTheory()) ? "Theory" : "Applied"; cout << i + 1 << ") " << lessons[i].getName() << " by Prof. " << lessons[i].getLecturer() << " (" << lessons[i].getUnits() << ' ' << theory << " units)" << endl; } } // متد ای برای گرفتن درس ارایه شده به صورت یک نمونه از کلاس درس با استفاده از کد درس Clesson listOfLessons::getLessonByCode(unsigned int code) { return lessons[(code - 1)]; } #endif <|endoftext|>
<commit_before>/*============================================================================= This file is part of FLINT. FLINT is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. FLINT is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with FLINT; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA =============================================================================*/ /****************************************************************************** Copyright (C) 2013 Tom Bachmann ******************************************************************************/ #include<sstream> #include "flintxx/expression.h" #include "flintxx/tuple.h" #include "flintxx/test/helpers.h" #include "flintxx/test/myint.h" using namespace flint; using namespace mp; using namespace traits; void test_initialization() { myint a; tassert(a._data().payload == -1 && a._data().extra == 42); a._data().payload = 17; myint b = a; tassert(b._data().payload == 17); myint c(8); tassert(c._data().payload == 8 && c._data().extra == 2); myint d('a'); tassert(d._data().payload == 'a' && d._data().extra == 3); myint e(c + c); tassert(e._data().payload == 16); } void test_destruction() { bool destroyed = false; { myint a; a._data().destroyed = &destroyed; } tassert(destroyed); } void test_printing() { std::ostringstream o; myint a(4); o << a; tassert(o.str() == "4"); } void test_assignment() { myint a; myint b(43); a = b; tassert(a._data().payload == 43); tassert(a._data().extra == 4); a = 44l; tassert(a._data().payload == 44 && a._data().extra == 5); mylong c(0); c = a + b; tassert(c == 87l); } void test_swap() { myint a(2), b(3); swap(a, b); tassert(a == 3 && b == 2 && a._data().extra == 1234); } void test_traits() { typedef myint immediate_expression; typedef int immediate_nonexpression; typedef my_expression< operations::plus, make_tuple<const myint&, const myint&>::type > lazy_expression; tassert(is_expression<immediate_expression>::val == true); tassert(is_expression<immediate_nonexpression>::val == false); tassert(is_expression<lazy_expression>::val == true); tassert(is_immediate_expr<immediate_expression>::val == true); tassert(is_immediate_expr<immediate_nonexpression>::val == false); tassert(is_immediate_expr<lazy_expression>::val == false); tassert(is_immediate<immediate_expression>::val == true); tassert(is_immediate<immediate_nonexpression>::val == true); tassert(is_immediate<lazy_expression>::val == false); tassert(is_lazy_expr<immediate_expression>::val == false); tassert(is_lazy_expr<immediate_nonexpression>::val == false); tassert(is_lazy_expr<lazy_expression>::val == true); //tassert(is_lazy_expr<lazy_expression&>::val == false); tassert(is_lazy_expr<const immediate_expression&>::val == false); } void test_equals() { myint a(3); myint b(4); myint c(3); tassert(a != b); tassert(a == c); tassert(a == 3); tassert(3 == a); tassert(a != 4); tassert(4 != a); tassert((a + b) == (a + 4)); } void test_arithmetic() { myint a(3); myint b(4); myint c(7); myint d(1); myint e(2); tassert((a + b).evaluate() == 7); tassert(a + b == c); tassert(a + b == 7); tassert(a - b == -1); tassert(a * b == 12); tassert(c / e == 3); tassert(c % e == 1); tassert(-a == -3); // Test arithmetic with immediates tassert(a + 4 == 7); tassert(4 + a == 7); tassert(a + 4l == 7); tassert(4u + a == 7); // Test composite arithmetic tassert((a + 1) + (b + 2) == 10); tassert((a + d) + (b + 2) == 10); tassert((a + d) + (b + e) == 10); tassert((3 + d) + (b + e) == 10); tassert((3 + d) + (4 + e) == 10); tassert(a + (b + c) == 14); tassert(3 + (b + c) == 14); tassert(3 + (4 + c) == 14); tassert(3 + (b + 7) == 14); tassert(a + (b + 7) == 14); tassert((b + c) + a == 14); tassert((b + c) + 3 == 14); tassert((4 + c) + 3== 14); tassert((b + 7) + 3== 14); tassert((b + 7) + a== 14); // test combining unary and binary arithmetic tassert(-(-a) == 3); tassert(-(a - b) == b - a); tassert(-((-a) + (-b)) == a + b); // Test mixed arithmetic mylong al(3l); mylong bl(4l); mylong cl(7l); tassert(al + bl == cl); tassert(al + bl == 7l); tassert(al + b == 7l); tassert(a + bl == 7l); tassert((a + bl) + cl == 14l); tassert((a + b) + cl == 14l); tassert((al + b) + c == 14l); tassert(cl + (a + bl) == 14l); tassert(cl + (a + b) == 14l); tassert(c + (al + b) == 14l); tassert((a + bl) + (cl + d) == 15l); tassert((a + bl) + (c + d) == 15l); tassert((a << 2) == 12); tassert(((a << 2) >> 2) == a); } void test_conversion() { myint a(4); mylong b(4l); tassert(typed_equals(a.to<int>(), 4)); tassert(typed_equals(a.to<mylong>(), b)); tassert(typed_equals((a + a).to<int>(), 8)); } void test_assignment_arith() { myint a(1); myint b(2); a += b; tassert(a == 3 && b == 2); a += a*b; tassert(a == 9); a += 1; tassert(a == 10); } template<class T, class Expr> bool is_subexpr(const Expr& e) { return tools::has_subexpr<tools::equal_types_pred<T>, Expr>::val; } void test_tools() { typedef tools::equal_types_pred<myint> intpred; myint a(1); mylong b(2l); tassert(tools::find_subexpr<intpred>(a) == 1); tassert(tools::find_subexpr<intpred>(a + b) == 1); tassert(tools::find_subexpr_T<mylong>(a + b) == 2l); tassert(tools::find_subexpr<intpred>(b + (a + 2) + b) == 1); tassert(is_subexpr<myint>(a+b)); tassert(!is_subexpr<mylong>(a+a)); } void test_temporaries() { myint a(1); #define T2 ((a + a) + (a + a)) #define T3 (T2 + T2) tassert(count_temporaries(T2) == 2); tassert(count_temporaries(T3) == 3); tassert(count_temporaries(T3 + T2) == 3); tassert(count_temporaries(T2 + T3) == 3); } void test_references() { mylong a(4); mylong_ref ar(a); mylong_cref acr(a); tassert(a == ar); tassert(a == acr); tassert(ar == acr); tassert(ar == 4l && acr == 4l); ar = 5l; tassert(a == 5l && acr == 5l && ar == 5l); mylong b(6); ar = b; tassert(a == b); mylong_cref bcr(b); b = 7l; ar = bcr; tassert(a == b); a = 4l; b = 5l; tassert(a + bcr == 9l); tassert(ar + bcr == 9l); a = acr + b; tassert(a == 9l); ar = acr + bcr; tassert(a == 14l); a = 4l; tassert((a + a) + bcr == 13l); tassert((acr + acr) + b == 13l); tassert(((a + bcr) + acr + (ar + bcr)) + ((a + a) + (bcr + bcr)) == 40l); a = ((a + bcr) + acr + (ar + bcr)) + ((a + a) + (bcr + bcr)); tassert(a == 40l); a = 4l; ar = ((a + bcr) + acr + (ar + bcr)) + ((a + a) + (bcr + bcr)); tassert(a == 40l); } struct S { }; S operator+(const S& s, const S&) {return s;} S operator-(const S&s) {return s;} template<class T> S operator*(const S& s, const T&) {return s;} void test_unrelated_overload() { // Test a bug in our operator overloading logic which used to not allow // this to compile. S s; s = s + s; s = -s; s = s * (myint(5) + myint(5)); } void test_multiary() { tassert(fourary_test(1, 2, 3, 4) == myint(1 + 2 + 3 + 4)); tassert(fiveary_test(1, 2, 3, 4, 5u) == 1 + 2 + 3 + 4 + 5); tassert(sixary_test(1, 2, 3, 4, 5, 6) == 1 + 2 + 3 + 4 + 5 + 6); tassert(sevenary_test(1, 2, 3, 4, 5, 6, 7) == 1 + 2 + 3 + 4 + 5 + 6 + 7); } void test_cstyle_io() { #if !defined (__WIN32) && !defined (__CYGWIN__) mylong c(17), d(0); FILE * f = std::fopen("expression_test", "w+"); tassert(f); print(f, c); std::fprintf(f, "\n"); print_pretty(f, c); std::fflush(f); std::fclose(f); f = std::fopen("expression_test", "r"); tassert(read(f, d) > 0); tassert(d == c); d = 0l; std::fscanf(f, "\n"); //tassert(read_pretty(f, d) > 0); //tassert(d == c); fclose(f); tassert(std::remove("expression_test") == 0); #endif } int main() { std::cout << "expression...."; test_traits(); test_initialization(); test_destruction(); test_printing(); test_assignment(); test_swap(); test_equals(); test_arithmetic(); test_conversion(); test_assignment_arith(); test_tools(); test_temporaries(); test_references(); test_multiary(); test_cstyle_io(); test_unrelated_overload(); std::cout << "PASS" << std::endl; // TODO test that certain things *don't* compile? return 0; } <commit_msg>Fixed a 0L.<commit_after>/*============================================================================= This file is part of FLINT. FLINT is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. FLINT is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with FLINT; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA =============================================================================*/ /****************************************************************************** Copyright (C) 2013 Tom Bachmann ******************************************************************************/ #include<sstream> #include "flintxx/expression.h" #include "flintxx/tuple.h" #include "flintxx/test/helpers.h" #include "flintxx/test/myint.h" using namespace flint; using namespace mp; using namespace traits; void test_initialization() { myint a; tassert(a._data().payload == -1 && a._data().extra == 42); a._data().payload = 17; myint b = a; tassert(b._data().payload == 17); myint c(8); tassert(c._data().payload == 8 && c._data().extra == 2); myint d('a'); tassert(d._data().payload == 'a' && d._data().extra == 3); myint e(c + c); tassert(e._data().payload == 16); } void test_destruction() { bool destroyed = false; { myint a; a._data().destroyed = &destroyed; } tassert(destroyed); } void test_printing() { std::ostringstream o; myint a(4); o << a; tassert(o.str() == "4"); } void test_assignment() { myint a; myint b(43); a = b; tassert(a._data().payload == 43); tassert(a._data().extra == 4); a = 44l; tassert(a._data().payload == 44 && a._data().extra == 5); mylong c(0); c = a + b; tassert(c == 87l); } void test_swap() { myint a(2), b(3); swap(a, b); tassert(a == 3 && b == 2 && a._data().extra == 1234); } void test_traits() { typedef myint immediate_expression; typedef int immediate_nonexpression; typedef my_expression< operations::plus, make_tuple<const myint&, const myint&>::type > lazy_expression; tassert(is_expression<immediate_expression>::val == true); tassert(is_expression<immediate_nonexpression>::val == false); tassert(is_expression<lazy_expression>::val == true); tassert(is_immediate_expr<immediate_expression>::val == true); tassert(is_immediate_expr<immediate_nonexpression>::val == false); tassert(is_immediate_expr<lazy_expression>::val == false); tassert(is_immediate<immediate_expression>::val == true); tassert(is_immediate<immediate_nonexpression>::val == true); tassert(is_immediate<lazy_expression>::val == false); tassert(is_lazy_expr<immediate_expression>::val == false); tassert(is_lazy_expr<immediate_nonexpression>::val == false); tassert(is_lazy_expr<lazy_expression>::val == true); //tassert(is_lazy_expr<lazy_expression&>::val == false); tassert(is_lazy_expr<const immediate_expression&>::val == false); } void test_equals() { myint a(3); myint b(4); myint c(3); tassert(a != b); tassert(a == c); tassert(a == 3); tassert(3 == a); tassert(a != 4); tassert(4 != a); tassert((a + b) == (a + 4)); } void test_arithmetic() { myint a(3); myint b(4); myint c(7); myint d(1); myint e(2); tassert((a + b).evaluate() == 7); tassert(a + b == c); tassert(a + b == 7); tassert(a - b == -1); tassert(a * b == 12); tassert(c / e == 3); tassert(c % e == 1); tassert(-a == -3); // Test arithmetic with immediates tassert(a + 4 == 7); tassert(4 + a == 7); tassert(a + 4l == 7); tassert(4u + a == 7); // Test composite arithmetic tassert((a + 1) + (b + 2) == 10); tassert((a + d) + (b + 2) == 10); tassert((a + d) + (b + e) == 10); tassert((3 + d) + (b + e) == 10); tassert((3 + d) + (4 + e) == 10); tassert(a + (b + c) == 14); tassert(3 + (b + c) == 14); tassert(3 + (4 + c) == 14); tassert(3 + (b + 7) == 14); tassert(a + (b + 7) == 14); tassert((b + c) + a == 14); tassert((b + c) + 3 == 14); tassert((4 + c) + 3== 14); tassert((b + 7) + 3== 14); tassert((b + 7) + a== 14); // test combining unary and binary arithmetic tassert(-(-a) == 3); tassert(-(a - b) == b - a); tassert(-((-a) + (-b)) == a + b); // Test mixed arithmetic mylong al(3l); mylong bl(4l); mylong cl(7l); tassert(al + bl == cl); tassert(al + bl == 7l); tassert(al + b == 7l); tassert(a + bl == 7l); tassert((a + bl) + cl == 14l); tassert((a + b) + cl == 14l); tassert((al + b) + c == 14l); tassert(cl + (a + bl) == 14l); tassert(cl + (a + b) == 14l); tassert(c + (al + b) == 14l); tassert((a + bl) + (cl + d) == 15l); tassert((a + bl) + (c + d) == 15l); tassert((a << 2) == 12); tassert(((a << 2) >> 2) == a); } void test_conversion() { myint a(4); mylong b(4l); tassert(typed_equals(a.to<int>(), 4)); tassert(typed_equals(a.to<mylong>(), b)); tassert(typed_equals((a + a).to<int>(), 8)); } void test_assignment_arith() { myint a(1); myint b(2); a += b; tassert(a == 3 && b == 2); a += a*b; tassert(a == 9); a += 1; tassert(a == 10); } template<class T, class Expr> bool is_subexpr(const Expr& e) { return tools::has_subexpr<tools::equal_types_pred<T>, Expr>::val; } void test_tools() { typedef tools::equal_types_pred<myint> intpred; myint a(1); mylong b(2l); tassert(tools::find_subexpr<intpred>(a) == 1); tassert(tools::find_subexpr<intpred>(a + b) == 1); tassert(tools::find_subexpr_T<mylong>(a + b) == 2l); tassert(tools::find_subexpr<intpred>(b + (a + 2) + b) == 1); tassert(is_subexpr<myint>(a+b)); tassert(!is_subexpr<mylong>(a+a)); } void test_temporaries() { myint a(1); #define T2 ((a + a) + (a + a)) #define T3 (T2 + T2) tassert(count_temporaries(T2) == 2); tassert(count_temporaries(T3) == 3); tassert(count_temporaries(T3 + T2) == 3); tassert(count_temporaries(T2 + T3) == 3); } void test_references() { mylong a(4); mylong_ref ar(a); mylong_cref acr(a); tassert(a == ar); tassert(a == acr); tassert(ar == acr); tassert(ar == 4l && acr == 4l); ar = 5l; tassert(a == 5l && acr == 5l && ar == 5l); mylong b(6); ar = b; tassert(a == b); mylong_cref bcr(b); b = 7l; ar = bcr; tassert(a == b); a = 4l; b = 5l; tassert(a + bcr == 9l); tassert(ar + bcr == 9l); a = acr + b; tassert(a == 9l); ar = acr + bcr; tassert(a == 14l); a = 4l; tassert((a + a) + bcr == 13l); tassert((acr + acr) + b == 13l); tassert(((a + bcr) + acr + (ar + bcr)) + ((a + a) + (bcr + bcr)) == 40l); a = ((a + bcr) + acr + (ar + bcr)) + ((a + a) + (bcr + bcr)); tassert(a == 40l); a = 4l; ar = ((a + bcr) + acr + (ar + bcr)) + ((a + a) + (bcr + bcr)); tassert(a == 40l); } struct S { }; S operator+(const S& s, const S&) {return s;} S operator-(const S&s) {return s;} template<class T> S operator*(const S& s, const T&) {return s;} void test_unrelated_overload() { // Test a bug in our operator overloading logic which used to not allow // this to compile. S s; s = s + s; s = -s; s = s * (myint(5) + myint(5)); } void test_multiary() { tassert(fourary_test(1, 2, 3, 4) == myint(1 + 2 + 3 + 4)); tassert(fiveary_test(1, 2, 3, 4, 5u) == 1 + 2 + 3 + 4 + 5); tassert(sixary_test(1, 2, 3, 4, 5, 6) == 1 + 2 + 3 + 4 + 5 + 6); tassert(sevenary_test(1, 2, 3, 4, 5, 6, 7) == 1 + 2 + 3 + 4 + 5 + 6 + 7); } void test_cstyle_io() { #if !defined (__WIN32) && !defined (__CYGWIN__) mylong c(17), d(0); FILE * f = std::fopen("expression_test", "w+"); tassert(f); print(f, c); std::fprintf(f, "\n"); print_pretty(f, c); std::fflush(f); std::fclose(f); f = std::fopen("expression_test", "r"); tassert(read(f, d) > 0); tassert(d == c); d = WORD(0); std::fscanf(f, "\n"); //tassert(read_pretty(f, d) > 0); //tassert(d == c); fclose(f); tassert(std::remove("expression_test") == 0); #endif } int main() { std::cout << "expression...."; test_traits(); test_initialization(); test_destruction(); test_printing(); test_assignment(); test_swap(); test_equals(); test_arithmetic(); test_conversion(); test_assignment_arith(); test_tools(); test_temporaries(); test_references(); test_multiary(); test_cstyle_io(); test_unrelated_overload(); std::cout << "PASS" << std::endl; // TODO test that certain things *don't* compile? return 0; } <|endoftext|>
<commit_before>/* * Copyright (C) 2010 O01eg <o01eg@yandex.ru> * * This file is part of Genetic Function Programming. * * Genetic Function Programming is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Genetic Function Programming is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Genetic Function Programming. If not, see <http://www.gnu.org/licenses/>. */ #include <cstdlib> #include <string> #include <algorithm> #include <locale> #include <sstream> #include <iomanip> #include <algorithm> #include "ioobject.h" using namespace VM; /// \brief convert string to atomic object. /// \param str String representation. /// \param env Environment form creating object. /// \return Atomic object. Object str2atom(const std::string& str, Environment &env); std::ostream& operator<<(std::ostream& ostr, const WeakObject& obj) { std::streamsize width = ostr.width(); ostr.width(0); std::stringstream os; /// \todo Use normal stack. if(! obj.IsNIL()) { //const Environment& env = obj.GetEnv(); switch(obj.GetType()) { case ERROR: os << "ERROR "; break; case INTEGER: os << static_cast<int>(obj.GetValue()) << " "; break; case FUNC: #if 0 os << "#" << obj.GetValue() << " "; #else os << obj.GetEnv().functions[obj.GetValue()].name << " "; #endif break; case ADF: os << "%" << obj.GetValue() << " "; break; case PARAM: os << "$ "; break; case QUOTE: os << "QUOTE "; break; case IF: os << "IF "; break; case EVAL: os << "EVAL "; break; case LIST: { std::stack<bool> arrow_stack; // true - head, false - tail std::stack<WeakObject> stack; arrow_stack.push(true); stack.push(obj); WeakObject object(obj); bool arrow = true; //size_t level = 0; while(! stack.empty()) { object = stack.top(); stack.pop(); arrow = arrow_stack.top(); arrow_stack.pop(); if(arrow) //head { if(object.IsNIL()) { os << "NIL "; } else { if(object.GetType() == LIST) { //os << std::endl; /*for(size_t i = 0; i < level; i ++) { os << " "; }*/ os << "( "; //level ++; stack.push(object.GetTail()); arrow_stack.push(false); stack.push(object.GetHead()); arrow_stack.push(true); } else { os << object; } } } else //tail { if(object.IsNIL()) { os << ") "; //level --; } else { if(object.GetType() == LIST) { stack.push(object.GetTail()); arrow_stack.push(false); stack.push(object.GetHead()); arrow_stack.push(true); } else { os << ". " << object << ") "; //level --; } } } } } break; default: os << "ERROR "; break; } } else { os << "NIL "; } if(width < os.str().size()) { //ostr << "{" << width << "}"; ostr.write(os.str().c_str(), std::min(static_cast<size_t>(width), os.str().size())); } else { ostr << os.str(); } return ostr; } std::istream& operator>>(std::istream& is, Object& obj) { /// \todo Use normal stack. /// \todo Add check for empty stacks. Environment& env = obj.GetEnv(); std::stack<Object> obj_stack; std::stack<size_t> stack; std::stack<bool> point_stack; std::stack<bool> quote_stack; Object obj_temp(env); bool reading = true; bool point_pair = false; bool quote = false; std::string str; size_t level = 0; while(reading) { is >> str; switch(str[0]) { case '(': level ++; point_stack.push(point_pair); point_pair = false; quote_stack.push(quote); quote = false; break; case ')': if(point_pair) { if((! stack.empty()) && (stack.top() == level)) { obj_temp = obj_stack.top(); obj_stack.pop(); stack.pop(); } else { THROW("Wrong S-expression."); } } else { obj_temp = Object(env); // NIL } while((! stack.empty()) && (stack.top() == level)) { stack.pop(); obj_temp = Object(obj_stack.top(), obj_temp); obj_stack.pop(); if(stack.empty()) { break; } } level --; point_pair = point_stack.top(); point_stack.pop(); quote = quote_stack.top(); quote_stack.pop(); if(quote) { obj_stack.push(Object(Object(env, QUOTE), Object(obj_temp, Object(env)))); quote = false; } else { obj_stack.push(obj_temp); } stack.push(level); break; case '.': point_pair = true; break; case '\'': quote = true; break; default: obj_temp = str2atom(str, env); if(quote) { obj_stack.push(Object(Object(env, QUOTE), Object(obj_temp, Object(env)))); quote = false; } else { obj_stack.push(obj_temp); } stack.push(level); break; } reading = static_cast<bool>(level); } obj = obj_stack.top(); return is; } Object str2atom(const std::string& str, Environment &env) { Heap::UInt value; std::locale loc; std::string strup; for(std::string::const_iterator it = str.begin(); it != str.end(); it ++) { strup += std::toupper(*it, loc); } std::vector<Environment::Func>::iterator ptr = std::find(env.functions.begin(), env.functions.end(), strup); if(ptr != env.functions.end()) { return Object(env, FUNC, ptr - env.functions.begin()); } else { switch(strup[0]) { case 'E': if(strup == "EVAL") { return Object(env, EVAL); } return Object(env, ERROR); case '%': value = atol(strup.c_str() + 1); return Object(env, ADF, value); case '$': return Object(env, PARAM); case 'Q': return Object(env, QUOTE); case 'I': return Object(env, IF); case 'N': return Object(env); default: // INTEGER or ERROR if((strup[0] == '-') || ((strup[0] >= '0') && (strup[0] <= '9'))) { value = atol(strup.c_str()); return Object(env, INTEGER, value); } else { return Object(env, ERROR); } } } return Object(env, ERROR); } <commit_msg>Fix wrong merge.<commit_after>/* * Copyright (C) 2010 O01eg <o01eg@yandex.ru> * * This file is part of Genetic Function Programming. * * Genetic Function Programming is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Genetic Function Programming is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Genetic Function Programming. If not, see <http://www.gnu.org/licenses/>. */ #include <cstdlib> #include <string> #include <algorithm> #include <locale> #include <sstream> #include <iomanip> #include <algorithm> #include "ioobject.h" using namespace VM; /// \brief convert string to atomic object. /// \param str String representation. /// \param env Environment form creating object. /// \return Atomic object. Object str2atom(const std::string& str, Environment &env); std::ostream& operator<<(std::ostream& ostr, const WeakObject& obj) { std::streamsize width = ostr.width(); ostr.width(0); std::stringstream os; /// \todo Use normal stack. if(! obj.IsNIL()) { //const Environment& env = obj.GetEnv(); switch(obj.GetType()) { case ERROR: os << "ERROR "; break; case INTEGER: os << static_cast<int>(obj.GetValue()) << " "; break; case FUNC: #if 0 os << "#" << obj.GetValue() << " "; #else os << obj.GetEnv().functions[obj.GetValue()].name << " "; #endif break; case ADF: os << "%" << obj.GetValue() << " "; break; case PARAM: os << "$ "; break; case QUOTE: os << "QUOTE "; break; case IF: os << "IF "; break; case EVAL: os << "EVAL "; break; case LIST: { std::stack<bool> arrow_stack; // true - head, false - tail std::stack<WeakObject> stack; arrow_stack.push(true); stack.push(obj); WeakObject object(obj); bool arrow = true; //size_t level = 0; while(! stack.empty()) { object = stack.top(); stack.pop(); arrow = arrow_stack.top(); arrow_stack.pop(); if(arrow) //head { if(object.IsNIL()) { os << "NIL "; } else { if(object.GetType() == LIST) { //os << std::endl; /*for(size_t i = 0; i < level; i ++) { os << " "; }*/ os << "( "; //level ++; stack.push(object.GetTail()); arrow_stack.push(false); stack.push(object.GetHead()); arrow_stack.push(true); } else { os << object; } } } else //tail { if(object.IsNIL()) { os << ") "; //level --; } else { if(object.GetType() == LIST) { stack.push(object.GetTail()); arrow_stack.push(false); stack.push(object.GetHead()); arrow_stack.push(true); } else { os << ". " << object << ") "; //level --; } } } } } break; default: os << "ERROR "; break; } } else { os << "NIL "; } if(width) { //ostr << "{" << width << "}"; ostr.write(os.str().c_str(), std::min(static_cast<size_t>(width), os.str().size())); } else { ostr << os.str(); } return ostr; } std::istream& operator>>(std::istream& is, Object& obj) { /// \todo Use normal stack. /// \todo Add check for empty stacks. Environment& env = obj.GetEnv(); std::stack<Object> obj_stack; std::stack<size_t> stack; std::stack<bool> point_stack; std::stack<bool> quote_stack; Object obj_temp(env); bool reading = true; bool point_pair = false; bool quote = false; std::string str; size_t level = 0; while(reading) { is >> str; switch(str[0]) { case '(': level ++; point_stack.push(point_pair); point_pair = false; quote_stack.push(quote); quote = false; break; case ')': if(point_pair) { if((! stack.empty()) && (stack.top() == level)) { obj_temp = obj_stack.top(); obj_stack.pop(); stack.pop(); } else { THROW("Wrong S-expression."); } } else { obj_temp = Object(env); // NIL } while((! stack.empty()) && (stack.top() == level)) { stack.pop(); obj_temp = Object(obj_stack.top(), obj_temp); obj_stack.pop(); if(stack.empty()) { break; } } level --; point_pair = point_stack.top(); point_stack.pop(); quote = quote_stack.top(); quote_stack.pop(); if(quote) { obj_stack.push(Object(Object(env, QUOTE), Object(obj_temp, Object(env)))); quote = false; } else { obj_stack.push(obj_temp); } stack.push(level); break; case '.': point_pair = true; break; case '\'': quote = true; break; default: obj_temp = str2atom(str, env); if(quote) { obj_stack.push(Object(Object(env, QUOTE), Object(obj_temp, Object(env)))); quote = false; } else { obj_stack.push(obj_temp); } stack.push(level); break; } reading = static_cast<bool>(level); } obj = obj_stack.top(); return is; } Object str2atom(const std::string& str, Environment &env) { Heap::UInt value; std::locale loc; std::string strup; for(std::string::const_iterator it = str.begin(); it != str.end(); it ++) { strup += std::toupper(*it, loc); } std::vector<Environment::Func>::iterator ptr = std::find(env.functions.begin(), env.functions.end(), strup); if(ptr != env.functions.end()) { return Object(env, FUNC, ptr - env.functions.begin()); } else { switch(strup[0]) { case 'E': if(strup == "EVAL") { return Object(env, EVAL); } return Object(env, ERROR); case '%': value = atol(strup.c_str() + 1); return Object(env, ADF, value); case '$': return Object(env, PARAM); case 'Q': return Object(env, QUOTE); case 'I': return Object(env, IF); case 'N': return Object(env); default: // INTEGER or ERROR if((strup[0] == '-') || ((strup[0] >= '0') && (strup[0] <= '9'))) { value = atol(strup.c_str()); return Object(env, INTEGER, value); } else { return Object(env, ERROR); } } } return Object(env, ERROR); } <|endoftext|>
<commit_before>/*========================================================================= Program: FEMuS Module: Line Authors: Eugenio Aulisa and Giacomo Capodaglio Copyright (c) FEMuS All rights reserved. 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. =========================================================================*/ #ifndef __femus_ism_Line_hpp__ #define __femus_ism_Line_hpp__ //---------------------------------------------------------------------------- // includes : //---------------------------------------------------------------------------- #include "MarkerTypeEnum.hpp" #include "ParallelObject.hpp" #include "Mesh.hpp" #include "Marker.hpp" #include "vector" #include "map" #include "MyVector.hpp" namespace femus { class Line : public ParallelObject { public: Line(std::vector < std::vector < double > > x, const std::vector <MarkerType> &markerType, Mesh *mesh, const unsigned & solType, const unsigned &size, const bool &debug = false) { std::vector < Marker*> particles(size); _dim = mesh->GetDimension(); _size = size; _markerOffset.resize(_nprocs + 1); _markerOffset[_nprocs] = size; _particles.resize(size); _printList.resize(size); for(unsigned j = 0; j < size; j++) { particles[j] = new Marker(x[j], markerType[j], mesh, solType, debug); } // std::cout << "FIRST OF ALL" << std::endl; // for(unsigned i = 0; i < size; i++) { // std::cout << "Particle: " << i << " , " << "Processor: " << particles[i]->GetMarkerProc() << " , " // << "Element: " << particles[i]->GetMarkerElement() << " " << std::endl; // } //BEGIN reorder the markers by proc unsigned counter = 0; for(unsigned iproc = 0; iproc < _nprocs; iproc++) { bool markersInProc = false; unsigned offsetCounter = counter; for(unsigned j = 0; j < size; j++) { unsigned markerProc = particles[j]->GetMarkerProc(); if(markerProc == iproc) { _particles[counter] = particles[j]; _printList[j] = counter; counter++; markersInProc = true; } } if(markersInProc == true) { if(iproc == 0) { _markerOffset[iproc] = 0; } else { unsigned firstCounter = 0; for(unsigned jproc = 0; jproc < iproc; jproc++) { if(_markerOffset[jproc] == UINT_MAX) firstCounter++; } if(firstCounter == iproc) _markerOffset[iproc] = 0; else { _markerOffset[iproc] = offsetCounter; } } } else { _markerOffset[iproc] = UINT_MAX; } // std::cout << "_markerOffset[" << iproc << "]= " << _markerOffset[iproc] << std::endl; } //END reorder the markers by proc // std::cout << "AFTER THE REORDERING BY PROC" << std::endl; // for(unsigned i = 0; i < size; i++) { // std::cout << "Particle: " << i << " , " << "Processor: " << _particles[i]->GetMarkerProc() << " , " // << "Element: " << _particles[i]->GetMarkerElement() << " " << std::endl; // } //BEGIN reorder markers also by element for(unsigned j = 0; j < _size; j++) { particles[j] = _particles[j]; } unsigned* elementList = new unsigned [mesh->GetNumberOfElements()]; std::vector < unsigned> printList(size); //flags to see if we already ordered by that element, 0 = not considered yet for(unsigned iFlag = 0; iFlag < mesh->GetNumberOfElements(); iFlag++) { elementList[iFlag] = 0; } printList = _printList; for(unsigned iproc = 0; iproc < _nprocs; iproc++) { if(_markerOffset[iproc] != UINT_MAX) { counter = 0; unsigned upperBound; bool upperBoundFound = 0; bool finishedProcs = 0; unsigned lproc = iproc + 1; while(upperBoundFound + finishedProcs == 0) { if(_markerOffset[lproc] != UINT_MAX) { upperBound = _markerOffset[lproc]; upperBoundFound = 1; } else { if(lproc < _nprocs) lproc ++; else finishedProcs = 1; } } std::cout << "upperBound =" << upperBound << std::endl; for(unsigned jp = _markerOffset[iproc]; jp < upperBound; jp++) { unsigned jel = particles[jp]->GetMarkerElement(); if(elementList[jel] == 0) { elementList[jel] = 1; _particles[_markerOffset[iproc] + counter] = particles[jp]; _printList[jp] = _markerOffset[iproc] + counter; counter++; for(unsigned ip = _markerOffset[iproc]; ip < upperBound; ip++) { unsigned iel = particles[ip]->GetMarkerElement(); if(ip != jp && iel == jel) { //std::cout << " jel =" << jel << " , " << "ip = " << ip << " , " << "jp = " << jp << std::endl; elementList[iel] = 1; _particles[_markerOffset[iproc] + counter] = particles[ip]; _printList[ip] = _markerOffset[iproc] + counter; //TODO FIX counter++; } } } } } } //END reorder markers also by element // for(unsigned i = 0; i < _size; i++) { // std::cout << "_printList[ " << i << "] = " << _printList[i] << std::endl; // } // std::cout << "AFTER THE REORDERING BY ELEM" << std::endl; // for(unsigned i = 0; i < size; i++) { // std::cout << "Particle: " << i << " , " << "Processor: " << _particles[i]->GetMarkerProc() << " , " // << "Element: " << _particles[i]->GetMarkerElement() << " " << std::endl; // } _line.resize(1); _line[0].resize(size + 1); for(unsigned j = 0; j < size; j++) { _particles[_printList[j]]->GetMarkerCoordinates(_line[0][j]); } _particles[_printList[0]]->GetMarkerCoordinates(_line[0][size]); for(unsigned j = 0; j < size; j++) { delete particles[j]; } delete[] elementList; std::vector < unsigned > ().swap(printList); }; std::vector < std::vector < std::vector < double > > > GetLine() { return _line; } void UpdateLine(); //TODO update the function void AdvectionParallel(Solution* sol, const unsigned &n, const double& T, const unsigned &order); private: std::vector < std::vector < std::vector < double > > > _line; std::vector < Marker*> _particles; std::vector < unsigned > _markerOffset; std::vector < unsigned > _printList; unsigned _size; unsigned _dim; std::vector < std::vector < std::vector < double > > > _K; static const double _a[4][4][4]; static const double _b[4][4]; static const double _c[4][4]; }; } //end namespace femus #endif <commit_msg>fixed the print, now it is ok<commit_after>/*========================================================================= Program: FEMuS Module: Line Authors: Eugenio Aulisa and Giacomo Capodaglio Copyright (c) FEMuS All rights reserved. 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. =========================================================================*/ #ifndef __femus_ism_Line_hpp__ #define __femus_ism_Line_hpp__ //---------------------------------------------------------------------------- // includes : //---------------------------------------------------------------------------- #include "MarkerTypeEnum.hpp" #include "ParallelObject.hpp" #include "Mesh.hpp" #include "Marker.hpp" #include "vector" #include "map" #include "MyVector.hpp" namespace femus { class Line : public ParallelObject { public: Line(std::vector < std::vector < double > > x, const std::vector <MarkerType> &markerType, Mesh *mesh, const unsigned & solType, const unsigned &size, const bool &debug = false) { std::vector < Marker*> particles(size); _dim = mesh->GetDimension(); _size = size; _markerOffset.resize(_nprocs + 1); _markerOffset[_nprocs] = size; _particles.resize(size); _printList.resize(size); for(unsigned j = 0; j < size; j++) { particles[j] = new Marker(x[j], markerType[j], mesh, solType, debug); } // std::cout << "FIRST OF ALL" << std::endl; // for(unsigned i = 0; i < size; i++) { // std::cout << "Particle: " << i << " , " << "Processor: " << particles[i]->GetMarkerProc() << " , " // << "Element: " << particles[i]->GetMarkerElement() << " " << std::endl; // } //BEGIN reorder the markers by proc unsigned counter = 0; for(unsigned iproc = 0; iproc < _nprocs; iproc++) { bool markersInProc = false; unsigned offsetCounter = counter; for(unsigned j = 0; j < size; j++) { unsigned markerProc = particles[j]->GetMarkerProc(); if(markerProc == iproc) { _particles[counter] = particles[j]; _printList[j] = counter; counter++; markersInProc = true; } } if(markersInProc == true) { if(iproc == 0) { _markerOffset[iproc] = 0; } else { unsigned firstCounter = 0; for(unsigned jproc = 0; jproc < iproc; jproc++) { if(_markerOffset[jproc] == UINT_MAX) firstCounter++; } if(firstCounter == iproc) _markerOffset[iproc] = 0; else { _markerOffset[iproc] = offsetCounter; } } } else { _markerOffset[iproc] = UINT_MAX; } // std::cout << "_markerOffset[" << iproc << "]= " << _markerOffset[iproc] << std::endl; } //END reorder the markers by proc // std::cout << "AFTER THE REORDERING BY PROC" << std::endl; // for(unsigned i = 0; i < size; i++) { // std::cout << "Particle: " << i << " , " << "Processor: " << _particles[i]->GetMarkerProc() << " , " // << "Element: " << _particles[i]->GetMarkerElement() << " " << std::endl; // } // for(unsigned i = 0; i < _size; i++) { // std::cout << "_printList[ " << i << "] = " << _printList[i] << std::endl; // } // // // std::cout << " ------------------------------------------------------------------------------------------------ " << std::endl; //BEGIN reorder markers also by element for(unsigned j = 0; j < _size; j++) { particles[j] = _particles[j]; } unsigned* elementList = new unsigned [mesh->GetNumberOfElements()]; std::vector < unsigned> printList(size); //flags to see if we already ordered by that element, 0 = not considered yet for(unsigned iFlag = 0; iFlag < mesh->GetNumberOfElements(); iFlag++) { elementList[iFlag] = 0; } printList = _printList; for(unsigned iproc = 0; iproc < _nprocs; iproc++) { if(_markerOffset[iproc] != UINT_MAX) { counter = 0; unsigned upperBound; bool upperBoundFound = 0; bool finishedProcs = 0; unsigned lproc = iproc + 1; while(upperBoundFound + finishedProcs == 0) { if(_markerOffset[lproc] != UINT_MAX) { upperBound = _markerOffset[lproc]; upperBoundFound = 1; } else { if(lproc < _nprocs) lproc ++; else finishedProcs = 1; } } //std::cout << "upperBound =" << upperBound << std::endl; for(unsigned jp = _markerOffset[iproc]; jp < upperBound; jp++) { unsigned jel = particles[jp]->GetMarkerElement(); if(elementList[jel] == 0) { elementList[jel] = 1; _particles[_markerOffset[iproc] + counter] = particles[jp]; for(unsigned iList = 0; iList < size; iList++) { if(printList[iList] == jp) { _printList[iList] = _markerOffset[iproc] + counter; break; } } counter++; for(unsigned ip = _markerOffset[iproc]; ip < upperBound; ip++) { unsigned iel = particles[ip]->GetMarkerElement(); if(ip != jp && iel == jel) { //std::cout << " jel =" << jel << " , " << "ip = " << ip << " , " << "jp = " << jp << std::endl; elementList[iel] = 1; _particles[_markerOffset[iproc] + counter] = particles[ip]; for(unsigned iList = 0; iList < size; iList++) { if(printList[iList] == ip) { _printList[iList] = _markerOffset[iproc] + counter; break; } } counter++; } } } } } } //END reorder markers also by element // for(unsigned i = 0; i < _size; i++) { // std::cout << "_printList[ " << i << "] = " << _printList[i] << std::endl; // } // std::cout << "AFTER THE REORDERING BY ELEM" << std::endl; // for(unsigned i = 0; i < size; i++) { // std::cout << "Particle: " << i << " , " << "Processor: " << _particles[i]->GetMarkerProc() << " , " // << "Element: " << _particles[i]->GetMarkerElement() << " " << std::endl; // } _line.resize(1); _line[0].resize(size + 1); for(unsigned j = 0; j < size; j++) { _particles[_printList[j]]->GetMarkerCoordinates(_line[0][j]); } _particles[_printList[0]]->GetMarkerCoordinates(_line[0][size]); for(unsigned j = 0; j < size; j++) { delete particles[j]; } delete[] elementList; std::vector < unsigned > ().swap(printList); }; std::vector < std::vector < std::vector < double > > > GetLine() { return _line; } void UpdateLine(); //TODO update the function void AdvectionParallel(Solution* sol, const unsigned &n, const double& T, const unsigned &order); private: std::vector < std::vector < std::vector < double > > > _line; std::vector < Marker*> _particles; std::vector < unsigned > _markerOffset; std::vector < unsigned > _printList; unsigned _size; unsigned _dim; std::vector < std::vector < std::vector < double > > > _K; static const double _a[4][4][4]; static const double _b[4][4]; static const double _c[4][4]; }; } //end namespace femus #endif <|endoftext|>
<commit_before>/* Copyright 1994, 1995 by Abacus Research and * Development, Inc. All rights reserved. */ #if !defined(NDEBUG) #include "rsys/common.h" #include "DialogMgr.h" #include "QuickDraw.h" #include "rsys/cquick.h" #include "rsys/region.h" #include "rsys/stdbits.h" #include "rsys/dump.h" #include "rsys/iv.h" #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <arpa/inet.h> #include <netinet/in.h> #include <netdb.h> using namespace Executor; #define print_errno_error_message(call, msg) \ ({ \ fprintf(stderr, "%s:%d; %s: %s; %s\n", \ __FILE__, __LINE__, \ call, strerror(errno), \ msg); \ }) void send_image(int width, int height, int row_bytes, int send_row_bytes, char *base_addr, CTabHandle ctab) { image_header_t header; int sockfd, retval, i; struct sockaddr_in srv_addr; char hostname[1024]; struct hostent *host; header.width = width; header.height = height; header.row_bytes = send_row_bytes; memset(header.image_color_map, '\0', sizeof header.image_color_map); for(i = 0; i <= CTAB_SIZE(ctab); i++) { color_t *color; ColorSpec *color_spec; color = &header.image_color_map[i]; color_spec = &CTAB_TABLE(ctab)[i]; color->red = CW(color_spec->rgb.red); color->green = CW(color_spec->rgb.green); color->blue = CW(color_spec->rgb.blue); } /* connect to server, and send */ gethostname(hostname, 1024); host = gethostbyname(hostname); sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if(sockfd < 0) { print_errno_error_message("socket", "unable to send image"); return; } srv_addr.sin_family = AF_INET; srv_addr.sin_port = PORT; srv_addr.sin_addr = *((struct in_addr *)host->h_addr); retval = connect(sockfd, (struct sockaddr *)&srv_addr, sizeof srv_addr); if(retval < 0) { print_errno_error_message("connect", "unable to send image"); return; } retval = write(sockfd, &header, sizeof header); if(retval < 0) { print_errno_error_message("write", "unable to send image"); return; } for(i = 0; i < height; i++) { retval = write(sockfd, base_addr, send_row_bytes); base_addr += row_bytes; if(retval < 0) { print_errno_error_message("write", "unable to send image"); return; } } close(sockfd); } void dump_image(BitMap *bogo_bitmap, Rect *rect); void dump_grafport_image(GrafPort *port) { Rect r, bounds; r = PORT_RECT(port); bounds = PORT_BOUNDS(port); OffsetRect(&bounds, CW(r.left) - CW(bounds.left), CW(r.top) - CW(bounds.top)); SectRect(&r, &bounds, &r); dump_image(&port->portBits, &r); } void dump_image(BitMap *bogo_bitmap, Rect *rect) { struct cleanup_info cleanup; int width, height, row_bytes; char *base_addr, *_base_addr; PixMap dummy_space; PixMap *pixmap = &dummy_space; int depth; int map_row_bytes; canonicalize_bogo_map(bogo_bitmap, &pixmap, &cleanup); width = RECT_WIDTH(rect); height = RECT_HEIGHT(rect); /* destination must be 8bpp */ depth = CW(pixmap->pixelSize); if(depth != 8) { int map_width, map_height; static PixMap new_pixmap; ColorTable *conv_table; int i; map_width = RECT_WIDTH(&pixmap->bounds); map_height = RECT_HEIGHT(&pixmap->bounds); map_row_bytes = ((width * 8 + 31) / 32) * 4; base_addr = (char *)alloca(map_row_bytes * height); new_pixmap.rowBytes = CW(map_row_bytes); new_pixmap.baseAddr = RM((Ptr)base_addr); new_pixmap.pixelSize = CWC(8); new_pixmap.cmpCount = CWC(1); new_pixmap.cmpSize = CWC(8); new_pixmap.pmTable = NULL; conv_table = (ColorTable *)alloca(CTAB_STORAGE_FOR_SIZE(1 << depth)); for(i = 0; i < (1 << depth); i++) conv_table->ctTable[i].value = CW(i); convert_pixmap(pixmap, &new_pixmap, rect, conv_table); new_pixmap.pmTable = pixmap->pmTable; pixmap = &new_pixmap; } else { map_row_bytes = CW(pixmap->rowBytes & ~ROWBYTES_FLAG_BITS_X); base_addr = (char *)MR(pixmap->baseAddr); } row_bytes = width; _base_addr = &base_addr[(CW(rect->top) - CW(pixmap->bounds.top)) * map_row_bytes + (CW(rect->left) - CW(pixmap->bounds.left))]; send_image(width, height, map_row_bytes, row_bytes, _base_addr, MR(pixmap->pmTable)); canonicalize_bogo_map_cleanup((BitMap *)&pixmap, &cleanup); } void dump_rgn_as_image(RgnHandle rh) { BitMap bm; int row_bytes; char *baseaddr; bm.bounds = RGN_BBOX(rh); row_bytes = ((RECT_WIDTH(&bm.bounds) + 31) / 32) * 4; bm.rowBytes = CW(row_bytes); baseaddr = (char *)alloca(row_bytes * RECT_HEIGHT(&bm.bounds)); bm.baseAddr = RM((Ptr)baseaddr); memset(baseaddr, '\377', row_bytes * RECT_HEIGHT(&bm.bounds)); CopyBits(&bm, &bm, &bm.bounds, &bm.bounds, srcXor, rh); dump_image(&bm, &bm.bounds); } #endif /* !NDEBUG */ <commit_msg>replace a ({}) with do {} while(0)<commit_after>/* Copyright 1994, 1995 by Abacus Research and * Development, Inc. All rights reserved. */ #if !defined(NDEBUG) #include "rsys/common.h" #include "DialogMgr.h" #include "QuickDraw.h" #include "rsys/cquick.h" #include "rsys/region.h" #include "rsys/stdbits.h" #include "rsys/dump.h" #include "rsys/iv.h" #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <arpa/inet.h> #include <netinet/in.h> #include <netdb.h> using namespace Executor; #define print_errno_error_message(call, msg) \ do { \ fprintf(stderr, "%s:%d; %s: %s; %s\n", \ __FILE__, __LINE__, \ call, strerror(errno), \ msg); \ } while(0) void send_image(int width, int height, int row_bytes, int send_row_bytes, char *base_addr, CTabHandle ctab) { image_header_t header; int sockfd, retval, i; struct sockaddr_in srv_addr; char hostname[1024]; struct hostent *host; header.width = width; header.height = height; header.row_bytes = send_row_bytes; memset(header.image_color_map, '\0', sizeof header.image_color_map); for(i = 0; i <= CTAB_SIZE(ctab); i++) { color_t *color; ColorSpec *color_spec; color = &header.image_color_map[i]; color_spec = &CTAB_TABLE(ctab)[i]; color->red = CW(color_spec->rgb.red); color->green = CW(color_spec->rgb.green); color->blue = CW(color_spec->rgb.blue); } /* connect to server, and send */ gethostname(hostname, 1024); host = gethostbyname(hostname); sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if(sockfd < 0) { print_errno_error_message("socket", "unable to send image"); return; } srv_addr.sin_family = AF_INET; srv_addr.sin_port = PORT; srv_addr.sin_addr = *((struct in_addr *)host->h_addr); retval = connect(sockfd, (struct sockaddr *)&srv_addr, sizeof srv_addr); if(retval < 0) { print_errno_error_message("connect", "unable to send image"); return; } retval = write(sockfd, &header, sizeof header); if(retval < 0) { print_errno_error_message("write", "unable to send image"); return; } for(i = 0; i < height; i++) { retval = write(sockfd, base_addr, send_row_bytes); base_addr += row_bytes; if(retval < 0) { print_errno_error_message("write", "unable to send image"); return; } } close(sockfd); } void dump_image(BitMap *bogo_bitmap, Rect *rect); void dump_grafport_image(GrafPort *port) { Rect r, bounds; r = PORT_RECT(port); bounds = PORT_BOUNDS(port); OffsetRect(&bounds, CW(r.left) - CW(bounds.left), CW(r.top) - CW(bounds.top)); SectRect(&r, &bounds, &r); dump_image(&port->portBits, &r); } void dump_image(BitMap *bogo_bitmap, Rect *rect) { struct cleanup_info cleanup; int width, height, row_bytes; char *base_addr, *_base_addr; PixMap dummy_space; PixMap *pixmap = &dummy_space; int depth; int map_row_bytes; canonicalize_bogo_map(bogo_bitmap, &pixmap, &cleanup); width = RECT_WIDTH(rect); height = RECT_HEIGHT(rect); /* destination must be 8bpp */ depth = CW(pixmap->pixelSize); if(depth != 8) { int map_width, map_height; static PixMap new_pixmap; ColorTable *conv_table; int i; map_width = RECT_WIDTH(&pixmap->bounds); map_height = RECT_HEIGHT(&pixmap->bounds); map_row_bytes = ((width * 8 + 31) / 32) * 4; base_addr = (char *)alloca(map_row_bytes * height); new_pixmap.rowBytes = CW(map_row_bytes); new_pixmap.baseAddr = RM((Ptr)base_addr); new_pixmap.pixelSize = CWC(8); new_pixmap.cmpCount = CWC(1); new_pixmap.cmpSize = CWC(8); new_pixmap.pmTable = NULL; conv_table = (ColorTable *)alloca(CTAB_STORAGE_FOR_SIZE(1 << depth)); for(i = 0; i < (1 << depth); i++) conv_table->ctTable[i].value = CW(i); convert_pixmap(pixmap, &new_pixmap, rect, conv_table); new_pixmap.pmTable = pixmap->pmTable; pixmap = &new_pixmap; } else { map_row_bytes = CW(pixmap->rowBytes & ~ROWBYTES_FLAG_BITS_X); base_addr = (char *)MR(pixmap->baseAddr); } row_bytes = width; _base_addr = &base_addr[(CW(rect->top) - CW(pixmap->bounds.top)) * map_row_bytes + (CW(rect->left) - CW(pixmap->bounds.left))]; send_image(width, height, map_row_bytes, row_bytes, _base_addr, MR(pixmap->pmTable)); canonicalize_bogo_map_cleanup((BitMap *)&pixmap, &cleanup); } void dump_rgn_as_image(RgnHandle rh) { BitMap bm; int row_bytes; char *baseaddr; bm.bounds = RGN_BBOX(rh); row_bytes = ((RECT_WIDTH(&bm.bounds) + 31) / 32) * 4; bm.rowBytes = CW(row_bytes); baseaddr = (char *)alloca(row_bytes * RECT_HEIGHT(&bm.bounds)); bm.baseAddr = RM((Ptr)baseaddr); memset(baseaddr, '\377', row_bytes * RECT_HEIGHT(&bm.bounds)); CopyBits(&bm, &bm, &bm.bounds, &bm.bounds, srcXor, rh); dump_image(&bm, &bm.bounds); } #endif /* !NDEBUG */ <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: joburl.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: hr $ $Date: 2003-03-25 18:19:48 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef __FRAMEWORK_JOBS_JOBURL_HXX_ #define __FRAMEWORK_JOBS_JOBURL_HXX_ //_______________________________________ // my own includes #ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_ #include <threadhelp/threadhelpbase.hxx> #endif #ifndef __FRAMEWORK_MACROS_DEBUG_HXX_ #include <macros/debug.hxx> #endif #ifndef __FRAMEWORK_STDTYPES_H_ #include <stdtypes.h> #endif #ifndef __FRAMEWORK_GENERAL_H_ #include <general.h> #endif //_______________________________________ // interface includes //_______________________________________ // other includes #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif //_______________________________________ // namespace namespace framework{ //_______________________________________ // const #define JOBURL_PROTOCOL_STR "vnd.sun.star.job:" #define JOBURL_PROTOCOL_LEN 17 #define JOBURL_EVENT_STR "event=" #define JOBURL_EVENT_LEN 6 #define JOBURL_ALIAS_STR "alias=" #define JOBURL_ALIAS_LEN 6 #define JOBURL_SERVICE_STR "service=" #define JOBURL_SERVICE_LEN 8 #define JOBURL_PART_SEPERATOR ';' #define JOBURL_PARTARGS_SEPERATOR ',' //_______________________________________ /** @short can be used to parse, validate and work with job URL's @descr Job URLs are specified by the following syntax: vnd.sun.star.job:{[event=<name>]|[alias=<name>]|[service=<name>]} This class can analyze this structure and seperate it into his different parts. After doing that these parts are accessible by the methods of this class. */ class JobURL : private ThreadHelpBase { //___________________________________ // types private: /** possible states of a job URL Note: These values are used in combination. So they must be values in form 2^n. */ enum ERequest { /// mark a job URL as not valid E_UNKNOWN = 0, /// it's an event E_EVENT = 1, /// it's an alias E_ALIAS = 2, /// it's a service E_SERVICE = 4 }; //___________________________________ // types private: /** knows the state of this URL instance */ sal_uInt32 m_eRequest; /** holds the event part of a job URL */ ::rtl::OUString m_sEvent; /** holds the alias part of a job URL */ ::rtl::OUString m_sAlias; /** holds the service part of a job URL */ ::rtl::OUString m_sService; /** holds the event arguments */ ::rtl::OUString m_sEventArgs; /** holds the alias arguments */ ::rtl::OUString m_sAliasArgs; /** holds the service arguments */ ::rtl::OUString m_sServiceArgs; //___________________________________ // native interface public: JobURL ( const ::rtl::OUString& sURL ); sal_Bool isValid ( ) const; sal_Bool getEvent ( ::rtl::OUString& sEvent ) const; sal_Bool getAlias ( ::rtl::OUString& sAlias ) const; sal_Bool getService ( ::rtl::OUString& sService ) const; sal_Bool getEventArgs ( ::rtl::OUString& sEventArgs ) const; sal_Bool getAliasArgs ( ::rtl::OUString& sAliasArgs ) const; sal_Bool getServiceArgs( ::rtl::OUString& sServiceArgs ) const; //___________________________________ // private helper private: static sal_Bool implst_split( const ::rtl::OUString& sPart , const sal_Char* pPartIdentifier , sal_Int32 nPartLength , ::rtl::OUString& rPartValue , ::rtl::OUString& rPartArguments ); //___________________________________ // debug methods! #ifdef ENABLE_COMPONENT_SELF_CHECK public: static void impldbg_checkIt(); private: static void impldbg_checkURL( const sal_Char* pURL , sal_uInt32 eExpectedPart , const sal_Char* pExpectedEvent , const sal_Char* pExpectedAlias , const sal_Char* pExpectedService , const sal_Char* pExpectedEventArgs , const sal_Char* pExpectedAliasArgs , const sal_Char* pExpectedServiceArgs ); ::rtl::OUString impldbg_toString() const; #endif // ENABLE_COMPONENT_SELF_CHECK }; } // namespace framework #endif // __FRAMEWORK_JOBS_JOBURL_HXX_ <commit_msg>INTEGRATION: CWS ooo19126 (1.2.502); FILE MERGED 2005/09/05 13:05:01 rt 1.2.502.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: joburl.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-09 00:23:36 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef __FRAMEWORK_JOBS_JOBURL_HXX_ #define __FRAMEWORK_JOBS_JOBURL_HXX_ //_______________________________________ // my own includes #ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_ #include <threadhelp/threadhelpbase.hxx> #endif #ifndef __FRAMEWORK_MACROS_DEBUG_HXX_ #include <macros/debug.hxx> #endif #ifndef __FRAMEWORK_STDTYPES_H_ #include <stdtypes.h> #endif #ifndef __FRAMEWORK_GENERAL_H_ #include <general.h> #endif //_______________________________________ // interface includes //_______________________________________ // other includes #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif //_______________________________________ // namespace namespace framework{ //_______________________________________ // const #define JOBURL_PROTOCOL_STR "vnd.sun.star.job:" #define JOBURL_PROTOCOL_LEN 17 #define JOBURL_EVENT_STR "event=" #define JOBURL_EVENT_LEN 6 #define JOBURL_ALIAS_STR "alias=" #define JOBURL_ALIAS_LEN 6 #define JOBURL_SERVICE_STR "service=" #define JOBURL_SERVICE_LEN 8 #define JOBURL_PART_SEPERATOR ';' #define JOBURL_PARTARGS_SEPERATOR ',' //_______________________________________ /** @short can be used to parse, validate and work with job URL's @descr Job URLs are specified by the following syntax: vnd.sun.star.job:{[event=<name>]|[alias=<name>]|[service=<name>]} This class can analyze this structure and seperate it into his different parts. After doing that these parts are accessible by the methods of this class. */ class JobURL : private ThreadHelpBase { //___________________________________ // types private: /** possible states of a job URL Note: These values are used in combination. So they must be values in form 2^n. */ enum ERequest { /// mark a job URL as not valid E_UNKNOWN = 0, /// it's an event E_EVENT = 1, /// it's an alias E_ALIAS = 2, /// it's a service E_SERVICE = 4 }; //___________________________________ // types private: /** knows the state of this URL instance */ sal_uInt32 m_eRequest; /** holds the event part of a job URL */ ::rtl::OUString m_sEvent; /** holds the alias part of a job URL */ ::rtl::OUString m_sAlias; /** holds the service part of a job URL */ ::rtl::OUString m_sService; /** holds the event arguments */ ::rtl::OUString m_sEventArgs; /** holds the alias arguments */ ::rtl::OUString m_sAliasArgs; /** holds the service arguments */ ::rtl::OUString m_sServiceArgs; //___________________________________ // native interface public: JobURL ( const ::rtl::OUString& sURL ); sal_Bool isValid ( ) const; sal_Bool getEvent ( ::rtl::OUString& sEvent ) const; sal_Bool getAlias ( ::rtl::OUString& sAlias ) const; sal_Bool getService ( ::rtl::OUString& sService ) const; sal_Bool getEventArgs ( ::rtl::OUString& sEventArgs ) const; sal_Bool getAliasArgs ( ::rtl::OUString& sAliasArgs ) const; sal_Bool getServiceArgs( ::rtl::OUString& sServiceArgs ) const; //___________________________________ // private helper private: static sal_Bool implst_split( const ::rtl::OUString& sPart , const sal_Char* pPartIdentifier , sal_Int32 nPartLength , ::rtl::OUString& rPartValue , ::rtl::OUString& rPartArguments ); //___________________________________ // debug methods! #ifdef ENABLE_COMPONENT_SELF_CHECK public: static void impldbg_checkIt(); private: static void impldbg_checkURL( const sal_Char* pURL , sal_uInt32 eExpectedPart , const sal_Char* pExpectedEvent , const sal_Char* pExpectedAlias , const sal_Char* pExpectedService , const sal_Char* pExpectedEventArgs , const sal_Char* pExpectedAliasArgs , const sal_Char* pExpectedServiceArgs ); ::rtl::OUString impldbg_toString() const; #endif // ENABLE_COMPONENT_SELF_CHECK }; } // namespace framework #endif // __FRAMEWORK_JOBS_JOBURL_HXX_ <|endoftext|>
<commit_before>#ifndef regex_hh_INCLUDED #define regex_hh_INCLUDED #include "string.hh" #include "exception.hh" #include "utf8_iterator.hh" #include <boost/regex.hpp> namespace Kakoune { struct regex_error : runtime_error { regex_error(StringView desc) : runtime_error{format("regex error: '{}'", desc)} {} }; using RegexBase = boost::basic_regex<wchar_t, boost::c_regex_traits<wchar_t>>; // Regex that keeps track of its string representation class Regex : RegexBase { public: Regex() = default; explicit Regex(StringView re, flag_type flags = ECMAScript); bool empty() const { return m_str.empty(); } bool operator==(const Regex& other) const { return m_str == other.m_str; } bool operator!=(const Regex& other) const { return m_str != other.m_str; } const String& str() const { return m_str; } static constexpr const char* option_type_name = "regex"; private: String m_str; }; template<typename It> using RegexUtf8It = utf8::iterator<It, wchar_t, ssize_t>; template<typename It> using RegexIteratorBase = boost::regex_iterator<RegexUtf8It<It>, wchar_t, boost::c_regex_traits<wchar_t>>; namespace RegexConstant = boost::regex_constants; template<typename Iterator> struct MatchResults : boost::match_results<RegexUtf8It<Iterator>> { using ParentType = boost::match_results<RegexUtf8It<Iterator>>; struct SubMatch : std::pair<Iterator, Iterator> { SubMatch() = default; SubMatch(const boost::sub_match<RegexUtf8It<Iterator>>& m) : std::pair<Iterator, Iterator>{m.first.base(), m.second.base()}, matched{m.matched} {} bool matched = false; }; struct iterator : boost::match_results<RegexUtf8It<Iterator>>::iterator { using ParentType = typename boost::match_results<RegexUtf8It<Iterator>>::iterator; iterator(const ParentType& it) : ParentType(it) {} SubMatch operator*() const { return {ParentType::operator*()}; } }; iterator begin() const { return {ParentType::begin()}; } iterator cbegin() const { return {ParentType::cbegin()}; } iterator end() const { return {ParentType::end()}; } iterator cend() const { return {ParentType::cend()}; } SubMatch operator[](size_t s) const { return {ParentType::operator[](s)}; } }; template<typename Iterator> struct RegexIterator : RegexIteratorBase<Iterator> { using Utf8It = RegexUtf8It<Iterator>; using ValueType = MatchResults<Iterator>; RegexIterator() = default; RegexIterator(Iterator begin, Iterator end, const Regex& re, RegexConstant::match_flag_type flags = RegexConstant::match_default) : RegexIteratorBase<Iterator>{Utf8It{begin, begin, end}, Utf8It{end, begin, end}, re, flags} {} const ValueType& operator*() const { return *reinterpret_cast<const ValueType*>(&RegexIteratorBase<Iterator>::operator*()); } const ValueType* operator->() const { return reinterpret_cast<const ValueType*>(RegexIteratorBase<Iterator>::operator->()); } }; inline RegexConstant::match_flag_type match_flags(bool bol, bool eol, bool bow, bool eow) { return (bol ? RegexConstant::match_default : RegexConstant::match_not_bol) | (eol ? RegexConstant::match_default : RegexConstant::match_not_eol) | (bow ? RegexConstant::match_default : RegexConstant::match_not_bow) | (eow ? RegexConstant::match_default : RegexConstant::match_not_eow); } template<typename It> bool regex_match(It begin, It end, const Regex& re) { using Utf8It = RegexUtf8It<It>; try { return boost::regex_match(Utf8It{begin, begin, end}, Utf8It{end, begin, end}, re); } catch (std::runtime_error& err) { throw runtime_error{format("Regex matching error: {}", err.what())}; } } template<typename It> bool regex_match(It begin, It end, MatchResults<It>& res, const Regex& re) { using Utf8It = RegexUtf8It<It>; try { return boost::regex_match(Utf8It{begin, begin, end}, Utf8It{end, begin, end}, res, re); } catch (std::runtime_error& err) { throw runtime_error{format("Regex matching error: {}", err.what())}; } } template<typename It> bool regex_search(It begin, It end, const Regex& re, RegexConstant::match_flag_type flags = RegexConstant::match_default) { using Utf8It = RegexUtf8It<It>; try { return boost::regex_search(Utf8It{begin, begin, end}, Utf8It{end, begin, end}, re, flags); } catch (std::runtime_error& err) { throw runtime_error{format("Regex searching error: {}", err.what())}; } } template<typename It> bool regex_search(It begin, It end, MatchResults<It>& res, const Regex& re, RegexConstant::match_flag_type flags = RegexConstant::match_default) { using Utf8It = RegexUtf8It<It>; try { return boost::regex_search(Utf8It{begin, begin, end}, Utf8It{end, begin, end}, res, re, flags); } catch (std::runtime_error& err) { throw runtime_error{format("Regex searching error: {}", err.what())}; } } String option_to_string(const Regex& re); void option_from_string(StringView str, Regex& re); } #endif // regex_hh_INCLUDED <commit_msg>Fix regex.hh compilation<commit_after>#ifndef regex_hh_INCLUDED #define regex_hh_INCLUDED #include "string.hh" #include "exception.hh" #include "utf8_iterator.hh" #include <boost/regex.hpp> namespace Kakoune { struct regex_error : runtime_error { regex_error(StringView desc) : runtime_error{format("regex error: '{}'", desc)} {} }; using RegexBase = boost::basic_regex<wchar_t, boost::c_regex_traits<wchar_t>>; // Regex that keeps track of its string representation class Regex : public RegexBase { public: Regex() = default; explicit Regex(StringView re, flag_type flags = ECMAScript); bool empty() const { return m_str.empty(); } bool operator==(const Regex& other) const { return m_str == other.m_str; } bool operator!=(const Regex& other) const { return m_str != other.m_str; } const String& str() const { return m_str; } static constexpr const char* option_type_name = "regex"; private: String m_str; }; template<typename It> using RegexUtf8It = utf8::iterator<It, wchar_t, ssize_t>; template<typename It> using RegexIteratorBase = boost::regex_iterator<RegexUtf8It<It>, wchar_t, boost::c_regex_traits<wchar_t>>; namespace RegexConstant = boost::regex_constants; template<typename Iterator> struct MatchResults : boost::match_results<RegexUtf8It<Iterator>> { using ParentType = boost::match_results<RegexUtf8It<Iterator>>; struct SubMatch : std::pair<Iterator, Iterator> { SubMatch() = default; SubMatch(const boost::sub_match<RegexUtf8It<Iterator>>& m) : std::pair<Iterator, Iterator>{m.first.base(), m.second.base()}, matched{m.matched} {} bool matched = false; }; struct iterator : boost::match_results<RegexUtf8It<Iterator>>::iterator { using ParentType = typename boost::match_results<RegexUtf8It<Iterator>>::iterator; iterator(const ParentType& it) : ParentType(it) {} SubMatch operator*() const { return {ParentType::operator*()}; } }; iterator begin() const { return {ParentType::begin()}; } iterator cbegin() const { return {ParentType::cbegin()}; } iterator end() const { return {ParentType::end()}; } iterator cend() const { return {ParentType::cend()}; } SubMatch operator[](size_t s) const { return {ParentType::operator[](s)}; } }; template<typename Iterator> struct RegexIterator : RegexIteratorBase<Iterator> { using Utf8It = RegexUtf8It<Iterator>; using ValueType = MatchResults<Iterator>; RegexIterator() = default; RegexIterator(Iterator begin, Iterator end, const Regex& re, RegexConstant::match_flag_type flags = RegexConstant::match_default) : RegexIteratorBase<Iterator>{Utf8It{begin, begin, end}, Utf8It{end, begin, end}, re, flags} {} const ValueType& operator*() const { return *reinterpret_cast<const ValueType*>(&RegexIteratorBase<Iterator>::operator*()); } const ValueType* operator->() const { return reinterpret_cast<const ValueType*>(RegexIteratorBase<Iterator>::operator->()); } }; inline RegexConstant::match_flag_type match_flags(bool bol, bool eol, bool bow, bool eow) { return (bol ? RegexConstant::match_default : RegexConstant::match_not_bol) | (eol ? RegexConstant::match_default : RegexConstant::match_not_eol) | (bow ? RegexConstant::match_default : RegexConstant::match_not_bow) | (eow ? RegexConstant::match_default : RegexConstant::match_not_eow); } template<typename It> bool regex_match(It begin, It end, const Regex& re) { using Utf8It = RegexUtf8It<It>; try { return boost::regex_match(Utf8It{begin, begin, end}, Utf8It{end, begin, end}, re); } catch (std::runtime_error& err) { throw runtime_error{format("Regex matching error: {}", err.what())}; } } template<typename It> bool regex_match(It begin, It end, MatchResults<It>& res, const Regex& re) { using Utf8It = RegexUtf8It<It>; try { return boost::regex_match(Utf8It{begin, begin, end}, Utf8It{end, begin, end}, res, re); } catch (std::runtime_error& err) { throw runtime_error{format("Regex matching error: {}", err.what())}; } } template<typename It> bool regex_search(It begin, It end, const Regex& re, RegexConstant::match_flag_type flags = RegexConstant::match_default) { using Utf8It = RegexUtf8It<It>; try { return boost::regex_search(Utf8It{begin, begin, end}, Utf8It{end, begin, end}, re, flags); } catch (std::runtime_error& err) { throw runtime_error{format("Regex searching error: {}", err.what())}; } } template<typename It> bool regex_search(It begin, It end, MatchResults<It>& res, const Regex& re, RegexConstant::match_flag_type flags = RegexConstant::match_default) { using Utf8It = RegexUtf8It<It>; try { return boost::regex_search(Utf8It{begin, begin, end}, Utf8It{end, begin, end}, res, re, flags); } catch (std::runtime_error& err) { throw runtime_error{format("Regex searching error: {}", err.what())}; } } String option_to_string(const Regex& re); void option_from_string(StringView str, Regex& re); } #endif // regex_hh_INCLUDED <|endoftext|>
<commit_before>/* * * Author: Jeffrey Leung * Last edited: 2015-09-19 * * This program contains implementations of a Room class, which is a template * to create a Labyrinth. * */ #include <iostream> #include <stdexcept> #include "../include/room_properties.hpp" #include "../include/room.hpp" // Parameterized constructor // This constructor sets the necessary properties of a Room. Room::Room( Inhabitant dark_thing, Item object, Direction exit, bool wall_north, bool wall_east, bool wall_south, bool wall_west ) { dark_thing_ = dark_thing; object_ = object; exit_ = exit; wall_north_ = wall_north; wall_east_ = wall_east; wall_south_ = wall_south; wall_west_ = wall_west; } // This method returns the current inhabitant of the Room. Inhabitant Room::GetInhabitant() const { return dark_thing_; } // This method changes the current inhabitant of the Room. void Room::SetInhabitant( Inhabitant inh ) { dark_thing_ = inh; return; } // This method returns the current item in the Room. Item Room::GetItem() const { return object_; } // This method changes the current item in the Room. void Room::SetItem( Item itm ) { object_ = itm; return; } // This method removes the Wall in the given direction so that the Room // may be connected to another, or to set the exit. // An exception is thrown if: // The Wall has already been removed (logic_error) // Direction d is null (i.e. Direction::kNone) (invalid_argument) void Room::BreakWall( Direction d ) { switch( d ) { case( Direction::kNone ): throw std::invalid_argument( "Error: BreakWall() was given an "\ "invalid Direction (kNone). "); case( Direction::kNorth ): if( !wall_north_ ) // Wall already removed { throw std::logic_error( "Error: BreakWall() was given an "\ "already-removed Wall." ); } wall_north_ = false; break; case( Direction::kEast ): if( !wall_east_ ) { throw std::logic_error( "Error: BreakWall() was given an "\ "already-removed Wall." ); } wall_east_ = false; break; case( Direction::kSouth ): if( !wall_south_ ) { throw std::logic_error( "Error: BreakWall() was given an "\ "already-removed Wall." ); } wall_south_ = false; break; case( Direction::kWest ): if( !wall_west_ ) { throw std::logic_error( "Error: BreakWall() was given an "\ "already-removed Wall." ); } wall_west_ = false; break; } return; } // This method returns: // RoomBorder::kExit if the direction has the exit, // RoomBorder::kRoom if the direction has another room, or // RoomBorder::kWall if the direction has a wall. // An exception is thrown if: // Direction d is kNone (invalid_argument) RoomBorder Room::DirectionCheck( Direction d ) const { if( d == Direction::kNone ) { throw std::invalid_argument( "Error: DirectionCheck() was given the "\ "direction kNone.\n" ) ; } if( d == exit_ ) { return RoomBorder::kExit; } else if( ( d == Direction::kNorth && !(wall_north_) ) || ( d == Direction::kEast && !(wall_east_) ) || ( d == Direction::kSouth && !(wall_south_) ) || ( d == Direction::kWest && !(wall_west_) ) ) { return RoomBorder::kRoom; } else { return RoomBorder::kWall; } } <commit_msg>Room: Adding newlines to exception messages.<commit_after>/* * * Author: Jeffrey Leung * Last edited: 2015-12-28 * * This program contains implementations of a Room class, which is a template * to create a Labyrinth. * */ #include <iostream> #include <stdexcept> #include "../include/room_properties.hpp" #include "../include/room.hpp" // Parameterized constructor // This constructor sets the necessary properties of a Room. Room::Room( Inhabitant dark_thing, Item object, Direction exit, bool wall_north, bool wall_east, bool wall_south, bool wall_west ) { dark_thing_ = dark_thing; object_ = object; exit_ = exit; wall_north_ = wall_north; wall_east_ = wall_east; wall_south_ = wall_south; wall_west_ = wall_west; } // This method returns the current inhabitant of the Room. Inhabitant Room::GetInhabitant() const { return dark_thing_; } // This method changes the current inhabitant of the Room. void Room::SetInhabitant( Inhabitant inh ) { dark_thing_ = inh; return; } // This method returns the current item in the Room. Item Room::GetItem() const { return object_; } // This method changes the current item in the Room. void Room::SetItem( Item itm ) { object_ = itm; return; } // This method removes the Wall in the given direction so that the Room // may be connected to another, or to set the exit. // An exception is thrown if: // The Wall has already been removed (logic_error) // Direction d is null (i.e. Direction::kNone) (invalid_argument) void Room::BreakWall( Direction d ) { switch( d ) { case( Direction::kNone ): throw std::invalid_argument( "Error: BreakWall() was given an "\ "invalid Direction (kNone).\n"); case( Direction::kNorth ): if( !wall_north_ ) // Wall already removed { throw std::logic_error( "Error: BreakWall() was given an "\ "already-removed Wall.\n" ); } wall_north_ = false; break; case( Direction::kEast ): if( !wall_east_ ) { throw std::logic_error( "Error: BreakWall() was given an "\ "already-removed Wall.\n" ); } wall_east_ = false; break; case( Direction::kSouth ): if( !wall_south_ ) { throw std::logic_error( "Error: BreakWall() was given an "\ "already-removed Wall.\n" ); } wall_south_ = false; break; case( Direction::kWest ): if( !wall_west_ ) { throw std::logic_error( "Error: BreakWall() was given an "\ "already-removed Wall.\n" ); } wall_west_ = false; break; } return; } // This method returns: // RoomBorder::kExit if the direction has the exit, // RoomBorder::kRoom if the direction has another room, or // RoomBorder::kWall if the direction has a wall. // An exception is thrown if: // Direction d is kNone (invalid_argument) RoomBorder Room::DirectionCheck( Direction d ) const { if( d == Direction::kNone ) { throw std::invalid_argument( "Error: DirectionCheck() was given the "\ "direction kNone.\n" ) ; } if( d == exit_ ) { return RoomBorder::kExit; } else if( ( d == Direction::kNorth && !(wall_north_) ) || ( d == Direction::kEast && !(wall_east_) ) || ( d == Direction::kSouth && !(wall_south_) ) || ( d == Direction::kWest && !(wall_west_) ) ) { return RoomBorder::kRoom; } else { return RoomBorder::kWall; } } <|endoftext|>
<commit_before>#include "lua/config.h" #include "lua/state.h" #include "rwte/logging.h" #include "rwte/rwte.h" #include "rwte/term.h" #include "rwte/tty.h" #include "rwte/window.h" #include <memory> // todo: mark [[noreturn]] funcs // todo: std::starts_with/ends_with // todo: std::span // todo: std::bit_cast // todo: std::shift_left/shift_right // globals Options options; std::unique_ptr<Rwte> rwte; lua_State* g_L = nullptr; #define LOGGER() (logging::get("rwte")) // default values to use if we don't have // a default value in config static const float DEFAULT_BLINK_RATE = 0.6; Rwte::Rwte(std::shared_ptr<event::Bus> bus) : m_bus(std::move(bus)), m_refreshReg(m_bus->reg<event::Refresh, Rwte, &Rwte::onrefresh>(this)), m_lua(std::make_shared<lua::State>()) { m_lua->openlibs(); m_child.set<Rwte, &Rwte::childcb>(this); m_flush.set<Rwte, &Rwte::flushcb>(this); m_blink.set<Rwte, &Rwte::blinkcb>(this); } Rwte::~Rwte() { m_bus->unreg<event::Refresh>(m_refreshReg); } void Rwte::watch_child(pid_t pid) { LOGGER()->debug("watching child {}", pid); m_child.start(pid); } void Rwte::refresh() { // with xcb, we throttle drawing here if (options.throttledraw) { if (!m_flush.is_active()) m_flush.start(1.0 / 60.0); } else { // for wayland, we let the window throttle if (auto window = m_window.lock()) window->draw(); } } void Rwte::start_blink() { if (!m_blink.is_active()) { float rate = lua::config::get_float( "blink_rate", DEFAULT_BLINK_RATE); m_blink.start(rate, rate); } else { // reset the timer if it's already active // (so we don't blink until idle) m_blink.stop(); m_blink.start(); } } void Rwte::stop_blink() { if (m_blink.is_active()) m_blink.stop(); } void Rwte::onrefresh(const event::Refresh& evt) { refresh(); } void Rwte::childcb(ev::child& w, int) { if (WIFEXITED(w.rstatus) && WEXITSTATUS(w.rstatus)) LOGGER()->warn("child exited with status {}", WEXITSTATUS(w.rstatus)); else if (WIFSIGNALED(w.rstatus)) LOGGER()->info("child terminated to to signal {}", WTERMSIG(w.rstatus)); w.loop.break_loop(ev::ALL); } void Rwte::flushcb(ev::timer&, int) { if (auto window = m_window.lock()) window->draw(); } void Rwte::blinkcb(ev::timer&, int) { if (auto term = m_term.lock()) term->blink(); } <commit_msg>Another constexpr, added more todos.<commit_after>#include "lua/config.h" #include "lua/state.h" #include "rwte/logging.h" #include "rwte/rwte.h" #include "rwte/term.h" #include "rwte/tty.h" #include "rwte/window.h" #include <memory> // todo: mark [[noreturn]] funcs // todo: std::starts_with/ends_with // todo: std::span // todo: std::bit_cast // todo: std::shift_left/shift_right // todo: more std::string_view // todo: memset/memcpy/memmove // todo: std::exit and EXIT_x // todo: nest impl classes // todo: use override keyword // todo: look for initializer in if or switch // todo: bench codecvt vs utf8 // globals Options options; std::unique_ptr<Rwte> rwte; lua_State* g_L = nullptr; #define LOGGER() (logging::get("rwte")) // default values to use if we don't have // a default value in config constexpr float DEFAULT_BLINK_RATE = 0.6; Rwte::Rwte(std::shared_ptr<event::Bus> bus) : m_bus(std::move(bus)), m_refreshReg(m_bus->reg<event::Refresh, Rwte, &Rwte::onrefresh>(this)), m_lua(std::make_shared<lua::State>()) { m_lua->openlibs(); m_child.set<Rwte, &Rwte::childcb>(this); m_flush.set<Rwte, &Rwte::flushcb>(this); m_blink.set<Rwte, &Rwte::blinkcb>(this); } Rwte::~Rwte() { m_bus->unreg<event::Refresh>(m_refreshReg); } void Rwte::watch_child(pid_t pid) { LOGGER()->debug("watching child {}", pid); m_child.start(pid); } void Rwte::refresh() { // with xcb, we throttle drawing here if (options.throttledraw) { if (!m_flush.is_active()) m_flush.start(1.0 / 60.0); } else { // for wayland, we let the window throttle if (auto window = m_window.lock()) window->draw(); } } void Rwte::start_blink() { if (!m_blink.is_active()) { float rate = lua::config::get_float( "blink_rate", DEFAULT_BLINK_RATE); m_blink.start(rate, rate); } else { // reset the timer if it's already active // (so we don't blink until idle) m_blink.stop(); m_blink.start(); } } void Rwte::stop_blink() { if (m_blink.is_active()) m_blink.stop(); } void Rwte::onrefresh(const event::Refresh& evt) { refresh(); } void Rwte::childcb(ev::child& w, int) { if (WIFEXITED(w.rstatus) && WEXITSTATUS(w.rstatus)) LOGGER()->warn("child exited with status {}", WEXITSTATUS(w.rstatus)); else if (WIFSIGNALED(w.rstatus)) LOGGER()->info("child terminated to to signal {}", WTERMSIG(w.rstatus)); w.loop.break_loop(ev::ALL); } void Rwte::flushcb(ev::timer&, int) { if (auto window = m_window.lock()) window->draw(); } void Rwte::blinkcb(ev::timer&, int) { if (auto term = m_term.lock()) term->blink(); } <|endoftext|>
<commit_before>// This file is a part of the OpenSurgSim project. // Copyright 2013, 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 <memory> #include <boost/thread.hpp> #include <SurgSim/Blocks/BasicSceneElement.h> #include <SurgSim/Blocks/TransferDeformableStateToVerticesBehavior.h> #include <SurgSim/Framework/Behavior.h> #include <SurgSim/Framework/BehaviorManager.h> #include <SurgSim/Framework/Runtime.h> #include <SurgSim/Framework/Scene.h> #include <SurgSim/Framework/SceneElement.h> #include <SurgSim/Graphics/OsgCamera.h> #include <SurgSim/Graphics/OsgManager.h> #include <SurgSim/Graphics/OsgView.h> #include <SurgSim/Graphics/OsgViewElement.h> #include <SurgSim/Graphics/OsgPointCloudRepresentation.h> #include <SurgSim/Physics/PhysicsManager.h> #include <SurgSim/Physics/Fem3DRepresentation.h> #include <SurgSim/Physics/FemElement3DTetrahedron.h> #include <SurgSim/Math/Vector.h> #include <SurgSim/Math/Quaternion.h> #include <SurgSim/Math/RigidTransform.h> using SurgSim::Blocks::BasicSceneElement; using SurgSim::Blocks::TransferDeformableStateToVerticesBehavior; using SurgSim::Framework::Logger; using SurgSim::Framework::SceneElement; using SurgSim::Graphics::OsgPointCloudRepresentation; using SurgSim::Physics::DeformableRepresentationState; using SurgSim::Physics::Fem3DRepresentation; using SurgSim::Physics::FemElement3DTetrahedron; using SurgSim::Physics::PhysicsManager; using SurgSim::Math::Vector3d; using SurgSim::Math::Vector4f; ///\file Example of how to put together a very simple demo of Fem3D namespace { // Cube nodes // 2*-----------*3 // / /| // 6*-----------*7 | ^ y // | | | | // | 0 | *1 *->x // | | / / // 4*-----------*5 z std::array<SurgSim::Math::Vector3d, 8> cubeNodes = {{ Vector3d(-0.5,-0.5,-0.5), Vector3d( 0.5,-0.5,-0.5), Vector3d(-0.5, 0.5,-0.5), Vector3d( 0.5, 0.5,-0.5), Vector3d(-0.5,-0.5, 0.5), Vector3d( 0.5,-0.5, 0.5), Vector3d(-0.5, 0.5, 0.5), Vector3d( 0.5, 0.5, 0.5) }}; // Cube decomposition into 5 tetrahedrons // https://www.math.ucdavis.edu/~deloera/CURRENT_INTERESTS/cube.html const unsigned int numTetrahedrons = 5; std::array< std::array<unsigned int, 4>, numTetrahedrons> tetrahedrons = {{ {{4, 7, 1, 2}}, // CCW (47)cross(41) . (42) > 0 {{4, 1, 7, 5}}, // CCW (41)cross(47) . (45) > 0 {{4, 2, 1, 0}}, // CCW (42)cross(41) . (40) > 0 {{4, 7, 2, 6}}, // CCW (47)cross(42) . (46) > 0 {{1, 2, 7, 3}} // CCW (12)cross(17) . (13) > 0 }}; // Boundary conditions (node indices) const unsigned int numBoundaryConditionsNodeIdx = 4; const std::array<unsigned int, numBoundaryConditionsNodeIdx> boundaryConditionsNodeIdx = {{ 0, 1, 2, 3 }}; void loadCubeModelFem3D(std::shared_ptr<Fem3DRepresentation> *physicsRepresentation) { std::shared_ptr<DeformableRepresentationState> restState = std::make_shared<DeformableRepresentationState>(); restState->setNumDof((*physicsRepresentation)->getNumDofPerNode(), 8); Vector& x = restState->getPositions(); // Sets the initial state (node positions and boundary conditions) for (int nodeId = 0; nodeId < 8; nodeId++) { SurgSim::Math::getSubVector(x, nodeId, 3) = cubeNodes[nodeId]; } for (unsigned int boundaryConditionId = 0; boundaryConditionId < numBoundaryConditionsNodeIdx; boundaryConditionId++) { // The boundary conditions in the state are the dof indices to be fixed restState->addBoundaryCondition(boundaryConditionsNodeIdx[boundaryConditionId] * 3 + 0); restState->addBoundaryCondition(boundaryConditionsNodeIdx[boundaryConditionId] * 3 + 1); restState->addBoundaryCondition(boundaryConditionsNodeIdx[boundaryConditionId] * 3 + 2); } (*physicsRepresentation)->setInitialState(restState); // Adds all the FemElements for (unsigned int tetId = 0; tetId < numTetrahedrons; tetId++) { std::shared_ptr<FemElement3DTetrahedron> tet = nullptr; tet = std::make_shared<FemElement3DTetrahedron>(tetrahedrons[tetId], *restState); tet->setMassDensity(8000.0); tet->setPoissonRatio(0.45); tet->setYoungModulus(1e6); (*physicsRepresentation)->addFemElement(tet); } // Calls Initialize() after adding the FemElements and setting the initial state (*physicsRepresentation)->Initialize(); } }; std::shared_ptr<SurgSim::Graphics::ViewElement> createView(const std::string& name, int x, int y, int width, int height) { using SurgSim::Graphics::OsgViewElement; std::shared_ptr<OsgViewElement> viewElement = std::make_shared<OsgViewElement>(name); viewElement->getView()->setPosition(x, y); viewElement->getView()->setDimensions(width, height); return viewElement; } std::shared_ptr<SceneElement> createFem3D(const std::string& name, const std::vector<SurgSim::Math::RigidTransform3d> gfxPoses, SurgSim::Math::Vector4d color, SurgSim::Math::IntegrationScheme integrationScheme) { std::shared_ptr<Fem3DRepresentation> physicsRepresentation = std::make_shared<Fem3DRepresentation>(name + " Physics"); // In this example, the physics representations are not transformed, // only the graphics one will apply a transform loadCubeModelFem3D(&physicsRepresentation); physicsRepresentation->setIntegrationScheme(integrationScheme); physicsRepresentation->setRayleighDampingMass(5e-2); physicsRepresentation->setRayleighDampingStiffness(5e-3); std::shared_ptr<SceneElement> massSpringElement = std::make_shared<BasicSceneElement>(name); massSpringElement->addComponent(physicsRepresentation); unsigned int gfxObjectId = 0; for (auto gfxPose = std::begin(gfxPoses); gfxPose != std::end(gfxPoses); gfxPose++) { std::stringstream ss; ss << name + " Graphics object " << gfxObjectId; std::shared_ptr<OsgPointCloudRepresentation<void>> graphicsRepresentation = std::make_shared<OsgPointCloudRepresentation<void>>(ss.str()); std::shared_ptr<SurgSim::DataStructures::Vertices<void>> vertices; vertices = std::make_shared<SurgSim::DataStructures::Vertices<void>>(); graphicsRepresentation->setInitialPose(*gfxPose); graphicsRepresentation->setVertices(vertices); graphicsRepresentation->setColor(color); graphicsRepresentation->setPointSize(3.0f); graphicsRepresentation->setVisible(true); massSpringElement->addComponent(graphicsRepresentation); ss.clear(); ss << "Physics to Graphics ("<< gfxObjectId <<") deformable points"; massSpringElement->addComponent(std::make_shared<TransferDeformableStateToVerticesBehavior<void>> (ss.str(), physicsRepresentation->getFinalState(), graphicsRepresentation->getVertices())); gfxObjectId++; } return massSpringElement; } int main(int argc, char* argv[]) { using SurgSim::Math::makeRigidTransform; using SurgSim::Math::Vector4d; std::shared_ptr<SurgSim::Graphics::OsgManager> graphicsManager = std::make_shared<SurgSim::Graphics::OsgManager>(); std::shared_ptr<PhysicsManager> physicsManager = std::make_shared<PhysicsManager>(); std::shared_ptr<SurgSim::Framework::BehaviorManager> behaviorManager = std::make_shared<SurgSim::Framework::BehaviorManager>(); std::shared_ptr<SurgSim::Framework::Runtime> runtime(new SurgSim::Framework::Runtime()); runtime->addManager(physicsManager); runtime->addManager(graphicsManager); runtime->addManager(behaviorManager); std::shared_ptr<SurgSim::Framework::Scene> scene(new SurgSim::Framework::Scene()); SurgSim::Math::Quaterniond qIdentity = SurgSim::Math::Quaterniond::Identity(); SurgSim::Math::Vector3d translate(0,0,-3); { std::vector<SurgSim::Math::RigidTransform3d> gfxPoses; gfxPoses.push_back(makeRigidTransform(qIdentity, translate+Vector3d(-3.0, 0.5, 0.0))); gfxPoses.push_back(makeRigidTransform(qIdentity, translate+Vector3d( 3.0, 0.5, 0.0))); scene->addSceneElement(createFem3D("Euler Explicit", gfxPoses, Vector4d(1, 0, 0, 1), SurgSim::Math::INTEGRATIONSCHEME_EXPLICIT_EULER)); gfxPoses.clear(); gfxPoses.push_back(makeRigidTransform(qIdentity, translate+Vector3d(-1.0, 0.5, 0.0))); gfxPoses.push_back(makeRigidTransform(qIdentity, translate+Vector3d( 3.0, 0.5, 0.0))); scene->addSceneElement(createFem3D("Modified Euler Explicit", gfxPoses, Vector4d(0, 1, 0, 1), SurgSim::Math::INTEGRATIONSCHEME_MODIFIED_EXPLICIT_EULER)); gfxPoses.clear(); gfxPoses.push_back(makeRigidTransform(qIdentity, translate+Vector3d( 1.0, 0.5, 0.0))); gfxPoses.push_back(makeRigidTransform(qIdentity, translate+Vector3d( 3.0, 0.5, 0.0))); scene->addSceneElement(createFem3D("Fem 3D Euler Implicit", gfxPoses, Vector4d(0, 0, 1, 1), SurgSim::Math::INTEGRATIONSCHEME_IMPLICIT_EULER)); } scene->addSceneElement(createView("view1", 0, 0, 1023, 768)); graphicsManager->getDefaultCamera()->setInitialPose( SurgSim::Math::makeRigidTransform(SurgSim::Math::Quaterniond::Identity(), Vector3d(0.0, 0.5, 5.0))); runtime->setScene(scene); runtime->execute(); return 0; } <commit_msg>Fix broken ExampleFem3D after merge with master (OsgPointCloud handles its vertices)<commit_after>// This file is a part of the OpenSurgSim project. // Copyright 2013, 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 <memory> #include <boost/thread.hpp> #include <SurgSim/Blocks/BasicSceneElement.h> #include <SurgSim/Blocks/TransferDeformableStateToVerticesBehavior.h> #include <SurgSim/Framework/Behavior.h> #include <SurgSim/Framework/BehaviorManager.h> #include <SurgSim/Framework/Runtime.h> #include <SurgSim/Framework/Scene.h> #include <SurgSim/Framework/SceneElement.h> #include <SurgSim/Graphics/OsgCamera.h> #include <SurgSim/Graphics/OsgManager.h> #include <SurgSim/Graphics/OsgView.h> #include <SurgSim/Graphics/OsgViewElement.h> #include <SurgSim/Graphics/OsgPointCloudRepresentation.h> #include <SurgSim/Physics/PhysicsManager.h> #include <SurgSim/Physics/Fem3DRepresentation.h> #include <SurgSim/Physics/FemElement3DTetrahedron.h> #include <SurgSim/Math/Vector.h> #include <SurgSim/Math/Quaternion.h> #include <SurgSim/Math/RigidTransform.h> using SurgSim::Blocks::BasicSceneElement; using SurgSim::Blocks::TransferDeformableStateToVerticesBehavior; using SurgSim::Framework::Logger; using SurgSim::Framework::SceneElement; using SurgSim::Graphics::OsgPointCloudRepresentation; using SurgSim::Physics::DeformableRepresentationState; using SurgSim::Physics::Fem3DRepresentation; using SurgSim::Physics::FemElement3DTetrahedron; using SurgSim::Physics::PhysicsManager; using SurgSim::Math::Vector3d; using SurgSim::Math::Vector4f; ///\file Example of how to put together a very simple demo of Fem3D namespace { // Cube nodes // 2*-----------*3 // / /| // 6*-----------*7 | ^ y // | | | | // | 0 | *1 *->x // | | / / // 4*-----------*5 z std::array<SurgSim::Math::Vector3d, 8> cubeNodes = {{ Vector3d(-0.5,-0.5,-0.5), Vector3d( 0.5,-0.5,-0.5), Vector3d(-0.5, 0.5,-0.5), Vector3d( 0.5, 0.5,-0.5), Vector3d(-0.5,-0.5, 0.5), Vector3d( 0.5,-0.5, 0.5), Vector3d(-0.5, 0.5, 0.5), Vector3d( 0.5, 0.5, 0.5) }}; // Cube decomposition into 5 tetrahedrons // https://www.math.ucdavis.edu/~deloera/CURRENT_INTERESTS/cube.html const unsigned int numTetrahedrons = 5; std::array< std::array<unsigned int, 4>, numTetrahedrons> tetrahedrons = {{ {{4, 7, 1, 2}}, // CCW (47)cross(41) . (42) > 0 {{4, 1, 7, 5}}, // CCW (41)cross(47) . (45) > 0 {{4, 2, 1, 0}}, // CCW (42)cross(41) . (40) > 0 {{4, 7, 2, 6}}, // CCW (47)cross(42) . (46) > 0 {{1, 2, 7, 3}} // CCW (12)cross(17) . (13) > 0 }}; // Boundary conditions (node indices) const unsigned int numBoundaryConditionsNodeIdx = 4; const std::array<unsigned int, numBoundaryConditionsNodeIdx> boundaryConditionsNodeIdx = {{ 0, 1, 2, 3 }}; void loadCubeModelFem3D(std::shared_ptr<Fem3DRepresentation> *physicsRepresentation) { std::shared_ptr<DeformableRepresentationState> restState = std::make_shared<DeformableRepresentationState>(); restState->setNumDof((*physicsRepresentation)->getNumDofPerNode(), 8); Vector& x = restState->getPositions(); // Sets the initial state (node positions and boundary conditions) for (int nodeId = 0; nodeId < 8; nodeId++) { SurgSim::Math::getSubVector(x, nodeId, 3) = cubeNodes[nodeId]; } for (unsigned int boundaryConditionId = 0; boundaryConditionId < numBoundaryConditionsNodeIdx; boundaryConditionId++) { // The boundary conditions in the state are the dof indices to be fixed restState->addBoundaryCondition(boundaryConditionsNodeIdx[boundaryConditionId] * 3 + 0); restState->addBoundaryCondition(boundaryConditionsNodeIdx[boundaryConditionId] * 3 + 1); restState->addBoundaryCondition(boundaryConditionsNodeIdx[boundaryConditionId] * 3 + 2); } (*physicsRepresentation)->setInitialState(restState); // Adds all the FemElements for (unsigned int tetId = 0; tetId < numTetrahedrons; tetId++) { std::shared_ptr<FemElement3DTetrahedron> tet = nullptr; tet = std::make_shared<FemElement3DTetrahedron>(tetrahedrons[tetId], *restState); tet->setMassDensity(8000.0); tet->setPoissonRatio(0.45); tet->setYoungModulus(1e6); (*physicsRepresentation)->addFemElement(tet); } // Calls Initialize() after adding the FemElements and setting the initial state (*physicsRepresentation)->Initialize(); } }; std::shared_ptr<SurgSim::Graphics::ViewElement> createView(const std::string& name, int x, int y, int width, int height) { using SurgSim::Graphics::OsgViewElement; std::shared_ptr<OsgViewElement> viewElement = std::make_shared<OsgViewElement>(name); viewElement->getView()->setPosition(x, y); viewElement->getView()->setDimensions(width, height); return viewElement; } std::shared_ptr<SceneElement> createFem3D(const std::string& name, const std::vector<SurgSim::Math::RigidTransform3d> gfxPoses, SurgSim::Math::Vector4d color, SurgSim::Math::IntegrationScheme integrationScheme) { std::shared_ptr<Fem3DRepresentation> physicsRepresentation = std::make_shared<Fem3DRepresentation>(name + " Physics"); // In this example, the physics representations are not transformed, // only the graphics one will apply a transform loadCubeModelFem3D(&physicsRepresentation); physicsRepresentation->setIntegrationScheme(integrationScheme); physicsRepresentation->setRayleighDampingMass(5e-2); physicsRepresentation->setRayleighDampingStiffness(5e-3); std::shared_ptr<SceneElement> massSpringElement = std::make_shared<BasicSceneElement>(name); massSpringElement->addComponent(physicsRepresentation); unsigned int gfxObjectId = 0; for (auto gfxPose = std::begin(gfxPoses); gfxPose != std::end(gfxPoses); gfxPose++) { std::stringstream ss; ss << name + " Graphics object " << gfxObjectId; std::shared_ptr<OsgPointCloudRepresentation<void>> graphicsRepresentation = std::make_shared<OsgPointCloudRepresentation<void>>(ss.str()); graphicsRepresentation->setInitialPose(*gfxPose); graphicsRepresentation->setColor(color); graphicsRepresentation->setPointSize(3.0f); graphicsRepresentation->setVisible(true); massSpringElement->addComponent(graphicsRepresentation); ss.clear(); ss << "Physics to Graphics ("<< gfxObjectId <<") deformable points"; massSpringElement->addComponent(std::make_shared<TransferDeformableStateToVerticesBehavior<void>> (ss.str(), physicsRepresentation->getFinalState(), graphicsRepresentation->getVertices())); gfxObjectId++; } return massSpringElement; } int main(int argc, char* argv[]) { using SurgSim::Math::makeRigidTransform; using SurgSim::Math::Vector4d; std::shared_ptr<SurgSim::Graphics::OsgManager> graphicsManager = std::make_shared<SurgSim::Graphics::OsgManager>(); std::shared_ptr<PhysicsManager> physicsManager = std::make_shared<PhysicsManager>(); std::shared_ptr<SurgSim::Framework::BehaviorManager> behaviorManager = std::make_shared<SurgSim::Framework::BehaviorManager>(); std::shared_ptr<SurgSim::Framework::Runtime> runtime(new SurgSim::Framework::Runtime()); runtime->addManager(physicsManager); runtime->addManager(graphicsManager); runtime->addManager(behaviorManager); std::shared_ptr<SurgSim::Framework::Scene> scene(new SurgSim::Framework::Scene()); SurgSim::Math::Quaterniond qIdentity = SurgSim::Math::Quaterniond::Identity(); SurgSim::Math::Vector3d translate(0,0,-3); { std::vector<SurgSim::Math::RigidTransform3d> gfxPoses; gfxPoses.push_back(makeRigidTransform(qIdentity, translate+Vector3d(-3.0, 0.5, 0.0))); gfxPoses.push_back(makeRigidTransform(qIdentity, translate+Vector3d( 3.0, 0.5, 0.0))); scene->addSceneElement(createFem3D("Euler Explicit", gfxPoses, Vector4d(1, 0, 0, 1), SurgSim::Math::INTEGRATIONSCHEME_EXPLICIT_EULER)); gfxPoses.clear(); gfxPoses.push_back(makeRigidTransform(qIdentity, translate+Vector3d(-1.0, 0.5, 0.0))); gfxPoses.push_back(makeRigidTransform(qIdentity, translate+Vector3d( 3.0, 0.5, 0.0))); scene->addSceneElement(createFem3D("Modified Euler Explicit", gfxPoses, Vector4d(0, 1, 0, 1), SurgSim::Math::INTEGRATIONSCHEME_MODIFIED_EXPLICIT_EULER)); gfxPoses.clear(); gfxPoses.push_back(makeRigidTransform(qIdentity, translate+Vector3d( 1.0, 0.5, 0.0))); gfxPoses.push_back(makeRigidTransform(qIdentity, translate+Vector3d( 3.0, 0.5, 0.0))); scene->addSceneElement(createFem3D("Fem 3D Euler Implicit", gfxPoses, Vector4d(0, 0, 1, 1), SurgSim::Math::INTEGRATIONSCHEME_IMPLICIT_EULER)); } scene->addSceneElement(createView("view1", 0, 0, 1023, 768)); graphicsManager->getDefaultCamera()->setInitialPose( SurgSim::Math::makeRigidTransform(SurgSim::Math::Quaterniond::Identity(), Vector3d(0.0, 0.5, 5.0))); runtime->setScene(scene); runtime->execute(); return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2011, Robert Escriva // 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 this project nor the names of its contributors may // be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #ifndef e_timer_h_ #define e_timer_h_ // C #include <stdint.h> #if HAVE_CONFIG_H #include <config.h> #endif #ifdef _MSC_VER // Windows #define _WINSOCKAPI_ #include <windows.h> #endif //mach #ifdef HAVE_MACH_ABSOLUTE_TIME #include <mach/mach_time.h> #endif // POSIX #include <errno.h> #include <time.h> // STL #include <exception> // po6 #include <po6/error.h> // e #include "e/time.h" uint64_t e :: time() { #ifdef _MSC_VER LARGE_INTEGER tickfreq, timestamp; tickfreq.QuadPart = 0; timestamp.QuadPart = 0; QueryPerformanceFrequency((LARGE_INTEGER*)&tickfreq); QueryPerformanceCounter((LARGE_INTEGER*)&timestamp); return timestamp.QuadPart / (tickfreq.QuadPart/1000000000.0); #elif defined HAVE_MACH_TIMEBASE_INFO mach_timebase_info_data_t info; mach_timebase_info(&info); return mach_absolute_time()*info.numer/info.denom; #else timespec ts; if (clock_gettime(CLOCK_REALTIME, &ts) < 0) { throw po6::error(errno); } return ts.tv_sec * 1000000000 + ts.tv_nsec; #endif } #endif // e_timer_h__ <commit_msg>fix ifdef for OSX<commit_after>// Copyright (c) 2011, Robert Escriva // 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 this project nor the names of its contributors may // be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #ifndef e_timer_h_ #define e_timer_h_ // C #include <stdint.h> #if HAVE_CONFIG_H #include <config.h> #endif #ifdef _MSC_VER // Windows #define _WINSOCKAPI_ #include <windows.h> #endif //mach #ifdef HAVE_MACH_ABSOLUTE_TIME #include <mach/mach_time.h> #endif // POSIX #include <errno.h> #include <time.h> // STL #include <exception> // po6 #include <po6/error.h> // e #include "e/time.h" uint64_t e :: time() { #ifdef _MSC_VER LARGE_INTEGER tickfreq, timestamp; tickfreq.QuadPart = 0; timestamp.QuadPart = 0; QueryPerformanceFrequency((LARGE_INTEGER*)&tickfreq); QueryPerformanceCounter((LARGE_INTEGER*)&timestamp); return timestamp.QuadPart / (tickfreq.QuadPart/1000000000.0); #elif defined HAVE_MACH_ABSOLUTE_TIME mach_timebase_info_data_t info; mach_timebase_info(&info); return mach_absolute_time()*info.numer/info.denom; #else timespec ts; if (clock_gettime(CLOCK_REALTIME, &ts) < 0) { throw po6::error(errno); } return ts.tv_sec * 1000000000 + ts.tv_nsec; #endif } #endif // e_timer_h__ <|endoftext|>
<commit_before>#include "keyboardinterface.h" #include <SDL2/SDL_keyboard.h> #include <SDL2/SDL_events.h> #include "context.h" namespace sdli { KeyboardInterface::KeyboardInterface(const int max_actions, const int max_axes) : logicAnalogData(max_axes), captureBuffer(max_actions) { } KeyboardInterface::~KeyboardInterface() { } void KeyboardInterface::poll(Context& ctx) { auto sdl_keystate = SDL_GetKeyboardState(NULL); auto& keymap = ctx.keyboardKeys(); auto& axisMap = ctx.axisMapping(); auto axisIt = axisMap.begin(); auto axisEnd = axisMap.end(); for(;axisIt!=axisEnd;++axisIt) { if(axisIt->idx.deviceType == SDL_Axis::Type::Keyboard) { auto data = axisIt->data; auto pollResult = 0.0f; auto neg = sdl_keystate[axisIt->idx.axis.rawNegative]; auto pos = sdl_keystate[axisIt->idx.axis.rawPositive]; if(neg == SDL_PRESSED) { pollResult -= 1.0f; } if(pos == SDL_PRESSED) { pollResult += 1.0f; } if(logicAnalogData.at(data->axis)==nullptr) { logicAnalogData.emplace(data->axis); } auto& currentStatus = logicAnalogData.get(data->axis).currentStatus; if(currentStatus!=0.0f) { currentStatus = sdli::clamp(currentStatus + pollResult, -1, 1) / data->normalize; } else { currentStatus = pollResult / data->normalize; } } } auto it = keymap.begin(); for(;it!=keymap.end();++it) { auto state = sdl_keystate[it->idx]; auto action = *(it->data); if(captureBuffer.at(action)==nullptr) { captureBuffer.emplace(action); } captureBuffer.get(action).previousStatus = captureBuffer.get(action).currentStatus; captureBuffer.get(action).currentStatus = state; } } void KeyboardInterface::push(unsigned int rawInput, int value) { perFrameCaptures.emplace_back(RawInputData{rawInput, value}); } void KeyboardInterface::dispatch(Context& ctx) { for(auto& raw : perFrameCaptures) { auto inputAction = ctx.keyAction(static_cast<SDL_Scancode>(raw.rawInput)); if(captureBuffer.at(inputAction) == nullptr) { captureBuffer.emplace(inputAction); } auto& logic = captureBuffer.get(inputAction); logic.currentStatus = raw.pollResult; if(::sdli::isPressed(logic)) { ctx.fireCallbacks(inputAction, sdli::CallType::OnPress); } if(::sdli::isReleased(logic)) { ctx.fireCallbacks(inputAction, sdli::CallType::OnRelease); } } perFrameCaptures.clear(); } float KeyboardInterface::getRange(InputAxis axis) { if(logicAnalogData.at(axis) == nullptr) { return ::sdli::RANGE_UNDEFINED; } return logicAnalogData.get(axis).currentStatus; } bool KeyboardInterface::isPressed(InputAction action) { if(captureBuffer.at(action) == nullptr) { return ::sdli::IS_PRESSED_UNDEFINED; } return ::sdli::isPressed(captureBuffer.get(action)); } bool KeyboardInterface::isReleased(InputAction action) { if(captureBuffer.at(action) == nullptr) { return ::sdli::IS_RELEASED_UNDEFINED; } return ::sdli::isReleased(captureBuffer.get(action)); } bool KeyboardInterface::isDown(InputAction action) { if(captureBuffer.at(action) == nullptr) { return ::sdli::IS_DOWN_UNDEFINED; } return ::sdli::isDown(captureBuffer.get(action)); } bool KeyboardInterface::isUp(InputAction action) { if(captureBuffer.at(action) == nullptr) { return ::sdli::IS_UP_UNDEFINED; } return ::sdli::isUp(captureBuffer.get(action)); } void KeyboardInterface::swap() { auto it = captureBuffer.dataBegin(); auto end = captureBuffer.dataEnd(); for(;it!=end;++it) { it->previousStatus = it->currentStatus; } auto pollIt = logicAnalogData.dataBegin(); auto pollEnd= logicAnalogData.dataEnd(); for(;pollIt!=pollEnd;++pollIt) { pollIt->currentStatus = 0.0f; } } } // sdli <commit_msg>Fixed multiple keys for a single action not correctly fetching events (isPressed)<commit_after>#include "keyboardinterface.h" #include <SDL2/SDL_keyboard.h> #include <SDL2/SDL_events.h> #include "context.h" namespace sdli { KeyboardInterface::KeyboardInterface(const int max_actions, const int max_axes) : logicAnalogData(max_axes), captureBuffer(max_actions) { } KeyboardInterface::~KeyboardInterface() { } void KeyboardInterface::poll(Context& ctx) { auto sdl_keystate = SDL_GetKeyboardState(NULL); auto& keymap = ctx.keyboardKeys(); auto& axisMap = ctx.axisMapping(); auto axisIt = axisMap.begin(); auto axisEnd = axisMap.end(); for(;axisIt!=axisEnd;++axisIt) { if(axisIt->idx.deviceType == SDL_Axis::Type::Keyboard) { auto data = axisIt->data; auto pollResult = 0.0f; auto neg = sdl_keystate[axisIt->idx.axis.rawNegative]; auto pos = sdl_keystate[axisIt->idx.axis.rawPositive]; if(neg == SDL_PRESSED) { pollResult -= 1.0f; } if(pos == SDL_PRESSED) { pollResult += 1.0f; } if(logicAnalogData.at(data->axis)==nullptr) { logicAnalogData.emplace(data->axis); } auto& currentStatus = logicAnalogData.get(data->axis).currentStatus; if(currentStatus!=0.0f) { currentStatus = sdli::clamp(currentStatus + pollResult, -1, 1) / data->normalize; } else { currentStatus = pollResult / data->normalize; } } } auto it = keymap.begin(); std::vector<unsigned int> polled(captureBuffer.size()); auto hasPolled = [](unsigned int id, std::vector<unsigned int>& v) { auto it = v.cbegin(); auto end = v.cend(); for(;it!=end;++it) { if(id == *it) return true; } return false; }; for(;it!=keymap.end();++it) { auto state = sdl_keystate[it->idx]; auto action = *(it->data); if(captureBuffer.at(action)==nullptr) { captureBuffer.emplace(action); } if(hasPolled(action, polled)) { captureBuffer.get(action).currentStatus |= state; } else { captureBuffer.get(action).previousStatus = captureBuffer.get(action).currentStatus; captureBuffer.get(action).currentStatus = state; polled.push_back(action); } } } void KeyboardInterface::push(unsigned int rawInput, int value) { perFrameCaptures.emplace_back(RawInputData{rawInput, value}); } void KeyboardInterface::dispatch(Context& ctx) { for(auto& raw : perFrameCaptures) { auto inputAction = ctx.keyAction(static_cast<SDL_Scancode>(raw.rawInput)); if(captureBuffer.at(inputAction) == nullptr) { captureBuffer.emplace(inputAction); } auto& logic = captureBuffer.get(inputAction); logic.currentStatus = raw.pollResult; if(::sdli::isPressed(logic)) { ctx.fireCallbacks(inputAction, sdli::CallType::OnPress); } if(::sdli::isReleased(logic)) { ctx.fireCallbacks(inputAction, sdli::CallType::OnRelease); } } perFrameCaptures.clear(); } float KeyboardInterface::getRange(InputAxis axis) { if(logicAnalogData.at(axis) == nullptr) { return ::sdli::RANGE_UNDEFINED; } return logicAnalogData.get(axis).currentStatus; } bool KeyboardInterface::isPressed(InputAction action) { if(captureBuffer.at(action) == nullptr) { return ::sdli::IS_PRESSED_UNDEFINED; } return ::sdli::isPressed(captureBuffer.get(action)); } bool KeyboardInterface::isReleased(InputAction action) { if(captureBuffer.at(action) == nullptr) { return ::sdli::IS_RELEASED_UNDEFINED; } return ::sdli::isReleased(captureBuffer.get(action)); } bool KeyboardInterface::isDown(InputAction action) { if(captureBuffer.at(action) == nullptr) { return ::sdli::IS_DOWN_UNDEFINED; } return ::sdli::isDown(captureBuffer.get(action)); } bool KeyboardInterface::isUp(InputAction action) { if(captureBuffer.at(action) == nullptr) { return ::sdli::IS_UP_UNDEFINED; } return ::sdli::isUp(captureBuffer.get(action)); } void KeyboardInterface::swap() { auto it = captureBuffer.dataBegin(); auto end = captureBuffer.dataEnd(); for(;it!=end;++it) { it->previousStatus = it->currentStatus; } auto pollIt = logicAnalogData.dataBegin(); auto pollEnd= logicAnalogData.dataEnd(); for(;pollIt!=pollEnd;++pollIt) { pollIt->currentStatus = 0.0f; } } } // sdli <|endoftext|>
<commit_before>#include "BinaryRRP.h" #include "Exception.h" #include "typedef.h" #include "tools.h" #include "Lzma.h" #include "ImageIDer.h" #include <json/json.h> #include <assert.h> #include <fstream> #include <algorithm> #include <dtex_rrp.h> namespace epbin { static const uint8_t TYPE = 11; BinaryRRP::BinaryRRP(const std::string& json_file, const std::string& img_id_file) { Load(json_file, img_id_file); } BinaryRRP::~BinaryRRP() { for (int i = 0, n = m_pics.size(); i < n; ++i) { Picture* pic = m_pics[i]; for (int j = 0, m = pic->parts.size(); j < m; ++j) { delete pic->parts[j]; } delete pic; } } void BinaryRRP::Pack(const std::string& outfile, bool compress) const { int32_t pic_sz = m_pics.size(); // data sz size_t data_sz = 0; data_sz += sizeof(int32_t); for (int i = 0; i < pic_sz; ++i) { data_sz += m_pics[i]->Size(); } // fill buffer uint8_t* data_buf = new uint8_t[data_sz]; uint8_t* ptr_data = data_buf; memcpy(ptr_data, &pic_sz, sizeof(pic_sz)); ptr_data += sizeof(pic_sz); for (int i = 0; i < pic_sz; ++i) { m_pics[i]->Store(&ptr_data); } assert(ptr_data - data_buf == data_sz); // final size_t sz = data_sz + sizeof(uint8_t) + sizeof(uint32_t); uint8_t* buf = new uint8_t[sz]; uint8_t* ptr = buf; memcpy(ptr, &TYPE, sizeof(uint8_t)); ptr += sizeof(uint8_t); int cap = dtex_rrp_size(data_buf, data_sz); memcpy(ptr, &cap, sizeof(uint32_t)); ptr += sizeof(uint32_t); memcpy(ptr, data_buf, data_sz); delete[] data_buf; // write to file std::ofstream fout(outfile.c_str(), std::ios::binary); if (compress) { uint8_t* dst = NULL; size_t dst_sz; Lzma::Compress(&dst, &dst_sz, buf, sz); fout.write(reinterpret_cast<const char*>(&dst_sz), sizeof(uint32_t)); fout.write(reinterpret_cast<const char*>(dst), dst_sz); } else { int _sz = -(int)sz; fout.write(reinterpret_cast<const char*>(&_sz), sizeof(int32_t)); fout.write(reinterpret_cast<const char*>(buf), sz); } delete[] buf; fout.close(); } void BinaryRRP::Load(const std::string& json_file, const std::string& img_id_file) { // load file Json::Value value; Json::Reader reader; std::locale::global(std::locale("")); std::ifstream fin(json_file.c_str()); std::locale::global(std::locale("C")); reader.parse(fin, value); fin.close(); // parser json std::vector<Part*> parts; int i = 0; Json::Value val = value["parts"][i++]; while (!val.isNull()) { std::string path = val["filepath"].asString(); Part* p = new Part; p->src.x = val["src"]["x"].asInt(); p->src.y = val["src"]["y"].asInt(); p->src.w = val["src"]["w"].asInt(); p->src.h = val["src"]["h"].asInt(); p->dst.x = val["dst"]["x"].asInt(); p->dst.y = val["dst"]["y"].asInt(); p->dst.w = val["dst"]["w"].asInt(); p->dst.h = val["dst"]["h"].asInt(); p->filepath = path; parts.push_back(p); val = value["parts"][i++]; } if (parts.empty()) { return; } // part to pictures std::sort(parts.begin(), parts.end(), PartCmp()); Picture* pic = new Picture; size_t ptr_s = parts[0]->filepath.find_last_of("\\")+1, ptr_e = parts[0]->filepath.find_first_of("#"); pic->path = parts[0]->filepath.substr(ptr_s, ptr_e - ptr_s); pic->parts.push_back(parts[0]); for (int i = 1, n = parts.size(); i < n; ++i) { Part* p = parts[i]; if (p->filepath.find(pic->path) != std::string::npos) { pic->parts.push_back(p); } else { m_pics.push_back(pic); pic = new Picture; size_t ptr_s = p->filepath.find_last_of("\\")+1, ptr_e = p->filepath.find_first_of("#"); pic->path = p->filepath.substr(ptr_s, ptr_e - ptr_s); std::transform(pic->path.begin(), pic->path.end(), pic->path.begin(), ::tolower); pic->parts.push_back(p); } } m_pics.push_back(pic); // set picture region for (int i = 0, n = m_pics.size(); i < n; ++i) { Picture* pic = m_pics[i]; int xmin = INT_MAX, ymin = INT_MAX, xmax = -INT_MAX, ymax = -INT_MAX; for (int j = 0, m = pic->parts.size(); j < m; ++j) { const Rect& r = pic->parts[j]->src; if (r.x < xmin) xmin = r.x; if (r.x+r.w > xmax) xmax = r.x+r.w; if (r.y < ymin) ymin = r.y; if (r.y+r.h > ymax) ymax = r.y+r.h; } pic->w = xmax - xmin; pic->h = ymax - ymin; } // set picture id ImageIDer ider(img_id_file); for (int i = 0, n = m_pics.size(); i < n; ++i) { m_pics[i]->id = ider.Query(pic->path); } } ////////////////////////////////////////////////////////////////////////// // struct BinaryRRP::Part ////////////////////////////////////////////////////////////////////////// size_t BinaryRRP::Part::Size() const { return sizeof(int16_t) * 6; } void BinaryRRP::Part::Store(uint8_t** ptr) { memcpy(*ptr, &src.x, sizeof(src.x)); *ptr += sizeof(src.x); memcpy(*ptr, &src.y, sizeof(src.y)); *ptr += sizeof(src.y); memcpy(*ptr, &dst.x, sizeof(dst.x)); *ptr += sizeof(dst.x); memcpy(*ptr, &dst.y, sizeof(dst.y)); *ptr += sizeof(dst.y); int16_t w = src.w, h = src.h; if (src.w != dst.w) { assert(src.w == dst.h); w = -w; h = -h; } memcpy(*ptr, &w, sizeof(w)); *ptr += sizeof(w); memcpy(*ptr, &h, sizeof(h)); *ptr += sizeof(h); } ////////////////////////////////////////////////////////////////////////// // struct BinaryRRP::Picture ////////////////////////////////////////////////////////////////////////// size_t BinaryRRP::Picture::Size() const { size_t sz = 0; sz += sizeof(int16_t) * 4; for (int i = 0, n = parts.size(); i < n; ++i) { sz += parts[i]->Size(); } return sz; } void BinaryRRP::Picture::Store(uint8_t** ptr) { memcpy(*ptr, &id, sizeof(id)); *ptr += sizeof(id); memcpy(*ptr, &w, sizeof(w)); *ptr += sizeof(w); memcpy(*ptr, &h, sizeof(h)); *ptr += sizeof(h); int16_t sz = parts.size(); memcpy(*ptr, &sz, sizeof(sz)); *ptr += sizeof(sz); for (int i = 0; i < sz; ++i) { parts[i]->Store(ptr); } } }<commit_msg>[FIXED] 打包rrp数据时y坐标转成向上<commit_after>#include "BinaryRRP.h" #include "Exception.h" #include "typedef.h" #include "tools.h" #include "Lzma.h" #include "ImageIDer.h" #include <json/json.h> #include <assert.h> #include <fstream> #include <algorithm> #include <dtex_rrp.h> namespace epbin { static const uint8_t TYPE = 11; BinaryRRP::BinaryRRP(const std::string& json_file, const std::string& img_id_file) { Load(json_file, img_id_file); } BinaryRRP::~BinaryRRP() { for (int i = 0, n = m_pics.size(); i < n; ++i) { Picture* pic = m_pics[i]; for (int j = 0, m = pic->parts.size(); j < m; ++j) { delete pic->parts[j]; } delete pic; } } void BinaryRRP::Pack(const std::string& outfile, bool compress) const { int32_t pic_sz = m_pics.size(); // data sz size_t data_sz = 0; data_sz += sizeof(int32_t); for (int i = 0; i < pic_sz; ++i) { data_sz += m_pics[i]->Size(); } // fill buffer uint8_t* data_buf = new uint8_t[data_sz]; uint8_t* ptr_data = data_buf; memcpy(ptr_data, &pic_sz, sizeof(pic_sz)); ptr_data += sizeof(pic_sz); for (int i = 0; i < pic_sz; ++i) { m_pics[i]->Store(&ptr_data); } assert(ptr_data - data_buf == data_sz); // final size_t sz = data_sz + sizeof(uint8_t) + sizeof(uint32_t); uint8_t* buf = new uint8_t[sz]; uint8_t* ptr = buf; memcpy(ptr, &TYPE, sizeof(uint8_t)); ptr += sizeof(uint8_t); int cap = dtex_rrp_size(data_buf, data_sz); memcpy(ptr, &cap, sizeof(uint32_t)); ptr += sizeof(uint32_t); memcpy(ptr, data_buf, data_sz); delete[] data_buf; // write to file std::ofstream fout(outfile.c_str(), std::ios::binary); if (compress) { uint8_t* dst = NULL; size_t dst_sz; Lzma::Compress(&dst, &dst_sz, buf, sz); fout.write(reinterpret_cast<const char*>(&dst_sz), sizeof(uint32_t)); fout.write(reinterpret_cast<const char*>(dst), dst_sz); } else { int _sz = -(int)sz; fout.write(reinterpret_cast<const char*>(&_sz), sizeof(int32_t)); fout.write(reinterpret_cast<const char*>(buf), sz); } delete[] buf; fout.close(); } void BinaryRRP::Load(const std::string& json_file, const std::string& img_id_file) { // load file Json::Value value; Json::Reader reader; std::locale::global(std::locale("")); std::ifstream fin(json_file.c_str()); std::locale::global(std::locale("C")); reader.parse(fin, value); fin.close(); // parser json int height = value["height"].asUInt(); std::vector<Part*> parts; int i = 0; Json::Value val = value["parts"][i++]; while (!val.isNull()) { std::string path = val["filepath"].asString(); Part* p = new Part; p->src.x = val["src"]["x"].asInt(); p->src.y = val["src"]["y"].asInt(); p->src.w = val["src"]["w"].asInt(); p->src.h = val["src"]["h"].asInt(); p->dst.x = val["dst"]["x"].asInt(); p->dst.y = val["dst"]["y"].asInt(); p->dst.w = val["dst"]["w"].asInt(); p->dst.h = val["dst"]["h"].asInt(); p->dst.y = height - (p->dst.y + p->dst.h); p->filepath = path; parts.push_back(p); val = value["parts"][i++]; } if (parts.empty()) { return; } // part to pictures std::sort(parts.begin(), parts.end(), PartCmp()); Picture* pic = new Picture; size_t ptr_s = parts[0]->filepath.find_last_of("\\")+1, ptr_e = parts[0]->filepath.find_first_of("#"); pic->path = parts[0]->filepath.substr(ptr_s, ptr_e - ptr_s); pic->parts.push_back(parts[0]); for (int i = 1, n = parts.size(); i < n; ++i) { Part* p = parts[i]; if (p->filepath.find(pic->path) != std::string::npos) { pic->parts.push_back(p); } else { m_pics.push_back(pic); pic = new Picture; size_t ptr_s = p->filepath.find_last_of("\\")+1, ptr_e = p->filepath.find_first_of("#"); pic->path = p->filepath.substr(ptr_s, ptr_e - ptr_s); std::transform(pic->path.begin(), pic->path.end(), pic->path.begin(), ::tolower); pic->parts.push_back(p); } } m_pics.push_back(pic); // set picture region for (int i = 0, n = m_pics.size(); i < n; ++i) { Picture* pic = m_pics[i]; int xmin = INT_MAX, ymin = INT_MAX, xmax = -INT_MAX, ymax = -INT_MAX; for (int j = 0, m = pic->parts.size(); j < m; ++j) { const Rect& r = pic->parts[j]->src; if (r.x < xmin) xmin = r.x; if (r.x+r.w > xmax) xmax = r.x+r.w; if (r.y < ymin) ymin = r.y; if (r.y+r.h > ymax) ymax = r.y+r.h; } pic->w = xmax - xmin; pic->h = ymax - ymin; } // set picture id ImageIDer ider(img_id_file); for (int i = 0, n = m_pics.size(); i < n; ++i) { m_pics[i]->id = ider.Query(pic->path); } } ////////////////////////////////////////////////////////////////////////// // struct BinaryRRP::Part ////////////////////////////////////////////////////////////////////////// size_t BinaryRRP::Part::Size() const { return sizeof(int16_t) * 6; } void BinaryRRP::Part::Store(uint8_t** ptr) { memcpy(*ptr, &src.x, sizeof(src.x)); *ptr += sizeof(src.x); memcpy(*ptr, &src.y, sizeof(src.y)); *ptr += sizeof(src.y); memcpy(*ptr, &dst.x, sizeof(dst.x)); *ptr += sizeof(dst.x); memcpy(*ptr, &dst.y, sizeof(dst.y)); *ptr += sizeof(dst.y); int16_t w = src.w, h = src.h; if (src.w != dst.w) { assert(src.w == dst.h); w = -w; h = -h; } memcpy(*ptr, &w, sizeof(w)); *ptr += sizeof(w); memcpy(*ptr, &h, sizeof(h)); *ptr += sizeof(h); } ////////////////////////////////////////////////////////////////////////// // struct BinaryRRP::Picture ////////////////////////////////////////////////////////////////////////// size_t BinaryRRP::Picture::Size() const { size_t sz = 0; sz += sizeof(int16_t) * 4; for (int i = 0, n = parts.size(); i < n; ++i) { sz += parts[i]->Size(); } return sz; } void BinaryRRP::Picture::Store(uint8_t** ptr) { memcpy(*ptr, &id, sizeof(id)); *ptr += sizeof(id); memcpy(*ptr, &w, sizeof(w)); *ptr += sizeof(w); memcpy(*ptr, &h, sizeof(h)); *ptr += sizeof(h); int16_t sz = parts.size(); memcpy(*ptr, &sz, sizeof(sz)); *ptr += sizeof(sz); for (int i = 0; i < sz; ++i) { parts[i]->Store(ptr); } } }<|endoftext|>
<commit_before>/*------------------------------------------------------------------------- * Vulkan Conformance Tests * ------------------------ * * Copyright (c) 2016 The Khronos Group Inc. * Copyright (c) 2016 Samsung Electronics Co., Ltd. * Copyright (c) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *//*! * \file * \brief Compressed texture tests. *//*--------------------------------------------------------------------*/ #include "vktTextureCompressedFormatTests.hpp" #include "deString.h" #include "deStringUtil.hpp" #include "tcuCompressedTexture.hpp" #include "tcuTexture.hpp" #include "tcuTextureUtil.hpp" #include "tcuAstcUtil.hpp" #include "vkImageUtil.hpp" #include "vktTestGroupUtil.hpp" #include "vktTextureTestUtil.hpp" #include <string> #include <vector> namespace vkt { namespace texture { namespace { using namespace vk; using namespace glu::TextureTestUtil; using namespace texture::util; using std::string; using std::vector; using tcu::Sampler; using tcu::TestLog; struct Compressed2DTestParameters : public Texture2DTestCaseParameters { Compressed2DTestParameters (void); TextureBinding::ImageBackingMode backingMode; }; Compressed2DTestParameters::Compressed2DTestParameters (void) : backingMode(TextureBinding::IMAGE_BACKING_MODE_REGULAR) { } class Compressed2DTestInstance : public TestInstance { public: typedef Compressed2DTestParameters ParameterType; Compressed2DTestInstance (Context& context, const ParameterType& testParameters); tcu::TestStatus iterate (void); private: Compressed2DTestInstance (const Compressed2DTestInstance& other); Compressed2DTestInstance& operator= (const Compressed2DTestInstance& other); const ParameterType& m_testParameters; const tcu::CompressedTexFormat m_compressedFormat; TestTexture2DSp m_texture; TextureRenderer m_renderer; }; Compressed2DTestInstance::Compressed2DTestInstance (Context& context, const ParameterType& testParameters) : TestInstance (context) , m_testParameters (testParameters) , m_compressedFormat (mapVkCompressedFormat(testParameters.format)) , m_texture (TestTexture2DSp(new pipeline::TestTexture2D(m_compressedFormat, testParameters.width, testParameters.height))) , m_renderer (context, testParameters.sampleCount, testParameters.width, testParameters.height) { m_renderer.add2DTexture(m_texture, testParameters.backingMode); } tcu::TestStatus Compressed2DTestInstance::iterate (void) { tcu::TestLog& log = m_context.getTestContext().getLog(); const pipeline::TestTexture2D& texture = m_renderer.get2DTexture(0); const tcu::TextureFormat textureFormat = texture.getTextureFormat(); const tcu::TextureFormatInfo formatInfo = tcu::getTextureFormatInfo(textureFormat); ReferenceParams sampleParams (TEXTURETYPE_2D); tcu::Surface rendered (m_renderer.getRenderWidth(), m_renderer.getRenderHeight()); vector<float> texCoord; // Setup params for reference. sampleParams.sampler = util::createSampler(m_testParameters.wrapS, m_testParameters.wrapT, m_testParameters.minFilter, m_testParameters.magFilter); sampleParams.samplerType = SAMPLERTYPE_FLOAT; sampleParams.lodMode = LODMODE_EXACT; if (isAstcFormat(m_compressedFormat)) { sampleParams.colorBias = tcu::Vec4(0.0f); sampleParams.colorScale = tcu::Vec4(1.0f); } else { sampleParams.colorBias = formatInfo.lookupBias; sampleParams.colorScale = formatInfo.lookupScale; } log << TestLog::Message << "Compare reference value = " << sampleParams.ref << TestLog::EndMessage; // Compute texture coordinates. computeQuadTexCoord2D(texCoord, tcu::Vec2(0.0f, 0.0f), tcu::Vec2(1.0f, 1.0f)); m_renderer.renderQuad(rendered, 0, &texCoord[0], sampleParams); // Compute reference. const tcu::IVec4 formatBitDepth = getTextureFormatBitDepth(vk::mapVkFormat(VK_FORMAT_R8G8B8A8_UNORM)); const tcu::PixelFormat pixelFormat (formatBitDepth[0], formatBitDepth[1], formatBitDepth[2], formatBitDepth[3]); tcu::Surface referenceFrame (m_renderer.getRenderWidth(), m_renderer.getRenderHeight()); sampleTexture(tcu::SurfaceAccess(referenceFrame, pixelFormat), m_texture->getTexture(), &texCoord[0], sampleParams); // Compare and log. tcu::RGBA threshold; if (isBcBitExactFormat(m_compressedFormat)) threshold = tcu::RGBA(1, 1, 1, 1); else if (isBcFormat(m_compressedFormat)) threshold = tcu::RGBA(8, 8, 8, 8); else threshold = pixelFormat.getColorThreshold() + tcu::RGBA(2, 2, 2, 2); const bool isOk = compareImages(log, referenceFrame, rendered, threshold); return isOk ? tcu::TestStatus::pass("Pass") : tcu::TestStatus::fail("Image verification failed"); } void populateTextureCompressedFormatTests (tcu::TestCaseGroup* compressedTextureTests) { tcu::TestContext& testCtx = compressedTextureTests->getTestContext(); // ETC2 and EAC compressed formats. static const struct { const VkFormat format; } formats[] = { { VK_FORMAT_ETC2_R8G8B8_UNORM_BLOCK }, { VK_FORMAT_ETC2_R8G8B8_SRGB_BLOCK }, { VK_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK }, { VK_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK }, { VK_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK }, { VK_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK }, { VK_FORMAT_EAC_R11_UNORM_BLOCK }, { VK_FORMAT_EAC_R11_SNORM_BLOCK }, { VK_FORMAT_EAC_R11G11_UNORM_BLOCK }, { VK_FORMAT_EAC_R11G11_SNORM_BLOCK }, { VK_FORMAT_ASTC_4x4_UNORM_BLOCK }, { VK_FORMAT_ASTC_4x4_SRGB_BLOCK }, { VK_FORMAT_ASTC_5x4_UNORM_BLOCK }, { VK_FORMAT_ASTC_5x4_SRGB_BLOCK }, { VK_FORMAT_ASTC_5x5_UNORM_BLOCK }, { VK_FORMAT_ASTC_5x5_SRGB_BLOCK }, { VK_FORMAT_ASTC_6x5_UNORM_BLOCK }, { VK_FORMAT_ASTC_6x5_SRGB_BLOCK }, { VK_FORMAT_ASTC_6x6_UNORM_BLOCK }, { VK_FORMAT_ASTC_6x6_SRGB_BLOCK }, { VK_FORMAT_ASTC_8x5_UNORM_BLOCK }, { VK_FORMAT_ASTC_8x5_SRGB_BLOCK }, { VK_FORMAT_ASTC_8x6_UNORM_BLOCK }, { VK_FORMAT_ASTC_8x6_SRGB_BLOCK }, { VK_FORMAT_ASTC_8x8_UNORM_BLOCK }, { VK_FORMAT_ASTC_8x8_SRGB_BLOCK }, { VK_FORMAT_ASTC_10x5_UNORM_BLOCK }, { VK_FORMAT_ASTC_10x5_SRGB_BLOCK }, { VK_FORMAT_ASTC_10x6_UNORM_BLOCK }, { VK_FORMAT_ASTC_10x6_SRGB_BLOCK }, { VK_FORMAT_ASTC_10x8_UNORM_BLOCK }, { VK_FORMAT_ASTC_10x8_SRGB_BLOCK }, { VK_FORMAT_ASTC_10x10_UNORM_BLOCK }, { VK_FORMAT_ASTC_10x10_SRGB_BLOCK }, { VK_FORMAT_ASTC_12x10_UNORM_BLOCK }, { VK_FORMAT_ASTC_12x10_SRGB_BLOCK }, { VK_FORMAT_ASTC_12x12_UNORM_BLOCK }, { VK_FORMAT_ASTC_12x12_SRGB_BLOCK }, { VK_FORMAT_BC1_RGB_UNORM_BLOCK }, { VK_FORMAT_BC1_RGB_SRGB_BLOCK }, { VK_FORMAT_BC1_RGBA_UNORM_BLOCK }, { VK_FORMAT_BC1_RGBA_SRGB_BLOCK }, { VK_FORMAT_BC2_UNORM_BLOCK }, { VK_FORMAT_BC2_SRGB_BLOCK }, { VK_FORMAT_BC3_UNORM_BLOCK }, { VK_FORMAT_BC3_SRGB_BLOCK }, { VK_FORMAT_BC4_UNORM_BLOCK }, { VK_FORMAT_BC4_SNORM_BLOCK }, { VK_FORMAT_BC5_UNORM_BLOCK }, { VK_FORMAT_BC5_SNORM_BLOCK }, { VK_FORMAT_BC6H_UFLOAT_BLOCK }, { VK_FORMAT_BC6H_SFLOAT_BLOCK }, { VK_FORMAT_BC7_UNORM_BLOCK }, { VK_FORMAT_BC7_SRGB_BLOCK } }; static const struct { const int width; const int height; const char* name; } sizes[] = { { 128, 64, "pot" }, { 51, 65, "npot" }, }; static const struct { const char* name; const TextureBinding::ImageBackingMode backingMode; } backingModes[] = { { "", TextureBinding::IMAGE_BACKING_MODE_REGULAR }, { "_sparse", TextureBinding::IMAGE_BACKING_MODE_SPARSE } }; for (int sizeNdx = 0; sizeNdx < DE_LENGTH_OF_ARRAY(sizes); sizeNdx++) for (int formatNdx = 0; formatNdx < DE_LENGTH_OF_ARRAY(formats); formatNdx++) for (int backingNdx = 0; backingNdx < DE_LENGTH_OF_ARRAY(backingModes); backingNdx++) { const string formatStr = de::toString(getFormatStr(formats[formatNdx].format)); const string nameBase = de::toLower(formatStr.substr(10)); Compressed2DTestParameters testParameters; testParameters.format = formats[formatNdx].format; testParameters.backingMode = backingModes[backingNdx].backingMode; testParameters.width = sizes[sizeNdx].width; testParameters.height = sizes[sizeNdx].height; testParameters.minFilter = tcu::Sampler::NEAREST; testParameters.magFilter = tcu::Sampler::NEAREST; testParameters.programs.push_back(PROGRAM_2D_FLOAT); compressedTextureTests->addChild(new TextureTestCase<Compressed2DTestInstance>(testCtx, (nameBase + "_2d_" + sizes[sizeNdx].name + backingModes[backingNdx].name).c_str(), (formatStr + ", TEXTURETYPE_2D").c_str(), testParameters)); } } } // anonymous tcu::TestCaseGroup* createTextureCompressedFormatTests (tcu::TestContext& testCtx) { return createTestGroup(testCtx, "compressed", "Texture compressed format tests.", populateTextureCompressedFormatTests); } } // texture } // vkt <commit_msg>Fixed color bias and scale for BC4-5 tests<commit_after>/*------------------------------------------------------------------------- * Vulkan Conformance Tests * ------------------------ * * Copyright (c) 2016 The Khronos Group Inc. * Copyright (c) 2016 Samsung Electronics Co., Ltd. * Copyright (c) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *//*! * \file * \brief Compressed texture tests. *//*--------------------------------------------------------------------*/ #include "vktTextureCompressedFormatTests.hpp" #include "deString.h" #include "deStringUtil.hpp" #include "tcuCompressedTexture.hpp" #include "tcuTexture.hpp" #include "tcuTextureUtil.hpp" #include "tcuAstcUtil.hpp" #include "vkImageUtil.hpp" #include "vktTestGroupUtil.hpp" #include "vktTextureTestUtil.hpp" #include <string> #include <vector> namespace vkt { namespace texture { namespace { using namespace vk; using namespace glu::TextureTestUtil; using namespace texture::util; using std::string; using std::vector; using tcu::Sampler; using tcu::TestLog; struct Compressed2DTestParameters : public Texture2DTestCaseParameters { Compressed2DTestParameters (void); TextureBinding::ImageBackingMode backingMode; }; Compressed2DTestParameters::Compressed2DTestParameters (void) : backingMode(TextureBinding::IMAGE_BACKING_MODE_REGULAR) { } class Compressed2DTestInstance : public TestInstance { public: typedef Compressed2DTestParameters ParameterType; Compressed2DTestInstance (Context& context, const ParameterType& testParameters); tcu::TestStatus iterate (void); private: Compressed2DTestInstance (const Compressed2DTestInstance& other); Compressed2DTestInstance& operator= (const Compressed2DTestInstance& other); const ParameterType& m_testParameters; const tcu::CompressedTexFormat m_compressedFormat; TestTexture2DSp m_texture; TextureRenderer m_renderer; }; Compressed2DTestInstance::Compressed2DTestInstance (Context& context, const ParameterType& testParameters) : TestInstance (context) , m_testParameters (testParameters) , m_compressedFormat (mapVkCompressedFormat(testParameters.format)) , m_texture (TestTexture2DSp(new pipeline::TestTexture2D(m_compressedFormat, testParameters.width, testParameters.height))) , m_renderer (context, testParameters.sampleCount, testParameters.width, testParameters.height) { m_renderer.add2DTexture(m_texture, testParameters.backingMode); } tcu::TestStatus Compressed2DTestInstance::iterate (void) { tcu::TestLog& log = m_context.getTestContext().getLog(); const pipeline::TestTexture2D& texture = m_renderer.get2DTexture(0); const tcu::TextureFormat textureFormat = texture.getTextureFormat(); const tcu::TextureFormatInfo formatInfo = tcu::getTextureFormatInfo(textureFormat); ReferenceParams sampleParams (TEXTURETYPE_2D); tcu::Surface rendered (m_renderer.getRenderWidth(), m_renderer.getRenderHeight()); vector<float> texCoord; // Setup params for reference. sampleParams.sampler = util::createSampler(m_testParameters.wrapS, m_testParameters.wrapT, m_testParameters.minFilter, m_testParameters.magFilter); sampleParams.samplerType = SAMPLERTYPE_FLOAT; sampleParams.lodMode = LODMODE_EXACT; if (isAstcFormat(m_compressedFormat) || m_compressedFormat == tcu::COMPRESSEDTEXFORMAT_BC4_UNORM_BLOCK || m_compressedFormat == tcu::COMPRESSEDTEXFORMAT_BC5_UNORM_BLOCK) { sampleParams.colorBias = tcu::Vec4(0.0f); sampleParams.colorScale = tcu::Vec4(1.0f); } else if (m_compressedFormat == tcu::COMPRESSEDTEXFORMAT_BC4_SNORM_BLOCK) { sampleParams.colorBias = tcu::Vec4(0.5f, 0.0f, 0.0f, 0.0f); sampleParams.colorScale = tcu::Vec4(0.5f, 1.0f, 1.0f, 1.0f); } else if (m_compressedFormat == tcu::COMPRESSEDTEXFORMAT_BC5_SNORM_BLOCK) { sampleParams.colorBias = tcu::Vec4(0.5f, 0.5f, 0.0f, 0.0f); sampleParams.colorScale = tcu::Vec4(0.5f, 0.5f, 1.0f, 1.0f); } else { sampleParams.colorBias = formatInfo.lookupBias; sampleParams.colorScale = formatInfo.lookupScale; } log << TestLog::Message << "Compare reference value = " << sampleParams.ref << TestLog::EndMessage; // Compute texture coordinates. computeQuadTexCoord2D(texCoord, tcu::Vec2(0.0f, 0.0f), tcu::Vec2(1.0f, 1.0f)); m_renderer.renderQuad(rendered, 0, &texCoord[0], sampleParams); // Compute reference. const tcu::IVec4 formatBitDepth = getTextureFormatBitDepth(vk::mapVkFormat(VK_FORMAT_R8G8B8A8_UNORM)); const tcu::PixelFormat pixelFormat (formatBitDepth[0], formatBitDepth[1], formatBitDepth[2], formatBitDepth[3]); tcu::Surface referenceFrame (m_renderer.getRenderWidth(), m_renderer.getRenderHeight()); sampleTexture(tcu::SurfaceAccess(referenceFrame, pixelFormat), m_texture->getTexture(), &texCoord[0], sampleParams); // Compare and log. tcu::RGBA threshold; if (isBcBitExactFormat(m_compressedFormat)) threshold = tcu::RGBA(1, 1, 1, 1); else if (isBcFormat(m_compressedFormat)) threshold = tcu::RGBA(8, 8, 8, 8); else threshold = pixelFormat.getColorThreshold() + tcu::RGBA(2, 2, 2, 2); const bool isOk = compareImages(log, referenceFrame, rendered, threshold); return isOk ? tcu::TestStatus::pass("Pass") : tcu::TestStatus::fail("Image verification failed"); } void populateTextureCompressedFormatTests (tcu::TestCaseGroup* compressedTextureTests) { tcu::TestContext& testCtx = compressedTextureTests->getTestContext(); // ETC2 and EAC compressed formats. static const struct { const VkFormat format; } formats[] = { { VK_FORMAT_ETC2_R8G8B8_UNORM_BLOCK }, { VK_FORMAT_ETC2_R8G8B8_SRGB_BLOCK }, { VK_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK }, { VK_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK }, { VK_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK }, { VK_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK }, { VK_FORMAT_EAC_R11_UNORM_BLOCK }, { VK_FORMAT_EAC_R11_SNORM_BLOCK }, { VK_FORMAT_EAC_R11G11_UNORM_BLOCK }, { VK_FORMAT_EAC_R11G11_SNORM_BLOCK }, { VK_FORMAT_ASTC_4x4_UNORM_BLOCK }, { VK_FORMAT_ASTC_4x4_SRGB_BLOCK }, { VK_FORMAT_ASTC_5x4_UNORM_BLOCK }, { VK_FORMAT_ASTC_5x4_SRGB_BLOCK }, { VK_FORMAT_ASTC_5x5_UNORM_BLOCK }, { VK_FORMAT_ASTC_5x5_SRGB_BLOCK }, { VK_FORMAT_ASTC_6x5_UNORM_BLOCK }, { VK_FORMAT_ASTC_6x5_SRGB_BLOCK }, { VK_FORMAT_ASTC_6x6_UNORM_BLOCK }, { VK_FORMAT_ASTC_6x6_SRGB_BLOCK }, { VK_FORMAT_ASTC_8x5_UNORM_BLOCK }, { VK_FORMAT_ASTC_8x5_SRGB_BLOCK }, { VK_FORMAT_ASTC_8x6_UNORM_BLOCK }, { VK_FORMAT_ASTC_8x6_SRGB_BLOCK }, { VK_FORMAT_ASTC_8x8_UNORM_BLOCK }, { VK_FORMAT_ASTC_8x8_SRGB_BLOCK }, { VK_FORMAT_ASTC_10x5_UNORM_BLOCK }, { VK_FORMAT_ASTC_10x5_SRGB_BLOCK }, { VK_FORMAT_ASTC_10x6_UNORM_BLOCK }, { VK_FORMAT_ASTC_10x6_SRGB_BLOCK }, { VK_FORMAT_ASTC_10x8_UNORM_BLOCK }, { VK_FORMAT_ASTC_10x8_SRGB_BLOCK }, { VK_FORMAT_ASTC_10x10_UNORM_BLOCK }, { VK_FORMAT_ASTC_10x10_SRGB_BLOCK }, { VK_FORMAT_ASTC_12x10_UNORM_BLOCK }, { VK_FORMAT_ASTC_12x10_SRGB_BLOCK }, { VK_FORMAT_ASTC_12x12_UNORM_BLOCK }, { VK_FORMAT_ASTC_12x12_SRGB_BLOCK }, { VK_FORMAT_BC1_RGB_UNORM_BLOCK }, { VK_FORMAT_BC1_RGB_SRGB_BLOCK }, { VK_FORMAT_BC1_RGBA_UNORM_BLOCK }, { VK_FORMAT_BC1_RGBA_SRGB_BLOCK }, { VK_FORMAT_BC2_UNORM_BLOCK }, { VK_FORMAT_BC2_SRGB_BLOCK }, { VK_FORMAT_BC3_UNORM_BLOCK }, { VK_FORMAT_BC3_SRGB_BLOCK }, { VK_FORMAT_BC4_UNORM_BLOCK }, { VK_FORMAT_BC4_SNORM_BLOCK }, { VK_FORMAT_BC5_UNORM_BLOCK }, { VK_FORMAT_BC5_SNORM_BLOCK }, { VK_FORMAT_BC6H_UFLOAT_BLOCK }, { VK_FORMAT_BC6H_SFLOAT_BLOCK }, { VK_FORMAT_BC7_UNORM_BLOCK }, { VK_FORMAT_BC7_SRGB_BLOCK } }; static const struct { const int width; const int height; const char* name; } sizes[] = { { 128, 64, "pot" }, { 51, 65, "npot" }, }; static const struct { const char* name; const TextureBinding::ImageBackingMode backingMode; } backingModes[] = { { "", TextureBinding::IMAGE_BACKING_MODE_REGULAR }, { "_sparse", TextureBinding::IMAGE_BACKING_MODE_SPARSE } }; for (int sizeNdx = 0; sizeNdx < DE_LENGTH_OF_ARRAY(sizes); sizeNdx++) for (int formatNdx = 0; formatNdx < DE_LENGTH_OF_ARRAY(formats); formatNdx++) for (int backingNdx = 0; backingNdx < DE_LENGTH_OF_ARRAY(backingModes); backingNdx++) { const string formatStr = de::toString(getFormatStr(formats[formatNdx].format)); const string nameBase = de::toLower(formatStr.substr(10)); Compressed2DTestParameters testParameters; testParameters.format = formats[formatNdx].format; testParameters.backingMode = backingModes[backingNdx].backingMode; testParameters.width = sizes[sizeNdx].width; testParameters.height = sizes[sizeNdx].height; testParameters.minFilter = tcu::Sampler::NEAREST; testParameters.magFilter = tcu::Sampler::NEAREST; testParameters.programs.push_back(PROGRAM_2D_FLOAT); compressedTextureTests->addChild(new TextureTestCase<Compressed2DTestInstance>(testCtx, (nameBase + "_2d_" + sizes[sizeNdx].name + backingModes[backingNdx].name).c_str(), (formatStr + ", TEXTURETYPE_2D").c_str(), testParameters)); } } } // anonymous tcu::TestCaseGroup* createTextureCompressedFormatTests (tcu::TestContext& testCtx) { return createTestGroup(testCtx, "compressed", "Texture compressed format tests.", populateTextureCompressedFormatTests); } } // texture } // vkt <|endoftext|>
<commit_before>// For conditions of distribution and use, see copyright notice in license.txt #include "StableHeaders.h" #include "DebugOperatorNew.h" #include "NaaliApplication.h" #include "Framework.h" #include "ConfigurationManager.h" #include <QDir> #include <QGraphicsView> #include <QTranslator> #include <QLocale> #include <QIcon> #include <QWebSettings> #include "MemoryLeakCheck.h" namespace Foundation { NaaliApplication::NaaliApplication(Framework *framework, int &argc, char **argv) : QApplication(argc, argv), framework_(framework), app_activated_(true), native_translator_(new QTranslator), app_translator_(new QTranslator)//, // main_window_(new MainWindow(framework_)) { QApplication::setApplicationName("realXtend-Naali"); #ifdef Q_WS_WIN // If under windows, add run_dir/plugins as library path // unix users will get plugins from their OS Qt installation folder automatically QString run_directory = applicationDirPath(); run_directory += "/qtplugins"; addLibraryPath(run_directory); #endif QDir dir("data/translations/qt_native_translations"); QStringList qmFiles = GetQmFiles(dir); // Search then that is there corresponding native translations for system locals. QString loc = QLocale::system().name(); loc.chop(3); QString name = "data/translations/qt_native_translations/qt_" + loc + ".qm"; QStringList lst = qmFiles.filter(name); if (!lst.empty() ) native_translator_->load(lst[0]); this->installTranslator(native_translator_); std::string default_language = framework_->GetConfigManager()->DeclareSetting(Framework::ConfigurationGroup(), "language", std::string("data/translations/naali_en")); ChangeLanguage(QString::fromStdString(default_language)); QWebSettings::globalSettings()->setAttribute(QWebSettings::PluginsEnabled, true); //enablig flash } NaaliApplication::~NaaliApplication() { // view_.reset(); SAFE_DELETE(native_translator_); SAFE_DELETE(app_translator_); // SAFE_DELETE(main_window_); } /* QGraphicsView *NaaliApplication::GetUIView() const { return view_.get(); } void NaaliApplication::SetUIView(std::auto_ptr <QGraphicsView> view) { view_ = view; } MainWindow *NaaliApplication::GetMainWindow() const { return main_window_; } */ QStringList NaaliApplication::GetQmFiles(const QDir& dir) { QStringList fileNames = dir.entryList(QStringList("*.qm"), QDir::Files, QDir::Name); QMutableStringListIterator i(fileNames); while (i.hasNext()) { i.next(); i.setValue(dir.filePath(i.value())); } return fileNames; } void NaaliApplication::Go() { installEventFilter(this); QObject::connect(&frame_update_timer_, SIGNAL(timeout()), this, SLOT(UpdateFrame())); frame_update_timer_.setSingleShot (true); frame_update_timer_.start (0); try { exec (); } catch(const std::exception &e) { RootLogCritical(std::string("NaaliApplication::Go caught an exception: ") + (e.what() ? e.what() : "(null)")); throw; } catch(...) { RootLogCritical(std::string("NaaliApplication::Go caught an unknown exception!")); throw; } } bool NaaliApplication::eventFilter(QObject *obj, QEvent *event) { try { if (obj == this) { if (event->type() == QEvent::ApplicationActivate) app_activated_ = true; if (event->type() == QEvent::ApplicationDeactivate) app_activated_ = false; /* if (event->type() == QEvent::LanguageChange) { // Now if exist remove our default translation engine. if (translator_ != 0) this->removeTranslator(translator_); } */ } return QObject::eventFilter(obj, event); } catch(const std::exception &e) { std::cout << std::string("QApp::eventFilter caught an exception: ") + (e.what() ? e.what() : "(null)") << std::endl; RootLogCritical(std::string("QApp::eventFilter caught an exception: ") + (e.what() ? e.what() : "(null)")); throw; } catch(...) { std::cout << std::string("QApp::eventFilter caught an unknown exception!") << std::endl; RootLogCritical(std::string("QApp::eventFilter caught an unknown exception!")); throw; } return true; } void NaaliApplication::ChangeLanguage(const QString& file) { QString filename = file; if (!filename.endsWith(".qm", Qt::CaseInsensitive)) filename.append(".qm"); QString tmp = filename; tmp.chop(3); QString str = tmp.right(2); QString name = "data/translations/qt_native_translations/qt_" + str + ".qm"; // Remove old translators then change them to new. removeTranslator(native_translator_); if ( QFile::exists(name) ) { if ( native_translator_ != 0) { native_translator_->load(name); installTranslator(native_translator_); } } else { if (native_translator_ != 0 && native_translator_->isEmpty()) { installTranslator(native_translator_); } else { SAFE_DELETE(native_translator_); native_translator_ = new QTranslator; installTranslator(native_translator_); } } // Remove old translators then change them to new. removeTranslator(app_translator_); if (app_translator_->load(filename)) { installTranslator(app_translator_); framework_->GetConfigManager()->SetSetting(Framework::ConfigurationGroup(), "language", file.toStdString()); } emit LanguageChanged(); } bool NaaliApplication::notify(QObject *receiver, QEvent *event) { try { return QApplication::notify(receiver, event); } catch(const std::exception &e) { std::cout << std::string("QApp::notify caught an exception: ") << (e.what() ? e.what() : "(null)") << std::endl; RootLogCritical(std::string("QApp::notify caught an exception: ") + (e.what() ? e.what() : "(null)")); throw; } catch(...) { std::cout << std::string("QApp::notify caught an unknown exception!") << std::endl; RootLogCritical(std::string("QApp::notify caught an unknown exception!")); throw; } return true; } void NaaliApplication::UpdateFrame() { try { QApplication::processEvents (QEventLoop::AllEvents, 1); QApplication::sendPostedEvents (); framework_-> ProcessOneFrame(); // Reduce framerate when unfocused if (app_activated_) frame_update_timer_.start(0); else frame_update_timer_.start(5); } catch(const std::exception &e) { std::cout << "QApp::UpdateFrame caught an exception: " << (e.what() ? e.what() : "(null)") << std::endl; RootLogCritical(std::string("QApp::UpdateFrame caught an exception: ") + (e.what() ? e.what() : "(null)")); throw; } catch(...) { std::cout << "QApp::UpdateFrame caught an unknown exception!" << std::endl; RootLogCritical(std::string("QApp::UpdateFrame caught an unknown exception!")); throw; } } void NaaliApplication::AboutToExit() { emit ExitRequested(); // If no-one canceled the exit as a response to the signal, exit if (framework_->IsExiting()) quit(); } } <commit_msg>Make possible to run naali from another directories.<commit_after>// For conditions of distribution and use, see copyright notice in license.txt #include "StableHeaders.h" #include "DebugOperatorNew.h" #include "NaaliApplication.h" #include "Framework.h" #include "ConfigurationManager.h" #include <QDir> #include <QGraphicsView> #include <QTranslator> #include <QLocale> #include <QIcon> #include <QWebSettings> #include "MemoryLeakCheck.h" namespace Foundation { NaaliApplication::NaaliApplication(Framework *framework, int &argc, char **argv) : QApplication(argc, argv), framework_(framework), app_activated_(true), native_translator_(new QTranslator), app_translator_(new QTranslator)//, // main_window_(new MainWindow(framework_)) { QApplication::setApplicationName("realXtend-Naali"); #ifdef Q_WS_WIN // On Windows the current directory have to be the application installation directory QDir::setCurrent(applicationDirPath()); // If under windows, add run_dir/plugins as library path // unix users will get plugins from their OS Qt installation folder automatically QString run_directory = applicationDirPath(); run_directory += "/qtplugins"; addLibraryPath(run_directory); #endif QDir dir("data/translations/qt_native_translations"); QStringList qmFiles = GetQmFiles(dir); // Search then that is there corresponding native translations for system locals. QString loc = QLocale::system().name(); loc.chop(3); QString name = "data/translations/qt_native_translations/qt_" + loc + ".qm"; QStringList lst = qmFiles.filter(name); if (!lst.empty() ) native_translator_->load(lst[0]); this->installTranslator(native_translator_); std::string default_language = framework_->GetConfigManager()->DeclareSetting(Framework::ConfigurationGroup(), "language", std::string("data/translations/naali_en")); ChangeLanguage(QString::fromStdString(default_language)); QWebSettings::globalSettings()->setAttribute(QWebSettings::PluginsEnabled, true); //enablig flash } NaaliApplication::~NaaliApplication() { // view_.reset(); SAFE_DELETE(native_translator_); SAFE_DELETE(app_translator_); // SAFE_DELETE(main_window_); } /* QGraphicsView *NaaliApplication::GetUIView() const { return view_.get(); } void NaaliApplication::SetUIView(std::auto_ptr <QGraphicsView> view) { view_ = view; } MainWindow *NaaliApplication::GetMainWindow() const { return main_window_; } */ QStringList NaaliApplication::GetQmFiles(const QDir& dir) { QStringList fileNames = dir.entryList(QStringList("*.qm"), QDir::Files, QDir::Name); QMutableStringListIterator i(fileNames); while (i.hasNext()) { i.next(); i.setValue(dir.filePath(i.value())); } return fileNames; } void NaaliApplication::Go() { installEventFilter(this); QObject::connect(&frame_update_timer_, SIGNAL(timeout()), this, SLOT(UpdateFrame())); frame_update_timer_.setSingleShot (true); frame_update_timer_.start (0); try { exec (); } catch(const std::exception &e) { RootLogCritical(std::string("NaaliApplication::Go caught an exception: ") + (e.what() ? e.what() : "(null)")); throw; } catch(...) { RootLogCritical(std::string("NaaliApplication::Go caught an unknown exception!")); throw; } } bool NaaliApplication::eventFilter(QObject *obj, QEvent *event) { try { if (obj == this) { if (event->type() == QEvent::ApplicationActivate) app_activated_ = true; if (event->type() == QEvent::ApplicationDeactivate) app_activated_ = false; /* if (event->type() == QEvent::LanguageChange) { // Now if exist remove our default translation engine. if (translator_ != 0) this->removeTranslator(translator_); } */ } return QObject::eventFilter(obj, event); } catch(const std::exception &e) { std::cout << std::string("QApp::eventFilter caught an exception: ") + (e.what() ? e.what() : "(null)") << std::endl; RootLogCritical(std::string("QApp::eventFilter caught an exception: ") + (e.what() ? e.what() : "(null)")); throw; } catch(...) { std::cout << std::string("QApp::eventFilter caught an unknown exception!") << std::endl; RootLogCritical(std::string("QApp::eventFilter caught an unknown exception!")); throw; } return true; } void NaaliApplication::ChangeLanguage(const QString& file) { QString filename = file; if (!filename.endsWith(".qm", Qt::CaseInsensitive)) filename.append(".qm"); QString tmp = filename; tmp.chop(3); QString str = tmp.right(2); QString name = "data/translations/qt_native_translations/qt_" + str + ".qm"; // Remove old translators then change them to new. removeTranslator(native_translator_); if ( QFile::exists(name) ) { if ( native_translator_ != 0) { native_translator_->load(name); installTranslator(native_translator_); } } else { if (native_translator_ != 0 && native_translator_->isEmpty()) { installTranslator(native_translator_); } else { SAFE_DELETE(native_translator_); native_translator_ = new QTranslator; installTranslator(native_translator_); } } // Remove old translators then change them to new. removeTranslator(app_translator_); if (app_translator_->load(filename)) { installTranslator(app_translator_); framework_->GetConfigManager()->SetSetting(Framework::ConfigurationGroup(), "language", file.toStdString()); } emit LanguageChanged(); } bool NaaliApplication::notify(QObject *receiver, QEvent *event) { try { return QApplication::notify(receiver, event); } catch(const std::exception &e) { std::cout << std::string("QApp::notify caught an exception: ") << (e.what() ? e.what() : "(null)") << std::endl; RootLogCritical(std::string("QApp::notify caught an exception: ") + (e.what() ? e.what() : "(null)")); throw; } catch(...) { std::cout << std::string("QApp::notify caught an unknown exception!") << std::endl; RootLogCritical(std::string("QApp::notify caught an unknown exception!")); throw; } return true; } void NaaliApplication::UpdateFrame() { try { QApplication::processEvents (QEventLoop::AllEvents, 1); QApplication::sendPostedEvents (); framework_-> ProcessOneFrame(); // Reduce framerate when unfocused if (app_activated_) frame_update_timer_.start(0); else frame_update_timer_.start(5); } catch(const std::exception &e) { std::cout << "QApp::UpdateFrame caught an exception: " << (e.what() ? e.what() : "(null)") << std::endl; RootLogCritical(std::string("QApp::UpdateFrame caught an exception: ") + (e.what() ? e.what() : "(null)")); throw; } catch(...) { std::cout << "QApp::UpdateFrame caught an unknown exception!" << std::endl; RootLogCritical(std::string("QApp::UpdateFrame caught an unknown exception!")); throw; } } void NaaliApplication::AboutToExit() { emit ExitRequested(); // If no-one canceled the exit as a response to the signal, exit if (framework_->IsExiting()) quit(); } } <|endoftext|>
<commit_before>#pragma once #include "logger.hpp" namespace blackhole { class scoped_attributes_t : public scoped_attributes_concept_t { // Attributes provided by this guard. mutable log::attributes_t m_guard_attributes; // Merged attributes are provided by this guard and all the parent guards. // This value is computed lazily. mutable log::attributes_t m_merged_attributes; public: scoped_attributes_t(logger_base_t& logger, log::attributes_t&& attributes) : scoped_attributes_concept_t(logger), m_guard_attributes(std::move(attributes)) { } virtual const log::attributes_t& attributes() const { if (m_merged_attributes.empty()) { m_merged_attributes = std::move(m_guard_attributes); if (has_parent()) { const auto &parent_attributes = parent().attributes(); m_merged_attributes.insert(parent_attributes.begin(), parent_attributes.end()); } } return m_merged_attributes; } }; } // namespace blackhole <commit_msg>[Code Style] Now it's time for scoped attributes.<commit_after>#pragma once #include "logger.hpp" namespace blackhole { class scoped_attributes_t : public scoped_attributes_concept_t { // Attributes provided by this guard. mutable log::attributes_t m_guard_attributes; // Merged attributes are provided by this guard and all the parent guards. // This value is computed lazily. mutable log::attributes_t m_merged_attributes; public: scoped_attributes_t(logger_base_t& logger, log::attributes_t&& attributes) : scoped_attributes_concept_t(logger), m_guard_attributes(std::move(attributes)) {} virtual const log::attributes_t& attributes() const { if (m_merged_attributes.empty()) { m_merged_attributes = std::move(m_guard_attributes); if (has_parent()) { const auto& parent_attributes = parent().attributes(); m_merged_attributes.insert(parent_attributes.begin(), parent_attributes.end()); } } return m_merged_attributes; } }; } // namespace blackhole <|endoftext|>
<commit_before>/* * Copyright(c) 2021 Intel Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this software except as stipulated in 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. */ #ifdef __cplusplus extern "C" { #endif //#include <tdi/common/c_frontend/tdi_common.h> #include <tdi/common/tdi_defs.h> #include <tdi/common/c_frontend/tdi_table_data.h> #ifdef __cplusplus } #endif #include <tdi/common/tdi_table_data.hpp> //#include <tdi_common/tdi_table_data_impl.hpp> /* Data field setters/getter */ tdi_status_t tdi_data_field_set_value(tdi_table_data_hdl *data_hdl, const tdi_id_t field_id, const uint64_t val) { auto data_field = reinterpret_cast<tdi::TableData *>(data_hdl); return data_field->setValue(field_id, val); } tdi_status_t tdi_data_field_set_float(tdi_table_data_hdl *data_hdl, const tdi_id_t field_id, const float val) { auto data_field = reinterpret_cast<tdi::TableData *>(data_hdl); return data_field->setValue(field_id, val); } tdi_status_t tdi_data_field_set_value_ptr(tdi_table_data_hdl *data_hdl, const tdi_id_t field_id, const uint8_t *val, const size_t s) { auto data_field = reinterpret_cast<tdi::TableData *>(data_hdl); return data_field->setValue(field_id, val, s); } tdi_status_t tdi_data_field_set_value_array(tdi_table_data_hdl *data_hdl, const tdi_id_t field_id, const uint32_t *val, const uint32_t num_array) { auto data_field = reinterpret_cast<tdi::TableData *>(data_hdl); // array pointers work as iterators const auto vec = std::vector<tdi_id_t>(val, val + num_array); return data_field->setValue(field_id, vec); } tdi_status_t tdi_data_field_set_value_bool_array( tdi_table_data_hdl *data_hdl, const tdi_id_t field_id, const bool *val, const uint32_t num_array) { auto data_field = reinterpret_cast<tdi::TableData *>(data_hdl); // array pointers work as iterators const auto vec = std::vector<bool>(val, val + num_array); return data_field->setValue(field_id, vec); } tdi_status_t tdi_data_field_set_value_str_array(tdi_table_data_hdl *data_hdl, const tdi_id_t field_id, const char *val) { auto data_field = reinterpret_cast<tdi::TableData *>(data_hdl); std::vector<std::string> vec; char *token = strtok(strdup(val), " "); while (token != NULL) { vec.push_back(std::string(token)); token = strtok(NULL, " "); } return data_field->setValue(field_id, vec); } tdi_status_t tdi_data_field_set_value_data_field_array( tdi_table_data_hdl *data_hdl, const tdi_id_t field_id, tdi_table_data_hdl *val[], const uint32_t num_array) { std::vector<std::unique_ptr<tdi::TableData>> inner_vec; for (uint32_t i = 0; i < num_array; i++) { auto inner_data = std::unique_ptr<tdi::TableData>( reinterpret_cast<tdi::TableData *>(val[i])); inner_vec.push_back(std::move(inner_data)); } auto data_field = reinterpret_cast<tdi::TableData *>(data_hdl); return data_field->setValue(field_id, std::move(inner_vec)); } tdi_status_t tdi_data_field_set_bool(tdi_table_data_hdl *data_hdl, const tdi_id_t field_id, const bool val) { auto data_field = reinterpret_cast<tdi::TableData *>(data_hdl); return data_field->setValue(field_id, val); } tdi_status_t tdi_data_field_set_string(tdi_table_data_hdl *data_hdl, const tdi_id_t field_id, const char *val) { auto data_field = reinterpret_cast<tdi::TableData *>(data_hdl); const std::string str_val(val); return data_field->setValue(field_id, str_val); } tdi_status_t tdi_data_field_get_value(const tdi_table_data_hdl *data_hdl, const tdi_id_t field_id, uint64_t *val) { auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl); return data_field->getValue(field_id, val); } tdi_status_t tdi_data_field_get_value_ptr(const tdi_table_data_hdl *data_hdl, const tdi_id_t field_id, const size_t size, uint8_t *val) { auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl); return data_field->getValue(field_id, size, val); } tdi_status_t tdi_data_field_get_value_array( const tdi_table_data_hdl *data_hdl, const tdi_id_t field_id, uint32_t *val) { auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl); std::vector<tdi_id_t> vec; auto status = data_field->getValue(field_id, &vec); int i = 0; for (auto const &item : vec) { val[i++] = item; } return status; } tdi_status_t tdi_data_field_get_value_array_size( const tdi_table_data_hdl *data_hdl, const tdi_id_t field_id, uint32_t *array_size) { auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl); std::vector<tdi_id_t> vec; auto status = data_field->getValue(field_id, &vec); *array_size = vec.size(); return status; } tdi_status_t tdi_data_field_get_value_bool_array( const tdi_table_data_hdl *data_hdl, const tdi_id_t field_id, bool *val) { auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl); std::vector<bool> vec; auto status = data_field->getValue(field_id, &vec); int i = 0; for (auto const &item : vec) { val[i++] = item; } return status; } tdi_status_t tdi_data_field_get_value_bool_array_size( const tdi_table_data_hdl *data_hdl, const tdi_id_t field_id, uint32_t *array_size) { auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl); std::vector<bool> vec; auto status = data_field->getValue(field_id, &vec); *array_size = vec.size(); return status; } tdi_status_t tdi_data_field_get_value_str_array( const tdi_table_data_hdl *data_hdl, const tdi_id_t field_id, uint32_t size, char *val) { auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl); std::vector<std::string> vec; auto status = data_field->getValue(field_id, &vec); if ((size == 0) && (vec.size() == 0)) return status; bool first_item = true; for (auto const &item : vec) { if (first_item) { first_item = false; } else { if (size == 0) return TDI_INVALID_ARG; val[0] = ' '; val++; size--; } if (size <= item.size()) return TDI_INVALID_ARG; item.copy(val, item.size()); val += item.size(); size -= item.size(); } if (size == 0) return TDI_INVALID_ARG; val[0] = '\0'; return status; } tdi_status_t tdi_data_field_get_value_str_array_size( const tdi_table_data_hdl *data_hdl, const tdi_id_t field_id, uint32_t *array_size) { auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl); std::vector<std::string> vec; auto status = data_field->getValue(field_id, &vec); /* Return the size of all strings plus white spaces between them. */ for (auto const &item : vec) *array_size += (item.size() + 1); return status; } tdi_status_t tdi_data_field_get_float(const tdi_table_data_hdl *data_hdl, const tdi_id_t field_id, float *val) { auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl); return data_field->getValue(field_id, val); } tdi_status_t tdi_data_field_get_bool(const tdi_table_data_hdl *data_hdl, const tdi_id_t field_id, bool *val) { auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl); return data_field->getValue(field_id, val); } tdi_status_t tdi_data_field_get_string_size( const tdi_table_data_hdl *data_hdl, const tdi_id_t field_id, uint32_t *str_size) { auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl); std::string str; auto status = data_field->getValue(field_id, &str); *str_size = str.size(); return status; } tdi_status_t tdi_data_field_get_string(const tdi_table_data_hdl *data_hdl, const tdi_id_t field_id, char *val) { auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl); std::string str; auto status = data_field->getValue(field_id, &str); str.copy(val, str.size()); return status; } tdi_status_t tdi_data_field_get_value_u64_array( const tdi_table_data_hdl *data_hdl, const tdi_id_t field_id, uint64_t *val) { auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl); std::vector<uint64_t> vec; auto status = data_field->getValue(field_id, &vec); int i = 0; for (auto const &item : vec) { val[i++] = item; } return status; } tdi_status_t tdi_data_field_get_value_u64_array_size( const tdi_table_data_hdl *data_hdl, const tdi_id_t field_id, uint32_t *array_size) { auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl); std::vector<uint64_t> vec; auto status = data_field->getValue(field_id, &vec); *array_size = vec.size(); return status; } tdi_status_t tdi_data_field_get_value_data_field_array( const tdi_table_data_hdl *data_hdl, const tdi_id_t field_id, tdi_table_data_hdl **val) { auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl); std::vector<tdi::TableData *> vec; auto status = data_field->getValue(field_id, &vec); int i = 0; for (auto const &item : vec) { val[i++] = reinterpret_cast<tdi_table_data_hdl *>(item); } return status; } tdi_status_t tdi_data_field_get_value_data_field_array_size( const tdi_table_data_hdl *data_hdl, const tdi_id_t field_id, uint32_t *array_size) { auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl); std::vector<tdi::TableData *> vec; auto status = data_field->getValue(field_id, &vec); *array_size = vec.size(); return status; } tdi_status_t tdi_data_action_id_get(const tdi_table_data_hdl *data_hdl, uint32_t *action_id) { auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl); *action_id = data_field->actionIdGet(); return TDI_SUCCESS; } tdi_status_t tdi_data_field_is_active(const tdi_table_data_hdl *data_hdl, const tdi_id_t field_id, bool *is_active) { auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl); return data_field->isActive(field_id, is_active); } <commit_msg>Fix for memory leak: klocwork ipdk-tdi #717 (#64)<commit_after>/* * Copyright(c) 2021 Intel Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this software except as stipulated in 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. */ #ifdef __cplusplus extern "C" { #endif //#include <tdi/common/c_frontend/tdi_common.h> #include <tdi/common/tdi_defs.h> #include <tdi/common/c_frontend/tdi_table_data.h> #ifdef __cplusplus } #endif #include <tdi/common/tdi_table_data.hpp> //#include <tdi_common/tdi_table_data_impl.hpp> /* Data field setters/getter */ tdi_status_t tdi_data_field_set_value(tdi_table_data_hdl *data_hdl, const tdi_id_t field_id, const uint64_t val) { auto data_field = reinterpret_cast<tdi::TableData *>(data_hdl); return data_field->setValue(field_id, val); } tdi_status_t tdi_data_field_set_float(tdi_table_data_hdl *data_hdl, const tdi_id_t field_id, const float val) { auto data_field = reinterpret_cast<tdi::TableData *>(data_hdl); return data_field->setValue(field_id, val); } tdi_status_t tdi_data_field_set_value_ptr(tdi_table_data_hdl *data_hdl, const tdi_id_t field_id, const uint8_t *val, const size_t s) { auto data_field = reinterpret_cast<tdi::TableData *>(data_hdl); return data_field->setValue(field_id, val, s); } tdi_status_t tdi_data_field_set_value_array(tdi_table_data_hdl *data_hdl, const tdi_id_t field_id, const uint32_t *val, const uint32_t num_array) { auto data_field = reinterpret_cast<tdi::TableData *>(data_hdl); // array pointers work as iterators const auto vec = std::vector<tdi_id_t>(val, val + num_array); return data_field->setValue(field_id, vec); } tdi_status_t tdi_data_field_set_value_bool_array( tdi_table_data_hdl *data_hdl, const tdi_id_t field_id, const bool *val, const uint32_t num_array) { auto data_field = reinterpret_cast<tdi::TableData *>(data_hdl); // array pointers work as iterators const auto vec = std::vector<bool>(val, val + num_array); return data_field->setValue(field_id, vec); } tdi_status_t tdi_data_field_set_value_str_array(tdi_table_data_hdl *data_hdl, const tdi_id_t field_id, const char *val) { auto data_field = reinterpret_cast<tdi::TableData *>(data_hdl); std::vector<std::string> vec; char *val_dup = strdup(val); char *token = strtok(val_dup, " "); while (token != NULL) { vec.push_back(std::string(token)); token = strtok(NULL, " "); } free(val_dup); return data_field->setValue(field_id, vec); } tdi_status_t tdi_data_field_set_value_data_field_array( tdi_table_data_hdl *data_hdl, const tdi_id_t field_id, tdi_table_data_hdl *val[], const uint32_t num_array) { std::vector<std::unique_ptr<tdi::TableData>> inner_vec; for (uint32_t i = 0; i < num_array; i++) { auto inner_data = std::unique_ptr<tdi::TableData>( reinterpret_cast<tdi::TableData *>(val[i])); inner_vec.push_back(std::move(inner_data)); } auto data_field = reinterpret_cast<tdi::TableData *>(data_hdl); return data_field->setValue(field_id, std::move(inner_vec)); } tdi_status_t tdi_data_field_set_bool(tdi_table_data_hdl *data_hdl, const tdi_id_t field_id, const bool val) { auto data_field = reinterpret_cast<tdi::TableData *>(data_hdl); return data_field->setValue(field_id, val); } tdi_status_t tdi_data_field_set_string(tdi_table_data_hdl *data_hdl, const tdi_id_t field_id, const char *val) { auto data_field = reinterpret_cast<tdi::TableData *>(data_hdl); const std::string str_val(val); return data_field->setValue(field_id, str_val); } tdi_status_t tdi_data_field_get_value(const tdi_table_data_hdl *data_hdl, const tdi_id_t field_id, uint64_t *val) { auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl); return data_field->getValue(field_id, val); } tdi_status_t tdi_data_field_get_value_ptr(const tdi_table_data_hdl *data_hdl, const tdi_id_t field_id, const size_t size, uint8_t *val) { auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl); return data_field->getValue(field_id, size, val); } tdi_status_t tdi_data_field_get_value_array( const tdi_table_data_hdl *data_hdl, const tdi_id_t field_id, uint32_t *val) { auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl); std::vector<tdi_id_t> vec; auto status = data_field->getValue(field_id, &vec); int i = 0; for (auto const &item : vec) { val[i++] = item; } return status; } tdi_status_t tdi_data_field_get_value_array_size( const tdi_table_data_hdl *data_hdl, const tdi_id_t field_id, uint32_t *array_size) { auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl); std::vector<tdi_id_t> vec; auto status = data_field->getValue(field_id, &vec); *array_size = vec.size(); return status; } tdi_status_t tdi_data_field_get_value_bool_array( const tdi_table_data_hdl *data_hdl, const tdi_id_t field_id, bool *val) { auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl); std::vector<bool> vec; auto status = data_field->getValue(field_id, &vec); int i = 0; for (auto const &item : vec) { val[i++] = item; } return status; } tdi_status_t tdi_data_field_get_value_bool_array_size( const tdi_table_data_hdl *data_hdl, const tdi_id_t field_id, uint32_t *array_size) { auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl); std::vector<bool> vec; auto status = data_field->getValue(field_id, &vec); *array_size = vec.size(); return status; } tdi_status_t tdi_data_field_get_value_str_array( const tdi_table_data_hdl *data_hdl, const tdi_id_t field_id, uint32_t size, char *val) { auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl); std::vector<std::string> vec; auto status = data_field->getValue(field_id, &vec); if ((size == 0) && (vec.size() == 0)) return status; bool first_item = true; for (auto const &item : vec) { if (first_item) { first_item = false; } else { if (size == 0) return TDI_INVALID_ARG; val[0] = ' '; val++; size--; } if (size <= item.size()) return TDI_INVALID_ARG; item.copy(val, item.size()); val += item.size(); size -= item.size(); } if (size == 0) return TDI_INVALID_ARG; val[0] = '\0'; return status; } tdi_status_t tdi_data_field_get_value_str_array_size( const tdi_table_data_hdl *data_hdl, const tdi_id_t field_id, uint32_t *array_size) { auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl); std::vector<std::string> vec; auto status = data_field->getValue(field_id, &vec); /* Return the size of all strings plus white spaces between them. */ for (auto const &item : vec) *array_size += (item.size() + 1); return status; } tdi_status_t tdi_data_field_get_float(const tdi_table_data_hdl *data_hdl, const tdi_id_t field_id, float *val) { auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl); return data_field->getValue(field_id, val); } tdi_status_t tdi_data_field_get_bool(const tdi_table_data_hdl *data_hdl, const tdi_id_t field_id, bool *val) { auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl); return data_field->getValue(field_id, val); } tdi_status_t tdi_data_field_get_string_size( const tdi_table_data_hdl *data_hdl, const tdi_id_t field_id, uint32_t *str_size) { auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl); std::string str; auto status = data_field->getValue(field_id, &str); *str_size = str.size(); return status; } tdi_status_t tdi_data_field_get_string(const tdi_table_data_hdl *data_hdl, const tdi_id_t field_id, char *val) { auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl); std::string str; auto status = data_field->getValue(field_id, &str); str.copy(val, str.size()); return status; } tdi_status_t tdi_data_field_get_value_u64_array( const tdi_table_data_hdl *data_hdl, const tdi_id_t field_id, uint64_t *val) { auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl); std::vector<uint64_t> vec; auto status = data_field->getValue(field_id, &vec); int i = 0; for (auto const &item : vec) { val[i++] = item; } return status; } tdi_status_t tdi_data_field_get_value_u64_array_size( const tdi_table_data_hdl *data_hdl, const tdi_id_t field_id, uint32_t *array_size) { auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl); std::vector<uint64_t> vec; auto status = data_field->getValue(field_id, &vec); *array_size = vec.size(); return status; } tdi_status_t tdi_data_field_get_value_data_field_array( const tdi_table_data_hdl *data_hdl, const tdi_id_t field_id, tdi_table_data_hdl **val) { auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl); std::vector<tdi::TableData *> vec; auto status = data_field->getValue(field_id, &vec); int i = 0; for (auto const &item : vec) { val[i++] = reinterpret_cast<tdi_table_data_hdl *>(item); } return status; } tdi_status_t tdi_data_field_get_value_data_field_array_size( const tdi_table_data_hdl *data_hdl, const tdi_id_t field_id, uint32_t *array_size) { auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl); std::vector<tdi::TableData *> vec; auto status = data_field->getValue(field_id, &vec); *array_size = vec.size(); return status; } tdi_status_t tdi_data_action_id_get(const tdi_table_data_hdl *data_hdl, uint32_t *action_id) { auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl); *action_id = data_field->actionIdGet(); return TDI_SUCCESS; } tdi_status_t tdi_data_field_is_active(const tdi_table_data_hdl *data_hdl, const tdi_id_t field_id, bool *is_active) { auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl); return data_field->isActive(field_id, is_active); } <|endoftext|>
<commit_before>/*! @file @copyright Edouard Alligand and Joel Falcou 2015-2017 (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ #ifndef BOOST_BRIGAND_ALGORITHMS_DETAIL_FIND_HPP #define BOOST_BRIGAND_ALGORITHMS_DETAIL_FIND_HPP #include <brigand/functions/lambda/apply.hpp> #include <brigand/types/bool.hpp> namespace brigand { namespace detail { template <template <typename...> class S, template <typename...> class F, typename... Ts> struct finder { template <typename T> using P = F<Ts..., T>; template <bool InNext8, bool Match, typename... Ls> struct find { using type = S<>; // not found case because none left }; template <typename L> struct find<true, false, L> { using type = S<>; // not found case because only one left and not true }; template <typename L, typename... Ls> // match case struct find<true, true, L, Ls...> { using type = S<L, Ls...>; }; template <typename L1, typename L2, typename... Ls> // not match case struct find<true, false, L1, L2, Ls...> : find<true, F<Ts..., L2>::value, L2, Ls...> { }; template <typename L0, typename L1, typename L2, typename L3, typename L4, typename L5, typename L6, typename L7, typename L8, typename... Ls> // not match no longer fast track case struct find<false, false, L0, L1, L2, L3, L4, L5, L6, L7, L8, Ls...> : find<true, F<Ts..., L8>::value, L8, Ls...> { }; template <typename L1, typename L2, typename L3, typename L4, typename L5, typename L6, typename L7, typename L8, typename L9, typename L10, typename L11, typename L12, typename L13, typename L14, typename L15, typename L16, typename... Ls> // not match can fast track again case struct find<false, false, L1, L2, L3, L4, L5, L6, L7, L8, L9, L10, L11, L12, L13, L14, L15, L16, Ls...> : find<(P<L9>::value || P<L10>::value || P<L11>::value || P<L12>::value || P<L13>::value || P<L14>::value || P<L15>::value || P<L16>::value), P<L9>::value, L9, L10, L11, L12, L13, L14, L15, L16, Ls...> { }; }; } } #endif <commit_msg>Delete find.hpp<commit_after><|endoftext|>
<commit_before>// Copyright (C) 2017 Jérôme Leclercq // This file is part of the "Nazara Development Kit" // For conditions of distribution and use, see copyright notice in Prerequisites.hpp #include <NDK/BaseWidget.hpp> #include <NDK/Canvas.hpp> #include <NDK/Components/GraphicsComponent.hpp> #include <NDK/Components/NodeComponent.hpp> #include <NDK/World.hpp> #include <algorithm> namespace Ndk { /*! * \ingroup NDK * \class Ndk::BaseWidget * \brief Abstract class serving as a base class for all widgets */ /*! * \brief Constructs a BaseWidget object using another widget as its parent * * \param parent Parent widget, must be valid and attached to a canvas * * Constructs a BaseWidget object using another widget as a base. * This will also register the widget to the canvas owning the top-most widget. */ BaseWidget::BaseWidget(BaseWidget* parent) : BaseWidget() { NazaraAssert(parent, "Invalid parent"); NazaraAssert(parent->GetCanvas(), "Parent has no canvas"); m_canvas = parent->GetCanvas(); m_widgetParent = parent; m_world = m_canvas->GetWorld(); RegisterToCanvas(); } /*! * \brief Frees the widget, unregistering it from its canvas */ BaseWidget::~BaseWidget() { UnregisterFromCanvas(); } /*! * \brief Clears keyboard focus if and only if this widget owns it. */ void BaseWidget::ClearFocus() { if (IsRegisteredToCanvas()) m_canvas->ClearKeyboardOwner(m_canvasIndex); } /*! * \brief Destroy the widget, deleting it in the process. * * Calling this function immediately destroys the widget, freeing its memory. */ void BaseWidget::Destroy() { NazaraAssert(this != m_canvas, "Canvas cannot be destroyed by calling Destroy()"); m_widgetParent->DestroyChild(this); //< This does delete us } /*! * \brief Enable or disables the widget background. */ void BaseWidget::EnableBackground(bool enable) { if (m_backgroundEntity.IsValid() == enable) return; if (enable) { m_backgroundSprite = Nz::Sprite::New(); m_backgroundSprite->SetColor(m_backgroundColor); m_backgroundSprite->SetMaterial(Nz::Material::New((m_backgroundColor.IsOpaque()) ? "Basic2D" : "Translucent2D")); //< TODO: Use a shared material instead of creating one everytime m_backgroundEntity = CreateEntity(); m_backgroundEntity->AddComponent<GraphicsComponent>().Attach(m_backgroundSprite, -1); m_backgroundEntity->AddComponent<NodeComponent>().SetParent(this); BaseWidget::Layout(); // Only layout background } else { DestroyEntity(m_backgroundEntity); m_backgroundEntity.Reset(); m_backgroundSprite.Reset(); } } /*! * \brief Checks if this widget has keyboard focus * \return true if widget has keyboard focus, false otherwise */ bool BaseWidget::HasFocus() const { if (!IsRegisteredToCanvas()) return false; return m_canvas->IsKeyboardOwner(m_canvasIndex); } void BaseWidget::Resize(const Nz::Vector2f& size) { // Adjust new size Nz::Vector2f newSize = size; newSize.Maximize(m_minimumSize); newSize.Minimize(m_maximumSize); NotifyParentResized(newSize); m_size = newSize; Layout(); } void BaseWidget::SetBackgroundColor(const Nz::Color& color) { m_backgroundColor = color; if (m_backgroundSprite) { m_backgroundSprite->SetColor(color); m_backgroundSprite->GetMaterial()->Configure((color.IsOpaque()) ? "Basic2D" : "Translucent2D"); //< Our sprite has its own material (see EnableBackground) } } void BaseWidget::SetCursor(Nz::SystemCursor systemCursor) { m_cursor = systemCursor; if (IsRegisteredToCanvas()) m_canvas->NotifyWidgetCursorUpdate(m_canvasIndex); } void BaseWidget::SetFocus() { if (IsRegisteredToCanvas()) m_canvas->SetKeyboardOwner(m_canvasIndex); } void BaseWidget::SetParent(BaseWidget* widget) { Canvas* oldCanvas = m_canvas; Canvas* newCanvas = widget->GetCanvas(); // Changing a widget canvas is a problem because of the canvas entities NazaraAssert(oldCanvas == newCanvas, "Transferring a widget between canvas is not yet supported"); Node::SetParent(widget); m_widgetParent = widget; Layout(); } void BaseWidget::SetRenderingRect(const Nz::Rectf& renderingRect) { m_renderingRect = renderingRect; UpdatePositionAndSize(); } void BaseWidget::Show(bool show) { if (m_visible != show) { m_visible = show; if (m_visible) RegisterToCanvas(); else UnregisterFromCanvas(); for (WidgetEntity& entity : m_entities) { if (entity.isEnabled) { entity.handle->Enable(show); //< This will override isEnabled entity.isEnabled = true; } } for (const auto& widgetPtr : m_children) widgetPtr->Show(show); } } const EntityHandle& BaseWidget::CreateEntity() { const EntityHandle& newEntity = m_world->CreateEntity(); newEntity->Enable(m_visible); m_entities.emplace_back(); WidgetEntity& newWidgetEntity = m_entities.back(); newWidgetEntity.handle = newEntity; newWidgetEntity.onDisabledSlot.Connect(newEntity->OnEntityDisabled, [this](Entity* entity) { auto it = std::find_if(m_entities.begin(), m_entities.end(), [&](const WidgetEntity& widgetEntity) { return widgetEntity.handle == entity; }); NazaraAssert(it != m_entities.end(), "Entity does not belong to this widget"); it->isEnabled = false; }); newWidgetEntity.onEnabledSlot.Connect(newEntity->OnEntityEnabled, [this](Entity* entity) { auto it = std::find_if(m_entities.begin(), m_entities.end(), [&](const WidgetEntity& widgetEntity) { return widgetEntity.handle == entity; }); NazaraAssert(it != m_entities.end(), "Entity does not belong to this widget"); it->isEnabled = true; }); return newEntity; } void BaseWidget::DestroyEntity(Entity* entity) { auto it = std::find_if(m_entities.begin(), m_entities.end(), [&](const WidgetEntity& widgetEntity) { return widgetEntity.handle == entity; }); NazaraAssert(it != m_entities.end(), "Entity does not belong to this widget"); m_entities.erase(it); } void BaseWidget::Layout() { if (m_backgroundSprite) m_backgroundSprite->SetSize(m_size.x, m_size.y); UpdatePositionAndSize(); } void BaseWidget::InvalidateNode() { Node::InvalidateNode(); UpdatePositionAndSize(); } bool BaseWidget::IsFocusable() const { return false; } void BaseWidget::OnFocusLost() { } void BaseWidget::OnFocusReceived() { } bool BaseWidget::OnKeyPressed(const Nz::WindowEvent::KeyEvent& key) { return false; } void BaseWidget::OnKeyReleased(const Nz::WindowEvent::KeyEvent& /*key*/) { } void BaseWidget::OnMouseEnter() { } void BaseWidget::OnMouseMoved(int /*x*/, int /*y*/, int /*deltaX*/, int /*deltaY*/) { } void BaseWidget::OnMouseButtonPress(int /*x*/, int /*y*/, Nz::Mouse::Button /*button*/) { } void BaseWidget::OnMouseButtonRelease(int /*x*/, int /*y*/, Nz::Mouse::Button /*button*/) { } void BaseWidget::OnMouseWheelMoved(int /*x*/, int /*y*/, float /*delta*/) { } void BaseWidget::OnMouseExit() { } void BaseWidget::OnParentResized(const Nz::Vector2f& /*newSize*/) { } void BaseWidget::OnTextEntered(char32_t /*character*/, bool /*repeated*/) { } void BaseWidget::DestroyChild(BaseWidget* widget) { auto it = std::find_if(m_children.begin(), m_children.end(), [widget] (const std::unique_ptr<BaseWidget>& widgetPtr) -> bool { return widgetPtr.get() == widget; }); NazaraAssert(it != m_children.end(), "Child widget not found in parent"); m_children.erase(it); } void BaseWidget::DestroyChildren() { m_children.clear(); } void BaseWidget::RegisterToCanvas() { NazaraAssert(!IsRegisteredToCanvas(), "Widget is already registered to canvas"); m_canvasIndex = m_canvas->RegisterWidget(this); } void BaseWidget::UnregisterFromCanvas() { if (IsRegisteredToCanvas()) { m_canvas->UnregisterWidget(m_canvasIndex); m_canvasIndex = InvalidCanvasIndex; } } void BaseWidget::UpdatePositionAndSize() { if (IsRegisteredToCanvas()) m_canvas->NotifyWidgetBoxUpdate(m_canvasIndex); Nz::Vector2f widgetPos = Nz::Vector2f(GetPosition()); Nz::Vector2f widgetSize = GetSize(); Nz::Rectf widgetRect(widgetPos.x, widgetPos.y, widgetSize.x, widgetSize.y); Nz::Rectf widgetRenderingRect(widgetPos.x + m_renderingRect.x, widgetPos.y + m_renderingRect.y, m_renderingRect.width, m_renderingRect.height); Nz::Rectf widgetBounds; widgetRect.Intersect(widgetRenderingRect, &widgetBounds); Nz::Recti fullBounds(widgetBounds); for (WidgetEntity& widgetEntity : m_entities) { const Ndk::EntityHandle& entity = widgetEntity.handle; if (entity->HasComponent<GraphicsComponent>()) entity->GetComponent<GraphicsComponent>().SetScissorRect(fullBounds); } } } <commit_msg>SDK/BaseWidget: Fix entity activation of disabled widgets<commit_after>// Copyright (C) 2017 Jérôme Leclercq // This file is part of the "Nazara Development Kit" // For conditions of distribution and use, see copyright notice in Prerequisites.hpp #include <NDK/BaseWidget.hpp> #include <NDK/Canvas.hpp> #include <NDK/Components/GraphicsComponent.hpp> #include <NDK/Components/NodeComponent.hpp> #include <NDK/World.hpp> #include <algorithm> namespace Ndk { /*! * \ingroup NDK * \class Ndk::BaseWidget * \brief Abstract class serving as a base class for all widgets */ /*! * \brief Constructs a BaseWidget object using another widget as its parent * * \param parent Parent widget, must be valid and attached to a canvas * * Constructs a BaseWidget object using another widget as a base. * This will also register the widget to the canvas owning the top-most widget. */ BaseWidget::BaseWidget(BaseWidget* parent) : BaseWidget() { NazaraAssert(parent, "Invalid parent"); NazaraAssert(parent->GetCanvas(), "Parent has no canvas"); m_canvas = parent->GetCanvas(); m_widgetParent = parent; m_world = m_canvas->GetWorld(); RegisterToCanvas(); } /*! * \brief Frees the widget, unregistering it from its canvas */ BaseWidget::~BaseWidget() { UnregisterFromCanvas(); } /*! * \brief Clears keyboard focus if and only if this widget owns it. */ void BaseWidget::ClearFocus() { if (IsRegisteredToCanvas()) m_canvas->ClearKeyboardOwner(m_canvasIndex); } /*! * \brief Destroy the widget, deleting it in the process. * * Calling this function immediately destroys the widget, freeing its memory. */ void BaseWidget::Destroy() { NazaraAssert(this != m_canvas, "Canvas cannot be destroyed by calling Destroy()"); m_widgetParent->DestroyChild(this); //< This does delete us } /*! * \brief Enable or disables the widget background. */ void BaseWidget::EnableBackground(bool enable) { if (m_backgroundEntity.IsValid() == enable) return; if (enable) { m_backgroundSprite = Nz::Sprite::New(); m_backgroundSprite->SetColor(m_backgroundColor); m_backgroundSprite->SetMaterial(Nz::Material::New((m_backgroundColor.IsOpaque()) ? "Basic2D" : "Translucent2D")); //< TODO: Use a shared material instead of creating one everytime m_backgroundEntity = CreateEntity(); m_backgroundEntity->AddComponent<GraphicsComponent>().Attach(m_backgroundSprite, -1); m_backgroundEntity->AddComponent<NodeComponent>().SetParent(this); BaseWidget::Layout(); // Only layout background } else { DestroyEntity(m_backgroundEntity); m_backgroundEntity.Reset(); m_backgroundSprite.Reset(); } } /*! * \brief Checks if this widget has keyboard focus * \return true if widget has keyboard focus, false otherwise */ bool BaseWidget::HasFocus() const { if (!IsRegisteredToCanvas()) return false; return m_canvas->IsKeyboardOwner(m_canvasIndex); } void BaseWidget::Resize(const Nz::Vector2f& size) { // Adjust new size Nz::Vector2f newSize = size; newSize.Maximize(m_minimumSize); newSize.Minimize(m_maximumSize); NotifyParentResized(newSize); m_size = newSize; Layout(); } void BaseWidget::SetBackgroundColor(const Nz::Color& color) { m_backgroundColor = color; if (m_backgroundSprite) { m_backgroundSprite->SetColor(color); m_backgroundSprite->GetMaterial()->Configure((color.IsOpaque()) ? "Basic2D" : "Translucent2D"); //< Our sprite has its own material (see EnableBackground) } } void BaseWidget::SetCursor(Nz::SystemCursor systemCursor) { m_cursor = systemCursor; if (IsRegisteredToCanvas()) m_canvas->NotifyWidgetCursorUpdate(m_canvasIndex); } void BaseWidget::SetFocus() { if (IsRegisteredToCanvas()) m_canvas->SetKeyboardOwner(m_canvasIndex); } void BaseWidget::SetParent(BaseWidget* widget) { Canvas* oldCanvas = m_canvas; Canvas* newCanvas = widget->GetCanvas(); // Changing a widget canvas is a problem because of the canvas entities NazaraAssert(oldCanvas == newCanvas, "Transferring a widget between canvas is not yet supported"); Node::SetParent(widget); m_widgetParent = widget; Layout(); } void BaseWidget::SetRenderingRect(const Nz::Rectf& renderingRect) { m_renderingRect = renderingRect; UpdatePositionAndSize(); } void BaseWidget::Show(bool show) { if (m_visible != show) { m_visible = show; if (m_visible) RegisterToCanvas(); else UnregisterFromCanvas(); for (WidgetEntity& entity : m_entities) { if (entity.isEnabled) { entity.handle->Enable(show); //< This will override isEnabled entity.isEnabled = true; } } for (const auto& widgetPtr : m_children) widgetPtr->Show(show); } } const EntityHandle& BaseWidget::CreateEntity() { const EntityHandle& newEntity = m_world->CreateEntity(); newEntity->Enable(m_visible); m_entities.emplace_back(); WidgetEntity& newWidgetEntity = m_entities.back(); newWidgetEntity.handle = newEntity; newWidgetEntity.onDisabledSlot.Connect(newEntity->OnEntityDisabled, [this](Entity* entity) { auto it = std::find_if(m_entities.begin(), m_entities.end(), [&](const WidgetEntity& widgetEntity) { return widgetEntity.handle == entity; }); NazaraAssert(it != m_entities.end(), "Entity does not belong to this widget"); it->isEnabled = false; }); newWidgetEntity.onEnabledSlot.Connect(newEntity->OnEntityEnabled, [this](Entity* entity) { auto it = std::find_if(m_entities.begin(), m_entities.end(), [&](const WidgetEntity& widgetEntity) { return widgetEntity.handle == entity; }); NazaraAssert(it != m_entities.end(), "Entity does not belong to this widget"); if (!IsVisible()) entity->Disable(); // Next line will override isEnabled status it->isEnabled = true; }); return newEntity; } void BaseWidget::DestroyEntity(Entity* entity) { auto it = std::find_if(m_entities.begin(), m_entities.end(), [&](const WidgetEntity& widgetEntity) { return widgetEntity.handle == entity; }); NazaraAssert(it != m_entities.end(), "Entity does not belong to this widget"); m_entities.erase(it); } void BaseWidget::Layout() { if (m_backgroundSprite) m_backgroundSprite->SetSize(m_size.x, m_size.y); UpdatePositionAndSize(); } void BaseWidget::InvalidateNode() { Node::InvalidateNode(); UpdatePositionAndSize(); } bool BaseWidget::IsFocusable() const { return false; } void BaseWidget::OnFocusLost() { } void BaseWidget::OnFocusReceived() { } bool BaseWidget::OnKeyPressed(const Nz::WindowEvent::KeyEvent& key) { return false; } void BaseWidget::OnKeyReleased(const Nz::WindowEvent::KeyEvent& /*key*/) { } void BaseWidget::OnMouseEnter() { } void BaseWidget::OnMouseMoved(int /*x*/, int /*y*/, int /*deltaX*/, int /*deltaY*/) { } void BaseWidget::OnMouseButtonPress(int /*x*/, int /*y*/, Nz::Mouse::Button /*button*/) { } void BaseWidget::OnMouseButtonRelease(int /*x*/, int /*y*/, Nz::Mouse::Button /*button*/) { } void BaseWidget::OnMouseWheelMoved(int /*x*/, int /*y*/, float /*delta*/) { } void BaseWidget::OnMouseExit() { } void BaseWidget::OnParentResized(const Nz::Vector2f& /*newSize*/) { } void BaseWidget::OnTextEntered(char32_t /*character*/, bool /*repeated*/) { } void BaseWidget::DestroyChild(BaseWidget* widget) { auto it = std::find_if(m_children.begin(), m_children.end(), [widget] (const std::unique_ptr<BaseWidget>& widgetPtr) -> bool { return widgetPtr.get() == widget; }); NazaraAssert(it != m_children.end(), "Child widget not found in parent"); m_children.erase(it); } void BaseWidget::DestroyChildren() { m_children.clear(); } void BaseWidget::RegisterToCanvas() { NazaraAssert(!IsRegisteredToCanvas(), "Widget is already registered to canvas"); m_canvasIndex = m_canvas->RegisterWidget(this); } void BaseWidget::UnregisterFromCanvas() { if (IsRegisteredToCanvas()) { m_canvas->UnregisterWidget(m_canvasIndex); m_canvasIndex = InvalidCanvasIndex; } } void BaseWidget::UpdatePositionAndSize() { if (IsRegisteredToCanvas()) m_canvas->NotifyWidgetBoxUpdate(m_canvasIndex); Nz::Vector2f widgetPos = Nz::Vector2f(GetPosition()); Nz::Vector2f widgetSize = GetSize(); Nz::Rectf widgetRect(widgetPos.x, widgetPos.y, widgetSize.x, widgetSize.y); Nz::Rectf widgetRenderingRect(widgetPos.x + m_renderingRect.x, widgetPos.y + m_renderingRect.y, m_renderingRect.width, m_renderingRect.height); Nz::Rectf widgetBounds; widgetRect.Intersect(widgetRenderingRect, &widgetBounds); Nz::Recti fullBounds(widgetBounds); for (WidgetEntity& widgetEntity : m_entities) { const Ndk::EntityHandle& entity = widgetEntity.handle; if (entity->HasComponent<GraphicsComponent>()) entity->GetComponent<GraphicsComponent>().SetScissorRect(fullBounds); } } } <|endoftext|>
<commit_before>#include "BackendWorker.hpp" #include <iostream> #include <opencv2/opencv.hpp> #include "SgPoint.h" #include "SgSystem.h" namespace Go_Controller { // converts a cv::Mat to a QImage // inspired from http://www.qtforum.de/forum/viewtopic.php?t=9721 // // Has two preconditions: // - depth of the cv::Mat has to be CV_8U = 8-bit unsigned integers ( 0..255 ) // - number of channels has to be 3 (RGB, or BGR in opencv) QImage mat_to_QImage(cv::Mat source) { assert(source.depth() == CV_8U); assert(source.channels() == 3); // "cast" or convert to an IplImage to get easier access to needed infos, // no copying involved IplImage image = source; // create QImage from IplImage QImage ret((uchar*) image.imageData, image.width, image.height, QImage::Format_RGB888); // swap BGR (opencv format) to RGB ret = ret.rgbSwapped(); return ret; } BackendWorker::BackendWorker() : _game(), _scanner(), _game_is_initialized(false), _cached_board_size(0), _scan_timer(this) // this makes sure that the timer has the same thread affinity as its parent (this) { /* define default game rules * handicap: 0 * komi: 6.5 * scoring: japanese * game end: after 2 consecutive passes */ _new_game_rules = GoRules(0, GoKomi(6.5), true, true); connect(&_scan_timer, SIGNAL(timeout()), this, SLOT(scan())); _scan_timer.setInterval(1000);// call the connected slot every 1000 msec (1 fps) _scan_timer.start(); // put one event in this threads event queue } BackendWorker::~BackendWorker() {} void BackendWorker::scan() { cv::Mat image; GoSetup setup; // fetch new camera image auto scan_result = _scanner.scanCamera(setup, _cached_board_size, image); using Go_Scanner::ScanResult; using Go_Backend::UpdateResult; switch (scan_result) { case ScanResult::Success: { if (_game_is_initialized) { // update game state UpdateResult result = _game.update(setup); if (result == UpdateResult::Illegal) { emit displayErrorMessage("Your board differs from virtual board!"); } else if (result == UpdateResult::ToCapture) { emit displayErrorMessage("There are stones left to capture.\nMake sure your board matches the virtual one."); } else { emit displayErrorMessage(""); // no error } } else { // the gui doesn't support other sizes if (_cached_board_size == 9 || _cached_board_size == 13 || _cached_board_size == 19 ) { _game.init(_cached_board_size, setup, _new_game_rules); _game_is_initialized = true; emit displayErrorMessage(""); } else { emit displayErrorMessage(QString("Not supported board size of %1x%1 detected!").arg(_cached_board_size)); } } signalGuiGameDataChanged(); // converting image (OpenCV data type) to QImage (Qt data type) const auto scanner_image = mat_to_QImage(image); // and send signal with new image to gui emit newImage(scanner_image); break; } case ScanResult::Failed: { // we still have a camera image to display, even when the scanning failed // converting image (OpenCV data type) to QImage (Qt data type) const auto scanner_image = mat_to_QImage(image); // send signal with new image to gui emit newImage(scanner_image); emit displayErrorMessage("Board could not be detected correctly!\nBoard selection still accurate?"); break; } case ScanResult::NoCamera: // disables board detection menu items // the menu items will be reactivated when the next newImage signal gets handled emit noCameraImage(); emit displayErrorMessage("No camera image could be retrieved!"); break; default: assert(!"Unknown ScanResult?!"); } } void BackendWorker::saveSgf(QString path, QString blackplayer_name, QString whiteplayer_name, QString game_name) { auto filepath = path.toStdString(); if (!_game.saveGame(filepath, blackplayer_name.toStdString(), whiteplayer_name.toStdString(), game_name.toStdString())) std::cerr << "Error writing game data to file \"" << filepath << "\"!" << std::endl; } void BackendWorker::loadSgf(QString path) { auto filepath = path.toStdString(); auto new_game = _game.loadGame(filepath); if (!new_game) { emit displayErrorMessagebox("Error loading the game", "Failed to open the selected sgf-file!"); return; } auto size = 0; if (!new_game->GetIntProp(SG_PROP_SIZE, &size)) { emit displayErrorMessagebox("Error loading the game", "You tried to load a sgf file with missing board size!\nOnly sgf-files with a defined board size are supported here."); // cleanup new_game->DeleteTree(); return; } if (size != 9 && size != 13 && size != 19) { emit displayErrorMessagebox("Error loading the game", "Only board sizes of 9x9, 13x13 and 19x19 are supported!"); // cleanup new_game->DeleteTree(); return; } // _game takes ownership of new_game _game.init(new_game); signalGuiGameDataChanged(); } void BackendWorker::pass() { _game.pass(); if (_game.hasEnded()) signalGuiGameHasEnded(); signalGuiGameDataChanged(); } void BackendWorker::resetGame(GoRules rules) { _game_is_initialized = false; _new_game_rules = rules; if (virtualModeActive()) { _game.init(19, GoSetup(), _new_game_rules); signalGuiGameDataChanged(); } } void BackendWorker::finish() { _game.finishGame(); signalGuiGameHasEnded(); } void BackendWorker::resign() { _game.resign(); signalGuiGameHasEnded(); } void BackendWorker::signalGuiGameHasEnded() const { auto result = _game.getResult(); // signal gui that game has ended with this result emit finishedGameResult(QString(result.c_str())); } void BackendWorker::setVirtualGameMode(bool checked) { if (virtualModeActive()) { // go into augmented mode -> do the scanning! _scan_timer.start(); } else { // go into virtual mode -> no scanning! _scan_timer.stop(); // also hide any scanning related error messages emit displayErrorMessage(""); // initialize a game if (!_game_is_initialized) _game.init(19, GoSetup(), _new_game_rules); signalGuiGameDataChanged(); } } void BackendWorker::playMove(const int x, const int y){ auto position = SgPointUtil::Pt(x, y); _game.playMove(position); signalGuiGameDataChanged(); } void BackendWorker::selectBoardManually() { _scan_timer.stop(); _scanner.selectBoardManually(); _scan_timer.start(); } void BackendWorker::selectBoardAutomatically() { _scan_timer.stop(); _scanner.selectBoardAutomatically(); _scan_timer.start(); } void BackendWorker::setScannerDebugImage(bool debug) { if (debug) _scanner.setDebugImage(); else _scanner.setNormalImage(); } bool BackendWorker::virtualModeActive() const { return !_scan_timer.isActive(); } void BackendWorker::signalGuiGameDataChanged() const { // send board data to gui // the GUI controls the lifetime of this thread, // so passing a pointer to the GoBoard is safe and won't be invalidated // as long as the GUI says so emit gameDataChanged(&_game); } void BackendWorker::navigateHistory(SgNode::Direction dir) { if (_game.canNavigateHistory(dir)) _game.navigateHistory(dir); signalGuiGameDataChanged(); } void BackendWorker::changeScanningRate(int milliseconds) { _scan_timer.setInterval(milliseconds); } } // namespace Go_Controller <commit_msg>[refs #4] Fixed bug where the controller didn't consider the game to be initialized after loading the sgf. Caused the sgf to being discarded when switching to virtual mode or when starting the scanning.<commit_after>#include "BackendWorker.hpp" #include <iostream> #include <opencv2/opencv.hpp> #include "SgPoint.h" #include "SgSystem.h" namespace Go_Controller { // converts a cv::Mat to a QImage // inspired from http://www.qtforum.de/forum/viewtopic.php?t=9721 // // Has two preconditions: // - depth of the cv::Mat has to be CV_8U = 8-bit unsigned integers ( 0..255 ) // - number of channels has to be 3 (RGB, or BGR in opencv) QImage mat_to_QImage(cv::Mat source) { assert(source.depth() == CV_8U); assert(source.channels() == 3); // "cast" or convert to an IplImage to get easier access to needed infos, // no copying involved IplImage image = source; // create QImage from IplImage QImage ret((uchar*) image.imageData, image.width, image.height, QImage::Format_RGB888); // swap BGR (opencv format) to RGB ret = ret.rgbSwapped(); return ret; } BackendWorker::BackendWorker() : _game(), _scanner(), _game_is_initialized(false), _cached_board_size(0), _scan_timer(this) // this makes sure that the timer has the same thread affinity as its parent (this) { /* define default game rules * handicap: 0 * komi: 6.5 * scoring: japanese * game end: after 2 consecutive passes */ _new_game_rules = GoRules(0, GoKomi(6.5), true, true); connect(&_scan_timer, SIGNAL(timeout()), this, SLOT(scan())); _scan_timer.setInterval(1000);// call the connected slot every 1000 msec (1 fps) _scan_timer.start(); // put one event in this threads event queue } BackendWorker::~BackendWorker() {} void BackendWorker::scan() { cv::Mat image; GoSetup setup; // fetch new camera image auto scan_result = _scanner.scanCamera(setup, _cached_board_size, image); using Go_Scanner::ScanResult; using Go_Backend::UpdateResult; switch (scan_result) { case ScanResult::Success: { if (_game_is_initialized) { // update game state UpdateResult result = _game.update(setup); if (result == UpdateResult::Illegal) { emit displayErrorMessage("Your board differs from virtual board!"); } else if (result == UpdateResult::ToCapture) { emit displayErrorMessage("There are stones left to capture.\nMake sure your board matches the virtual one."); } else { emit displayErrorMessage(""); // no error } } else { // the gui doesn't support other sizes if (_cached_board_size == 9 || _cached_board_size == 13 || _cached_board_size == 19 ) { _game.init(_cached_board_size, setup, _new_game_rules); _game_is_initialized = true; emit displayErrorMessage(""); } else { emit displayErrorMessage(QString("Not supported board size of %1x%1 detected!").arg(_cached_board_size)); } } signalGuiGameDataChanged(); // converting image (OpenCV data type) to QImage (Qt data type) const auto scanner_image = mat_to_QImage(image); // and send signal with new image to gui emit newImage(scanner_image); break; } case ScanResult::Failed: { // we still have a camera image to display, even when the scanning failed // converting image (OpenCV data type) to QImage (Qt data type) const auto scanner_image = mat_to_QImage(image); // send signal with new image to gui emit newImage(scanner_image); emit displayErrorMessage("Board could not be detected correctly!\nBoard selection still accurate?"); break; } case ScanResult::NoCamera: // disables board detection menu items // the menu items will be reactivated when the next newImage signal gets handled emit noCameraImage(); emit displayErrorMessage("No camera image could be retrieved!"); break; default: assert(!"Unknown ScanResult?!"); } } void BackendWorker::saveSgf(QString path, QString blackplayer_name, QString whiteplayer_name, QString game_name) { auto filepath = path.toStdString(); if (!_game.saveGame(filepath, blackplayer_name.toStdString(), whiteplayer_name.toStdString(), game_name.toStdString())) std::cerr << "Error writing game data to file \"" << filepath << "\"!" << std::endl; } void BackendWorker::loadSgf(QString path) { auto filepath = path.toStdString(); auto new_game = _game.loadGame(filepath); if (!new_game) { emit displayErrorMessagebox("Error loading the game", "Failed to open the selected sgf-file!"); return; } auto size = 0; if (!new_game->GetIntProp(SG_PROP_SIZE, &size)) { emit displayErrorMessagebox("Error loading the game", "You tried to load a sgf file with missing board size!\nOnly sgf-files with a defined board size are supported here."); // cleanup new_game->DeleteTree(); return; } if (size != 9 && size != 13 && size != 19) { emit displayErrorMessagebox("Error loading the game", "Only board sizes of 9x9, 13x13 and 19x19 are supported!"); // cleanup new_game->DeleteTree(); return; } // _game takes ownership of new_game _game.init(new_game); _game_is_initialized = true; signalGuiGameDataChanged(); } void BackendWorker::pass() { _game.pass(); if (_game.hasEnded()) signalGuiGameHasEnded(); signalGuiGameDataChanged(); } void BackendWorker::resetGame(GoRules rules) { _game_is_initialized = false; _new_game_rules = rules; if (virtualModeActive()) { _game.init(19, GoSetup(), _new_game_rules); signalGuiGameDataChanged(); } } void BackendWorker::finish() { _game.finishGame(); signalGuiGameHasEnded(); } void BackendWorker::resign() { _game.resign(); signalGuiGameHasEnded(); } void BackendWorker::signalGuiGameHasEnded() const { auto result = _game.getResult(); // signal gui that game has ended with this result emit finishedGameResult(QString(result.c_str())); } void BackendWorker::setVirtualGameMode(bool checked) { if (virtualModeActive()) { // go into augmented mode -> do the scanning! _scan_timer.start(); } else { // go into virtual mode -> no scanning! _scan_timer.stop(); // also hide any scanning related error messages emit displayErrorMessage(""); // initialize a game if (!_game_is_initialized) _game.init(19, GoSetup(), _new_game_rules); signalGuiGameDataChanged(); } } void BackendWorker::playMove(const int x, const int y){ auto position = SgPointUtil::Pt(x, y); _game.playMove(position); signalGuiGameDataChanged(); } void BackendWorker::selectBoardManually() { _scan_timer.stop(); _scanner.selectBoardManually(); _scan_timer.start(); } void BackendWorker::selectBoardAutomatically() { _scan_timer.stop(); _scanner.selectBoardAutomatically(); _scan_timer.start(); } void BackendWorker::setScannerDebugImage(bool debug) { if (debug) _scanner.setDebugImage(); else _scanner.setNormalImage(); } bool BackendWorker::virtualModeActive() const { return !_scan_timer.isActive(); } void BackendWorker::signalGuiGameDataChanged() const { // send board data to gui // the GUI controls the lifetime of this thread, // so passing a pointer to the GoBoard is safe and won't be invalidated // as long as the GUI says so emit gameDataChanged(&_game); } void BackendWorker::navigateHistory(SgNode::Direction dir) { if (_game.canNavigateHistory(dir)) _game.navigateHistory(dir); signalGuiGameDataChanged(); } void BackendWorker::changeScanningRate(int milliseconds) { _scan_timer.setInterval(milliseconds); } } // namespace Go_Controller <|endoftext|>
<commit_before>class segtree{ struct e { int sz, ans; }; public: int n; // array size vector<e> t; void combine(e &l, e &r, e &res) { if (l.sz == 0) { res = r; return; } if (r.sz == 0) { res = l; return; } res.sz = l.sz + r.sz; res.ans = l.ans + r.ans; } void combine_left(e &l, e &r) { e res; combine(l, r, res); l = res; } void combine_right(e &l, e &r) { e res; combine(l, r, res); r = res; } void build(vector<int> &v) { // build the tree for (int i = n; i < 2 * n; i++) { t[i].sz = 1; t[i].ans = v[i - n]; } for (int i = n - 1; i > 0; --i) combine(t[i<<1], t[i<<1|1], t[i]); } void modify(int p, int value) { // set value at position p for (t[p += n].ans = value; p >>= 1; ) combine(t[p<<1], t[p<<1|1], t[p]); } int query(int l, int r) { // sum on interval [l, r) e ansl, ansr; ansl.sz = ansr.sz = 0; for (l += n, r += n; l < r; l >>= 1, r >>= 1) { if (l&1) combine_left(ansl, t[l++]); if (r&1) combine_right(t[--r], ansr); } combine_left(ansl, ansr); return ansl.ans; } segtree(int n):n(n),t(){ t.resize(n << 1); } };<commit_msg>Tab fixes<commit_after>class segtree{ struct e { int sz, ans; }; public: int n; // array size vector<e> t; void combine(e &l, e &r, e &res) { if (l.sz == 0) { res = r; return; } if (r.sz == 0) { res = l; return; } res.sz = l.sz + r.sz; res.ans = l.ans + r.ans; } void combine_left(e &l, e &r) { e res; combine(l, r, res); l = res; } void combine_right(e &l, e &r) { e res; combine(l, r, res); r = res; } void build(vector<int> &v) { // build the tree for (int i = n; i < 2 * n; i++) { t[i].sz = 1; t[i].ans = v[i - n]; } for (int i = n - 1; i > 0; --i) combine(t[i<<1], t[i<<1|1], t[i]); } void modify(int p, int value) { // set value at position p for (t[p += n].ans = value; p >>= 1; ) combine(t[p<<1], t[p<<1|1], t[p]); } int query(int l, int r) { // sum on interval [l, r) e ansl, ansr; ansl.sz = ansr.sz = 0; for (l += n, r += n; l < r; l >>= 1, r >>= 1) { if (l&1) combine_left(ansl, t[l++]); if (r&1) combine_right(t[--r], ansr); } combine_left(ansl, ansr); return ansl.ans; } segtree(int n):n(n),t(){ t.resize(n << 1); } }; <|endoftext|>
<commit_before>#include "PyMeshPlugin.hh" // todo: some switch for boost static build or not #include <boost/python.hpp> #include <OpenFlipper/BasePlugin/PluginFunctions.hh> #include <OpenFlipper/common/GlobalOptions.hh> // adds openmesh python module for inter language communication //#include <OpenMesh/src/Python/Bindings.cc> #include "OMPyModule.hh" #include "MeshFactory.hh" #include <QFileDialog> static const char* g_job_id = "PyMesh Interpreter"; PyMeshPlugin::PyMeshPlugin(): main_module_(), toolbox_(), createdObjects_() { } PyMeshPlugin::~PyMeshPlugin() { Py_Finalize(); } void PyMeshPlugin::initializePlugin() { } void PyMeshPlugin::slotSelectFile() { QString fileName = QFileDialog::getOpenFileName(NULL, tr("Open Python Script"), toolbox_->filename->text(), tr("Python Script (*.py)")); if (!QFile::exists(fileName)) return; toolbox_->filename->setText(fileName); } void PyMeshPlugin::pluginsInitialized() { toolbox_ = new PyMeshToolbox(); Q_EMIT addToolbox("PyMesh", toolbox_, new QIcon(OpenFlipper::Options::iconDirStr() + OpenFlipper::Options::dirSeparator() + "pymesh_python.png")); toolbox_->pbRunFile->setIcon(QIcon(OpenFlipper::Options::iconDirStr() + OpenFlipper::Options::dirSeparator() + "arrow-right.png")); toolbox_->pbRunFile->setText(""); toolbox_->pbFileSelect->setIcon(QIcon(OpenFlipper::Options::iconDirStr() + OpenFlipper::Options::dirSeparator() + "document-open.png")); toolbox_->pbFileSelect->setText(""); toolbox_->filename->setText(OpenFlipperSettings().value("Plugin-PyMesh/LastOpenedFile", OpenFlipper::Options::applicationDirStr() + OpenFlipper::Options::dirSeparator()).toString()); connect(toolbox_->pbRunFile, SIGNAL(clicked()), this, SLOT(slotRunScript())); connect(toolbox_->pbFileSelect, SIGNAL(clicked()), this, SLOT(slotSelectFile())); } void PyMeshPlugin::slotRunScript() { const QString filename = toolbox_->filename->text(); OpenFlipperSettings().setValue("Plugin-PyMesh/LastOpenedFile", filename); runPyScriptFileAsync(filename, toolbox_->cbClearPrevious->isChecked()); } //////////////////////////////////////////////////////////////// // Python Interpreter Setup&Run void PyMeshPlugin::runPyScriptFile(const QString& _filename, bool _clearPrevious) { QFile f(_filename); if (!f.exists()) { Q_EMIT log(LOGERR, QString("Could not find file %1").arg(_filename)); } f.open(QFile::ReadOnly); runPyScript(QTextStream(&f).readAll(), _clearPrevious); } void PyMeshPlugin::runPyScriptFileAsync(const QString& _filename, bool _clearPrevious) { QFile f(_filename); if (!f.exists()) { Q_EMIT log(LOGERR, QString("Could not find file %1").arg(_filename)); } f.open(QFile::ReadOnly); runPyScriptAsync(QTextStream(&f).readAll(), _clearPrevious); } void PyMeshPlugin::runPyScriptAsync(const QString& _script, bool _clearPrevious) { OpenFlipperThread* th = new OpenFlipperThread(g_job_id); connect(th, SIGNAL(finished()), this, SLOT(runPyScriptFinished())); connect(th, &OpenFlipperThread::function, this, [_script, _clearPrevious, this]() { this->runPyScript_internal(_script, _clearPrevious); Q_EMIT this->finishJob(QString(g_job_id)); } , Qt::DirectConnection); // Run Script emit startJob(QString(g_job_id), "Runs Python Script", 0, 0, true); th->start(); th->startProcessing(); } void PyMeshPlugin::runPyScript(const QString& _script, bool _clearPrevious) { runPyScript_internal(_script, _clearPrevious); runPyScriptFinished(); } void PyMeshPlugin::runPyScript_internal(const QString& _script, bool _clearPrevious) { // init initPython(); // clear env if (_clearPrevious) for (size_t i = 0; i < createdObjects_.size(); ++i) Q_EMIT deleteObject(createdObjects_[i]); createdObjects_.clear(); QString jobName = name() + " PyRun Worker"; OpenFlipperThread* th = new OpenFlipperThread(jobName); connect(th, SIGNAL(finished()), this, SLOT(runPyScriptFinished())); PyRun_SimpleString(_script.toLatin1()); } void PyMeshPlugin::runPyScriptFinished() { // Update for (size_t i = 0; i < createdObjects_.size(); ++i) { Q_EMIT updatedObject(createdObjects_[i], UPDATE_ALL); Q_EMIT createBackup(createdObjects_[i], "Original Object"); } PluginFunctions::viewAll(); } void PyMeshPlugin::initPython() { if (Py_IsInitialized()) return; PyImport_AppendInittab("openmesh", openmesh_pyinit_function); Py_Initialize(); PyEval_InitThreads(); main_module_ = boost::python::object(boost::python::handle<>(PyImport_AddModule("__main__"))); // redirect python output initPyLogger(main_module_.ptr(), this); // add openmesh module boost::python::object main_namespace = main_module_.attr("__dict__"); boost::python::object om_module((boost::python::handle<>(PyImport_ImportModule("openmesh")))); main_namespace["openmesh"] = om_module; // hook into mesh constructors registerFactoryMethods(this, om_module); } // Abort functions int quitPython(void*) { PyErr_SetInterrupt(); return -1; } void PyMeshPlugin::canceledJob(QString _job) { if (!_job.contains(g_job_id)) return; PyGILState_STATE state = PyGILState_Ensure(); Py_AddPendingCall(&quitPython, NULL); PyGILState_Release(state); Q_EMIT log(LOGINFO, "Python Execution Canceled."); } /////////////////////////////////////////////////////////////////// // Python callback functions void PyMeshPlugin::pyOutput(const char* w) { Q_EMIT log(LOGOUT, QString(w)); } void PyMeshPlugin::pyError(const char* w) { Q_EMIT log(LOGERR, QString(w)); } OpenMesh::Python::TriMesh* PyMeshPlugin::createTriMesh() { int objectId = -1; Q_EMIT addEmptyObject(DATA_TRIANGLE_MESH, objectId); TriMeshObject* object; PluginFunctions::getObject(objectId, object); createdObjects_.push_back(objectId); return reinterpret_cast<OpenMesh::Python::TriMesh*>(object->mesh()); } OpenMesh::Python::PolyMesh* PyMeshPlugin::createPolyMesh() { int objectId = -1; Q_EMIT addEmptyObject(DATA_POLY_MESH, objectId); PolyMeshObject* object; PluginFunctions::getObject(objectId, object); createdObjects_.push_back(objectId); return reinterpret_cast<OpenMesh::Python::PolyMesh*>(object->mesh()); } <commit_msg>moved python init to main thread<commit_after>#include "PyMeshPlugin.hh" // todo: some switch for boost static build or not #include <boost/python.hpp> #include <OpenFlipper/BasePlugin/PluginFunctions.hh> #include <OpenFlipper/common/GlobalOptions.hh> // adds openmesh python module for inter language communication //#include <OpenMesh/src/Python/Bindings.cc> #include "OMPyModule.hh" #include "MeshFactory.hh" #include <QFileDialog> static const char* g_job_id = "PyMesh Interpreter"; PyMeshPlugin::PyMeshPlugin(): main_module_(), toolbox_(), createdObjects_() { } PyMeshPlugin::~PyMeshPlugin() { Py_Finalize(); } void PyMeshPlugin::initializePlugin() { } void PyMeshPlugin::slotSelectFile() { QString fileName = QFileDialog::getOpenFileName(NULL, tr("Open Python Script"), toolbox_->filename->text(), tr("Python Script (*.py)")); if (!QFile::exists(fileName)) return; toolbox_->filename->setText(fileName); } void PyMeshPlugin::pluginsInitialized() { toolbox_ = new PyMeshToolbox(); Q_EMIT addToolbox("PyMesh", toolbox_, new QIcon(OpenFlipper::Options::iconDirStr() + OpenFlipper::Options::dirSeparator() + "pymesh_python.png")); toolbox_->pbRunFile->setIcon(QIcon(OpenFlipper::Options::iconDirStr() + OpenFlipper::Options::dirSeparator() + "arrow-right.png")); toolbox_->pbRunFile->setText(""); toolbox_->pbFileSelect->setIcon(QIcon(OpenFlipper::Options::iconDirStr() + OpenFlipper::Options::dirSeparator() + "document-open.png")); toolbox_->pbFileSelect->setText(""); toolbox_->filename->setText(OpenFlipperSettings().value("Plugin-PyMesh/LastOpenedFile", OpenFlipper::Options::applicationDirStr() + OpenFlipper::Options::dirSeparator()).toString()); connect(toolbox_->pbRunFile, SIGNAL(clicked()), this, SLOT(slotRunScript())); connect(toolbox_->pbFileSelect, SIGNAL(clicked()), this, SLOT(slotSelectFile())); } void PyMeshPlugin::slotRunScript() { const QString filename = toolbox_->filename->text(); OpenFlipperSettings().setValue("Plugin-PyMesh/LastOpenedFile", filename); runPyScriptFileAsync(filename, toolbox_->cbClearPrevious->isChecked()); } //////////////////////////////////////////////////////////////// // Python Interpreter Setup&Run void PyMeshPlugin::runPyScriptFile(const QString& _filename, bool _clearPrevious) { QFile f(_filename); if (!f.exists()) { Q_EMIT log(LOGERR, QString("Could not find file %1").arg(_filename)); } f.open(QFile::ReadOnly); runPyScript(QTextStream(&f).readAll(), _clearPrevious); } void PyMeshPlugin::runPyScriptFileAsync(const QString& _filename, bool _clearPrevious) { QFile f(_filename); if (!f.exists()) { Q_EMIT log(LOGERR, QString("Could not find file %1").arg(_filename)); } f.open(QFile::ReadOnly); runPyScriptAsync(QTextStream(&f).readAll(), _clearPrevious); } void PyMeshPlugin::runPyScriptAsync(const QString& _script, bool _clearPrevious) { initPython(); OpenFlipperThread* th = new OpenFlipperThread(g_job_id); connect(th, SIGNAL(finished()), this, SLOT(runPyScriptFinished())); connect(th, &OpenFlipperThread::function, this, [_script, _clearPrevious, this]() { this->runPyScript_internal(_script, _clearPrevious); Q_EMIT this->finishJob(QString(g_job_id)); } , Qt::DirectConnection); // Run Script emit startJob(QString(g_job_id), "Runs Python Script", 0, 0, true); th->start(); th->startProcessing(); } void PyMeshPlugin::runPyScript(const QString& _script, bool _clearPrevious) { runPyScript_internal(_script, _clearPrevious); runPyScriptFinished(); } void PyMeshPlugin::runPyScript_internal(const QString& _script, bool _clearPrevious) { // init initPython(); // clear env if (_clearPrevious) for (size_t i = 0; i < createdObjects_.size(); ++i) Q_EMIT deleteObject(createdObjects_[i]); createdObjects_.clear(); QString jobName = name() + " PyRun Worker"; OpenFlipperThread* th = new OpenFlipperThread(jobName); connect(th, SIGNAL(finished()), this, SLOT(runPyScriptFinished())); PyRun_SimpleString(_script.toLatin1()); } void PyMeshPlugin::runPyScriptFinished() { // Update for (size_t i = 0; i < createdObjects_.size(); ++i) { Q_EMIT updatedObject(createdObjects_[i], UPDATE_ALL); Q_EMIT createBackup(createdObjects_[i], "Original Object"); } PluginFunctions::viewAll(); } void PyMeshPlugin::initPython() { if (Py_IsInitialized()) return; PyImport_AppendInittab("openmesh", openmesh_pyinit_function); Py_Initialize(); PyEval_InitThreads(); main_module_ = boost::python::object(boost::python::handle<>(PyImport_AddModule("__main__"))); // redirect python output initPyLogger(main_module_.ptr(), this); // add openmesh module boost::python::object main_namespace = main_module_.attr("__dict__"); boost::python::object om_module((boost::python::handle<>(PyImport_ImportModule("openmesh")))); main_namespace["openmesh"] = om_module; // hook into mesh constructors registerFactoryMethods(this, om_module); } // Abort functions int quitPython(void*) { PyErr_SetInterrupt(); return -1; } void PyMeshPlugin::canceledJob(QString _job) { if (!_job.contains(g_job_id)) return; PyGILState_STATE state = PyGILState_Ensure(); Py_AddPendingCall(&quitPython, NULL); PyGILState_Release(state); Q_EMIT log(LOGINFO, "Python Execution Canceled."); } /////////////////////////////////////////////////////////////////// // Python callback functions void PyMeshPlugin::pyOutput(const char* w) { Q_EMIT log(LOGOUT, QString(w)); } void PyMeshPlugin::pyError(const char* w) { Q_EMIT log(LOGERR, QString(w)); } OpenMesh::Python::TriMesh* PyMeshPlugin::createTriMesh() { int objectId = -1; Q_EMIT addEmptyObject(DATA_TRIANGLE_MESH, objectId); TriMeshObject* object; PluginFunctions::getObject(objectId, object); createdObjects_.push_back(objectId); return reinterpret_cast<OpenMesh::Python::TriMesh*>(object->mesh()); } OpenMesh::Python::PolyMesh* PyMeshPlugin::createPolyMesh() { int objectId = -1; Q_EMIT addEmptyObject(DATA_POLY_MESH, objectId); PolyMeshObject* object; PluginFunctions::getObject(objectId, object); createdObjects_.push_back(objectId); return reinterpret_cast<OpenMesh::Python::PolyMesh*>(object->mesh()); } <|endoftext|>
<commit_before>/* * Quad2.h * * Created on: May 15, 2013 * Author: Ryler Hockenbury * * Quad2 */ // Do not remove the include below #include "Quad2.h" uint8_t vehicleStatus = 0x0; bool onGround = TRUE; ITG3200 gyro; ADXL345 accel; HMC5883L comp; AR6210 receiver; PID controller[2]; // pitch and roll controllers float gyroData[3] = {0.0, 0.0, 0.0}; // x, y and z axis float accelData[3] = {0.0, 0.0, 0.0}; float compData[3] = {0.0, 0.0, 0.0}; float currentFlightAngle[3] = {0.0, 0.0, 0.0}; // roll, pitch, yaw float targetFlightAngle[3] = {0.0, 0.0}; // roll and pitch float stickCommands[6] = {1500, 1500, 1500, 1000, 1000, 1000}; //raw throttle, roll, pitch, yaw bool auxStatus[2] = {ON, OFF}; // controller mode uint16_t currentSystemTime = 0; // millis() is a 16 bit timer uint16_t lastSystemTime = 0; uint16_t deltaSystemTime = 0; uint16_t last100HzTime = 0; uint16_t last50HzTime = 0; uint16_t last10HzTime = 0; void handleReceiverInterrupt() { receiver.readChannels(); } void setup() { Wire.begin(); // initialize I2C bus Serial.begin(57600); // initialize serial link receiver.init(); // initialize receiver // set up interrupts to read receiver channels pinMode(PPM_PIN, INPUT); attachInterrupt(0, handleReceiverInterrupt, RISING); // process stick inputs to bring sensors and ESCs online Serial.println("Entering process init commands"); receiver.processInitCommands(&gyro, &accel, &comp); // run system test // turn on green LED //Serial.println("Initializing Sensors"); //gyro.init(); //accel.init(); //comp.init(); delay(200); Serial.println("Starting main loop"); } // TODO config file void loop() { currentSystemTime = millis(); deltaSystemTime = currentSystemTime - lastSystemTime; //Serial.println(currentSystemTime); //Serial.println(last100HzTime); //Serial.println(deltaSystemTime); // loop time if(currentSystemTime < last100HzTime) last100HzTime = 0; if(currentSystemTime < last50HzTime) last50HzTime = 0; if(currentSystemTime < last10HzTime) last10HzTime = 0; // TODO there is a problem with timer overflow here, and maintaining frequency // TODO Can i make the assumption that these happend periodically as i would except? /* 100 Hz Tasks * Poll IMU sensors, calculate orientation, update controller and command motors. * */ if(currentSystemTime >= (last100HzTime + 10)) { /* gyro.getRate(gyroData); accel.getValue(accelData); comp.getHeading(compData); getOrientation(currentFlightAngle, gyroData, accelData, compData); */ //levelAdjust[ROLL_AXIS] = targetFlightAngle[ROLL_AXIS] - currentFlightAngle[ROLL_AXIS]; //levelAdjust[PITCH_AXIS] = targetFlightAngle[PITCH_AXIS] - currentFlightAngle[PITCH_AXIS]; //motor.axisCommand[ROLL_AXIS] = controller[ROLL_AXIS].updatePid(1500.0 + gyroData[1], stickCommands[ROLL] + levelAdjust[ROLL_AXIS]); //motor.axisCommand[PITCH_AXIS] = controller[PITCH_AXIS].updatePid(1500.0 + gyroData[0], stickCommands[PITCH] + levelAdjust[PITCH_AXIS]); //motor.axisCommand[THROTTLE] = stickCommands[THROTTLE]; //motor.axisCommand[YAW_AXIS] = stickCommands[YAW]; //motor.command[MOTOR1] = throttle + roll + pitch + yaw commands; last100HzTime = currentSystemTime; } /* 50 Hz Tasks * Read and sanitize commands from radio, and monitor battery. * */ if(currentSystemTime >= (last50HzTime + 20)) { receiver.getStickCommands(stickCommands); //targetFlightAngle[ROLL_AXIS] = reciever.mapStickCommandToAngle(stickCommands[ROLL]); //targetFlightAngle[PITCH_AXIS] = reciever.mapStickCommandToAngle(stickCommands[PITCH]); //bool auxStatus[AUX1] = reciever.mapStickCommandToBool(stickCommands[AUX1]); //bool auxStatus[AUX2] = reciever.mapStickCommandToBool(stickCommands[AUX2]); //controller[ROLL_AXIS].setMode(aux1Status[AUX1]); //controller[PITCH_AXIS].setMode(aux1Status[AUX1]); //TODO - monitor battery health last50HzTime = currentSystemTime; } /* 10 Hz Tasks * Send serial stream to ground station. * */ if(currentSystemTime >= (last10HzTime + 100)) { serialOpen(); //serialPrint(currentFlightAngle, 3); // must remove extra comma serialPrint(stickCommands, 6); //serialPrint(battVoltage); //serialPrint(battCurrent); serialClose(); // TODO - check for and process serial input // pid gains // stick scale/senstivitiy last10HzTime = currentSystemTime; } lastSystemTime = currentSystemTime; } ///////////////////////////////////////////// // CODE TO READ SERIES OF SENSOR REGSITERS // ///////////////////////////////////////////// /* byte buffer[6]; Serial.print("\n"); Serial.println("Reading Initialized Bytes"); I2Cdev::readByte(0x53, 0x0, buffer); Serial.print("\n"); Serial.print(buffer[0], HEX); Serial.print("\n"); I2Cdev::readByte(0x53, 0x1E, buffer); Serial.print("\n"); Serial.print(buffer[0]); Serial.print("\n"); I2Cdev::readByte(0x53, 0x1F, buffer); Serial.print("\n"); Serial.print(buffer[0]); Serial.print("\n"); I2Cdev::readByte(0x53, 0x20, buffer); Serial.print("\n"); Serial.print(buffer[0]); Serial.print("\n"); I2Cdev::readByte(0x53, 0x2C, buffer); Serial.print("\n"); Serial.print(buffer[0], BIN); Serial.print("\n"); I2Cdev::readByte(0x53, 0x2d, buffer); Serial.print("\n"); Serial.print(buffer[0], BIN); Serial.print("\n"); I2Cdev::readByte(0x53, 0x31, buffer); Serial.print("\n"); Serial.print(buffer[0], BIN); Serial.print("\n"); */ //delay(20); //Serial.print(buffer[0]); //Serial.print("\n"); //delay(5000); //gyro.setSampleRate(0x9); //Serial.println("Writing Byte"); //byte status = I2Cdev::writeByte(0x68, 0x15, 0x9); //Serial.print(status); //delay(5000); //I2Cdev::readBytes(0x68, 0x1D, 6, buffer); //Serial.print("\n"); //Serial.println("Reading Byte"); //I2Cdev::readByte(0x68, 0x15, buffer); //Serial.print(buffer[0]); //Serial.print("\n"); <commit_msg>Changed timer variables to 32 bits <commit_after>/* * Quad2.h * * Created on: May 15, 2013 * Author: Ryler Hockenbury * * Quad2 */ // Do not remove the include below #include "Quad2.h" uint8_t vehicleStatus = 0x0; bool onGround = TRUE; ITG3200 gyro; ADXL345 accel; HMC5883L comp; AR6210 receiver; PID controller[2]; // pitch and roll controllers float gyroData[3] = {0.0, 0.0, 0.0}; // x, y and z axis float accelData[3] = {0.0, 0.0, 0.0}; float compData[3] = {0.0, 0.0, 0.0}; float currentFlightAngle[3] = {0.0, 0.0, 0.0}; // roll, pitch, yaw float targetFlightAngle[3] = {0.0, 0.0}; // roll and pitch float stickCommands[6] = {1500, 1500, 1500, 1000, 1000, 1000}; //raw throttle, roll, pitch, yaw bool auxStatus[2] = {ON, OFF}; // controller mode uint32_t currentSystemTime = 0; uint32_t lastSystemTime = 0; uint32_t deltaSystemTime = 0; uint32_t last100HzTime = 0; uint32_t last50HzTime = 0; uint32_t last10HzTime = 0; void handleReceiverInterrupt() { receiver.readChannels(); } void setup() { Wire.begin(); // initialize I2C bus Serial.begin(57600); // initialize serial link receiver.init(); // initialize receiver // set up interrupts to read receiver channels pinMode(PPM_PIN, INPUT); attachInterrupt(0, handleReceiverInterrupt, RISING); // process stick inputs to bring sensors and ESCs online Serial.println("Entering process init commands"); receiver.processInitCommands(&gyro, &accel, &comp); // run system test // turn on green LED //Serial.println("Initializing Sensors"); //gyro.init(); //accel.init(); //comp.init(); delay(200); Serial.println("Starting main loop"); } // TODO config file void loop() { currentSystemTime = millis(); deltaSystemTime = currentSystemTime - lastSystemTime; Serial.println("current:" + currentSystemTime); Serial.println("100Hz:" + last100HzTime); Serial.println("50Hz:" + last50HzTime); Serial.println("10Hz:" + last10HzTime); Serial.println("last:" + deltaSystemTime); // loop time //if(currentSystemTime < last100HzTime) // last100HzTime = 0; //if(currentSystemTime < last50HzTime) // last50HzTime = 0; //if(currentSystemTime < last10HzTime) // last10HzTime = 0; // TODO there is a problem with timer overflow here, and maintaining frequency /// this is fixed, i think, just need testing // TODO Can i make the assumption that these happend periodically as i would except? /* 100 Hz Tasks * Poll IMU sensors, calculate orientation, update controller and command motors. * */ if(currentSystemTime >= (last100HzTime + 10)) { /* gyro.getRate(gyroData); accel.getValue(accelData); comp.getHeading(compData); getOrientation(currentFlightAngle, gyroData, accelData, compData); */ //levelAdjust[ROLL_AXIS] = targetFlightAngle[ROLL_AXIS] - currentFlightAngle[ROLL_AXIS]; //levelAdjust[PITCH_AXIS] = targetFlightAngle[PITCH_AXIS] - currentFlightAngle[PITCH_AXIS]; //motor.axisCommand[ROLL_AXIS] = controller[ROLL_AXIS].updatePid(1500.0 + gyroData[1], stickCommands[ROLL] + levelAdjust[ROLL_AXIS]); //motor.axisCommand[PITCH_AXIS] = controller[PITCH_AXIS].updatePid(1500.0 + gyroData[0], stickCommands[PITCH] + levelAdjust[PITCH_AXIS]); //motor.axisCommand[THROTTLE] = stickCommands[THROTTLE]; //motor.axisCommand[YAW_AXIS] = stickCommands[YAW]; //motor.command[MOTOR1] = throttle + roll + pitch + yaw commands; last100HzTime = currentSystemTime; } /* 50 Hz Tasks * Read and sanitize commands from radio, and monitor battery. * */ if(currentSystemTime >= (last50HzTime + 20)) { //receiver.getStickCommands(stickCommands); //targetFlightAngle[ROLL_AXIS] = reciever.mapStickCommandToAngle(stickCommands[ROLL]); //targetFlightAngle[PITCH_AXIS] = reciever.mapStickCommandToAngle(stickCommands[PITCH]); //bool auxStatus[AUX1] = reciever.mapStickCommandToBool(stickCommands[AUX1]); //bool auxStatus[AUX2] = reciever.mapStickCommandToBool(stickCommands[AUX2]); //controller[ROLL_AXIS].setMode(aux1Status[AUX1]); //controller[PITCH_AXIS].setMode(aux1Status[AUX1]); //TODO - monitor battery health last50HzTime = currentSystemTime; } /* 10 Hz Tasks * Send serial stream to ground station. * */ if(currentSystemTime >= (last10HzTime + 100)) { serialOpen(); //serialPrint(currentFlightAngle, 3); // must remove extra comma //serialPrint(stickCommands, 6); //serialPrint(battVoltage); //serialPrint(battCurrent); serialClose(); // TODO - check for and process serial input // pid gains // stick scale/senstivitiy last10HzTime = currentSystemTime; } lastSystemTime = currentSystemTime; } ///////////////////////////////////////////// // CODE TO READ SERIES OF SENSOR REGSITERS // ///////////////////////////////////////////// /* byte buffer[6]; Serial.print("\n"); Serial.println("Reading Initialized Bytes"); I2Cdev::readByte(0x53, 0x0, buffer); Serial.print("\n"); Serial.print(buffer[0], HEX); Serial.print("\n"); I2Cdev::readByte(0x53, 0x1E, buffer); Serial.print("\n"); Serial.print(buffer[0]); Serial.print("\n"); I2Cdev::readByte(0x53, 0x1F, buffer); Serial.print("\n"); Serial.print(buffer[0]); Serial.print("\n"); I2Cdev::readByte(0x53, 0x20, buffer); Serial.print("\n"); Serial.print(buffer[0]); Serial.print("\n"); I2Cdev::readByte(0x53, 0x2C, buffer); Serial.print("\n"); Serial.print(buffer[0], BIN); Serial.print("\n"); I2Cdev::readByte(0x53, 0x2d, buffer); Serial.print("\n"); Serial.print(buffer[0], BIN); Serial.print("\n"); I2Cdev::readByte(0x53, 0x31, buffer); Serial.print("\n"); Serial.print(buffer[0], BIN); Serial.print("\n"); */ //delay(20); //Serial.print(buffer[0]); //Serial.print("\n"); //delay(5000); //gyro.setSampleRate(0x9); //Serial.println("Writing Byte"); //byte status = I2Cdev::writeByte(0x68, 0x15, 0x9); //Serial.print(status); //delay(5000); //I2Cdev::readBytes(0x68, 0x1D, 6, buffer); //Serial.print("\n"); //Serial.println("Reading Byte"); //I2Cdev::readByte(0x68, 0x15, buffer); //Serial.print(buffer[0]); //Serial.print("\n"); <|endoftext|>
<commit_before>/* This is an example file shipped by 'Aleph - A Library for Exploring Persistent Homology'. This example demonstrates how to load a network---a graph---from a variety of input files. The graph will subsequently be expanded to a simplicial complex and the persistent homology of the graph will be calculated. Demonstrated classes: - aleph::PersistenceDiagram - aleph::geometry::RipsExpander - aleph::topology::io::EdgeListReader - aleph::topology::io::GMLReader - aleph::topology::io::PajekReader - aleph::topology::Simplex - aleph::topology::SimplicialComplex - aleph::topology::filtrations::Data Demonstrated functions: - aleph::calculatePersistenceDiagrams - aleph::utilities::basename - aleph::utilities::extension - aleph::utilities::format - aleph::utilities::stem - Betti numbers of persistence diagrams - Simplicial complex dimensionality queries - Simplicial complex sorting (for filtrations) Original author: Bastian Rieck */ #include <aleph/geometry/RipsExpander.hh> #include <aleph/topology/io/EdgeLists.hh> #include <aleph/topology/io/GML.hh> #include <aleph/topology/io/Pajek.hh> #include <aleph/persistentHomology/Calculation.hh> #include <aleph/topology/Simplex.hh> #include <aleph/topology/SimplicialComplex.hh> #include <aleph/topology/filtrations/Data.hh> #include <aleph/utilities/Filesystem.hh> #include <aleph/utilities/Format.hh> #include <cmath> #include <algorithm> #include <iostream> #include <fstream> #include <limits> #include <sstream> #include <string> #include <vector> #include <getopt.h> void usage() { std::cerr << "Usage: network_analysis FILE [DIMENSION]\n" << "\n" << "Loads a weighted network (graph) from FILE, expands it up to\n" << "the specified DIMENSION, and calculates persistence diagrams\n" << "of the weight function of the input.\n" << "\n" << "Diagrams will be written to STDOUT in a gnuplot-like style.\n" << "\n" << "Optional arguments:\n" << "\n" << " --infinity FACTOR: Sets the value to use for unpaired points\n" << " in the persistence diagram. By default, a\n" << " large number or +inf will be used. If the\n" << " specified number is non-zero, it shall be\n" << " used as a factor in the weight assignment\n" << " of these points.\n" << "\n" << " --invert-weights: If specified, inverts input weights. This\n" << " is useful if the original weights measure\n" << " the strength of a relationship, and not a\n" << " dissimilarity between nodes.\n" << "\n" << " --normalize : Normalizes all weights to [0,1]. Use this\n" << " to compare multiple networks.\n" << "\n" << " --output PATH : Uses the specified path to store diagrams\n" << " instead of writing them to STDOUT.\n" << "\n" << "\n"; } int main( int argc, char** argv ) { // We have to specify the required data type and vertex type for the // simplex class here. These settings are generic and should cover // most situations. If your weights are floats or even integers, you // can of course change it here. Likewise, if your simplicial complex // is very small, you could use `short` instead of `unsigned` to // represent all possible values for vertices. using DataType = double; using VertexType = unsigned; static option commandLineOptions[] = { { "infinity" , required_argument, nullptr, 'f' }, { "invert-weights", no_argument , nullptr, 'i' }, { "normalize" , no_argument , nullptr, 'n' }, { "output" , required_argument, nullptr, 'o' }, { nullptr , 0 , nullptr, 0 } }; bool invertWeights = false; bool normalize = false; DataType infinity = std::numeric_limits<DataType>::has_infinity ? std::numeric_limits<DataType>::infinity() : std::numeric_limits<DataType>::max(); std::string basePath = std::string(); { int option = 0; while( ( option = getopt_long( argc, argv, "f:ino:", commandLineOptions, nullptr ) ) != -1 ) { switch( option ) { case 'f': infinity = static_cast<DataType>( std::stod( optarg ) ); break; case 'i': invertWeights = true; break; case 'n': normalize = true; break; case 'o': basePath = optarg; break; default: break; } } } if( (argc - optind ) < 1 ) { usage(); return -1; } // These are just given for convenience. It makes declaring an // instance of a simplicial complex much easier. using Simplex = aleph::topology::Simplex<DataType, VertexType>; using SimplicialComplex = aleph::topology::SimplicialComplex<Simplex>; // By convention, simplicial complexes are always called K (or L if // you need two of them). This is probably bad style. ;) SimplicialComplex K; // Reading ----------------------------------------------------------- std::string filename = argv[optind++]; std::cerr << "* Reading '" << filename << "'..."; // For supporting different graph formats, Aleph offers different // loader classes. Every loader class uses the same interface for // reading simplicial complexes, via `operator()()`. // // Some loader classes support special features of a given format // such as label reading. Here, we do not make use of any of them // because we are only interested in demonstrating the expansion. // // Every reader attempts to read edge weights from the file. They // are assigned to the 1-simplices in the simplicial complex. { auto extension = aleph::utilities::extension( filename ); if( extension == ".gml" ) { aleph::topology::io::GMLReader reader; reader( filename, K ); } else if( extension == ".net" ) { aleph::topology::io::PajekReader reader; reader( filename, K ); } else { aleph::topology::io::EdgeListReader reader; reader( filename, K ); } } std::cerr << "finished\n" << "* Extracted simplicial complex with " << K.size() << " simplices\n"; // Pre-processing ---------------------------------------------------- // // Determine the minimum and the maximum weight. If desired by the // user, normalize those weights and/or invert them. DataType maxWeight = std::numeric_limits<DataType>::lowest(); DataType minWeight = std::numeric_limits<DataType>::max(); for( auto&& simplex : K ) { maxWeight = std::max( maxWeight, simplex.data() ); minWeight = std::min( minWeight, simplex.data() ); } if( normalize && maxWeight != minWeight ) { std::cerr << "* Normalizing weights to [0,1]..."; auto range = maxWeight - minWeight; for (auto it = K.begin(); it != K.end(); ++it ) { if( it->dimension() == 0 ) continue; auto s = *it; s.setData( ( s.data() - minWeight ) / range ); K.replace( it, s ); } maxWeight = DataType(1); minWeight = DataType(0); std::cerr << "finished\n"; } if( invertWeights ) { std::cerr << "* Inverting filtration weights..."; for( auto it = K.begin(); it != K.end(); ++it ) { if( it->dimension() == 0 ) continue; auto s = *it; s.setData( maxWeight - s.data() ); K.replace( it, s ); } std::cerr << "finished\n"; } // Rips expansion ---------------------------------------------------- // // The Rips expander is a generic class for expanding a graph into a // higher-dimensional simplicial complex. This follows the procedure // described in: // // Fast construction of the Vietoris--Rips complex // Afra Zomorodian // Computers & Graphics, Volume 34, Issue 3, pp. 263-–271 // // Formally speaking, the algorithm creates a k-simplex for subsets // of simplices in which k+1 simplices have pairwise intersections. // // Hence, if all three edges of a triangle are present, a 2-simplex // will be added to the simplicial complex. std::cerr << "* Expanding simplicial complex..."; aleph::geometry::RipsExpander<SimplicialComplex> ripsExpander; if( argc - optind > 0 ) K = ripsExpander( K, static_cast<unsigned>( std::stoul( argv[optind++] ) ) ); // This leaves the simplicial complex untouched. The simplices with // highest dimension are the edges, i.e. the 1-simplices. else K = ripsExpander( K, 1 ); // This tells the expander to use the maximum weight of the faces of // a simplex in order to assign the weight of the simplex. Thus, the // simplicial complex models a sublevel set filtration after sorting // it with the appropriate functor. K = ripsExpander.assignMaximumWeight( K ); std::cerr << "...finished\n" << "* Expanded complex has dimension " << K.dimension() << "\n" << "* Expanded complex has " << K.size() << " simplices\n"; std::cerr << "* Establishing filtration order..."; // A filtration is an ordering of K in which faces precede co-faces in // order to ensure that the ordering represents a growing complex. The // functor used below sorts simplices based on their data. It hence is // just another way of expressing the weights specified in the graph. // // The data-based filtration ensures that upon coinciding weights, the // lower-dimensional simplex will precede the higher-dimensional one. K.sort( aleph::topology::filtrations::Data<Simplex>() ); std::cerr << "...finished\n"; // Persistent homology calculation ----------------------------------- // // This uses a convenience function. It expects a simplicial complex // in filtration order, calculates it persistent homology using the // default algorithms, and returns a vector of persistence diagrams. std::cerr << "* Calculating persistent homology..."; auto diagrams = aleph::calculatePersistenceDiagrams( K ); std::cerr << "...finished\n"; for( auto&& D : diagrams ) { // This removes all features with a persistence of zero. They only // clutter up the diagram. D.removeDiagonal(); if( std::isfinite( infinity ) && infinity != std::numeric_limits<DataType>::max() ) { std::cerr << "* Transforming unpaired points in persistence diagram with a factor of " << infinity << "...\n"; using PersistenceDiagram = aleph::PersistenceDiagram<DataType>; std::transform( D.begin(), D.end(), D.begin(), [&maxWeight, &infinity] ( const PersistenceDiagram::Point& p ) { if( !std::isfinite( p.y() ) ) return PersistenceDiagram::Point( p.x(), infinity * maxWeight ); else return PersistenceDiagram::Point( p ); } ); } std::ostringstream stream; // This 'header' contains some informative entries about the // persistence diagram. // // The Betti number counts how many simplices are without a // partner in the diagram. // // Notice that the diagram has pre-defined output operator; // if you do not like the output, you may of course iterate // over the points in the diagram yourself. stream << "# Persistence diagram <" << filename << ">\n" << "#\n" << "# Dimension : " << D.dimension() << "\n" << "# Entries : " << D.size() << "\n" << "# Betti number: " << D.betti() << "\n" << D; // Use the separator for all but the last persistence diagram. Else, // the output format is inconsistent and results in empty files. if( D != diagrams.back() ) stream << "\n\n"; if( basePath.empty() ) std::cout << stream.str(); else { using namespace aleph::utilities; auto outputFilename = basePath + "/" + stem( basename( filename ) ) + "_d" + format( D.dimension(), K.dimension() ) + ".txt"; std::cerr << "* Storing output in '" << outputFilename << "'...\n"; std::ofstream out( outputFilename ); out << stream.str(); } } } <commit_msg>Fixed file formatting for network analysis example<commit_after>/* This is an example file shipped by 'Aleph - A Library for Exploring Persistent Homology'. This example demonstrates how to load a network---a graph---from a variety of input files. The graph will subsequently be expanded to a simplicial complex and the persistent homology of the graph will be calculated. Demonstrated classes: - aleph::PersistenceDiagram - aleph::geometry::RipsExpander - aleph::topology::io::EdgeListReader - aleph::topology::io::GMLReader - aleph::topology::io::PajekReader - aleph::topology::Simplex - aleph::topology::SimplicialComplex - aleph::topology::filtrations::Data Demonstrated functions: - aleph::calculatePersistenceDiagrams - aleph::utilities::basename - aleph::utilities::extension - aleph::utilities::format - aleph::utilities::stem - Betti numbers of persistence diagrams - Simplicial complex dimensionality queries - Simplicial complex sorting (for filtrations) Original author: Bastian Rieck */ #include <aleph/geometry/RipsExpander.hh> #include <aleph/topology/io/EdgeLists.hh> #include <aleph/topology/io/GML.hh> #include <aleph/topology/io/Pajek.hh> #include <aleph/persistentHomology/Calculation.hh> #include <aleph/topology/Simplex.hh> #include <aleph/topology/SimplicialComplex.hh> #include <aleph/topology/filtrations/Data.hh> #include <aleph/utilities/Filesystem.hh> #include <aleph/utilities/Format.hh> #include <cmath> #include <algorithm> #include <iostream> #include <fstream> #include <limits> #include <sstream> #include <string> #include <vector> #include <getopt.h> void usage() { std::cerr << "Usage: network_analysis FILE [DIMENSION]\n" << "\n" << "Loads a weighted network (graph) from FILE, expands it up to\n" << "the specified DIMENSION, and calculates persistence diagrams\n" << "of the weight function of the input.\n" << "\n" << "Diagrams will be written to STDOUT in a gnuplot-like style.\n" << "\n" << "Optional arguments:\n" << "\n" << " --infinity FACTOR: Sets the value to use for unpaired points\n" << " in the persistence diagram. By default, a\n" << " large number or +inf will be used. If the\n" << " specified number is non-zero, it shall be\n" << " used as a factor in the weight assignment\n" << " of these points.\n" << "\n" << " --invert-weights: If specified, inverts input weights. This\n" << " is useful if the original weights measure\n" << " the strength of a relationship, and not a\n" << " dissimilarity between nodes.\n" << "\n" << " --normalize : Normalizes all weights to [0,1]. Use this\n" << " to compare multiple networks.\n" << "\n" << " --output PATH : Uses the specified path to store diagrams\n" << " instead of writing them to STDOUT.\n" << "\n" << "\n"; } int main( int argc, char** argv ) { // We have to specify the required data type and vertex type for the // simplex class here. These settings are generic and should cover // most situations. If your weights are floats or even integers, you // can of course change it here. Likewise, if your simplicial complex // is very small, you could use `short` instead of `unsigned` to // represent all possible values for vertices. using DataType = double; using VertexType = unsigned; static option commandLineOptions[] = { { "infinity" , required_argument, nullptr, 'f' }, { "invert-weights", no_argument , nullptr, 'i' }, { "normalize" , no_argument , nullptr, 'n' }, { "output" , required_argument, nullptr, 'o' }, { nullptr , 0 , nullptr, 0 } }; bool invertWeights = false; bool normalize = false; DataType infinity = std::numeric_limits<DataType>::has_infinity ? std::numeric_limits<DataType>::infinity() : std::numeric_limits<DataType>::max(); std::string basePath = std::string(); { int option = 0; while( ( option = getopt_long( argc, argv, "f:ino:", commandLineOptions, nullptr ) ) != -1 ) { switch( option ) { case 'f': infinity = static_cast<DataType>( std::stod( optarg ) ); break; case 'i': invertWeights = true; break; case 'n': normalize = true; break; case 'o': basePath = optarg; break; default: break; } } } if( (argc - optind ) < 1 ) { usage(); return -1; } // These are just given for convenience. It makes declaring an // instance of a simplicial complex much easier. using Simplex = aleph::topology::Simplex<DataType, VertexType>; using SimplicialComplex = aleph::topology::SimplicialComplex<Simplex>; // By convention, simplicial complexes are always called K (or L if // you need two of them). This is probably bad style. ;) SimplicialComplex K; // Reading ----------------------------------------------------------- std::string filename = argv[optind++]; std::cerr << "* Reading '" << filename << "'..."; // For supporting different graph formats, Aleph offers different // loader classes. Every loader class uses the same interface for // reading simplicial complexes, via `operator()()`. // // Some loader classes support special features of a given format // such as label reading. Here, we do not make use of any of them // because we are only interested in demonstrating the expansion. // // Every reader attempts to read edge weights from the file. They // are assigned to the 1-simplices in the simplicial complex. { auto extension = aleph::utilities::extension( filename ); if( extension == ".gml" ) { aleph::topology::io::GMLReader reader; reader( filename, K ); } else if( extension == ".net" ) { aleph::topology::io::PajekReader reader; reader( filename, K ); } else { aleph::topology::io::EdgeListReader reader; reader( filename, K ); } } std::cerr << "finished\n" << "* Extracted simplicial complex with " << K.size() << " simplices\n"; // Pre-processing ---------------------------------------------------- // // Determine the minimum and the maximum weight. If desired by the // user, normalize those weights and/or invert them. DataType maxWeight = std::numeric_limits<DataType>::lowest(); DataType minWeight = std::numeric_limits<DataType>::max(); for( auto&& simplex : K ) { maxWeight = std::max( maxWeight, simplex.data() ); minWeight = std::min( minWeight, simplex.data() ); } if( normalize && maxWeight != minWeight ) { std::cerr << "* Normalizing weights to [0,1]..."; auto range = maxWeight - minWeight; for (auto it = K.begin(); it != K.end(); ++it ) { if( it->dimension() == 0 ) continue; auto s = *it; s.setData( ( s.data() - minWeight ) / range ); K.replace( it, s ); } maxWeight = DataType(1); minWeight = DataType(0); std::cerr << "finished\n"; } if( invertWeights ) { std::cerr << "* Inverting filtration weights..."; for( auto it = K.begin(); it != K.end(); ++it ) { if( it->dimension() == 0 ) continue; auto s = *it; s.setData( maxWeight - s.data() ); K.replace( it, s ); } std::cerr << "finished\n"; } // Rips expansion ---------------------------------------------------- // // The Rips expander is a generic class for expanding a graph into a // higher-dimensional simplicial complex. This follows the procedure // described in: // // Fast construction of the Vietoris--Rips complex // Afra Zomorodian // Computers & Graphics, Volume 34, Issue 3, pp. 263-–271 // // Formally speaking, the algorithm creates a k-simplex for subsets // of simplices in which k+1 simplices have pairwise intersections. // // Hence, if all three edges of a triangle are present, a 2-simplex // will be added to the simplicial complex. std::cerr << "* Expanding simplicial complex..."; // By default, tThis leaves the simplicial complex untouched. The // simplices with highest dimension are the 1-simplices, i.e. the // edges. If the user specified an optional parameter, we use it. unsigned k = 1; if( argc - optind > 0 ) k = static_cast<unsigned>( std::stoul( argv[optind++] ) ); aleph::geometry::RipsExpander<SimplicialComplex> ripsExpander; K = ripsExpander( K, k ); // This tells the expander to use the maximum weight of the faces of // a simplex in order to assign the weight of the simplex. Thus, the // simplicial complex models a sublevel set filtration after sorting // it with the appropriate functor. K = ripsExpander.assignMaximumWeight( K ); std::cerr << "...finished\n" << "* Expanded complex has dimension " << K.dimension() << "\n" << "* Expanded complex has " << K.size() << " simplices\n"; std::cerr << "* Establishing filtration order..."; // A filtration is an ordering of K in which faces precede co-faces in // order to ensure that the ordering represents a growing complex. The // functor used below sorts simplices based on their data. It hence is // just another way of expressing the weights specified in the graph. // // The data-based filtration ensures that upon coinciding weights, the // lower-dimensional simplex will precede the higher-dimensional one. K.sort( aleph::topology::filtrations::Data<Simplex>() ); std::cerr << "...finished\n"; // Persistent homology calculation ----------------------------------- // // This uses a convenience function. It expects a simplicial complex // in filtration order, calculates it persistent homology using the // default algorithms, and returns a vector of persistence diagrams. std::cerr << "* Calculating persistent homology..."; auto diagrams = aleph::calculatePersistenceDiagrams( K ); std::cerr << "...finished\n"; for( auto&& D : diagrams ) { // This removes all features with a persistence of zero. They only // clutter up the diagram. D.removeDiagonal(); if( std::isfinite( infinity ) && infinity != std::numeric_limits<DataType>::max() ) { std::cerr << "* Transforming unpaired points in persistence diagram with a factor of " << infinity << "...\n"; using PersistenceDiagram = aleph::PersistenceDiagram<DataType>; std::transform( D.begin(), D.end(), D.begin(), [&maxWeight, &infinity] ( const PersistenceDiagram::Point& p ) { if( !std::isfinite( p.y() ) ) return PersistenceDiagram::Point( p.x(), infinity * maxWeight ); else return PersistenceDiagram::Point( p ); } ); } std::ostringstream stream; // This 'header' contains some informative entries about the // persistence diagram. // // The Betti number counts how many simplices are without a // partner in the diagram. // // Notice that the diagram has pre-defined output operator; // if you do not like the output, you may of course iterate // over the points in the diagram yourself. stream << "# Persistence diagram <" << filename << ">\n" << "#\n" << "# Dimension : " << D.dimension() << "\n" << "# Entries : " << D.size() << "\n" << "# Betti number: " << D.betti() << "\n" << D; // Use the separator for all but the last persistence diagram. Else, // the output format is inconsistent and results in empty files. if( D != diagrams.back() ) stream << "\n\n"; if( basePath.empty() ) std::cout << stream.str(); else { using namespace aleph::utilities; // The formatting ensures that if the user specified an expansion // up to, say, 10, the resulting files will use two-digit numbers // instead of one-digit numbers, regardless of how many complexes // there are. auto outputFilename = basePath + "/" + stem( basename( filename ) ) + "_d" + format( D.dimension(), std::max( K.dimension(), static_cast<std::size_t>(k) ) ) + ".txt"; std::cerr << "* Storing output in '" << outputFilename << "'...\n"; std::ofstream out( outputFilename ); out << stream.str(); } } } <|endoftext|>
<commit_before>/* Copyright (C) 2012-2013 Collabora Ltd. <info@collabora.com> @author George Kiagiadakis <george.kiagiadakis@collabora.com> Copyright (C) 2013 basysKom GmbH <info@basyskom.com> @author Benjamin Federau <benjamin.federau@basyskom.com> 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 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "player.h" #include <QtGui/QGuiApplication> #include <QtQuick/QQuickView> #include <QtQml/QQmlContext> #include <QtQml/QQmlEngine> #include <QGst/Init> #include <QGst/Quick/VideoSurface> int main(int argc, char **argv) { #if defined(QTVIDEOSINK_PATH) //this allows the example to run from the QtGStreamer build tree without installing QtGStreamer qputenv("GST_PLUGIN_PATH", QTVIDEOSINK_PATH); #endif QGuiApplication app(argc, argv); QGst::init(&argc, &argv); QQuickView view; QGst::Quick::VideoSurface *surface = new QGst::Quick::VideoSurface; view.rootContext()->setContextProperty(QLatin1String("videoSurface1"), surface); Player *player = new Player(&view); player->setVideoSink(surface->videoSink()); player->setUri(QLatin1Literal("http://download.blender.org/peach/bigbuckbunny_movies/big_buck_bunny_480p_surround-fix.avi")); view.rootContext()->setContextProperty(QLatin1String("player"), player); #if defined(UNINSTALLED_IMPORTS_DIR) //this allows the example to run from the QtGStreamer build tree without installing QtGStreamer view.engine()->addImportPath(QLatin1String(UNINSTALLED_IMPORTS_DIR)); #endif view.setSource(QUrl(QLatin1String("qrc:///qmlplayer2.qml"))); view.show(); return app.exec(); } <commit_msg>examples/qmlplayer2: allow setting a different video uri from the command line<commit_after>/* Copyright (C) 2012-2013 Collabora Ltd. <info@collabora.com> @author George Kiagiadakis <george.kiagiadakis@collabora.com> Copyright (C) 2013 basysKom GmbH <info@basyskom.com> @author Benjamin Federau <benjamin.federau@basyskom.com> 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 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "player.h" #include <QtGui/QGuiApplication> #include <QtQuick/QQuickView> #include <QtQml/QQmlContext> #include <QtQml/QQmlEngine> #include <QGst/Init> #include <QGst/Quick/VideoSurface> int main(int argc, char **argv) { #if defined(QTVIDEOSINK_PATH) //this allows the example to run from the QtGStreamer build tree without installing QtGStreamer qputenv("GST_PLUGIN_PATH", QTVIDEOSINK_PATH); #endif QGuiApplication app(argc, argv); QGst::init(&argc, &argv); QQuickView view; QGst::Quick::VideoSurface *surface = new QGst::Quick::VideoSurface; view.rootContext()->setContextProperty(QLatin1String("videoSurface1"), surface); Player *player = new Player(&view); player->setVideoSink(surface->videoSink()); if (argc > 1) player->setUri(QString::fromLocal8Bit(argv[1])); else player->setUri(QLatin1Literal("http://download.blender.org/peach/bigbuckbunny_movies/big_buck_bunny_480p_surround-fix.avi")); view.rootContext()->setContextProperty(QLatin1String("player"), player); #if defined(UNINSTALLED_IMPORTS_DIR) //this allows the example to run from the QtGStreamer build tree without installing QtGStreamer view.engine()->addImportPath(QLatin1String(UNINSTALLED_IMPORTS_DIR)); #endif view.setSource(QUrl(QLatin1String("qrc:///qmlplayer2.qml"))); view.show(); return app.exec(); } <|endoftext|>
<commit_before>#include <iostream> #include <utility> #include <algorithm> using namespace std; typedef pair<int, int> pii; void chmin(int &a,int &b) { if(a > b) a = b; } void chmax(int &a,int &b) { if(a < b) a = b; } #define A first #define B second const int MAXN = 15010; const int MAX = 30010; int n, k; int A[MAXN]; int pref[MAXN]; int pref2[MAXN], idx[MAXN]; pii dat[MAXN]; inline void init() { for(int i = 0;i <= n;i++) dat[i].A = n, dat[i].B = 0; } inline void update(pii &a, pii b) { chmin(a.A, b.A); chmax(a.B, b.B); } inline void insertVal(int i, pii v) { for(;i <= n;i += i & - i) update(dat[i], v); } inline pii getVal(int i) { pii ret(MAXN, 0); for(;i > 0;i -= i & -i) update(ret, dat[i]); return ret; } bool OK(int M) { init(); pii res; for(int i = 1;i < n - 1;i++) { int k = n - (lower_bound(pref2, pref2 + n, pref[i] - M) - pref2); res = getVal(k); if(pref[i] <= M) insertVal(idx[i], pii(1, 1)); if(res.A < n && res.B > 0) { res.A++; res.B++; insertVal(idx[i], res); } } return res.A <= k && k <= res.B; } int solve(int L, int R) { while(R - L > 1) { int M = (L + R) / 2; if(OK(M)) R = M; else L = M; } return R; } int main() { ios::sync_with_stdio(false); int tcase; cin >> tcase; while(tcase--) { cin >> n >> k; int L = -1, R = 1; pref[0] = pref2[0] = 0; for(int i = 1;i <= n;i++) { int a; cin >> a; pref2[i] = (pref[i] = pref[i - 1] + a); if(a > 0) R += a; else L += a; } pref2[n + 1] = pref[n + 1] = L; n+=2; sort(pref2, pref2 + n); for(int i = 1;i < n - 1;i++) { idx[i] = n - (lower_bound(pref2, pref2 + n, pref[i]) - pref2); } cout << solve(L, R) << endl; } return 0; } <commit_msg>add comment<commit_after>// O(n log n log c) #include <iostream> #include <utility> #include <algorithm> using namespace std; typedef pair<int, int> pii; void chmin(int &a,int &b) { if(a > b) a = b; } void chmax(int &a,int &b) { if(a < b) a = b; } #define A first #define B second const int MAXN = 15010; const int MAX = 30010; int n, k; int A[MAXN]; int pref[MAXN]; int pref2[MAXN], idx[MAXN]; pii dat[MAXN]; inline void init() { for(int i = 0;i <= n;i++) dat[i].A = n, dat[i].B = 0; } inline void update(pii &a, pii b) { chmin(a.A, b.A); chmax(a.B, b.B); } inline void insertVal(int i, pii v) { for(;i <= n;i += i & - i) update(dat[i], v); } inline pii getVal(int i) { pii ret(MAXN, 0); for(;i > 0;i -= i & -i) update(ret, dat[i]); return ret; } bool OK(int M) { init(); pii res; for(int i = 1;i < n - 1;i++) { int k = n - (lower_bound(pref2, pref2 + n, pref[i] - M) - pref2); res = getVal(k); if(pref[i] <= M) insertVal(idx[i], pii(1, 1)); if(res.A < n && res.B > 0) { res.A++; res.B++; insertVal(idx[i], res); } } return res.A <= k && k <= res.B; } int solve(int L, int R) { while(R - L > 1) { int M = (L + R) / 2; if(OK(M)) R = M; else L = M; } return R; } int main() { ios::sync_with_stdio(false); int tcase; cin >> tcase; while(tcase--) { cin >> n >> k; int L = -1, R = 1; pref[0] = pref2[0] = 0; for(int i = 1;i <= n;i++) { int a; cin >> a; pref2[i] = (pref[i] = pref[i - 1] + a); if(a > 0) R += a; else L += a; } pref2[n + 1] = pref[n + 1] = L; n+=2; sort(pref2, pref2 + n); for(int i = 1;i < n - 1;i++) { idx[i] = n - (lower_bound(pref2, pref2 + n, pref[i]) - pref2); } cout << solve(L, R) << endl; } return 0; } <|endoftext|>
<commit_before> // // IEEE754 text encode/decode of double values // #include <clutl/Serialise.h> #include <clutl/Containers.h> extern "C" double strtod(const char* s00, char** se); namespace { enum TokenType { TT_NONE, // Single character tokens match their character values for simpler switch code TT_LBRACE = '{', TT_RBRACE = '}', TT_COMMA = ',', TT_COLON = ':', TT_LBRACKET = '[', TT_RBRACKET = ']', TT_STRING, TT_INTEGER, TT_DECIMAL, }; struct Token { Token() : type(TT_NONE) , position(0) , length(0) { } explicit Token(TokenType type, int position, int length) : type(type) , position(position) , length(length) { } TokenType type; int position; int length; struct { union { const char* string; __int64 integer; double decimal; }; } val; }; // TODO: buffer overflow checking without the data buffer asserting! bool isdigit(char c) { return c >= '0' && c <= '9'; } bool ishexdigit(char c) { return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f'); } bool Parse32bitHexDigits(clutl::DataBuffer& in) { in.SeekRel(1); // TODO: verify there are enough bytes to read 4 characters // NOTE: \u is not valid - C has the equivalent \xhh and \xhhhh // Ensure the next 4 bytes are hex digits int pos = in.GetPosition(); const char* digits = in.ReadAt(pos); return ishexdigit(digits[0]) && ishexdigit(digits[1]) && ishexdigit(digits[2]) && ishexdigit(digits[3]); } bool ParseEscapeSequence(clutl::DataBuffer& in) { in.SeekRel(1); int pos = in.GetPosition(); char c = *in.ReadAt(pos); switch (c) { // Pass all single character sequences case ('\"'): case ('\\'): case ('/'): case ('\b'): case ('\f'): case ('\n'): case ('\r'): case ('\t'): in.SeekRel(1); return true; // Parse the unicode hex digits case ('u'): return Parse32bitHexDigits(in); default: // ERROR: Invalid escape sequence return false; } } Token ParseString(clutl::DataBuffer& in) { // Start off construction of the string int pos = in.GetPosition(); Token token(TT_STRING, pos, 0); in.SeekRel(1); token.val.string = in.ReadAt(pos); // The common case here is another character as opposed to quotes so // keep looping until that happens while (true) { pos = in.GetPosition(); char c = *in.ReadAt(pos); switch (c) { // The string terminates with a quote case ('\"'): in.SeekRel(1); return token; // Escape sequence case ('\\'): if (!ParseEscapeSequence(in)) return Token(); token.length += in.GetPosition() - pos; break; // A typical string character default: in.SeekRel(1); token.length++; } } return token; } // // This will return an integer in the range [-9,223,372,036,854,775,808:9,223,372,036,854,775,807] // bool ParseInteger(clutl::DataBuffer& in, unsigned __int64& uintval) { // Consume the first digit int pos = in.GetPosition(); char c = *in.ReadAt(pos); if (!isdigit(c)) return false; uintval = 0; do { // Consume and accumulate the digit in.SeekRel(1); uintval = (uintval * 10) + (c - '0'); // Peek at the next character and leave if its not a digit pos = in.GetPosition(); c = *in.ReadAt(pos); } while (isdigit(c)); return true; } Token ParseNumber(clutl::DataBuffer& in) { // Start off construction of an integer int start_pos = in.GetPosition(); Token token(TT_INTEGER, start_pos, 0); // Consume negative bool is_negative = false; if (*in.ReadAt(start_pos) == '-') { is_negative = true; in.SeekRel(1); } // Parse the integer digits unsigned __int64 uintval; if (!ParseInteger(in, uintval)) // TODO: error return Token(); // Convert to signed integer if (is_negative) token.val.integer = 0ULL - uintval; else token.val.integer = uintval; // Is this a decimal? int pos = in.GetPosition(); char c = *in.ReadAt(pos); if (c == '.') { // Re-evaluate as a decimal using the more expensive strtod function const char* decimal_start = in.ReadAt(start_pos); char* decimal_end; token.type = TT_DECIMAL; token.val.decimal = strtod(decimal_start, &decimal_end); // Skip over the parsed decimal in.SeekAbs(start_pos + (decimal_end - decimal_start)); } return token; } Token ParseToken(clutl::DataBuffer& in) { start: unsigned int pos = in.GetPosition(); char c = *in.ReadAt(pos); switch (c) { // Branch to the start only if it's a whitespace (the least-common case) case (' '): case ('\t'): case ('\n'): case ('\v'): case ('\f'): case ('\r'): in.SeekRel(1); goto start; // Structural single character tokens case ('{'): case ('}'): case (','): case ('['): case (']'): in.SeekRel(1); return Token((TokenType)c, pos, 1); // Strings case ('\"'): return ParseString(in); case ('-'): case ('0'): case ('1'): case ('2'): case ('3'): case ('4'): case ('5'): case ('6'): case ('7'): case ('8'): case ('9'): return ParseNumber(in); default: // sequence of chars break; } return Token(); } }<commit_msg>Implemented outline of the JSON parser.<commit_after> // // IEEE754 text encode/decode of double values // #include <clutl/Serialise.h> #include <clutl/Containers.h> extern "C" double strtod(const char* s00, char** se); namespace { enum TokenType { TT_NONE, // Single character tokens match their character values for simpler switch code TT_LBRACE = '{', TT_RBRACE = '}', TT_COMMA = ',', TT_COLON = ':', TT_LBRACKET = '[', TT_RBRACKET = ']', TT_STRING, TT_TRUE, TT_FALSE, TT_NULL, TT_INTEGER, TT_DECIMAL, }; struct Token { Token() : type(TT_NONE) , position(0) , length(0) { } explicit Token(TokenType type, int position, int length) : type(type) , position(position) , length(length) { } TokenType type; int position; int length; struct { union { const char* string; __int64 integer; double decimal; }; } val; }; // TODO: buffer overflow checking without the data buffer asserting! bool isdigit(char c) { return c >= '0' && c <= '9'; } bool ishexdigit(char c) { return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f'); } bool Lexer32bitHexDigits(clutl::DataBuffer& in) { in.SeekRel(1); // TODO: verify there are enough bytes to read 4 characters // NOTE: \u is not valid - C has the equivalent \xhh and \xhhhh // Ensure the next 4 bytes are hex digits int pos = in.GetPosition(); const char* digits = in.ReadAt(pos); return ishexdigit(digits[0]) && ishexdigit(digits[1]) && ishexdigit(digits[2]) && ishexdigit(digits[3]); } bool LexerEscapeSequence(clutl::DataBuffer& in) { in.SeekRel(1); int pos = in.GetPosition(); char c = *in.ReadAt(pos); switch (c) { // Pass all single character sequences case ('\"'): case ('\\'): case ('/'): case ('\b'): case ('\f'): case ('\n'): case ('\r'): case ('\t'): in.SeekRel(1); return true; // Parse the unicode hex digits case ('u'): return Lexer32bitHexDigits(in); default: // ERROR: Invalid escape sequence return false; } } Token LexerString(clutl::DataBuffer& in) { // Start off construction of the string int pos = in.GetPosition(); Token token(TT_STRING, pos, 0); in.SeekRel(1); token.val.string = in.ReadAt(pos); // The common case here is another character as opposed to quotes so // keep looping until that happens while (true) { pos = in.GetPosition(); char c = *in.ReadAt(pos); switch (c) { // The string terminates with a quote case ('\"'): in.SeekRel(1); return token; // Escape sequence case ('\\'): if (!LexerEscapeSequence(in)) return Token(); token.length += in.GetPosition() - pos; break; // A typical string character default: in.SeekRel(1); token.length++; } } return token; } // // This will return an integer in the range [-9,223,372,036,854,775,808:9,223,372,036,854,775,807] // bool LexerInteger(clutl::DataBuffer& in, unsigned __int64& uintval) { // Consume the first digit int pos = in.GetPosition(); char c = *in.ReadAt(pos); if (!isdigit(c)) return false; uintval = 0; do { // Consume and accumulate the digit in.SeekRel(1); uintval = (uintval * 10) + (c - '0'); // Peek at the next character and leave if its not a digit pos = in.GetPosition(); c = *in.ReadAt(pos); } while (isdigit(c)); return true; } Token LexerNumber(clutl::DataBuffer& in) { // Start off construction of an integer int start_pos = in.GetPosition(); Token token(TT_INTEGER, start_pos, 0); // Consume negative bool is_negative = false; if (*in.ReadAt(start_pos) == '-') { is_negative = true; in.SeekRel(1); } // Parse the integer digits unsigned __int64 uintval; if (!LexerInteger(in, uintval)) // TODO: error return Token(); // Convert to signed integer if (is_negative) token.val.integer = 0ULL - uintval; else token.val.integer = uintval; // Is this a decimal? int pos = in.GetPosition(); char c = *in.ReadAt(pos); if (c == '.') { // Re-evaluate as a decimal using the more expensive strtod function const char* decimal_start = in.ReadAt(start_pos); char* decimal_end; token.type = TT_DECIMAL; token.val.decimal = strtod(decimal_start, &decimal_end); // Skip over the parsed decimal in.SeekAbs(start_pos + (decimal_end - decimal_start)); } return token; } Token LexerKeyword(clutl::DataBuffer& in, TokenType type, const char* keyword, int len) { // Consume the first letter int start_pos = in.GetPosition(); in.SeekRel(1); // TODO: Overflow without buffer assert // Try to match the remaining letters of the keyword int pos = in.GetPosition(); while (len && *in.ReadAt(pos) == *keyword) { keyword++; pos++; } if (len) // ERROR: Keyword didn't match return Token(); return Token(type, start_pos, in.GetPosition() - start_pos); } Token LexerToken(clutl::DataBuffer& in) { start: unsigned int pos = in.GetPosition(); char c = *in.ReadAt(pos); switch (c) { // Branch to the start only if it's a whitespace (the least-common case) case (' '): case ('\t'): case ('\n'): case ('\v'): case ('\f'): case ('\r'): in.SeekRel(1); goto start; // Structural single character tokens case ('{'): case ('}'): case (','): case ('['): case (']'): in.SeekRel(1); return Token((TokenType)c, pos, 1); // Strings case ('\"'): return LexerString(in); // Integer or floating point numbers case ('-'): case ('0'): case ('1'): case ('2'): case ('3'): case ('4'): case ('5'): case ('6'): case ('7'): case ('8'): case ('9'): return LexerNumber(in); // Keywords case ('t'): return LexerKeyword(in, TT_TRUE, "rue", 3); case ('f'): return LexerKeyword(in, TT_FALSE, "alse", 4); case ('n'): return LexerKeyword(in, TT_NULL, "ull", 3); default: // ERROR: Unexpected character break; } return Token(); } void ParserValue(clutl::DataBuffer& in, Token& t); void ParserObject(clutl::DataBuffer& in, Token& t); Token Expect(clutl::DataBuffer& in, Token& t, TokenType type) { if (t.type != type) // ERROR return Token(); Token old = t; t = LexerToken(in); return old; } void ParserString(const Token& t) { } void ParserInteger(const Token& t) { } void ParserDecimal(const Token& t) { } void ParserElements(clutl::DataBuffer& in, Token& t) { // Expect a value first ParserValue(in, t); if (t.type == TT_COMMA) { t = LexerToken(in); ParserElements(in, t); } } void ParserArray(clutl::DataBuffer& in, Token& t) { Expect(in, t, TT_LBRACKET); if (t.type == TT_RBRACKET) { t = LexerToken(in); return; } ParserElements(in, t); Expect(in, t, TT_RBRACKET); } void ParserLiteralValue(clutl::DataBuffer& in, Token& t, TokenType type, int val) { if (t.type != type) // ERROR return; // process integer t = LexerToken(in); } void ParserValue(clutl::DataBuffer& in, Token& t) { switch (t.type) { case (TT_STRING): return ParserString(Expect(in, t, TT_STRING)); case (TT_INTEGER): return ParserInteger(Expect(in, t, TT_INTEGER)); case (TT_DECIMAL): return ParserDecimal(Expect(in, t, TT_DECIMAL)); case (TT_LBRACE): return ParserObject(in, t); case (TT_LBRACKET): return ParserArray(in, t); case (TT_TRUE): return ParserLiteralValue(in, t, TT_TRUE, 1); case (TT_FALSE): return ParserLiteralValue(in, t, TT_FALSE, 0); case (TT_NULL): return ParserLiteralValue(in, t, TT_NULL, 0); default: // ERROR unexpected token break; } } void ParserPair(clutl::DataBuffer& in, Token& t) { Expect(in, t, TT_STRING); Expect(in, t, TT_COLON); ParserValue(in, t); } void ParserMembers(clutl::DataBuffer& in, Token& t) { ParserPair(in, t); if (t.type == TT_COMMA) { t = LexerToken(in); ParserMembers(in, t); } } void ParserObject(clutl::DataBuffer& in, Token& t) { Expect(in, t, TT_LBRACE); if (t.type == TT_RBRACE) { t = LexerToken(in); return; } ParserMembers(in, t); Expect(in, t, TT_RBRACE); } }<|endoftext|>
<commit_before>// sota.cpp : Defines the entry point for the console application. // #include <regex> #include "stdafx.h" #include "utils.h" #include "lexer.h" #include "token.h" #include "stream.hpp" #include <array> using namespace sota; std::vector<char> load(std::string filename) { std::vector<char> chars; std::ifstream file(filename, std::ios::in | std::ios::binary | std::ios::ate); if (!file.eof() && !file.fail() ) { file.seekg(0, std::ios_base::end); auto size = (unsigned int)file.tellg(); chars.resize(size); file.seekg(0, std::ios_base::beg); file.read(&chars[0], (long int)size); } return chars; } int main(int argc, char* argv[]) { if (argc < 2) return 1; const char *filename = argv[1]; std::cout << "sota parsing: " << filename << std::endl << std::endl; auto chars = load(filename); auto lexer = SotaLexer(chars); while(auto token = lexer.Scan()) { switch (token.Type) { case TokenType::EndOfLine: std::cout << lexer.Pretty(token) << std::endl; break; case TokenType::WhiteSpace: break; default: std::cout << lexer.Pretty(token) << " "; break; } } return 0; } <commit_msg>added some variable to help with debugging off by one error... -sai<commit_after>// sota.cpp : Defines the entry point for the console application. // #include <regex> #include "stdafx.h" #include "utils.h" #include "lexer.h" #include "token.h" #include "stream.hpp" #include <array> using namespace sota; std::vector<char> load(std::string filename) { std::vector<char> chars; std::ifstream file(filename, std::ios::in | std::ios::binary | std::ios::ate); if (!file.eof() && !file.fail() ) { file.seekg(0, std::ios_base::end); auto size = (unsigned int)file.tellg(); chars.resize(size); file.seekg(0, std::ios_base::beg); file.read(&chars[0], (long int)size); } return chars; } int main(int argc, char* argv[]) { if (argc < 2) return 1; const char *filename = argv[1]; std::cout << "sota parsing: " << filename << std::endl << std::endl; auto chars = load(filename); auto lexer = SotaLexer(chars); while(auto token = lexer.Scan()) { auto index = lexer.Index; auto curr = lexer.Curr; switch (token.Type) { case TokenType::EndOfLine: std::cout << lexer.Pretty(token) << std::endl; break; case TokenType::WhiteSpace: break; default: std::cout << lexer.Pretty(token) << " "; break; } } return 0; } <|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/chromeos/notifications/desktop_notifications_unittest.h" namespace chromeos { // static std::string DesktopNotificationsTest::log_output_; class MockNotificationUI : public BalloonCollectionImpl::NotificationUI { public: virtual void Add(Balloon* balloon) {} virtual bool Update(Balloon* balloon) { return false; } virtual void Remove(Balloon* balloon) {} virtual void ResizeNotification(Balloon* balloon, const gfx::Size& size) {} }; MockBalloonCollection::MockBalloonCollection() : log_proxy_(new LoggingNotificationProxy()) { set_notification_ui(new MockNotificationUI()); } void MockBalloonCollection::Add(const Notification& notification, Profile* profile) { // Swap in the logging proxy for the purpose of logging calls that // would be made into javascript, then pass this down to the // balloon collection. Notification test_notification(notification.origin_url(), notification.content_url(), notification.display_source(), log_proxy_.get()); BalloonCollectionImpl::Add(test_notification, profile); } bool MockBalloonCollection::Remove(const Notification& notification) { Notification test_notification(notification.origin_url(), notification.content_url(), notification.display_source(), log_proxy_.get()); return BalloonCollectionImpl::Remove(test_notification); } Balloon* MockBalloonCollection::MakeBalloon(const Notification& notification, Profile* profile) { // Start with a normal balloon but mock out the view. Balloon* balloon = BalloonCollectionImpl::MakeBalloon(notification, profile); balloon->set_view(new MockBalloonView(balloon)); balloons_.insert(balloon); return balloon; } void MockBalloonCollection::OnBalloonClosed(Balloon* source) { balloons_.erase(source); BalloonCollectionImpl::OnBalloonClosed(source); } int MockBalloonCollection::UppermostVerticalPosition() { int min = 0; std::set<Balloon*>::iterator iter; for (iter = balloons_.begin(); iter != balloons_.end(); ++iter) { int pos = (*iter)->position().y(); if (iter == balloons_.begin() || pos < min) min = pos; } return min; } DesktopNotificationsTest::DesktopNotificationsTest() : ui_thread_(ChromeThread::UI, &message_loop_) { } DesktopNotificationsTest::~DesktopNotificationsTest() { } void DesktopNotificationsTest::SetUp() { profile_.reset(new TestingProfile()); balloon_collection_ = new MockBalloonCollection(); ui_manager_.reset(new NotificationUIManager()); ui_manager_->Initialize(balloon_collection_); balloon_collection_->set_space_change_listener(ui_manager_.get()); service_.reset(new DesktopNotificationService(profile(), ui_manager_.get())); log_output_.clear(); } void DesktopNotificationsTest::TearDown() { profile_.reset(NULL); ui_manager_.reset(NULL); service_.reset(NULL); } TEST_F(DesktopNotificationsTest, TestShow) { EXPECT_TRUE(service_->ShowDesktopNotificationText( GURL("http://www.google.com"), GURL("/icon.png"), ASCIIToUTF16("Title"), ASCIIToUTF16("Text"), 0, 0, DesktopNotificationService::PageNotification, 1)); MessageLoopForUI::current()->RunAllPending(); EXPECT_EQ(1, balloon_collection_->count()); EXPECT_TRUE(service_->ShowDesktopNotification( GURL("http://www.google.com"), GURL("http://www.google.com/notification.html"), 0, 0, DesktopNotificationService::PageNotification, 2)); MessageLoopForUI::current()->RunAllPending(); EXPECT_EQ(2, balloon_collection_->count()); EXPECT_EQ("notification displayed\n" "notification displayed\n", log_output_); } TEST_F(DesktopNotificationsTest, TestClose) { // Request a notification; should open a balloon. EXPECT_TRUE(service_->ShowDesktopNotificationText( GURL("http://www.google.com"), GURL("/icon.png"), ASCIIToUTF16("Title"), ASCIIToUTF16("Text"), 0, 0, DesktopNotificationService::PageNotification, 1)); MessageLoopForUI::current()->RunAllPending(); EXPECT_EQ(1, balloon_collection_->count()); // Close all the open balloons. std::set<Balloon*> balloons = balloon_collection_->balloons(); std::set<Balloon*>::iterator iter; for (iter = balloons.begin(); iter != balloons.end(); ++iter) { (*iter)->OnClose(true); } // Verify that the balloon collection is now empty. EXPECT_EQ(0, balloon_collection_->count()); EXPECT_EQ("notification displayed\n" "notification closed by user\n", log_output_); } TEST_F(DesktopNotificationsTest, TestCancel) { int process_id = 0; int route_id = 0; int notification_id = 1; // Request a notification; should open a balloon. EXPECT_TRUE(service_->ShowDesktopNotificationText( GURL("http://www.google.com"), GURL("/icon.png"), ASCIIToUTF16("Title"), ASCIIToUTF16("Text"), process_id, route_id, DesktopNotificationService::PageNotification, notification_id)); MessageLoopForUI::current()->RunAllPending(); EXPECT_EQ(1, balloon_collection_->count()); // Cancel the same notification service_->CancelDesktopNotification(process_id, route_id, notification_id); MessageLoopForUI::current()->RunAllPending(); // Verify that the balloon collection is now empty. EXPECT_EQ(0, balloon_collection_->count()); EXPECT_EQ("notification displayed\n" "notification closed by script\n", log_output_); } TEST_F(DesktopNotificationsTest, TestManyNotifications) { int process_id = 0; int route_id = 0; // Request lots of identical notifications. const int kLotsOfToasts = 20; for (int id = 1; id <= kLotsOfToasts; ++id) { SCOPED_TRACE(StringPrintf("Creation loop: id=%d", id)); EXPECT_TRUE(service_->ShowDesktopNotificationText( GURL("http://www.google.com"), GURL("/icon.png"), ASCIIToUTF16("Title"), ASCIIToUTF16("Text"), process_id, route_id, DesktopNotificationService::PageNotification, id)); } MessageLoopForUI::current()->RunAllPending(); // Build up an expected log of what should be happening. std::string expected_log; for (int i = 0; i < kLotsOfToasts; ++i) { expected_log.append("notification displayed\n"); } EXPECT_EQ(kLotsOfToasts, balloon_collection_->count()); EXPECT_EQ(expected_log, log_output_); // Cancel half of the notifications from the start int id; int cancelled = kLotsOfToasts / 2; for (id = 1; id <= cancelled; ++id) { SCOPED_TRACE(StringPrintf("Cancel half of notifications: id=%d", id)); service_->CancelDesktopNotification(process_id, route_id, id); MessageLoopForUI::current()->RunAllPending(); expected_log.append("notification closed by script\n"); EXPECT_EQ(kLotsOfToasts - id, balloon_collection_->count()); EXPECT_EQ(expected_log, log_output_); } // Now cancel the rest. It should empty the balloon space. for (; id <= kLotsOfToasts; ++id) { SCOPED_TRACE(StringPrintf("Cancel loop: id=%d", id)); service_->CancelDesktopNotification(process_id, route_id, id); expected_log.append("notification closed by script\n"); MessageLoopForUI::current()->RunAllPending(); EXPECT_EQ(expected_log, log_output_); } // Verify that the balloon collection is now empty. EXPECT_EQ(0, balloon_collection_->count()); } TEST_F(DesktopNotificationsTest, TestEarlyDestruction) { // Create some toasts and then prematurely delete the notification service, // just to make sure nothing crashes/leaks. for (int id = 0; id <= 3; ++id) { SCOPED_TRACE(StringPrintf("Show Text loop: id=%d", id)); EXPECT_TRUE(service_->ShowDesktopNotificationText( GURL("http://www.google.com"), GURL("/icon.png"), ASCIIToUTF16("Title"), ASCIIToUTF16("Text"), 0, 0, DesktopNotificationService::PageNotification, id)); } service_.reset(NULL); } TEST_F(DesktopNotificationsTest, TestUserInputEscaping) { // Create a test script with some HTML; assert that it doesn't get into the // data:// URL that's produced for the balloon. EXPECT_TRUE(service_->ShowDesktopNotificationText( GURL("http://www.google.com"), GURL("/icon.png"), ASCIIToUTF16("<script>window.alert('uh oh');</script>"), ASCIIToUTF16("<i>this text is in italics</i>"), 0, 0, DesktopNotificationService::PageNotification, 1)); MessageLoopForUI::current()->RunAllPending(); EXPECT_EQ(1, balloon_collection_->count()); Balloon* balloon = (*balloon_collection_->balloons().begin()); GURL data_url = balloon->notification().content_url(); EXPECT_EQ(std::string::npos, data_url.spec().find("<script>")); EXPECT_EQ(std::string::npos, data_url.spec().find("<i>")); } } // namespace chromeos <commit_msg>TBR: skrul@chromium.org<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/chromeos/notifications/desktop_notifications_unittest.h" namespace chromeos { // static std::string DesktopNotificationsTest::log_output_; class MockNotificationUI : public BalloonCollectionImpl::NotificationUI { public: virtual void Add(Balloon* balloon) {} virtual bool Update(Balloon* balloon) { return false; } virtual void Remove(Balloon* balloon) {} virtual void ResizeNotification(Balloon* balloon, const gfx::Size& size) {} }; MockBalloonCollection::MockBalloonCollection() : log_proxy_(new LoggingNotificationProxy()) { set_notification_ui(new MockNotificationUI()); } void MockBalloonCollection::Add(const Notification& notification, Profile* profile) { // Swap in the logging proxy for the purpose of logging calls that // would be made into javascript, then pass this down to the // balloon collection. Notification test_notification(notification.origin_url(), notification.content_url(), notification.display_source(), log_proxy_.get()); BalloonCollectionImpl::Add(test_notification, profile); } bool MockBalloonCollection::Remove(const Notification& notification) { Notification test_notification(notification.origin_url(), notification.content_url(), notification.display_source(), log_proxy_.get()); return BalloonCollectionImpl::Remove(test_notification); } Balloon* MockBalloonCollection::MakeBalloon(const Notification& notification, Profile* profile) { // Start with a normal balloon but mock out the view. Balloon* balloon = BalloonCollectionImpl::MakeBalloon(notification, profile); balloon->set_view(new MockBalloonView(balloon)); balloons_.insert(balloon); return balloon; } void MockBalloonCollection::OnBalloonClosed(Balloon* source) { balloons_.erase(source); BalloonCollectionImpl::OnBalloonClosed(source); } int MockBalloonCollection::UppermostVerticalPosition() { int min = 0; std::set<Balloon*>::iterator iter; for (iter = balloons_.begin(); iter != balloons_.end(); ++iter) { int pos = (*iter)->position().y(); if (iter == balloons_.begin() || pos < min) min = pos; } return min; } DesktopNotificationsTest::DesktopNotificationsTest() : ui_thread_(ChromeThread::UI, &message_loop_) { } DesktopNotificationsTest::~DesktopNotificationsTest() { } void DesktopNotificationsTest::SetUp() { profile_.reset(new TestingProfile()); balloon_collection_ = new MockBalloonCollection(); ui_manager_.reset(new NotificationUIManager()); ui_manager_->Initialize(balloon_collection_); balloon_collection_->set_space_change_listener(ui_manager_.get()); service_.reset(new DesktopNotificationService(profile(), ui_manager_.get())); log_output_.clear(); } void DesktopNotificationsTest::TearDown() { service_.reset(NULL); profile_.reset(NULL); ui_manager_.reset(NULL); } TEST_F(DesktopNotificationsTest, TestShow) { EXPECT_TRUE(service_->ShowDesktopNotificationText( GURL("http://www.google.com"), GURL("/icon.png"), ASCIIToUTF16("Title"), ASCIIToUTF16("Text"), 0, 0, DesktopNotificationService::PageNotification, 1)); MessageLoopForUI::current()->RunAllPending(); EXPECT_EQ(1, balloon_collection_->count()); EXPECT_TRUE(service_->ShowDesktopNotification( GURL("http://www.google.com"), GURL("http://www.google.com/notification.html"), 0, 0, DesktopNotificationService::PageNotification, 2)); MessageLoopForUI::current()->RunAllPending(); EXPECT_EQ(2, balloon_collection_->count()); EXPECT_EQ("notification displayed\n" "notification displayed\n", log_output_); } TEST_F(DesktopNotificationsTest, TestClose) { // Request a notification; should open a balloon. EXPECT_TRUE(service_->ShowDesktopNotificationText( GURL("http://www.google.com"), GURL("/icon.png"), ASCIIToUTF16("Title"), ASCIIToUTF16("Text"), 0, 0, DesktopNotificationService::PageNotification, 1)); MessageLoopForUI::current()->RunAllPending(); EXPECT_EQ(1, balloon_collection_->count()); // Close all the open balloons. std::set<Balloon*> balloons = balloon_collection_->balloons(); std::set<Balloon*>::iterator iter; for (iter = balloons.begin(); iter != balloons.end(); ++iter) { (*iter)->OnClose(true); } // Verify that the balloon collection is now empty. EXPECT_EQ(0, balloon_collection_->count()); EXPECT_EQ("notification displayed\n" "notification closed by user\n", log_output_); } TEST_F(DesktopNotificationsTest, TestCancel) { int process_id = 0; int route_id = 0; int notification_id = 1; // Request a notification; should open a balloon. EXPECT_TRUE(service_->ShowDesktopNotificationText( GURL("http://www.google.com"), GURL("/icon.png"), ASCIIToUTF16("Title"), ASCIIToUTF16("Text"), process_id, route_id, DesktopNotificationService::PageNotification, notification_id)); MessageLoopForUI::current()->RunAllPending(); EXPECT_EQ(1, balloon_collection_->count()); // Cancel the same notification service_->CancelDesktopNotification(process_id, route_id, notification_id); MessageLoopForUI::current()->RunAllPending(); // Verify that the balloon collection is now empty. EXPECT_EQ(0, balloon_collection_->count()); EXPECT_EQ("notification displayed\n" "notification closed by script\n", log_output_); } TEST_F(DesktopNotificationsTest, TestManyNotifications) { int process_id = 0; int route_id = 0; // Request lots of identical notifications. const int kLotsOfToasts = 20; for (int id = 1; id <= kLotsOfToasts; ++id) { SCOPED_TRACE(StringPrintf("Creation loop: id=%d", id)); EXPECT_TRUE(service_->ShowDesktopNotificationText( GURL("http://www.google.com"), GURL("/icon.png"), ASCIIToUTF16("Title"), ASCIIToUTF16("Text"), process_id, route_id, DesktopNotificationService::PageNotification, id)); } MessageLoopForUI::current()->RunAllPending(); // Build up an expected log of what should be happening. std::string expected_log; for (int i = 0; i < kLotsOfToasts; ++i) { expected_log.append("notification displayed\n"); } EXPECT_EQ(kLotsOfToasts, balloon_collection_->count()); EXPECT_EQ(expected_log, log_output_); // Cancel half of the notifications from the start int id; int cancelled = kLotsOfToasts / 2; for (id = 1; id <= cancelled; ++id) { SCOPED_TRACE(StringPrintf("Cancel half of notifications: id=%d", id)); service_->CancelDesktopNotification(process_id, route_id, id); MessageLoopForUI::current()->RunAllPending(); expected_log.append("notification closed by script\n"); EXPECT_EQ(kLotsOfToasts - id, balloon_collection_->count()); EXPECT_EQ(expected_log, log_output_); } // Now cancel the rest. It should empty the balloon space. for (; id <= kLotsOfToasts; ++id) { SCOPED_TRACE(StringPrintf("Cancel loop: id=%d", id)); service_->CancelDesktopNotification(process_id, route_id, id); expected_log.append("notification closed by script\n"); MessageLoopForUI::current()->RunAllPending(); EXPECT_EQ(expected_log, log_output_); } // Verify that the balloon collection is now empty. EXPECT_EQ(0, balloon_collection_->count()); } TEST_F(DesktopNotificationsTest, TestEarlyDestruction) { // Create some toasts and then prematurely delete the notification service, // just to make sure nothing crashes/leaks. for (int id = 0; id <= 3; ++id) { SCOPED_TRACE(StringPrintf("Show Text loop: id=%d", id)); EXPECT_TRUE(service_->ShowDesktopNotificationText( GURL("http://www.google.com"), GURL("/icon.png"), ASCIIToUTF16("Title"), ASCIIToUTF16("Text"), 0, 0, DesktopNotificationService::PageNotification, id)); } service_.reset(NULL); } TEST_F(DesktopNotificationsTest, TestUserInputEscaping) { // Create a test script with some HTML; assert that it doesn't get into the // data:// URL that's produced for the balloon. EXPECT_TRUE(service_->ShowDesktopNotificationText( GURL("http://www.google.com"), GURL("/icon.png"), ASCIIToUTF16("<script>window.alert('uh oh');</script>"), ASCIIToUTF16("<i>this text is in italics</i>"), 0, 0, DesktopNotificationService::PageNotification, 1)); MessageLoopForUI::current()->RunAllPending(); EXPECT_EQ(1, balloon_collection_->count()); Balloon* balloon = (*balloon_collection_->balloons().begin()); GURL data_url = balloon->notification().content_url(); EXPECT_EQ(std::string::npos, data_url.spec().find("<script>")); EXPECT_EQ(std::string::npos, data_url.spec().find("<i>")); } } // namespace chromeos <|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 "base/scoped_temp_dir.h" #include "base/scoped_vector.h" #include "chrome/browser/search_engines/template_url.h" #include "chrome/browser/search_engines/template_url_prepopulate_data.h" #include "chrome/common/pref_names.h" #include "chrome/test/testing_profile.h" #include "testing/gtest/include/gtest/gtest.h" typedef testing::Test TemplateURLPrepopulateDataTest; // Verifies the set of prepopulate data doesn't contain entries with duplicate // ids. TEST_F(TemplateURLPrepopulateDataTest, UniqueIDs) { int ids[] = { 'A'<<8|'D', 'A'<<8|'E', 'A'<<8|'F', 'A'<<8|'G', 'A'<<8|'I', 'A'<<8|'L', 'A'<<8|'M', 'A'<<8|'N', 'A'<<8|'O', 'A'<<8|'Q', 'A'<<8|'R', 'A'<<8|'S', 'A'<<8|'T', 'A'<<8|'U', 'A'<<8|'W', 'A'<<8|'X', 'A'<<8|'Z', 'B'<<8|'A', 'B'<<8|'B', 'B'<<8|'D', 'B'<<8|'E', 'B'<<8|'F', 'B'<<8|'G', 'B'<<8|'H', 'B'<<8|'I', 'B'<<8|'J', 'B'<<8|'M', 'B'<<8|'N', 'B'<<8|'O', 'B'<<8|'R', 'B'<<8|'S', 'B'<<8|'T', 'B'<<8|'V', 'B'<<8|'W', 'B'<<8|'Y', 'B'<<8|'Z', 'C'<<8|'A', 'C'<<8|'C', 'C'<<8|'D', 'C'<<8|'F', 'C'<<8|'G', 'C'<<8|'H', 'C'<<8|'I', 'C'<<8|'K', 'C'<<8|'L', 'C'<<8|'M', 'C'<<8|'N', 'C'<<8|'O', 'C'<<8|'R', 'C'<<8|'U', 'C'<<8|'V', 'C'<<8|'X', 'C'<<8|'Y', 'C'<<8|'Z', 'D'<<8|'E', 'D'<<8|'J', 'D'<<8|'K', 'D'<<8|'M', 'D'<<8|'O', 'D'<<8|'Z', 'E'<<8|'C', 'E'<<8|'E', 'E'<<8|'G', 'E'<<8|'R', 'E'<<8|'S', 'E'<<8|'T', 'F'<<8|'I', 'F'<<8|'J', 'F'<<8|'K', 'F'<<8|'M', 'F'<<8|'O', 'F'<<8|'R', 'G'<<8|'A', 'G'<<8|'B', 'G'<<8|'D', 'G'<<8|'E', 'G'<<8|'F', 'G'<<8|'G', 'G'<<8|'H', 'G'<<8|'I', 'G'<<8|'L', 'G'<<8|'M', 'G'<<8|'N', 'G'<<8|'P', 'G'<<8|'Q', 'G'<<8|'R', 'G'<<8|'S', 'G'<<8|'T', 'G'<<8|'U', 'G'<<8|'W', 'G'<<8|'Y', 'H'<<8|'K', 'H'<<8|'M', 'H'<<8|'N', 'H'<<8|'R', 'H'<<8|'T', 'H'<<8|'U', 'I'<<8|'D', 'I'<<8|'E', 'I'<<8|'L', 'I'<<8|'M', 'I'<<8|'N', 'I'<<8|'O', 'I'<<8|'P', 'I'<<8|'Q', 'I'<<8|'R', 'I'<<8|'S', 'I'<<8|'T', 'J'<<8|'E', 'J'<<8|'M', 'J'<<8|'O', 'J'<<8|'P', 'K'<<8|'E', 'K'<<8|'G', 'K'<<8|'H', 'K'<<8|'I', 'K'<<8|'M', 'K'<<8|'N', 'K'<<8|'P', 'K'<<8|'R', 'K'<<8|'W', 'K'<<8|'Y', 'K'<<8|'Z', 'L'<<8|'A', 'L'<<8|'B', 'L'<<8|'C', 'L'<<8|'I', 'L'<<8|'K', 'L'<<8|'R', 'L'<<8|'S', 'L'<<8|'T', 'L'<<8|'U', 'L'<<8|'V', 'L'<<8|'Y', 'M'<<8|'A', 'M'<<8|'C', 'M'<<8|'D', 'M'<<8|'E', 'M'<<8|'G', 'M'<<8|'H', 'M'<<8|'K', 'M'<<8|'L', 'M'<<8|'M', 'M'<<8|'N', 'M'<<8|'O', 'M'<<8|'P', 'M'<<8|'Q', 'M'<<8|'R', 'M'<<8|'S', 'M'<<8|'T', 'M'<<8|'U', 'M'<<8|'V', 'M'<<8|'W', 'M'<<8|'X', 'M'<<8|'Y', 'M'<<8|'Z', 'N'<<8|'A', 'N'<<8|'C', 'N'<<8|'E', 'N'<<8|'F', 'N'<<8|'G', 'N'<<8|'I', 'N'<<8|'L', 'N'<<8|'O', 'N'<<8|'P', 'N'<<8|'R', 'N'<<8|'U', 'N'<<8|'Z', 'O'<<8|'M', 'P'<<8|'A', 'P'<<8|'E', 'P'<<8|'F', 'P'<<8|'G', 'P'<<8|'H', 'P'<<8|'K', 'P'<<8|'L', 'P'<<8|'M', 'P'<<8|'N', 'P'<<8|'R', 'P'<<8|'S', 'P'<<8|'T', 'P'<<8|'W', 'P'<<8|'Y', 'Q'<<8|'A', 'R'<<8|'E', 'R'<<8|'O', 'R'<<8|'S', 'R'<<8|'U', 'R'<<8|'W', 'S'<<8|'A', 'S'<<8|'B', 'S'<<8|'C', 'S'<<8|'D', 'S'<<8|'E', 'S'<<8|'G', 'S'<<8|'H', 'S'<<8|'I', 'S'<<8|'J', 'S'<<8|'K', 'S'<<8|'L', 'S'<<8|'M', 'S'<<8|'N', 'S'<<8|'O', 'S'<<8|'R', 'S'<<8|'T', 'S'<<8|'V', 'S'<<8|'Y', 'S'<<8|'Z', 'T'<<8|'C', 'T'<<8|'D', 'T'<<8|'F', 'T'<<8|'G', 'T'<<8|'H', 'T'<<8|'J', 'T'<<8|'K', 'T'<<8|'L', 'T'<<8|'M', 'T'<<8|'N', 'T'<<8|'O', 'T'<<8|'R', 'T'<<8|'T', 'T'<<8|'V', 'T'<<8|'W', 'T'<<8|'Z', 'U'<<8|'A', 'U'<<8|'G', 'U'<<8|'M', 'U'<<8|'S', 'U'<<8|'Y', 'U'<<8|'Z', 'V'<<8|'A', 'V'<<8|'C', 'V'<<8|'E', 'V'<<8|'G', 'V'<<8|'I', 'V'<<8|'N', 'V'<<8|'U', 'W'<<8|'F', 'W'<<8|'S', 'Y'<<8|'E', 'Y'<<8|'T', 'Z'<<8|'A', 'Z'<<8|'M', 'Z'<<8|'W', -1 }; TestingProfile profile; for (size_t i = 0; i < arraysize(ids); ++i) { profile.GetPrefs()->SetInteger(prefs::kCountryIDAtInstall, ids[i]); ScopedVector<TemplateURL> urls; size_t url_count; TemplateURLPrepopulateData::GetPrepopulatedEngines( profile.GetPrefs(), &(urls.get()), &url_count); std::set<int> unique_ids; for (size_t turl_i = 0; turl_i < urls.size(); ++turl_i) { ASSERT_TRUE(unique_ids.find(urls[turl_i]->prepopulate_id()) == unique_ids.end()); unique_ids.insert(urls[turl_i]->prepopulate_id()); } } } // Verifies that default search providers from the preferences file // override the built-in ones. TEST_F(TemplateURLPrepopulateDataTest, ProvidersFromPrefs) { const char pref_data[] = "{ " " \"search_provider_overrides_version\":1," " \"search_provider_overrides\": [" " { \"name\":\"foo\"," " \"keyword\":\"fook\"," " \"search_url\":\"http://foo.com/s?q={searchTerms}\"," " \"favicon_url\":\"http://foi.com/favicon.ico\"," " \"suggest_url\":\"\"," " \"encoding\":\"UTF-8\"," " \"id\":1001" " }" " ]" "}"; ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); FilePath preferences_file = temp_dir.path().AppendASCII("Preferences"); file_util::WriteFile(preferences_file, pref_data, sizeof(pref_data)); scoped_ptr<PrefService> prefs( PrefService::CreateUserPrefService(preferences_file)); TemplateURLPrepopulateData::RegisterUserPrefs(prefs.get()); int version = TemplateURLPrepopulateData::GetDataVersion(prefs.get()); EXPECT_EQ(1, version); std::vector<TemplateURL*> t_urls; size_t default_index; TemplateURLPrepopulateData::GetPrepopulatedEngines( prefs.get(), &t_urls, &default_index); ASSERT_EQ(1u, t_urls.size()); EXPECT_EQ(L"foo", t_urls[0]->short_name()); EXPECT_EQ(L"fook", t_urls[0]->keyword()); EXPECT_EQ("foo.com", t_urls[0]->url()->GetHost()); EXPECT_EQ("foi.com", t_urls[0]->GetFavIconURL().host()); EXPECT_EQ(1u, t_urls[0]->input_encodings().size()); EXPECT_EQ(1001, t_urls[0]->prepopulate_id()); } <commit_msg>Fix memory leak in unit test<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 "base/scoped_temp_dir.h" #include "base/scoped_vector.h" #include "chrome/browser/search_engines/template_url.h" #include "chrome/browser/search_engines/template_url_prepopulate_data.h" #include "chrome/common/pref_names.h" #include "chrome/test/testing_profile.h" #include "testing/gtest/include/gtest/gtest.h" typedef testing::Test TemplateURLPrepopulateDataTest; // Verifies the set of prepopulate data doesn't contain entries with duplicate // ids. TEST_F(TemplateURLPrepopulateDataTest, UniqueIDs) { int ids[] = { 'A'<<8|'D', 'A'<<8|'E', 'A'<<8|'F', 'A'<<8|'G', 'A'<<8|'I', 'A'<<8|'L', 'A'<<8|'M', 'A'<<8|'N', 'A'<<8|'O', 'A'<<8|'Q', 'A'<<8|'R', 'A'<<8|'S', 'A'<<8|'T', 'A'<<8|'U', 'A'<<8|'W', 'A'<<8|'X', 'A'<<8|'Z', 'B'<<8|'A', 'B'<<8|'B', 'B'<<8|'D', 'B'<<8|'E', 'B'<<8|'F', 'B'<<8|'G', 'B'<<8|'H', 'B'<<8|'I', 'B'<<8|'J', 'B'<<8|'M', 'B'<<8|'N', 'B'<<8|'O', 'B'<<8|'R', 'B'<<8|'S', 'B'<<8|'T', 'B'<<8|'V', 'B'<<8|'W', 'B'<<8|'Y', 'B'<<8|'Z', 'C'<<8|'A', 'C'<<8|'C', 'C'<<8|'D', 'C'<<8|'F', 'C'<<8|'G', 'C'<<8|'H', 'C'<<8|'I', 'C'<<8|'K', 'C'<<8|'L', 'C'<<8|'M', 'C'<<8|'N', 'C'<<8|'O', 'C'<<8|'R', 'C'<<8|'U', 'C'<<8|'V', 'C'<<8|'X', 'C'<<8|'Y', 'C'<<8|'Z', 'D'<<8|'E', 'D'<<8|'J', 'D'<<8|'K', 'D'<<8|'M', 'D'<<8|'O', 'D'<<8|'Z', 'E'<<8|'C', 'E'<<8|'E', 'E'<<8|'G', 'E'<<8|'R', 'E'<<8|'S', 'E'<<8|'T', 'F'<<8|'I', 'F'<<8|'J', 'F'<<8|'K', 'F'<<8|'M', 'F'<<8|'O', 'F'<<8|'R', 'G'<<8|'A', 'G'<<8|'B', 'G'<<8|'D', 'G'<<8|'E', 'G'<<8|'F', 'G'<<8|'G', 'G'<<8|'H', 'G'<<8|'I', 'G'<<8|'L', 'G'<<8|'M', 'G'<<8|'N', 'G'<<8|'P', 'G'<<8|'Q', 'G'<<8|'R', 'G'<<8|'S', 'G'<<8|'T', 'G'<<8|'U', 'G'<<8|'W', 'G'<<8|'Y', 'H'<<8|'K', 'H'<<8|'M', 'H'<<8|'N', 'H'<<8|'R', 'H'<<8|'T', 'H'<<8|'U', 'I'<<8|'D', 'I'<<8|'E', 'I'<<8|'L', 'I'<<8|'M', 'I'<<8|'N', 'I'<<8|'O', 'I'<<8|'P', 'I'<<8|'Q', 'I'<<8|'R', 'I'<<8|'S', 'I'<<8|'T', 'J'<<8|'E', 'J'<<8|'M', 'J'<<8|'O', 'J'<<8|'P', 'K'<<8|'E', 'K'<<8|'G', 'K'<<8|'H', 'K'<<8|'I', 'K'<<8|'M', 'K'<<8|'N', 'K'<<8|'P', 'K'<<8|'R', 'K'<<8|'W', 'K'<<8|'Y', 'K'<<8|'Z', 'L'<<8|'A', 'L'<<8|'B', 'L'<<8|'C', 'L'<<8|'I', 'L'<<8|'K', 'L'<<8|'R', 'L'<<8|'S', 'L'<<8|'T', 'L'<<8|'U', 'L'<<8|'V', 'L'<<8|'Y', 'M'<<8|'A', 'M'<<8|'C', 'M'<<8|'D', 'M'<<8|'E', 'M'<<8|'G', 'M'<<8|'H', 'M'<<8|'K', 'M'<<8|'L', 'M'<<8|'M', 'M'<<8|'N', 'M'<<8|'O', 'M'<<8|'P', 'M'<<8|'Q', 'M'<<8|'R', 'M'<<8|'S', 'M'<<8|'T', 'M'<<8|'U', 'M'<<8|'V', 'M'<<8|'W', 'M'<<8|'X', 'M'<<8|'Y', 'M'<<8|'Z', 'N'<<8|'A', 'N'<<8|'C', 'N'<<8|'E', 'N'<<8|'F', 'N'<<8|'G', 'N'<<8|'I', 'N'<<8|'L', 'N'<<8|'O', 'N'<<8|'P', 'N'<<8|'R', 'N'<<8|'U', 'N'<<8|'Z', 'O'<<8|'M', 'P'<<8|'A', 'P'<<8|'E', 'P'<<8|'F', 'P'<<8|'G', 'P'<<8|'H', 'P'<<8|'K', 'P'<<8|'L', 'P'<<8|'M', 'P'<<8|'N', 'P'<<8|'R', 'P'<<8|'S', 'P'<<8|'T', 'P'<<8|'W', 'P'<<8|'Y', 'Q'<<8|'A', 'R'<<8|'E', 'R'<<8|'O', 'R'<<8|'S', 'R'<<8|'U', 'R'<<8|'W', 'S'<<8|'A', 'S'<<8|'B', 'S'<<8|'C', 'S'<<8|'D', 'S'<<8|'E', 'S'<<8|'G', 'S'<<8|'H', 'S'<<8|'I', 'S'<<8|'J', 'S'<<8|'K', 'S'<<8|'L', 'S'<<8|'M', 'S'<<8|'N', 'S'<<8|'O', 'S'<<8|'R', 'S'<<8|'T', 'S'<<8|'V', 'S'<<8|'Y', 'S'<<8|'Z', 'T'<<8|'C', 'T'<<8|'D', 'T'<<8|'F', 'T'<<8|'G', 'T'<<8|'H', 'T'<<8|'J', 'T'<<8|'K', 'T'<<8|'L', 'T'<<8|'M', 'T'<<8|'N', 'T'<<8|'O', 'T'<<8|'R', 'T'<<8|'T', 'T'<<8|'V', 'T'<<8|'W', 'T'<<8|'Z', 'U'<<8|'A', 'U'<<8|'G', 'U'<<8|'M', 'U'<<8|'S', 'U'<<8|'Y', 'U'<<8|'Z', 'V'<<8|'A', 'V'<<8|'C', 'V'<<8|'E', 'V'<<8|'G', 'V'<<8|'I', 'V'<<8|'N', 'V'<<8|'U', 'W'<<8|'F', 'W'<<8|'S', 'Y'<<8|'E', 'Y'<<8|'T', 'Z'<<8|'A', 'Z'<<8|'M', 'Z'<<8|'W', -1 }; TestingProfile profile; for (size_t i = 0; i < arraysize(ids); ++i) { profile.GetPrefs()->SetInteger(prefs::kCountryIDAtInstall, ids[i]); ScopedVector<TemplateURL> urls; size_t default_index; TemplateURLPrepopulateData::GetPrepopulatedEngines( profile.GetPrefs(), &(urls.get()), &default_index); std::set<int> unique_ids; for (size_t turl_i = 0; turl_i < urls.size(); ++turl_i) { ASSERT_TRUE(unique_ids.find(urls[turl_i]->prepopulate_id()) == unique_ids.end()); unique_ids.insert(urls[turl_i]->prepopulate_id()); } } } // Verifies that default search providers from the preferences file // override the built-in ones. TEST_F(TemplateURLPrepopulateDataTest, ProvidersFromPrefs) { const char pref_data[] = "{ " " \"search_provider_overrides_version\":1," " \"search_provider_overrides\": [" " { \"name\":\"foo\"," " \"keyword\":\"fook\"," " \"search_url\":\"http://foo.com/s?q={searchTerms}\"," " \"favicon_url\":\"http://foi.com/favicon.ico\"," " \"suggest_url\":\"\"," " \"encoding\":\"UTF-8\"," " \"id\":1001" " }" " ]" "}"; ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); FilePath preferences_file = temp_dir.path().AppendASCII("Preferences"); file_util::WriteFile(preferences_file, pref_data, sizeof(pref_data)); scoped_ptr<PrefService> prefs( PrefService::CreateUserPrefService(preferences_file)); TemplateURLPrepopulateData::RegisterUserPrefs(prefs.get()); int version = TemplateURLPrepopulateData::GetDataVersion(prefs.get()); EXPECT_EQ(1, version); ScopedVector<TemplateURL> t_urls; size_t default_index; TemplateURLPrepopulateData::GetPrepopulatedEngines( prefs.get(), &(t_urls.get()), &default_index); ASSERT_EQ(1u, t_urls.size()); EXPECT_EQ(L"foo", t_urls[0]->short_name()); EXPECT_EQ(L"fook", t_urls[0]->keyword()); EXPECT_EQ("foo.com", t_urls[0]->url()->GetHost()); EXPECT_EQ("foi.com", t_urls[0]->GetFavIconURL().host()); EXPECT_EQ(1u, t_urls[0]->input_encodings().size()); EXPECT_EQ(1001, t_urls[0]->prepopulate_id()); } <|endoftext|>
<commit_before>/* * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/video/send_statistics_proxy.h" #include <algorithm> #include <map> #include "webrtc/base/checks.h" #include "webrtc/base/logging.h" #include "webrtc/system_wrappers/interface/critical_section_wrapper.h" #include "webrtc/system_wrappers/interface/metrics.h" namespace webrtc { const int SendStatisticsProxy::kStatsTimeoutMs = 5000; SendStatisticsProxy::SendStatisticsProxy(Clock* clock, const VideoSendStream::Config& config) : clock_(clock), config_(config), input_frame_rate_tracker_(100u, 10u), sent_frame_rate_tracker_(100u, 10u), last_sent_frame_timestamp_(0), max_sent_width_per_timestamp_(0), max_sent_height_per_timestamp_(0) { } SendStatisticsProxy::~SendStatisticsProxy() { UpdateHistograms(); } void SendStatisticsProxy::UpdateHistograms() { int input_fps = static_cast<int>(input_frame_rate_tracker_.ComputeTotalRate()); if (input_fps > 0) RTC_HISTOGRAM_COUNTS_100("WebRTC.Video.InputFramesPerSecond", input_fps); int sent_fps = static_cast<int>(sent_frame_rate_tracker_.ComputeTotalRate()); if (sent_fps > 0) RTC_HISTOGRAM_COUNTS_100("WebRTC.Video.SentFramesPerSecond", sent_fps); const int kMinRequiredSamples = 200; int in_width = input_width_counter_.Avg(kMinRequiredSamples); int in_height = input_height_counter_.Avg(kMinRequiredSamples); if (in_width != -1) { RTC_HISTOGRAM_COUNTS_10000("WebRTC.Video.InputWidthInPixels", in_width); RTC_HISTOGRAM_COUNTS_10000("WebRTC.Video.InputHeightInPixels", in_height); } int sent_width = sent_width_counter_.Avg(kMinRequiredSamples); int sent_height = sent_height_counter_.Avg(kMinRequiredSamples); if (sent_width != -1) { RTC_HISTOGRAM_COUNTS_10000("WebRTC.Video.SentWidthInPixels", sent_width); RTC_HISTOGRAM_COUNTS_10000("WebRTC.Video.SentHeightInPixels", sent_height); } int encode_ms = encode_time_counter_.Avg(kMinRequiredSamples); if (encode_ms != -1) RTC_HISTOGRAM_COUNTS_1000("WebRTC.Video.EncodeTimeInMs", encode_ms); int key_frames_permille = key_frame_counter_.Permille(kMinRequiredSamples); if (key_frames_permille != -1) { RTC_HISTOGRAM_COUNTS_1000("WebRTC.Video.KeyFramesSentInPermille", key_frames_permille); } int quality_limited = quality_limited_frame_counter_.Percent(kMinRequiredSamples); if (quality_limited != -1) { RTC_HISTOGRAM_PERCENTAGE("WebRTC.Video.QualityLimitedResolutionInPercent", quality_limited); } int downscales = quality_downscales_counter_.Avg(kMinRequiredSamples); if (downscales != -1) { RTC_HISTOGRAM_ENUMERATION("WebRTC.Video.QualityLimitedResolutionDownscales", downscales, 20); } int bw_limited = bw_limited_frame_counter_.Percent(kMinRequiredSamples); if (bw_limited != -1) { RTC_HISTOGRAM_PERCENTAGE("WebRTC.Video.BandwidthLimitedResolutionInPercent", bw_limited); } int num_disabled = bw_resolutions_disabled_counter_.Avg(kMinRequiredSamples); if (num_disabled != -1) { RTC_HISTOGRAM_ENUMERATION( "WebRTC.Video.BandwidthLimitedResolutionsDisabled", num_disabled, 10); } } void SendStatisticsProxy::OnOutgoingRate(uint32_t framerate, uint32_t bitrate) { rtc::CritScope lock(&crit_); stats_.encode_frame_rate = framerate; stats_.media_bitrate_bps = bitrate; } void SendStatisticsProxy::CpuOveruseMetricsUpdated( const CpuOveruseMetrics& metrics) { rtc::CritScope lock(&crit_); // TODO(asapersson): Change to use OnEncodedFrame() for avg_encode_time_ms. stats_.avg_encode_time_ms = metrics.avg_encode_time_ms; stats_.encode_usage_percent = metrics.encode_usage_percent; } void SendStatisticsProxy::OnSuspendChange(bool is_suspended) { rtc::CritScope lock(&crit_); stats_.suspended = is_suspended; } VideoSendStream::Stats SendStatisticsProxy::GetStats() { rtc::CritScope lock(&crit_); PurgeOldStats(); stats_.input_frame_rate = static_cast<int>(input_frame_rate_tracker_.ComputeRate()); return stats_; } void SendStatisticsProxy::PurgeOldStats() { int64_t old_stats_ms = clock_->TimeInMilliseconds() - kStatsTimeoutMs; for (std::map<uint32_t, VideoSendStream::StreamStats>::iterator it = stats_.substreams.begin(); it != stats_.substreams.end(); ++it) { uint32_t ssrc = it->first; if (update_times_[ssrc].resolution_update_ms <= old_stats_ms) { it->second.width = 0; it->second.height = 0; } } } VideoSendStream::StreamStats* SendStatisticsProxy::GetStatsEntry( uint32_t ssrc) { std::map<uint32_t, VideoSendStream::StreamStats>::iterator it = stats_.substreams.find(ssrc); if (it != stats_.substreams.end()) return &it->second; if (std::find(config_.rtp.ssrcs.begin(), config_.rtp.ssrcs.end(), ssrc) == config_.rtp.ssrcs.end() && std::find(config_.rtp.rtx.ssrcs.begin(), config_.rtp.rtx.ssrcs.end(), ssrc) == config_.rtp.rtx.ssrcs.end()) { return nullptr; } return &stats_.substreams[ssrc]; // Insert new entry and return ptr. } void SendStatisticsProxy::OnInactiveSsrc(uint32_t ssrc) { rtc::CritScope lock(&crit_); VideoSendStream::StreamStats* stats = GetStatsEntry(ssrc); if (stats == nullptr) return; stats->total_bitrate_bps = 0; stats->retransmit_bitrate_bps = 0; stats->height = 0; stats->width = 0; } void SendStatisticsProxy::OnSetRates(uint32_t bitrate_bps, int framerate) { rtc::CritScope lock(&crit_); stats_.target_media_bitrate_bps = bitrate_bps; } void SendStatisticsProxy::OnSendEncodedImage( const EncodedImage& encoded_image, const RTPVideoHeader* rtp_video_header) { size_t simulcast_idx = rtp_video_header != nullptr ? rtp_video_header->simulcastIdx : 0; if (simulcast_idx >= config_.rtp.ssrcs.size()) { LOG(LS_ERROR) << "Encoded image outside simulcast range (" << simulcast_idx << " >= " << config_.rtp.ssrcs.size() << ")."; return; } uint32_t ssrc = config_.rtp.ssrcs[simulcast_idx]; rtc::CritScope lock(&crit_); VideoSendStream::StreamStats* stats = GetStatsEntry(ssrc); if (stats == nullptr) return; stats->width = encoded_image._encodedWidth; stats->height = encoded_image._encodedHeight; update_times_[ssrc].resolution_update_ms = clock_->TimeInMilliseconds(); key_frame_counter_.Add(encoded_image._frameType == kVideoFrameKey); if (encoded_image.adapt_reason_.quality_resolution_downscales != -1) { bool downscaled = encoded_image.adapt_reason_.quality_resolution_downscales > 0; quality_limited_frame_counter_.Add(downscaled); if (downscaled) { quality_downscales_counter_.Add( encoded_image.adapt_reason_.quality_resolution_downscales); } } if (encoded_image.adapt_reason_.bw_resolutions_disabled != -1) { bool bw_limited = encoded_image.adapt_reason_.bw_resolutions_disabled > 0; bw_limited_frame_counter_.Add(bw_limited); if (bw_limited) { bw_resolutions_disabled_counter_.Add( encoded_image.adapt_reason_.bw_resolutions_disabled); } } // TODO(asapersson): This is incorrect if simulcast layers are encoded on // different threads and there is no guarantee that one frame of all layers // are encoded before the next start. if (last_sent_frame_timestamp_ > 0 && encoded_image._timeStamp != last_sent_frame_timestamp_) { sent_frame_rate_tracker_.AddSamples(1); sent_width_counter_.Add(max_sent_width_per_timestamp_); sent_height_counter_.Add(max_sent_height_per_timestamp_); max_sent_width_per_timestamp_ = 0; max_sent_height_per_timestamp_ = 0; } last_sent_frame_timestamp_ = encoded_image._timeStamp; max_sent_width_per_timestamp_ = std::max(max_sent_width_per_timestamp_, static_cast<int>(encoded_image._encodedWidth)); max_sent_height_per_timestamp_ = std::max(max_sent_height_per_timestamp_, static_cast<int>(encoded_image._encodedHeight)); } void SendStatisticsProxy::OnIncomingFrame(int width, int height) { rtc::CritScope lock(&crit_); input_frame_rate_tracker_.AddSamples(1); input_width_counter_.Add(width); input_height_counter_.Add(height); } void SendStatisticsProxy::OnEncodedFrame(int encode_time_ms) { rtc::CritScope lock(&crit_); encode_time_counter_.Add(encode_time_ms); } void SendStatisticsProxy::RtcpPacketTypesCounterUpdated( uint32_t ssrc, const RtcpPacketTypeCounter& packet_counter) { rtc::CritScope lock(&crit_); VideoSendStream::StreamStats* stats = GetStatsEntry(ssrc); if (stats == nullptr) return; stats->rtcp_packet_type_counts = packet_counter; } void SendStatisticsProxy::StatisticsUpdated(const RtcpStatistics& statistics, uint32_t ssrc) { rtc::CritScope lock(&crit_); VideoSendStream::StreamStats* stats = GetStatsEntry(ssrc); if (stats == nullptr) return; stats->rtcp_stats = statistics; } void SendStatisticsProxy::CNameChanged(const char* cname, uint32_t ssrc) { } void SendStatisticsProxy::DataCountersUpdated( const StreamDataCounters& counters, uint32_t ssrc) { rtc::CritScope lock(&crit_); VideoSendStream::StreamStats* stats = GetStatsEntry(ssrc); RTC_DCHECK(stats != nullptr) << "DataCountersUpdated reported for unknown ssrc: " << ssrc; stats->rtp_stats = counters; } void SendStatisticsProxy::Notify(const BitrateStatistics& total_stats, const BitrateStatistics& retransmit_stats, uint32_t ssrc) { rtc::CritScope lock(&crit_); VideoSendStream::StreamStats* stats = GetStatsEntry(ssrc); if (stats == nullptr) return; stats->total_bitrate_bps = total_stats.bitrate_bps; stats->retransmit_bitrate_bps = retransmit_stats.bitrate_bps; } void SendStatisticsProxy::FrameCountUpdated(const FrameCounts& frame_counts, uint32_t ssrc) { rtc::CritScope lock(&crit_); VideoSendStream::StreamStats* stats = GetStatsEntry(ssrc); if (stats == nullptr) return; stats->frame_counts = frame_counts; } void SendStatisticsProxy::SendSideDelayUpdated(int avg_delay_ms, int max_delay_ms, uint32_t ssrc) { rtc::CritScope lock(&crit_); VideoSendStream::StreamStats* stats = GetStatsEntry(ssrc); if (stats == nullptr) return; stats->avg_delay_ms = avg_delay_ms; stats->max_delay_ms = max_delay_ms; } void SendStatisticsProxy::SampleCounter::Add(int sample) { sum += sample; ++num_samples; } int SendStatisticsProxy::SampleCounter::Avg(int min_required_samples) const { if (num_samples < min_required_samples || num_samples == 0) return -1; return (sum + (num_samples / 2)) / num_samples; } void SendStatisticsProxy::BoolSampleCounter::Add(bool sample) { if (sample) ++sum; ++num_samples; } int SendStatisticsProxy::BoolSampleCounter::Percent( int min_required_samples) const { return Fraction(min_required_samples, 100.0f); } int SendStatisticsProxy::BoolSampleCounter::Permille( int min_required_samples) const { return Fraction(min_required_samples, 1000.0f); } int SendStatisticsProxy::BoolSampleCounter::Fraction( int min_required_samples, float multiplier) const { if (num_samples < min_required_samples || num_samples == 0) return -1; return static_cast<int>((sum * multiplier / num_samples) + 0.5f); } } // namespace webrtc <commit_msg>Add stats for used video codec type for a sent video stream:<commit_after>/* * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/video/send_statistics_proxy.h" #include <algorithm> #include <map> #include "webrtc/base/checks.h" #include "webrtc/base/logging.h" #include "webrtc/system_wrappers/interface/critical_section_wrapper.h" #include "webrtc/system_wrappers/interface/metrics.h" namespace webrtc { namespace { // Used by histograms. Values of entries should not be changed. enum HistogramCodecType { kVideoUnknown = 0, kVideoVp8 = 1, kVideoVp9 = 2, kVideoH264 = 3, kVideoMax = 64, }; HistogramCodecType PayloadNameToHistogramCodecType( const std::string& payload_name) { if (payload_name == "VP8") { return kVideoVp8; } else if (payload_name == "VP9") { return kVideoVp9; } else if (payload_name == "H264") { return kVideoH264; } else { return kVideoUnknown; } } void UpdateCodecTypeHistogram(const std::string& payload_name) { RTC_HISTOGRAM_ENUMERATION("WebRTC.Video.Encoder.CodecType", PayloadNameToHistogramCodecType(payload_name), kVideoMax); } } // namespace const int SendStatisticsProxy::kStatsTimeoutMs = 5000; SendStatisticsProxy::SendStatisticsProxy(Clock* clock, const VideoSendStream::Config& config) : clock_(clock), config_(config), input_frame_rate_tracker_(100u, 10u), sent_frame_rate_tracker_(100u, 10u), last_sent_frame_timestamp_(0), max_sent_width_per_timestamp_(0), max_sent_height_per_timestamp_(0) { UpdateCodecTypeHistogram(config_.encoder_settings.payload_name); } SendStatisticsProxy::~SendStatisticsProxy() { UpdateHistograms(); } void SendStatisticsProxy::UpdateHistograms() { int input_fps = static_cast<int>(input_frame_rate_tracker_.ComputeTotalRate()); if (input_fps > 0) RTC_HISTOGRAM_COUNTS_100("WebRTC.Video.InputFramesPerSecond", input_fps); int sent_fps = static_cast<int>(sent_frame_rate_tracker_.ComputeTotalRate()); if (sent_fps > 0) RTC_HISTOGRAM_COUNTS_100("WebRTC.Video.SentFramesPerSecond", sent_fps); const int kMinRequiredSamples = 200; int in_width = input_width_counter_.Avg(kMinRequiredSamples); int in_height = input_height_counter_.Avg(kMinRequiredSamples); if (in_width != -1) { RTC_HISTOGRAM_COUNTS_10000("WebRTC.Video.InputWidthInPixels", in_width); RTC_HISTOGRAM_COUNTS_10000("WebRTC.Video.InputHeightInPixels", in_height); } int sent_width = sent_width_counter_.Avg(kMinRequiredSamples); int sent_height = sent_height_counter_.Avg(kMinRequiredSamples); if (sent_width != -1) { RTC_HISTOGRAM_COUNTS_10000("WebRTC.Video.SentWidthInPixels", sent_width); RTC_HISTOGRAM_COUNTS_10000("WebRTC.Video.SentHeightInPixels", sent_height); } int encode_ms = encode_time_counter_.Avg(kMinRequiredSamples); if (encode_ms != -1) RTC_HISTOGRAM_COUNTS_1000("WebRTC.Video.EncodeTimeInMs", encode_ms); int key_frames_permille = key_frame_counter_.Permille(kMinRequiredSamples); if (key_frames_permille != -1) { RTC_HISTOGRAM_COUNTS_1000("WebRTC.Video.KeyFramesSentInPermille", key_frames_permille); } int quality_limited = quality_limited_frame_counter_.Percent(kMinRequiredSamples); if (quality_limited != -1) { RTC_HISTOGRAM_PERCENTAGE("WebRTC.Video.QualityLimitedResolutionInPercent", quality_limited); } int downscales = quality_downscales_counter_.Avg(kMinRequiredSamples); if (downscales != -1) { RTC_HISTOGRAM_ENUMERATION("WebRTC.Video.QualityLimitedResolutionDownscales", downscales, 20); } int bw_limited = bw_limited_frame_counter_.Percent(kMinRequiredSamples); if (bw_limited != -1) { RTC_HISTOGRAM_PERCENTAGE("WebRTC.Video.BandwidthLimitedResolutionInPercent", bw_limited); } int num_disabled = bw_resolutions_disabled_counter_.Avg(kMinRequiredSamples); if (num_disabled != -1) { RTC_HISTOGRAM_ENUMERATION( "WebRTC.Video.BandwidthLimitedResolutionsDisabled", num_disabled, 10); } } void SendStatisticsProxy::OnOutgoingRate(uint32_t framerate, uint32_t bitrate) { rtc::CritScope lock(&crit_); stats_.encode_frame_rate = framerate; stats_.media_bitrate_bps = bitrate; } void SendStatisticsProxy::CpuOveruseMetricsUpdated( const CpuOveruseMetrics& metrics) { rtc::CritScope lock(&crit_); // TODO(asapersson): Change to use OnEncodedFrame() for avg_encode_time_ms. stats_.avg_encode_time_ms = metrics.avg_encode_time_ms; stats_.encode_usage_percent = metrics.encode_usage_percent; } void SendStatisticsProxy::OnSuspendChange(bool is_suspended) { rtc::CritScope lock(&crit_); stats_.suspended = is_suspended; } VideoSendStream::Stats SendStatisticsProxy::GetStats() { rtc::CritScope lock(&crit_); PurgeOldStats(); stats_.input_frame_rate = static_cast<int>(input_frame_rate_tracker_.ComputeRate()); return stats_; } void SendStatisticsProxy::PurgeOldStats() { int64_t old_stats_ms = clock_->TimeInMilliseconds() - kStatsTimeoutMs; for (std::map<uint32_t, VideoSendStream::StreamStats>::iterator it = stats_.substreams.begin(); it != stats_.substreams.end(); ++it) { uint32_t ssrc = it->first; if (update_times_[ssrc].resolution_update_ms <= old_stats_ms) { it->second.width = 0; it->second.height = 0; } } } VideoSendStream::StreamStats* SendStatisticsProxy::GetStatsEntry( uint32_t ssrc) { std::map<uint32_t, VideoSendStream::StreamStats>::iterator it = stats_.substreams.find(ssrc); if (it != stats_.substreams.end()) return &it->second; if (std::find(config_.rtp.ssrcs.begin(), config_.rtp.ssrcs.end(), ssrc) == config_.rtp.ssrcs.end() && std::find(config_.rtp.rtx.ssrcs.begin(), config_.rtp.rtx.ssrcs.end(), ssrc) == config_.rtp.rtx.ssrcs.end()) { return nullptr; } return &stats_.substreams[ssrc]; // Insert new entry and return ptr. } void SendStatisticsProxy::OnInactiveSsrc(uint32_t ssrc) { rtc::CritScope lock(&crit_); VideoSendStream::StreamStats* stats = GetStatsEntry(ssrc); if (stats == nullptr) return; stats->total_bitrate_bps = 0; stats->retransmit_bitrate_bps = 0; stats->height = 0; stats->width = 0; } void SendStatisticsProxy::OnSetRates(uint32_t bitrate_bps, int framerate) { rtc::CritScope lock(&crit_); stats_.target_media_bitrate_bps = bitrate_bps; } void SendStatisticsProxy::OnSendEncodedImage( const EncodedImage& encoded_image, const RTPVideoHeader* rtp_video_header) { size_t simulcast_idx = rtp_video_header != nullptr ? rtp_video_header->simulcastIdx : 0; if (simulcast_idx >= config_.rtp.ssrcs.size()) { LOG(LS_ERROR) << "Encoded image outside simulcast range (" << simulcast_idx << " >= " << config_.rtp.ssrcs.size() << ")."; return; } uint32_t ssrc = config_.rtp.ssrcs[simulcast_idx]; rtc::CritScope lock(&crit_); VideoSendStream::StreamStats* stats = GetStatsEntry(ssrc); if (stats == nullptr) return; stats->width = encoded_image._encodedWidth; stats->height = encoded_image._encodedHeight; update_times_[ssrc].resolution_update_ms = clock_->TimeInMilliseconds(); key_frame_counter_.Add(encoded_image._frameType == kVideoFrameKey); if (encoded_image.adapt_reason_.quality_resolution_downscales != -1) { bool downscaled = encoded_image.adapt_reason_.quality_resolution_downscales > 0; quality_limited_frame_counter_.Add(downscaled); if (downscaled) { quality_downscales_counter_.Add( encoded_image.adapt_reason_.quality_resolution_downscales); } } if (encoded_image.adapt_reason_.bw_resolutions_disabled != -1) { bool bw_limited = encoded_image.adapt_reason_.bw_resolutions_disabled > 0; bw_limited_frame_counter_.Add(bw_limited); if (bw_limited) { bw_resolutions_disabled_counter_.Add( encoded_image.adapt_reason_.bw_resolutions_disabled); } } // TODO(asapersson): This is incorrect if simulcast layers are encoded on // different threads and there is no guarantee that one frame of all layers // are encoded before the next start. if (last_sent_frame_timestamp_ > 0 && encoded_image._timeStamp != last_sent_frame_timestamp_) { sent_frame_rate_tracker_.AddSamples(1); sent_width_counter_.Add(max_sent_width_per_timestamp_); sent_height_counter_.Add(max_sent_height_per_timestamp_); max_sent_width_per_timestamp_ = 0; max_sent_height_per_timestamp_ = 0; } last_sent_frame_timestamp_ = encoded_image._timeStamp; max_sent_width_per_timestamp_ = std::max(max_sent_width_per_timestamp_, static_cast<int>(encoded_image._encodedWidth)); max_sent_height_per_timestamp_ = std::max(max_sent_height_per_timestamp_, static_cast<int>(encoded_image._encodedHeight)); } void SendStatisticsProxy::OnIncomingFrame(int width, int height) { rtc::CritScope lock(&crit_); input_frame_rate_tracker_.AddSamples(1); input_width_counter_.Add(width); input_height_counter_.Add(height); } void SendStatisticsProxy::OnEncodedFrame(int encode_time_ms) { rtc::CritScope lock(&crit_); encode_time_counter_.Add(encode_time_ms); } void SendStatisticsProxy::RtcpPacketTypesCounterUpdated( uint32_t ssrc, const RtcpPacketTypeCounter& packet_counter) { rtc::CritScope lock(&crit_); VideoSendStream::StreamStats* stats = GetStatsEntry(ssrc); if (stats == nullptr) return; stats->rtcp_packet_type_counts = packet_counter; } void SendStatisticsProxy::StatisticsUpdated(const RtcpStatistics& statistics, uint32_t ssrc) { rtc::CritScope lock(&crit_); VideoSendStream::StreamStats* stats = GetStatsEntry(ssrc); if (stats == nullptr) return; stats->rtcp_stats = statistics; } void SendStatisticsProxy::CNameChanged(const char* cname, uint32_t ssrc) { } void SendStatisticsProxy::DataCountersUpdated( const StreamDataCounters& counters, uint32_t ssrc) { rtc::CritScope lock(&crit_); VideoSendStream::StreamStats* stats = GetStatsEntry(ssrc); RTC_DCHECK(stats != nullptr) << "DataCountersUpdated reported for unknown ssrc: " << ssrc; stats->rtp_stats = counters; } void SendStatisticsProxy::Notify(const BitrateStatistics& total_stats, const BitrateStatistics& retransmit_stats, uint32_t ssrc) { rtc::CritScope lock(&crit_); VideoSendStream::StreamStats* stats = GetStatsEntry(ssrc); if (stats == nullptr) return; stats->total_bitrate_bps = total_stats.bitrate_bps; stats->retransmit_bitrate_bps = retransmit_stats.bitrate_bps; } void SendStatisticsProxy::FrameCountUpdated(const FrameCounts& frame_counts, uint32_t ssrc) { rtc::CritScope lock(&crit_); VideoSendStream::StreamStats* stats = GetStatsEntry(ssrc); if (stats == nullptr) return; stats->frame_counts = frame_counts; } void SendStatisticsProxy::SendSideDelayUpdated(int avg_delay_ms, int max_delay_ms, uint32_t ssrc) { rtc::CritScope lock(&crit_); VideoSendStream::StreamStats* stats = GetStatsEntry(ssrc); if (stats == nullptr) return; stats->avg_delay_ms = avg_delay_ms; stats->max_delay_ms = max_delay_ms; } void SendStatisticsProxy::SampleCounter::Add(int sample) { sum += sample; ++num_samples; } int SendStatisticsProxy::SampleCounter::Avg(int min_required_samples) const { if (num_samples < min_required_samples || num_samples == 0) return -1; return (sum + (num_samples / 2)) / num_samples; } void SendStatisticsProxy::BoolSampleCounter::Add(bool sample) { if (sample) ++sum; ++num_samples; } int SendStatisticsProxy::BoolSampleCounter::Percent( int min_required_samples) const { return Fraction(min_required_samples, 100.0f); } int SendStatisticsProxy::BoolSampleCounter::Permille( int min_required_samples) const { return Fraction(min_required_samples, 1000.0f); } int SendStatisticsProxy::BoolSampleCounter::Fraction( int min_required_samples, float multiplier) const { if (num_samples < min_required_samples || num_samples == 0) return -1; return static_cast<int>((sum * multiplier / num_samples) + 0.5f); } } // namespace webrtc <|endoftext|>