<commit_before>/*************************************************************************
 *
 *  $RCSfile: idlc.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: obo $ $Date: 2004-06-03 15:06:20 $
 *
 *  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 _IDLC_IDLC_HXX_
#define _IDLC_IDLC_HXX_

#ifndef _IDLC_IDLCTYPES_HXX_
#include <idlc/idlctypes.hxx>
#endif
#ifndef _IDLC_ASTSTACK_HXX_
#include <idlc/aststack.hxx>
#endif
#ifndef _IDLC_OPTIONS_HXX_
#include <idlc/options.hxx>
#endif

#ifdef SAL_UNX
#define SEPARATOR '/'
#define PATH_SEPARATOR "/"
#else
#define SEPARATOR '\\'
#define PATH_SEPARATOR "\\"
#endif

class AstInterface;
class AstModule;
class AstType;
class Options;
class ErrorHandler;

class Idlc
{
public:
    Idlc(Options* pOptions);
    virtual ~Idlc();

    void init();

    Options* getOptions()
        { return m_pOptions; }
    AstStack* scopes()
        { return m_pScopes; }
    AstModule* getRoot()
        { return m_pRoot; }
    ErrorHandler* error()
        { return m_pErrorHandler; }
    const ::rtl::OString& getFileName()
        { return m_fileName; }
    void setFileName(const ::rtl::OString& fileName)
        { m_fileName = fileName; }
    const ::rtl::OString& getMainFileName()
        { return m_mainFileName; }
    void setMainFileName(const ::rtl::OString& mainFileName)
        { m_mainFileName = mainFileName; }
    const ::rtl::OString& getRealFileName()
        { return m_realFileName; }
    void setRealFileName(const ::rtl::OString& realFileName)
        { m_realFileName = realFileName; }
    const ::rtl::OString& getDocumentation()
        {
            m_bIsDocValid = sal_False;
            return m_documentation;
        }
    void setDocumentation(const ::rtl::OString& documentation)
        {
            m_documentation = documentation;
            m_bIsDocValid = sal_True;
        }
    sal_Bool isDocValid();
    sal_Bool isInMainFile()
        { return m_bIsInMainfile; }
    void setInMainfile(sal_Bool bInMainfile)
        { m_bIsInMainfile = bInMainfile; }
    sal_uInt32 getErrorCount()
        { return m_errorCount; }
    void setErrorCount(sal_uInt32 errorCount)
        { m_errorCount = errorCount; }
    void incErrorCount()
        { m_errorCount++; }
    sal_uInt32 getWarningCount()
        { return m_warningCount; }
    void setWarningCount(sal_uInt32 warningCount)
        { m_warningCount = warningCount; }
    void incWarningCount()
        { m_warningCount++; }
    sal_uInt32 getLineNumber()
        { return m_lineNumber; }
    void setLineNumber(sal_uInt32 lineNumber)
        { m_lineNumber = lineNumber; }
    void incLineNumber()
        { m_lineNumber++; }
    ParseState getParseState()
        { return m_parseState; }
    void setParseState(ParseState parseState)
        { m_parseState = parseState; }

    void insertInclude(const ::rtl::OString& inc)
        { m_includes.insert(inc); }
    StringSet* getIncludes()
        { return &m_includes; }

    void setPublished(bool published) { m_published = published; }
    bool isPublished() const { return m_published; }

    void reset();
private:
    Options*            m_pOptions;
    AstStack*           m_pScopes;
    AstModule*          m_pRoot;
    ErrorHandler*       m_pErrorHandler;
    ::rtl::OString      m_fileName;
    ::rtl::OString      m_mainFileName;
    ::rtl::OString      m_realFileName;
    ::rtl::OString      m_documentation;
    sal_Bool            m_bIsDocValid;
    sal_Bool            m_bGenerateDoc;
    sal_Bool            m_bIsInMainfile;
    bool                m_published;
    sal_uInt32          m_errorCount;
    sal_uInt32          m_warningCount;
    sal_uInt32          m_lineNumber;
    ParseState          m_parseState;
    StringSet           m_includes;
};

sal_Int32 compileFile(const ::rtl::OString * pathname);
    // a null pathname means stdin
sal_Int32 produceFile(const ::rtl::OString& filenameBase);
    // filenameBase is filename without ".idl"
void removeIfExists(const ::rtl::OString& pathname);

::rtl::OString makeTempName(const ::rtl::OString& prefix, const ::rtl::OString& postfix);
sal_Bool copyFile(const ::rtl::OString* source, const ::rtl::OString& target);
    // a null source means stdin

sal_Bool isFileUrl(const ::rtl::OString& fileName);
::rtl::OString convertToAbsoluteSystemPath(const ::rtl::OString& fileName);
::rtl::OString convertToFileUrl(const ::rtl::OString& fileName);

Idlc* SAL_CALL idlc();
Idlc* SAL_CALL setIdlc(Options* pOptions);

AstDeclaration const * resolveTypedefs(AstDeclaration const * type);

AstInterface const * resolveInterfaceTypedefs(AstType const * type);

#endif // _IDLC_IDLC_HXX_

<commit_msg>INTEGRATION: CWS ooo19126 (1.5.32); FILE MERGED 2005/09/05 17:39:35 rt 1.5.32.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: idlc.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 18:04:17 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _IDLC_IDLC_HXX_
#define _IDLC_IDLC_HXX_

#ifndef _IDLC_IDLCTYPES_HXX_
#include <idlc/idlctypes.hxx>
#endif
#ifndef _IDLC_ASTSTACK_HXX_
#include <idlc/aststack.hxx>
#endif
#ifndef _IDLC_OPTIONS_HXX_
#include <idlc/options.hxx>
#endif

#ifdef SAL_UNX
#define SEPARATOR '/'
#define PATH_SEPARATOR "/"
#else
#define SEPARATOR '\\'
#define PATH_SEPARATOR "\\"
#endif

class AstInterface;
class AstModule;
class AstType;
class Options;
class ErrorHandler;

class Idlc
{
public:
    Idlc(Options* pOptions);
    virtual ~Idlc();

    void init();

    Options* getOptions()
        { return m_pOptions; }
    AstStack* scopes()
        { return m_pScopes; }
    AstModule* getRoot()
        { return m_pRoot; }
    ErrorHandler* error()
        { return m_pErrorHandler; }
    const ::rtl::OString& getFileName()
        { return m_fileName; }
    void setFileName(const ::rtl::OString& fileName)
        { m_fileName = fileName; }
    const ::rtl::OString& getMainFileName()
        { return m_mainFileName; }
    void setMainFileName(const ::rtl::OString& mainFileName)
        { m_mainFileName = mainFileName; }
    const ::rtl::OString& getRealFileName()
        { return m_realFileName; }
    void setRealFileName(const ::rtl::OString& realFileName)
        { m_realFileName = realFileName; }
    const ::rtl::OString& getDocumentation()
        {
            m_bIsDocValid = sal_False;
            return m_documentation;
        }
    void setDocumentation(const ::rtl::OString& documentation)
        {
            m_documentation = documentation;
            m_bIsDocValid = sal_True;
        }
    sal_Bool isDocValid();
    sal_Bool isInMainFile()
        { return m_bIsInMainfile; }
    void setInMainfile(sal_Bool bInMainfile)
        { m_bIsInMainfile = bInMainfile; }
    sal_uInt32 getErrorCount()
        { return m_errorCount; }
    void setErrorCount(sal_uInt32 errorCount)
        { m_errorCount = errorCount; }
    void incErrorCount()
        { m_errorCount++; }
    sal_uInt32 getWarningCount()
        { return m_warningCount; }
    void setWarningCount(sal_uInt32 warningCount)
        { m_warningCount = warningCount; }
    void incWarningCount()
        { m_warningCount++; }
    sal_uInt32 getLineNumber()
        { return m_lineNumber; }
    void setLineNumber(sal_uInt32 lineNumber)
        { m_lineNumber = lineNumber; }
    void incLineNumber()
        { m_lineNumber++; }
    ParseState getParseState()
        { return m_parseState; }
    void setParseState(ParseState parseState)
        { m_parseState = parseState; }

    void insertInclude(const ::rtl::OString& inc)
        { m_includes.insert(inc); }
    StringSet* getIncludes()
        { return &m_includes; }

    void setPublished(bool published) { m_published = published; }
    bool isPublished() const { return m_published; }

    void reset();
private:
    Options*            m_pOptions;
    AstStack*           m_pScopes;
    AstModule*          m_pRoot;
    ErrorHandler*       m_pErrorHandler;
    ::rtl::OString      m_fileName;
    ::rtl::OString      m_mainFileName;
    ::rtl::OString      m_realFileName;
    ::rtl::OString      m_documentation;
    sal_Bool            m_bIsDocValid;
    sal_Bool            m_bGenerateDoc;
    sal_Bool            m_bIsInMainfile;
    bool                m_published;
    sal_uInt32          m_errorCount;
    sal_uInt32          m_warningCount;
    sal_uInt32          m_lineNumber;
    ParseState          m_parseState;
    StringSet           m_includes;
};

sal_Int32 compileFile(const ::rtl::OString * pathname);
    // a null pathname means stdin
sal_Int32 produceFile(const ::rtl::OString& filenameBase);
    // filenameBase is filename without ".idl"
void removeIfExists(const ::rtl::OString& pathname);

::rtl::OString makeTempName(const ::rtl::OString& prefix, const ::rtl::OString& postfix);
sal_Bool copyFile(const ::rtl::OString* source, const ::rtl::OString& target);
    // a null source means stdin

sal_Bool isFileUrl(const ::rtl::OString& fileName);
::rtl::OString convertToAbsoluteSystemPath(const ::rtl::OString& fileName);
::rtl::OString convertToFileUrl(const ::rtl::OString& fileName);

Idlc* SAL_CALL idlc();
Idlc* SAL_CALL setIdlc(Options* pOptions);

AstDeclaration const * resolveTypedefs(AstDeclaration const * type);

AstInterface const * resolveInterfaceTypedefs(AstType const * type);

#endif // _IDLC_IDLC_HXX_

<|endoftext|>


<commit_before>a1d4fbfa-2747-11e6-9e6b-e0f84713e7b8<commit_msg>We apologise for the previous fix. Those responsible have been sacked<commit_after>a1efb397-2747-11e6-9417-e0f84713e7b8<|endoftext|>


<commit_before>c8282bc5-2747-11e6-94c7-e0f84713e7b8<commit_msg>( ͡° ͜ʖ ͡°)<commit_after>c8449294-2747-11e6-8d2c-e0f84713e7b8<|endoftext|>


<commit_before>a56e4b00-4b02-11e5-b240-28cfe9171a43<commit_msg>Put the thingie in the thingie<commit_after>a57a2157-4b02-11e5-b536-28cfe9171a43<|endoftext|>


<commit_before>#ifndef CUSTOMPROJECTION_HH
#define CUSTOMPROJECTION_HH

#include <dune/fem/quadrature/cachingquadrature.hh>
#include <dune/fem/operator/common/operator.hh>
#include <dune/fem/function/common/discretefunction.hh>
#include <dune/fem/function/common/discretefunctionadapter.hh>
#include <dune/fem/operator/1order/localmassmatrix.hh>

namespace Stuff {

/** A custom projection of an analytical function that uses a non-standard evalute signature:\n

template < class IntersectionIteratorType >\n
		void evaluate( const DomainType& arg, RangeType& ret, const IntersectionIteratorType& faceIter ) const
\n
	\note example being our boundary functions
	\note output currently somewhat meaningless
	\see analyticaldata.hh
**/

class CustomProjection {

public:
	template < class OriginFunctionType, class DestinationFunctionType >
	static void project (const OriginFunctionType& f, DestinationFunctionType& discFunc)
	{
		typedef typename DestinationFunctionType::FunctionSpaceType
			DiscreteFunctionSpace;
		typedef typename DiscreteFunctionSpace::GridPartType
			GridPart;
		typedef typename GridPart::template Codim< 0 >::IteratorType
			EntityIteratorType;
		typedef typename GridPart::GridType::template Codim< 0 >::Entity
			EntityType;
		typedef typename GridPart::IntersectionIteratorType
			IntersectionIteratorType;
		typedef typename IntersectionIteratorType::EntityPointer
			EntityPointer;
		typedef typename DestinationFunctionType::LocalFunctionType
			LocalFunctionType;
		typedef Dune::CachingQuadrature< GridPart, 1 >
			FaceQuadratureType;
		typedef typename DiscreteFunctionSpace::BaseFunctionSetType
			BaseFunctionSetType;
		typedef typename DiscreteFunctionSpace::RangeType
			RangeType;
		const DiscreteFunctionSpace& space_ = discFunc.space();
		const GridPart& gridPart_ = space_.gridPart();
		RangeType phi (0.0);
		EntityIteratorType entityItEndLog = space_.end();
		for (   EntityIteratorType it = space_.begin();
				it != entityItEndLog;
				++it )
		{
			EntityType& e = *it;
			LocalFunctionType lf = discFunc.localFunction( e );
			BaseFunctionSetType baseFunctionset = space_.baseFunctionSet( *it );
			unsigned int intersection_count = 0;
			IntersectionIteratorType intItEnd = gridPart_.iend( *it );
			for (   IntersectionIteratorType intIt = gridPart_.ibegin( *it );
					intIt != intItEnd;
					++intIt ) {
				intersection_count++;
				FaceQuadratureType faceQuadrature( gridPart_,
												   intIt,
												   ( 4 * space_.order() ) + 1,
												   FaceQuadratureType::INSIDE );
				typename DestinationFunctionType::RangeType ret;
				for ( int qP = 0; qP < faceQuadrature.nop(); ++qP ) {
					const double intel =
						 faceQuadrature.weight(qP) * e.geometry().integrationElement( faceQuadrature.point(qP) ); // general case

					if ( intIt.boundary() )
					{
						f.evaluate( faceQuadrature.point(qP), ret, intIt );

						for ( int i = 0; i < baseFunctionset.numBaseFunctions(); ++i ) {
							baseFunctionset.evaluate(i, faceQuadrature[qP], phi);
							lf[i] += intel * (ret * phi) ;
						}
					}
				}
			}
		}
	}
};

}//end namespace Stuff
#endif // CUSTOMPROJECTION_HH
<commit_msg>fix custom projection compile (still logical not functioning)<commit_after>#ifndef CUSTOMPROJECTION_HH
#define CUSTOMPROJECTION_HH

#include <dune/fem/quadrature/cachingquadrature.hh>
#include <dune/fem/operator/common/operator.hh>
#include <dune/fem/function/common/discretefunction.hh>
#include <dune/fem/function/common/discretefunctionadapter.hh>
#include <dune/fem/operator/1order/localmassmatrix.hh>

namespace Stuff {

/** A custom projection of an analytical function that uses a non-standard evalute signature:\n

template < class IntersectionIteratorType >\n
		void evaluate( const DomainType& arg, RangeType& ret, const IntersectionIteratorType& faceIter ) const
\n
	\note example being our boundary functions
	\note output currently somewhat meaningless
	\see analyticaldata.hh
**/

class CustomProjection {

public:
	template < class OriginFunctionType, class DestinationFunctionType >
	static void project (const OriginFunctionType& f, DestinationFunctionType& discFunc)
	{
		const double time = 0.0;
		typedef typename DestinationFunctionType::FunctionSpaceType
			DiscreteFunctionSpace;
		typedef typename DiscreteFunctionSpace::GridPartType
			GridPart;
		typedef typename GridPart::template Codim< 0 >::IteratorType
			EntityIteratorType;
		typedef typename GridPart::GridType::template Codim< 0 >::Entity
			EntityType;
		typedef typename GridPart::IntersectionIteratorType
			IntersectionIteratorType;
		typedef typename IntersectionIteratorType::EntityPointer
			EntityPointer;
		typedef typename DestinationFunctionType::LocalFunctionType
			LocalFunctionType;
		typedef Dune::CachingQuadrature< GridPart, 1 >
			FaceQuadratureType;
		typedef typename DiscreteFunctionSpace::BaseFunctionSetType
			BaseFunctionSetType;
		typedef typename DiscreteFunctionSpace::RangeType
			RangeType;
		const DiscreteFunctionSpace& space_ = discFunc.space();
		const GridPart& gridPart_ = space_.gridPart();
		RangeType phi (0.0);
		EntityIteratorType entityItEndLog = space_.end();
		for (   EntityIteratorType it = space_.begin();
				it != entityItEndLog;
				++it )
		{
			EntityType& e = *it;
			LocalFunctionType lf = discFunc.localFunction( e );
			BaseFunctionSetType baseFunctionset = space_.baseFunctionSet( *it );
			unsigned int intersection_count = 0;
			IntersectionIteratorType intItEnd = gridPart_.iend( *it );
			for (   IntersectionIteratorType intIt = gridPart_.ibegin( *it );
					intIt != intItEnd;
					++intIt ) {
				intersection_count++;
				FaceQuadratureType faceQuadrature( gridPart_,
												   *intIt,
												   ( 4 * space_.order() ) + 1,
												   FaceQuadratureType::INSIDE );
				typename DestinationFunctionType::RangeType ret;
				for ( size_t qP = 0; qP < faceQuadrature.nop(); ++qP ) {
					const double intel =
						 faceQuadrature.weight(qP) * e.geometry().integrationElement( faceQuadrature.point(qP) ); // general case

					if ( intIt->boundary() )
					{
						f.evaluate( faceQuadrature.point(qP), ret, *intIt );

						for ( int i = 0; i < baseFunctionset.numBaseFunctions(); ++i ) {
							baseFunctionset.evaluate(i, faceQuadrature[qP], phi);
							lf[i] += intel * (ret * phi) ;
						}
					}
				}
			}
		}
	}
};

}//end namespace Stuff
#endif // CUSTOMPROJECTION_HH
<|endoftext|>


<commit_before>/* ux++ - ux implementation for C++ */

/* LICENSE - The MIT License (MIT)

Copyright (c) 2013 Tomona Nanase

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#ifndef HANDLETYPE_HPP
#define	HANDLETYPE_HPP

namespace uxpp {

  /**
   * 内部で扱われるハンドルのタイプを表す列挙体です。
   */
  enum class HandleType {
    /**
     * ゼロのゲートを持ち、発音されないノートを表します。
     */
    zeroGate = 0,

    /**
     * パートまたはマスターの各パラメータをリセットします。
     */
    reset = 1,

    /**
     * ノートのエンベロープをサイレンス状態に移行させ、無音状態にします。
     */
    silence = 2,

    /**
     * ノートのエンベロープをリリース状態に移行させます。
     */
    noteOff = 3,

    /**
     * ボリューム (音量) を変更します。
     */
    volume = 4,

    /**
     * パンポット (定位) を変更します。
     */
    panpot = 5,

    /**
     * ビブラートに関するパラメータを設定します。
     */
    vibrate = 6,

    /**
     * パートに波形を割り当てます。
     */
    waveform = 7,

    /**
     * 波形のパラメータを編集します。
     */
    editWaveform = 8,

    /**
     * パートの音量エンベロープを変更します。
     */
    envelope = 9,

    /**
     * パートのファインチューン値を変更します。
     */
    fineTune = 10,

    /**
     * パートの発音ノートキーをシフトします。
     */
    keyShift = 11,

    /**
     * ポルタメント効果に関するパラメータを設定します。
     */
    portament = 12,

    /**
     * パートを指定されたノートまたは周波数でアタック状態にします。
     */
    noteOn = 13,
  };
}

#endif	/* HANDLETYPE_HPP */

<commit_msg>HandleType列挙体に対する文字列マップオブジェクトを追加<commit_after>/* ux++ - ux implementation for C++ */

/* LICENSE - The MIT License (MIT)

Copyright (c) 2013 Tomona Nanase

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#ifndef HANDLETYPE_HPP
#define	HANDLETYPE_HPP

namespace uxpp {

  /**
   * 内部で扱われるハンドルのタイプを表す列挙体です。
   */
  enum class HandleType {
    /**
     * ゼロのゲートを持ち、発音されないノートを表します。
     */
    zeroGate = 0,

    /**
     * パートまたはマスターの各パラメータをリセットします。
     */
    reset = 1,

    /**
     * ノートのエンベロープをサイレンス状態に移行させ、無音状態にします。
     */
    silence = 2,

    /**
     * ノートのエンベロープをリリース状態に移行させます。
     */
    noteOff = 3,

    /**
     * ボリューム (音量) を変更します。
     */
    volume = 4,

    /**
     * パンポット (定位) を変更します。
     */
    panpot = 5,

    /**
     * ビブラートに関するパラメータを設定します。
     */
    vibrate = 6,

    /**
     * パートに波形を割り当てます。
     */
    waveform = 7,

    /**
     * 波形のパラメータを編集します。
     */
    editWaveform = 8,

    /**
     * パートの音量エンベロープを変更します。
     */
    envelope = 9,

    /**
     * パートのファインチューン値を変更します。
     */
    fineTune = 10,

    /**
     * パートの発音ノートキーをシフトします。
     */
    keyShift = 11,

    /**
     * ポルタメント効果に関するパラメータを設定します。
     */
    portament = 12,

    /**
     * パートを指定されたノートまたは周波数でアタック状態にします。
     */
    noteOn = 13,
  };

  const std::unordered_map<std::string, HandleType>
          HandleTypeString = {
    {"zeroGate", HandleType::zeroGate},
    {"reset", HandleType::reset},
    {"silence", HandleType::silence},
    {"noteOff", HandleType::noteOff},
    {"volume", HandleType::volume},
    {"panpot", HandleType::panpot},
    {"vibrate", HandleType::vibrate},
    {"waveform", HandleType::waveform},
    {"editWaveform", HandleType::editWaveform},
    {"envelope", HandleType::envelope},
    {"fineTune", HandleType::fineTune},
    {"keyShift", HandleType::keyShift},
    {"portament", HandleType::portament},
    {"noteOn", HandleType::noteOn},
  };
}

#endif	/* HANDLETYPE_HPP */

<|endoftext|>


<commit_before>/*
Copyright (c) 2014, Vlad Mesco
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

// DISCLAIMER: this is pretty much prototype/test code :D
#include <cstdlib>
#include <cmath>
#include <iostream>
#include "core.hxx"
#include "drawing.hxx"

static bool moving = false, moving2 = false;
static float dlta = 0.1, dlta2 = 0.f;

static float jx = 0, jy = 0, jz = 0;

static float rx = 0, ry = 0;
static Point3D ppos(0, 0.5, -2);

static enum {
    FLY,
    GRAVITY
} mvmntType = FLY;

#define ngmap (10)
#define mgmap (10)
static float gmap[mgmap][ngmap] = {
    { -5.f, -5.f, -5.f, -5.f, -5.f, -5.f, -5.f, -5.f, -5.f, -5.f },
    { -5.f, -6.f, -6.f, -5.f, -5.f, -5.f, -5.f, -5.f, -5.f, -5.f },
    { -5.f, -6.f, -7.f, -5.f, -5.f, -5.f, -5.f, -5.f, -5.f, -5.f },
    { -5.f, -5.f, -6.f, -5.f, -5.f, -5.f, -5.f, -5.f, -5.f, -5.f },
    { -5.f, -5.f, -5.f, -5.f, -5.f, -5.f, -5.f, -5.f, -5.f, -5.f },
    { -5.f, -5.f, -5.f, -5.f, -5.f, -6.f, -6.f, -6.f, -6.f, -6.f },
    { -4.f, -4.f, -5.f, -5.f, -6.f, -6.f, -7.f, -7.f, -7.f, -7.f },
    { -3.f, -4.f, -4.f, -5.f, -6.f, -7.f, -7.f, -8.f, -8.f, -8.f },
    { -3.f, -3.f, -4.f, -5.f, -6.f, -7.f, -8.f, -8.f, -8.f, -8.f },
    { -2.f, -3.f, -4.f, -5.f, -6.f, -7.f, -8.f, -8.f, -8.f, -8.f },
};

static void drawMap(Drawing& dwg)
{
    struct {
        float first;
        float step;
    }
    nn = { -((float)ngmap) / 2.f, 1.f },
    mm = { -((float)mgmap) / 2.f, 1.f };

    dwg.SetColor(Drawing::WHITE);
    for(size_t i = 0; i < ngmap - 1; ++i) {
        for(size_t j = 0; j < mgmap - 1; ++j) {
            dwg.MoveTo(Point3D(nn.first + i * nn.step, gmap[i][j], mm.first + j * mm.step));
            dwg.LineTo(Point3D(nn.first + i * nn.step, gmap[i][j + 1], mm.first + (j + 1) * mm.step));
            dwg.LineTo(Point3D(nn.first + (i + 1) * nn.step, gmap[i + 1][j + 1], mm.first + (j + 1) * mm.step));
            dwg.LineTo(Point3D(nn.first + (i + 1) * nn.step, gmap[i + 1][j], mm.first + j * mm.step));
            dwg.LineTo(Point3D(nn.first + i * nn.step, gmap[i][j], mm.first + j * mm.step));
        }
    }
}

static void drawScene(Drawing& dwg)
{
    dwg.MoveCamera(
        ppos,
        -ry,
        -rx);

    dwg.SetColor(Drawing::WHITE);
    dwg.SetRotations(jx, jy, jz);
    dwg.MoveTo(Point3D(0, 1, -5));
    dwg.WireCube(1);
    dwg.SetRotations(-jx, -jy, -jz);
    dwg.SetColor(Drawing::YELLOW);
    dwg.WireCube(0.5);

    dwg.SetColor(Drawing::CYAN);
    dwg.MoveTo(Point3D(-5, 0, 0));
    dwg.LineTo(Point3D(5, 0, 0));
    dwg.SetColor(Drawing::YELLOW);
    dwg.MoveTo(Point3D(0, -5, 0));
    dwg.LineTo(Point3D(0, 5, 0));
    dwg.SetColor(Drawing::CYAN);
    dwg.MoveTo(Point3D(0, 0, -5));
    dwg.LineTo(Point3D(0, 0, 5));

    dwg.MoveTo(Point3D(0, 0, 0));
    dwg.SetColor(Drawing::SEABLUE);
    dwg.SetRotations(0, 0, 45);
    dwg.Quad(1, 1);
    dwg.SetColor(Drawing::CYAN);
    dwg.WireQuad(1, 1);

    dwg.MoveTo(Point3D(0, 0, 0));
    dwg.SetColor(Drawing::SEAGREEN);
    dwg.SetRotations(90, 0, 0);
    dwg.Quad(0.7, 0.7);
    dwg.SetColor(Drawing::LIME);
    dwg.WireQuad(0.7, 0.7);

    dwg.MoveTo(Point3D(0, 0, 0));
    dwg.SetColor(Drawing::SEAYELLOW);
    dwg.SetRotations(0, 90, 0);
    dwg.Quad(0.4, 0.4);
    dwg.SetColor(Drawing::YELLOW);
    dwg.WireQuad(0.4, 0.4);

    dwg.MoveTo(Point3D(0, 0, 2));
    dwg.SetTexture(1);
    dwg.SetTextureScale(0, 0);
    dwg.SetRotations(0, 90, 90);
    dwg.TextureQuad(10, 5);

    dwg.SetTexture(0);
    dwg.MoveTo(Point3D(0, 0, 4));
    dwg.SetTextureScale(1, 1);
    dwg.SetRotations(0, 0, 0);
    dwg.TextureQuad(10, 1);
    dwg.MoveTo(Point3D(5, 0, 4));
    dwg.SetTextureScale(1, 1);
    dwg.SetRotations(0, 0, 0);
    dwg.TextureQuad(10, 1);

    dwg.SetTexture(1);
    dwg.MoveTo(Point3D(10, 0, 5.5));
    dwg.SetTextureScale(1, 1);
    dwg.SetRotations(0, 0, 0);
    dwg.TextureQuad(10, 1);
    dwg.SetColor(Drawing::WHITE);
    dwg.WireQuad(10, 1);

    dwg.MoveTo(Point3D(20, 0, 5.5));
    dwg.SetTextureScale(1, 1);
    dwg.SetRotations(0, 0, 0);
    dwg.TextureQuad(10, 1);
    dwg.SetColor(Drawing::WHITE);
    dwg.WireQuad(10, 1);

    // camera facing sprites
    dwg.MoveTo(Point3D(-10, 1, -1));
    dwg.SetTextureScale(0, 0);
    dwg.SetTexture(0);
    dwg.SpriteQuad(1, 1);

    dwg.MoveTo(Point3D(-10, 1, -3));
    dwg.SetTexture(1);
    dwg.SpriteQuad(1, 1);

    // cylindrical billboard
    dwg.MoveTo(Point3D(-10, 1, 3));
    dwg.SetTexture(0);
    dwg.SetRotations(90, 0, -ry);
    dwg.TextureQuad(1, 1);

    // in case texture's missing
    dwg.MoveTo(Point3D(-10, 1, -5));
    dwg.SetTexture(-1);
    dwg.SpriteQuad(1, 2);

    drawMap(dwg);

    if(mvmntType == GRAVITY) {
        dwg.SetRotations(0, 0, 0);
        dwg.SetColor(Drawing::LIME);
        Point3D p(-ppos.x, ppos.y - 1.f, -ppos.z);
        dwg.MoveTo(p);
        dwg.Quad(0.05, 0.05);
    }
}

static void onmousedown(int x, int y, int btn)
{
    if(btn == 1) {
    }
    if(btn == 2) {
    }
    if(btn == 3) {
    }
}

static void onmouseup(int x, int y, int btn)
{
}

static void onmousemove(int dx, int dy)
{
    ry += dx * 0.1;
    rx += dy * 0.1;
    if(rx > 90.f) rx = 90.f;
    if(rx < -90.f) rx = -90.f;
}

static bool computeZ()
{
    float x = -ppos.z;
    float y = -ppos.x;
    if(x == (float)(int)x) x += 1.e-5f;
    if(y == (float)(int)y) y += 1.e-5f;
    struct {
        int x1, x2;
        float w1, w2;
    }
    X = {
        (int)floorf(x) + 5, (int)ceilf(x) + 5,
        x - floorf(x), ceilf(x) - x
    },
    Y = {
        (int)floorf(y) + 5, (int)ceilf(y) + 5,
        y - floorf(y), ceilf(y) - y
    };

    if(X.x1 < 0 || X.x2 > 9 || Y.x1 < 0 || Y.x2 > 9) return false;

#define OP(A, B) ((1.f/A + 1.f/B) / 2.f)
    float z =
          gmap[Y.x1][X.x1] * OP(Y.w1, X.w1)
        + gmap[Y.x1][X.x2] * OP(Y.w1, X.w2)
        + gmap[Y.x2][X.x2] * OP(Y.w2, X.w2)
        + gmap[Y.x2][X.x1] * OP(Y.w2, X.w1);
    z /=
          OP(X.w1, Y.w1)
        + OP(X.w2, Y.w1)
        + OP(X.w2, Y.w2)
        + OP(X.w1, Y.w2);
#undef OP

    ppos.y = z + 2.f;

    return true;
}

static void updateScene()
{
#define ACTUAL_FRAMES_PER_ANIMATION_FRAME 30
    static size_t frameCounter = 0;

    if(moving || moving2) {
        switch(mvmntType) {
            case GRAVITY: {
                Point3D dir(dlta2, 0, dlta);
                dir = Drawing::UtilityHelpers::normalizeVector(dir);
                dir.x /= 10.f;
                dir.y /= 10.f;
                dir.z /= 10.f;
                dir = Drawing::UtilityHelpers::RotateDeltaVector(dir, -ry, 0);
                Point3D oldPpos = ppos;
                ppos = Drawing::UtilityHelpers::Translate(ppos, dir);
                if(!computeZ())
                {
                    ppos = oldPpos;
                }
                break; }
            case FLY: {
                Point3D dir(dlta2, 0, dlta);
                dir = Drawing::UtilityHelpers::normalizeVector(dir);
                dir.x /= 10.f;
                dir.y /= 10.f;
                dir.z /= 10.f;
                dir = Drawing::UtilityHelpers::RotateDeltaVector(dir, -ry, -rx);
                ppos = Drawing::UtilityHelpers::Translate(ppos, dir);
                break; }
        }
    }

    jx += 5;
    jy += 3;
    jz += 2;
    if(jx > 360) jx -= 360;
    if(jy > 360) jy -= 360;
    if(jz > 360) jz -= 360;
}

static void onkeyup(char key)
{
    if(key == 27) exit(0);
    switch(key) {
    case 'd':
    case 'a':
        moving2 = false;
        dlta2 = 0.f;
        break;
    case 'w':
    case 's':
        moving = false;
        dlta = 0.f;
        break;
    case 'm':
        if(mvmntType == GRAVITY) {
            mvmntType = FLY;
            break;
        }
        if(mvmntType == FLY &&
                ppos.x >= -((float)mgmap)/2.f &&
                ppos.x <= ((float)mgmap)/2.f &&
                ppos.z >= -((float)ngmap)/2.f &&
                ppos.z <= ((float)ngmap)/2.f)
        {
            mvmntType = GRAVITY;
            computeZ();
        }
        break;
    }
}

static void onkeydown(char key)
{
    switch(key) {
    case 'w':
        moving = true;
        dlta = 0.1;
        break;
    case 's':
        moving = true;
        dlta = -0.1;
        break;
    case 'a':
        moving2 = true;
        dlta2 = -0.1;
        break;
    case 'd':
        moving2 = true;
        dlta2 = 0.1;
    }
}

int main(int argc, char* argv[])
{
    Drawing::Init(&argc, argv);
    Drawing::SetWindowSize(728, 500);
    Drawing::SetOnMouseDown(onmousedown);
    Drawing::SetOnMouseUp(onmouseup);
    Drawing::SetOnMouseMove(onmousemove);
    Drawing::SetOnKeyUp(onkeyup);
    Drawing::SetOnKeyDown(onkeydown);

    Drawing::LoadBitmapTexture("sample.bmp");

    Drawing::LoadBitmapTexture("sample.bmp", 34 + 256 * 177 + 256 * 256 * 76);

    Drawing::Loop(updateScene, drawScene);

    return 0;
}
<commit_msg>use params<commit_after>/*
Copyright (c) 2014, Vlad Mesco
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

// DISCLAIMER: this is pretty much prototype/test code :D
#include <cstdlib>
#include <cmath>
#include <iostream>
#include "core.hxx"
#include "drawing.hxx"

static bool moving = false, moving2 = false;
static float dlta = 0.1, dlta2 = 0.f;

static float jx = 0, jy = 0, jz = 0;

static float rx = 0, ry = 0;
static Point3D ppos(0, 0.5, -2);

static enum {
    FLY,
    GRAVITY
} mvmntType = FLY;

#define ngmap (10)
#define mgmap (10)
static float gmap[mgmap][ngmap] = {
    { -5.f, -5.f, -5.f, -5.f, -5.f, -5.f, -5.f, -5.f, -5.f, -5.f },
    { -5.f, -6.f, -6.f, -5.f, -5.f, -5.f, -5.f, -5.f, -5.f, -5.f },
    { -5.f, -6.f, -7.f, -5.f, -5.f, -5.f, -5.f, -5.f, -5.f, -5.f },
    { -5.f, -5.f, -6.f, -5.f, -5.f, -5.f, -5.f, -5.f, -5.f, -5.f },
    { -5.f, -5.f, -5.f, -5.f, -5.f, -5.f, -5.f, -5.f, -5.f, -5.f },
    { -5.f, -5.f, -5.f, -5.f, -5.f, -6.f, -6.f, -6.f, -6.f, -6.f },
    { -4.f, -4.f, -5.f, -5.f, -6.f, -6.f, -7.f, -7.f, -7.f, -7.f },
    { -3.f, -4.f, -4.f, -5.f, -6.f, -7.f, -7.f, -8.f, -8.f, -8.f },
    { -3.f, -3.f, -4.f, -5.f, -6.f, -7.f, -8.f, -8.f, -8.f, -8.f },
    { -2.f, -3.f, -4.f, -5.f, -6.f, -7.f, -8.f, -8.f, -8.f, -8.f },
};

static void drawMap(Drawing& dwg)
{
    struct {
        float first;
        float step;
    }
    nn = { -((float)ngmap) / 2.f, 1.f },
    mm = { -((float)mgmap) / 2.f, 1.f };

    dwg.SetColor(Drawing::WHITE);
    for(size_t i = 0; i < ngmap - 1; ++i) {
        for(size_t j = 0; j < mgmap - 1; ++j) {
            dwg.MoveTo(Point3D(nn.first + i * nn.step, gmap[i][j], mm.first + j * mm.step));
            dwg.LineTo(Point3D(nn.first + i * nn.step, gmap[i][j + 1], mm.first + (j + 1) * mm.step));
            dwg.LineTo(Point3D(nn.first + (i + 1) * nn.step, gmap[i + 1][j + 1], mm.first + (j + 1) * mm.step));
            dwg.LineTo(Point3D(nn.first + (i + 1) * nn.step, gmap[i + 1][j], mm.first + j * mm.step));
            dwg.LineTo(Point3D(nn.first + i * nn.step, gmap[i][j], mm.first + j * mm.step));
        }
    }
}

static void drawScene(Drawing& dwg)
{
    dwg.MoveCamera(
        ppos,
        -ry,
        -rx);

    dwg.SetColor(Drawing::WHITE);
    dwg.SetRotations(jx, jy, jz);
    dwg.MoveTo(Point3D(0, 1, -5));
    dwg.WireCube(1);
    dwg.SetRotations(-jx, -jy, -jz);
    dwg.SetColor(Drawing::YELLOW);
    dwg.WireCube(0.5);

    dwg.SetColor(Drawing::CYAN);
    dwg.MoveTo(Point3D(-5, 0, 0));
    dwg.LineTo(Point3D(5, 0, 0));
    dwg.SetColor(Drawing::YELLOW);
    dwg.MoveTo(Point3D(0, -5, 0));
    dwg.LineTo(Point3D(0, 5, 0));
    dwg.SetColor(Drawing::CYAN);
    dwg.MoveTo(Point3D(0, 0, -5));
    dwg.LineTo(Point3D(0, 0, 5));

    dwg.MoveTo(Point3D(0, 0, 0));
    dwg.SetColor(Drawing::SEABLUE);
    dwg.SetRotations(0, 0, 45);
    dwg.Quad(1, 1);
    dwg.SetColor(Drawing::CYAN);
    dwg.WireQuad(1, 1);

    dwg.MoveTo(Point3D(0, 0, 0));
    dwg.SetColor(Drawing::SEAGREEN);
    dwg.SetRotations(90, 0, 0);
    dwg.Quad(0.7, 0.7);
    dwg.SetColor(Drawing::LIME);
    dwg.WireQuad(0.7, 0.7);

    dwg.MoveTo(Point3D(0, 0, 0));
    dwg.SetColor(Drawing::SEAYELLOW);
    dwg.SetRotations(0, 90, 0);
    dwg.Quad(0.4, 0.4);
    dwg.SetColor(Drawing::YELLOW);
    dwg.WireQuad(0.4, 0.4);

    dwg.MoveTo(Point3D(0, 0, 2));
    dwg.SetTexture(1);
    dwg.SetTextureScale(0, 0);
    dwg.SetRotations(0, 90, 90);
    dwg.TextureQuad(10, 5);

    dwg.SetTexture(0);
    dwg.MoveTo(Point3D(0, 0, 4));
    dwg.SetTextureScale(1, 1);
    dwg.SetRotations(0, 0, 0);
    dwg.TextureQuad(10, 1);
    dwg.MoveTo(Point3D(5, 0, 4));
    dwg.SetTextureScale(1, 1);
    dwg.SetRotations(0, 0, 0);
    dwg.TextureQuad(10, 1);

    dwg.SetTexture(1);
    dwg.MoveTo(Point3D(10, 0, 5.5));
    dwg.SetTextureScale(1, 1);
    dwg.SetRotations(0, 0, 0);
    dwg.TextureQuad(10, 1);
    dwg.SetColor(Drawing::WHITE);
    dwg.WireQuad(10, 1);

    dwg.MoveTo(Point3D(20, 0, 5.5));
    dwg.SetTextureScale(1, 1);
    dwg.SetRotations(0, 0, 0);
    dwg.TextureQuad(10, 1);
    dwg.SetColor(Drawing::WHITE);
    dwg.WireQuad(10, 1);

    // camera facing sprites
    dwg.MoveTo(Point3D(-10, 1, -1));
    dwg.SetTextureScale(0, 0);
    dwg.SetTexture(0);
    dwg.SpriteQuad(1, 1);

    dwg.MoveTo(Point3D(-10, 1, -3));
    dwg.SetTexture(1);
    dwg.SpriteQuad(1, 1);

    // cylindrical billboard
    dwg.MoveTo(Point3D(-10, 1, 3));
    dwg.SetTexture(0);
    dwg.SetRotations(90, 0, -ry);
    dwg.TextureQuad(1, 1);

    // in case texture's missing
    dwg.MoveTo(Point3D(-10, 1, -5));
    dwg.SetTexture(-1);
    dwg.SpriteQuad(1, 2);

    drawMap(dwg);

    if(mvmntType == GRAVITY) {
        dwg.SetRotations(0, 0, 0);
        dwg.SetColor(Drawing::LIME);
        Point3D p(-ppos.x, ppos.y - 1.f, -ppos.z);
        dwg.MoveTo(p);
        dwg.Quad(0.05, 0.05);
    }
}

static void onmousedown(int x, int y, int btn)
{
    if(btn == 1) {
    }
    if(btn == 2) {
    }
    if(btn == 3) {
    }
}

static void onmouseup(int x, int y, int btn)
{
}

static void onmousemove(int dx, int dy)
{
    ry += dx * 0.1;
    rx += dy * 0.1;
    if(rx > 90.f) rx = 90.f;
    if(rx < -90.f) rx = -90.f;
}

static bool computeZ()
{
    float x = -ppos.z;
    float y = -ppos.x;
    if(x == (float)(int)x) x += 1.e-5f;
    if(y == (float)(int)y) y += 1.e-5f;
    struct {
        int x1, x2;
        float w1, w2;
    }
    X = {
        (int)floorf(x) + mgmap/2, (int)ceilf(x) + mgmap/2,
        x - floorf(x), ceilf(x) - x
    },
    Y = {
        (int)floorf(y) + ngmap/2, (int)ceilf(y) + ngmap/2,
        y - floorf(y), ceilf(y) - y
    };

    if(X.x1 < 0 || X.x2 >= mgmap || Y.x1 < 0 || Y.x2 >= ngmap) return false;

#define OP(A, B) ((1.f/A + 1.f/B) / 2.f)
    float z =
          gmap[Y.x1][X.x1] * OP(Y.w1, X.w1)
        + gmap[Y.x1][X.x2] * OP(Y.w1, X.w2)
        + gmap[Y.x2][X.x2] * OP(Y.w2, X.w2)
        + gmap[Y.x2][X.x1] * OP(Y.w2, X.w1);
    z /=
          OP(X.w1, Y.w1)
        + OP(X.w2, Y.w1)
        + OP(X.w2, Y.w2)
        + OP(X.w1, Y.w2);
#undef OP

    ppos.y = z + 2.f;

    return true;
}

static void updateScene()
{
#define ACTUAL_FRAMES_PER_ANIMATION_FRAME 30
    static size_t frameCounter = 0;

    if(moving || moving2) {
        switch(mvmntType) {
            case GRAVITY: {
                Point3D dir(dlta2, 0, dlta);
                dir = Drawing::UtilityHelpers::normalizeVector(dir);
                dir.x /= 10.f;
                dir.y /= 10.f;
                dir.z /= 10.f;
                dir = Drawing::UtilityHelpers::RotateDeltaVector(dir, -ry, 0);
                Point3D oldPpos = ppos;
                ppos = Drawing::UtilityHelpers::Translate(ppos, dir);
                if(!computeZ())
                {
                    ppos = oldPpos;
                }
                break; }
            case FLY: {
                Point3D dir(dlta2, 0, dlta);
                dir = Drawing::UtilityHelpers::normalizeVector(dir);
                dir.x /= 10.f;
                dir.y /= 10.f;
                dir.z /= 10.f;
                dir = Drawing::UtilityHelpers::RotateDeltaVector(dir, -ry, -rx);
                ppos = Drawing::UtilityHelpers::Translate(ppos, dir);
                break; }
        }
    }

    jx += 5;
    jy += 3;
    jz += 2;
    if(jx > 360) jx -= 360;
    if(jy > 360) jy -= 360;
    if(jz > 360) jz -= 360;
}

static void onkeyup(char key)
{
    if(key == 27) exit(0);
    switch(key) {
    case 'd':
    case 'a':
        moving2 = false;
        dlta2 = 0.f;
        break;
    case 'w':
    case 's':
        moving = false;
        dlta = 0.f;
        break;
    case 'm':
        if(mvmntType == GRAVITY) {
            mvmntType = FLY;
            break;
        }
        if(mvmntType == FLY &&
                ppos.x >= -((float)mgmap)/2.f &&
                ppos.x <= ((float)mgmap)/2.f &&
                ppos.z >= -((float)ngmap)/2.f &&
                ppos.z <= ((float)ngmap)/2.f)
        {
            mvmntType = GRAVITY;
            computeZ();
        }
        break;
    }
}

static void onkeydown(char key)
{
    switch(key) {
    case 'w':
        moving = true;
        dlta = 0.1;
        break;
    case 's':
        moving = true;
        dlta = -0.1;
        break;
    case 'a':
        moving2 = true;
        dlta2 = -0.1;
        break;
    case 'd':
        moving2 = true;
        dlta2 = 0.1;
    }
}

int main(int argc, char* argv[])
{
    Drawing::Init(&argc, argv);
    Drawing::SetWindowSize(728, 500);
    Drawing::SetOnMouseDown(onmousedown);
    Drawing::SetOnMouseUp(onmouseup);
    Drawing::SetOnMouseMove(onmousemove);
    Drawing::SetOnKeyUp(onkeyup);
    Drawing::SetOnKeyDown(onkeydown);

    Drawing::LoadBitmapTexture("sample.bmp");

    Drawing::LoadBitmapTexture("sample.bmp", 34 + 256 * 177 + 256 * 256 * 76);

    Drawing::Loop(updateScene, drawScene);

    return 0;
}
<|endoftext|>


<commit_before>/*
 * This File is part of Davix, The IO library for HTTP based protocols
 * Copyright (C) CERN 2013
 * Author: Adrien Devresse <adrien.devresse@cern.ch>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
*/

#ifndef HTTPIOCHAIN_HPP
#define HTTPIOCHAIN_HPP

#include <davix_internal.hpp>

namespace Davix{

class HttpIOChain;

#define CHAIN_FORWARD(X) \
        do{ \
        if(_next.get() != NULL){ \
            return _next->X; \
        } \
        throw DavixException(davix_scope_io_buff(), StatusCode::OperationNonSupported, "I/O operation not supported"); \
    }while(0)

// stores state for readToFd operations - necessary, so as not to write the same
// data again to an fd after a retry / metalink recovery.
struct FdHandler {
    int fd = -1;
    dav_ssize_t bytes_written_to_fd = 0;
};

// parameter handler for any IO Chain operation
struct IOChainContext{
    IOChainContext(Context & c, const Uri & u, const RequestParams * p): _context(c), _uri(u), _reqparams(p), _end_time() {
        if(_reqparams->getOperationTimeout()->tv_sec > 0){
            _end_time = Chrono::Clock(Chrono::Clock::Monolitic).now();
            _end_time += Chrono::Duration(_reqparams->getOperationTimeout()->tv_sec);
        }
    }

    void checkTimeout(){
        if( _end_time.isValid() && _end_time < Chrono::Clock(Chrono::Clock::Monolitic).now()){
            std::ostringstream ss;
            ss << "operation timeout of " << _reqparams->getOperationTimeout()->tv_sec << "s expired";
            throw DavixException(davix_scope_io_buff(), StatusCode::OperationTimeout, ss.str());
        }
    }

    // context parameter
    Context& _context;
    Uri const & _uri;
    RequestParams const * _reqparams;

    // Operation parameter
    Chrono::TimePoint _end_time;

    // Keep track of how many bytes we've written to an fd, so as to avoid
    // writing the same bytes again in an event of retries / metalink recovery
    FdHandler fdHandler;
};

// Davix IO chain
// Complete I/O Stack implementation of Davix
class HttpIOChain : NonCopyable{
public:

    HttpIOChain();
    virtual ~HttpIOChain();

    HttpIOChain* add(HttpIOChain* elem);

    /*
     *   Meta data opts
     *
     **/
    // calculate hecksum
    virtual void checksum(IOChainContext & iocontext, std::string & checksm, const std::string & chk_algo);

    // calc replica
    virtual std::vector<DavFile> & getReplicas(IOChainContext & iocontext, std::vector<DavFile> & vec);

    // delete resource
    virtual void deleteResource(IOChainContext & iocontext);

    // make collection
    virtual void makeCollection(IOChainContext & iocontext);

    // move/rename resource
    virtual void move(IOChainContext & iocontext, const std::string & target_url);

    // get statInfo
    virtual StatInfo & statInfo(IOChainContext & iocontext, StatInfo & st_info);

    // get quota info
    virtual QuotaInfo & quotaInfo(IOChainContext & iocontext, QuotaInfo & info);

    // listing
    // return false if end of directory is reached
    virtual bool nextSubItem(IOChainContext & iocontext, std::string & entry_name, StatInfo & info);

    /*
     *     I/O Layer
     **/
    virtual bool open(IOChainContext & iocontext, int flags);

    virtual void prefetchInfo(IOChainContext & iocontext, off_t offset, dav_size_t size_read, advise_t adv);

    virtual dav_ssize_t readFull(IOChainContext & iocontext, std::vector<char> & buffer);

    // overloaded version for string content
    virtual dav_ssize_t readFull(IOChainContext & iocontext, std::string & buffer);

    // read to fd
    virtual dav_ssize_t readToFd(IOChainContext & iocontext, int fd, dav_size_t size);

    virtual dav_ssize_t preadVec(IOChainContext & iocontext, const DavIOVecInput * input_vec,
                              DavIOVecOuput * output_vec,
                              const dav_size_t count_vec);

    // reset file position and status
    virtual void resetIO(IOChainContext & iocontext);

    // position independant read operation,
    // similar to pread except that does not need open() before
    virtual dav_ssize_t pread(IOChainContext & iocontext, void* buf, dav_size_t count, dav_off_t offset);

    // sequential read of a file from begining to the end
    virtual dav_ssize_t read(IOChainContext & iocontext, void* buf, dav_size_t count);

    // lseek prototype
    virtual dav_off_t lseek(IOChainContext & iocontext, dav_off_t offset, int flags);

    // write the entire content from a file descriptor
    virtual dav_ssize_t writeFromFd(IOChainContext & iocontext, int fd, dav_size_t size);

    // wirte the entire content from a defined callback
    virtual dav_ssize_t writeFromCb(IOChainContext & iocontext, const DataProviderFun & func, dav_size_t size);

    // sequential write
    virtual dav_ssize_t write(IOChainContext & iocontext, const void* buf, dav_size_t count);

protected:
    Ptr::Scoped<HttpIOChain> _next;
    HttpIOChain* _start;

};

}

#endif // HTTPIOCHAIN_HPP
<commit_msg>DMC-958 Fix SLC6 build<commit_after>/*
 * This File is part of Davix, The IO library for HTTP based protocols
 * Copyright (C) CERN 2013
 * Author: Adrien Devresse <adrien.devresse@cern.ch>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
*/

#ifndef HTTPIOCHAIN_HPP
#define HTTPIOCHAIN_HPP

#include <davix_internal.hpp>

namespace Davix{

class HttpIOChain;

#define CHAIN_FORWARD(X) \
        do{ \
        if(_next.get() != NULL){ \
            return _next->X; \
        } \
        throw DavixException(davix_scope_io_buff(), StatusCode::OperationNonSupported, "I/O operation not supported"); \
    }while(0)

// stores state for readToFd operations - necessary, so as not to write the same
// data again to an fd after a retry / metalink recovery.
struct FdHandler {
    FdHandler() : fd(-1), bytes_written_to_fd(0) { }

    int fd;
    dav_ssize_t bytes_written_to_fd;
};

// parameter handler for any IO Chain operation
struct IOChainContext{
    IOChainContext(Context & c, const Uri & u, const RequestParams * p): _context(c), _uri(u), _reqparams(p), _end_time() {
        if(_reqparams->getOperationTimeout()->tv_sec > 0){
            _end_time = Chrono::Clock(Chrono::Clock::Monolitic).now();
            _end_time += Chrono::Duration(_reqparams->getOperationTimeout()->tv_sec);
        }
    }

    void checkTimeout(){
        if( _end_time.isValid() && _end_time < Chrono::Clock(Chrono::Clock::Monolitic).now()){
            std::ostringstream ss;
            ss << "operation timeout of " << _reqparams->getOperationTimeout()->tv_sec << "s expired";
            throw DavixException(davix_scope_io_buff(), StatusCode::OperationTimeout, ss.str());
        }
    }

    // context parameter
    Context& _context;
    Uri const & _uri;
    RequestParams const * _reqparams;

    // Operation parameter
    Chrono::TimePoint _end_time;

    // Keep track of how many bytes we've written to an fd, so as to avoid
    // writing the same bytes again in an event of retries / metalink recovery
    FdHandler fdHandler;
};

// Davix IO chain
// Complete I/O Stack implementation of Davix
class HttpIOChain : NonCopyable{
public:

    HttpIOChain();
    virtual ~HttpIOChain();

    HttpIOChain* add(HttpIOChain* elem);

    /*
     *   Meta data opts
     *
     **/
    // calculate hecksum
    virtual void checksum(IOChainContext & iocontext, std::string & checksm, const std::string & chk_algo);

    // calc replica
    virtual std::vector<DavFile> & getReplicas(IOChainContext & iocontext, std::vector<DavFile> & vec);

    // delete resource
    virtual void deleteResource(IOChainContext & iocontext);

    // make collection
    virtual void makeCollection(IOChainContext & iocontext);

    // move/rename resource
    virtual void move(IOChainContext & iocontext, const std::string & target_url);

    // get statInfo
    virtual StatInfo & statInfo(IOChainContext & iocontext, StatInfo & st_info);

    // get quota info
    virtual QuotaInfo & quotaInfo(IOChainContext & iocontext, QuotaInfo & info);

    // listing
    // return false if end of directory is reached
    virtual bool nextSubItem(IOChainContext & iocontext, std::string & entry_name, StatInfo & info);

    /*
     *     I/O Layer
     **/
    virtual bool open(IOChainContext & iocontext, int flags);

    virtual void prefetchInfo(IOChainContext & iocontext, off_t offset, dav_size_t size_read, advise_t adv);

    virtual dav_ssize_t readFull(IOChainContext & iocontext, std::vector<char> & buffer);

    // overloaded version for string content
    virtual dav_ssize_t readFull(IOChainContext & iocontext, std::string & buffer);

    // read to fd
    virtual dav_ssize_t readToFd(IOChainContext & iocontext, int fd, dav_size_t size);

    virtual dav_ssize_t preadVec(IOChainContext & iocontext, const DavIOVecInput * input_vec,
                              DavIOVecOuput * output_vec,
                              const dav_size_t count_vec);

    // reset file position and status
    virtual void resetIO(IOChainContext & iocontext);

    // position independant read operation,
    // similar to pread except that does not need open() before
    virtual dav_ssize_t pread(IOChainContext & iocontext, void* buf, dav_size_t count, dav_off_t offset);

    // sequential read of a file from begining to the end
    virtual dav_ssize_t read(IOChainContext & iocontext, void* buf, dav_size_t count);

    // lseek prototype
    virtual dav_off_t lseek(IOChainContext & iocontext, dav_off_t offset, int flags);

    // write the entire content from a file descriptor
    virtual dav_ssize_t writeFromFd(IOChainContext & iocontext, int fd, dav_size_t size);

    // wirte the entire content from a defined callback
    virtual dav_ssize_t writeFromCb(IOChainContext & iocontext, const DataProviderFun & func, dav_size_t size);

    // sequential write
    virtual dav_ssize_t write(IOChainContext & iocontext, const void* buf, dav_size_t count);

protected:
    Ptr::Scoped<HttpIOChain> _next;
    HttpIOChain* _start;

};

}

#endif // HTTPIOCHAIN_HPP
<|endoftext|>


<commit_before>#include "threadedParsers.hh"

using namespace khmer;
using namespace khmer:: threaded_parsers;

/* This function returns the proper parser factory for a given
 * file type
 */
ThreadedIParserFactory* ThreadedIParserFactory::get_parser(const std::string &inputfile, long int chunkSize)
{
   std::string filename(inputfile);
   int found = filename.find_last_of(".");

   std::string type = filename.substr(found+1);

   if (type == "fq" || type == "fastq") {
      return new ThreadedFastqParserFactory(inputfile, chunkSize);
   } else if (type == "fa" || type == "fasta") {
      return new ThreadedFastaParserFactory(inputfile, chunkSize);
   } else {
      return new ThreadedFastaParserFactory(inputfile, chunkSize);
   }
}

/* Constructer for ThreadedFastaParserFactory */
ThreadedFastaParserFactory::ThreadedFastaParserFactory(
    const std::string &inputfile, long int size)
{
    /* Save off the filename and chunk size */
    filename = inputfile;
    chunkSize = size;
    curPos = 0;

    /* Get the file size */
    std::ifstream myFile;
    myFile.open(filename.c_str(), std::ifstream::in);
    myFile.seekg (0, std::ios::end);

    /* Subtract off one so that if there is only one
     * byte left (which is the case since we call unget)
     * we will still indicate that we have reached the end
     * of the file */
    fileSize = (long int)myFile.tellg() - 1;
    myFile.close();
}

ThreadedIParser* ThreadedFastaParserFactory::get_next_parser()
{
    /* Open the file */
    std::ifstream myFile;
    myFile.open(filename.c_str(), std::ifstream::in);
    long int myCurPos, endPos;

    do {
        /* Save off the current curPos so that we can use it in the compare
         * and swap later, to make this call threadsafe */
        myCurPos = curPos;

        /* Start the end position off at the current position + the chunk size */
        endPos = myCurPos + chunkSize;

        if (endPos > fileSize)
            endPos = fileSize;

        /* Read until we see
         * a '>', which indicates the start of the next read, or we reach EOF
         */
        myFile.seekg(endPos, std::ios::beg);

        while (!myFile.eof() && myFile.get() != '>');

        /* We get here as soon as we read a '>' */
        /* Put the '>' back */
        myFile.unget();
        endPos = myFile.tellg();

        if (endPos == -1)
            endPos = fileSize;

    } while(!__sync_bool_compare_and_swap(&curPos, myCurPos, endPos));

    myFile.close();
    return new ThreadedFastaParser(filename, myCurPos, endPos);
}

/* Constructer for ThreadedFastqParserFactory */
ThreadedFastqParserFactory::ThreadedFastqParserFactory(
    const std::string &inputfile, long int size)
{
    /* Save off the filename and chunk size */
    filename = inputfile;
    chunkSize = size;
    curPos = 0;

    /* Get the file size */
    std::ifstream myFile;
    myFile.open(filename.c_str(), std::ifstream::in);
    myFile.seekg (0, std::ios::end);
    /* Subtract off one so that if there is only one
     * byte left (which is the case since we call unget)
     * we will still indicate that we have reached the end
     * of the file */
    fileSize = (long int)myFile.tellg() - 1;
    myFile.close();
}

ThreadedIParser* ThreadedFastqParserFactory::get_next_parser()
{
    /* Open the file */
    std::ifstream myFile;
    myFile.open(filename.c_str(), std::ifstream::in);
    long int myCurPos, endPos;

    do {
        /* Save off the current curPos so that we can use it in the compare
         * and swap later, to make this call threadsafe */
        myCurPos = curPos;

        /* Start the end position off at the current position + the chunk size */
        endPos = myCurPos + chunkSize;

        if (endPos > fileSize)
            endPos = fileSize;

        /* Read until we see
         * a '@', which indicates the start of the next read, or we reach EOF
         * We have to be careful - a '@' can show up in the quality scores too
         * so watch for that
         */
        myFile.seekg(endPos, std::ios::beg);

        char prevChar = myFile.get();
        while (!myFile.eof())
        {
            char curChar = myFile.get();
            if (curChar == '@' && prevChar == '\n')
                break;
            prevChar = curChar;
        }

        /* We get here as soon as we read a '@' */
        /* Put the '@' back */
        if (!myFile.eof())
            myFile.unget();
        endPos = myFile.tellg();

        if (endPos == -1)
            endPos = fileSize;

    } while(!__sync_bool_compare_and_swap(&curPos, myCurPos, endPos));

    myFile.close();
    return new ThreadedFastqParser(filename, myCurPos, endPos);
}

ThreadedFastaParser::ThreadedFastaParser(const std::string &inputfile,
    long int startPos, long int end) :
                         infile(inputfile.c_str())
{

    assert(infile.is_open());

    /* Lay the start pointer down in the right location */
    infile.seekg(startPos, std::ios::beg);

    /* Set the end ptr */
    endPos = end;
}

Read ThreadedFastaParser::get_next_read()
{
   std::string line = "", seq = "";
   Read read;

   bool valid_read = 0;

   while (!valid_read)  {
      getline(infile, line);

      assert(line[0] == '>');
      read.name = line.substr(1);

      /* Get all the lines that are sequence data */
      while(infile.get() != '>' && !infile.eof())
      {
         infile.unget();
         getline(infile, line);
         seq += line;
      }
      /* Put the character back if we are not at EOF */
      if (!infile.eof())
          infile.unget();

      if ((int)seq.find_first_of("Nn") == -1)  {
         valid_read = 1;
      }

      read.seq = seq;
      seq = "";

   }

   return read;
}

ThreadedFastqParser::ThreadedFastqParser(const std::string &inputfile,
                long int startPos, long int end) :
                         infile(inputfile.c_str())
{
    assert(infile.is_open());

    /* Lay the start pointer down in the right location */
    infile.seekg(startPos, std::ios::beg);

    /* Set the end ptr */
    endPos = end;
}

Read ThreadedFastqParser::get_next_read()
{
   Read read;
   std::string line_three, quality_scores;

   bool valid_read = 0;

   while (!valid_read && !infile.eof())  {

      getline(infile, read.name);
      getline(infile, read.seq);
      getline(infile, line_three);
      getline(infile, quality_scores);

      assert(read.name[0] == '@');
      assert(line_three[0] == '+' || line_three[0] == '#');
      assert(quality_scores.length() == read.seq.length());

      read.name = read.name.substr(1);

      if ((int)read.seq.find_first_of("Nn") == -1)  {
         valid_read = 1;
      }
   }

   return read;
}

// vim: set sts=2 sw=2:
<commit_msg>Bug fix to multi-threaded parser. Only assert that a valid read name was found if not at end of file. (Technically, one could question rather this should be an assert or whether it should throw an exception.)<commit_after>#include "threadedParsers.hh"

using namespace khmer;
using namespace khmer:: threaded_parsers;

/* This function returns the proper parser factory for a given
 * file type
 */
ThreadedIParserFactory* ThreadedIParserFactory::get_parser(const std::string &inputfile, long int chunkSize)
{
   std::string filename(inputfile);
   int found = filename.find_last_of(".");

   std::string type = filename.substr(found+1);

   if (type == "fq" || type == "fastq") {
      return new ThreadedFastqParserFactory(inputfile, chunkSize);
   } else if (type == "fa" || type == "fasta") {
      return new ThreadedFastaParserFactory(inputfile, chunkSize);
   } else {
      return new ThreadedFastaParserFactory(inputfile, chunkSize);
   }
}

/* Constructer for ThreadedFastaParserFactory */
ThreadedFastaParserFactory::ThreadedFastaParserFactory(
    const std::string &inputfile, long int size)
{
    /* Save off the filename and chunk size */
    filename = inputfile;
    chunkSize = size;
    curPos = 0;

    /* Get the file size */
    std::ifstream myFile;
    myFile.open(filename.c_str(), std::ifstream::in);
    myFile.seekg (0, std::ios::end);

    /* Subtract off one so that if there is only one
     * byte left (which is the case since we call unget)
     * we will still indicate that we have reached the end
     * of the file */
    fileSize = (long int)myFile.tellg() - 1;
    myFile.close();
}

ThreadedIParser* ThreadedFastaParserFactory::get_next_parser()
{
    /* Open the file */
    std::ifstream myFile;
    myFile.open(filename.c_str(), std::ifstream::in);
    long int myCurPos, endPos;

    do {
        /* Save off the current curPos so that we can use it in the compare
         * and swap later, to make this call threadsafe */
        myCurPos = curPos;

        /* Start the end position off at the current position + the chunk size */
        endPos = myCurPos + chunkSize;

        if (endPos > fileSize)
            endPos = fileSize;

        /* Read until we see
         * a '>', which indicates the start of the next read, or we reach EOF
         */
        myFile.seekg(endPos, std::ios::beg);

        while (!myFile.eof() && myFile.get() != '>');

        /* We get here as soon as we read a '>' */
        /* Put the '>' back */
        myFile.unget();
        endPos = myFile.tellg();

        if (endPos == -1)
            endPos = fileSize;

    } while(!__sync_bool_compare_and_swap(&curPos, myCurPos, endPos));

    myFile.close();
    return new ThreadedFastaParser(filename, myCurPos, endPos);
}

/* Constructer for ThreadedFastqParserFactory */
ThreadedFastqParserFactory::ThreadedFastqParserFactory(
    const std::string &inputfile, long int size)
{
    /* Save off the filename and chunk size */
    filename = inputfile;
    chunkSize = size;
    curPos = 0;

    /* Get the file size */
    std::ifstream myFile;
    myFile.open(filename.c_str(), std::ifstream::in);
    myFile.seekg (0, std::ios::end);
    /* Subtract off one so that if there is only one
     * byte left (which is the case since we call unget)
     * we will still indicate that we have reached the end
     * of the file */
    fileSize = (long int)myFile.tellg() - 1;
    myFile.close();
}

ThreadedIParser* ThreadedFastqParserFactory::get_next_parser()
{
    /* Open the file */
    std::ifstream myFile;
    myFile.open(filename.c_str(), std::ifstream::in);
    long int myCurPos, endPos;

    do {
        /* Save off the current curPos so that we can use it in the compare
         * and swap later, to make this call threadsafe */
        myCurPos = curPos;

        /* Start the end position off at the current position + the chunk size */
        endPos = myCurPos + chunkSize;

        if (endPos > fileSize)
            endPos = fileSize;

        /* Read until we see
         * a '@', which indicates the start of the next read, or we reach EOF
         * We have to be careful - a '@' can show up in the quality scores too
         * so watch for that
         */
        myFile.seekg(endPos, std::ios::beg);

        char prevChar = myFile.get();
        while (!myFile.eof())
        {
            char curChar = myFile.get();
            if (curChar == '@' && prevChar == '\n')
                break;
            prevChar = curChar;
        }

        /* We get here as soon as we read a '@' */
        /* Put the '@' back */
        if (!myFile.eof())
            myFile.unget();
        endPos = myFile.tellg();

        if (endPos == -1)
            endPos = fileSize;

    } while(!__sync_bool_compare_and_swap(&curPos, myCurPos, endPos));

    myFile.close();
    return new ThreadedFastqParser(filename, myCurPos, endPos);
}

ThreadedFastaParser::ThreadedFastaParser(const std::string &inputfile,
    long int startPos, long int end) :
                         infile(inputfile.c_str())
{

    assert(infile.is_open());

    /* Lay the start pointer down in the right location */
    infile.seekg(startPos, std::ios::beg);

    /* Set the end ptr */
    endPos = end;
}

Read ThreadedFastaParser::get_next_read()
{
   std::string line = "", seq = "";
   Read read;

   bool valid_read = 0;

   while (!valid_read)  {
      getline(infile, line);

      if (!infile.eof( ))
	assert(line[0] == '>');
      read.name = line.substr(1);

      /* Get all the lines that are sequence data */
      while(infile.get() != '>' && !infile.eof())
      {
         infile.unget();
         getline(infile, line);
         seq += line;
      }
      /* Put the character back if we are not at EOF */
      if (!infile.eof())
          infile.unget();

      if ((int)seq.find_first_of("Nn") == -1)  {
          valid_read = 1;
      }

      read.seq = seq;
      seq = "";

   }

   return read;
}

ThreadedFastqParser::ThreadedFastqParser(const std::string &inputfile,
                long int startPos, long int end) :
                         infile(inputfile.c_str())
{
    assert(infile.is_open());

    /* Lay the start pointer down in the right location */
    infile.seekg(startPos, std::ios::beg);

    /* Set the end ptr */
    endPos = end;
}

Read ThreadedFastqParser::get_next_read()
{
   Read read;
   std::string line_three, quality_scores;

   bool valid_read = 0;

   while (!valid_read && !infile.eof())  {

      getline(infile, read.name);
      getline(infile, read.seq);
      getline(infile, line_three);
      getline(infile, quality_scores);

      assert(read.name[0] == '@');
      assert(line_three[0] == '+' || line_three[0] == '#');
      assert(quality_scores.length() == read.seq.length());

      read.name = read.name.substr(1);

      if ((int)read.seq.find_first_of("Nn") == -1)  {
         valid_read = 1;
      }
   }

   return read;
}

// vim: set sts=2 sw=2:
<|endoftext|>


<commit_before>
#include "AConfig.h"
#if(HAS_STD_PILOT)
#include "Device.h"
#include "Pin.h"
#include "Pilot.h"
#include "Timer.h"

Timer pilotTimer;
bool _headingHoldEnabled = false;
int  _headingHoldTarget = 0;
int hdg = 0;
int hdg_Error;
int raw_Left, raw_Right;
int left, right;  // motor outputs in microseconds, +/-500
int loop_Gain = 1;
int integral_Divisor = 100;
long hdg_Error_Integral = 0;
int tgt_Hdg = 0;
bool _depthHoldEnabled = false;
int _depthHoldTarget = 0;
int depth = 0;
int depth_Error = 0;
int raw_lift =0;
int lift = 0;
int target_depth;
int raw_yaw, yaw;

void Pilot::device_setup(){
  pilotTimer.reset();
  Serial.println(F("log:pilot setup complete;"));
}

void Pilot::device_loop(Command command){
//intended to respond to fly by wire commands: MaintainHeading(); TurnTo(compassheading); DiveTo(depth);
    if( command.cmp("holdHeading_toggle")){
      if (_headingHoldEnabled) {
        _headingHoldEnabled = false;
        raw_Left = 0;
        raw_Right = 0;
        hdg_Error_Integral = 0;  // Reset error integrator
        tgt_Hdg = -500;  // -500 = system not in hdg hold

        int argsToSend[] = {1,00}; //include number of parms as last parm
        command.pushCommand("yaw",argsToSend);
        Serial.println(F("log:heading_hold_disabled;"));

      } else {
        _headingHoldEnabled = true;
        if(command.args[0]==0){
          _headingHoldTarget = navdata::HDGD;
        } else {
          _headingHoldTarget = command.args[1];
        }
        tgt_Hdg = _headingHoldTarget;
        Serial.print(F("log:heading_hold_enabled on="));
        Serial.print(tgt_Hdg);
        Serial.println(';');
      }
      Serial.print(F("targetHeading:"));
      if (_headingHoldEnabled) {
        Serial.print(tgt_Hdg);
      } else {
        Serial.print(DISABLED);
      }
      Serial.println(';');
    }

    if( command.cmp("holdDepth_toggle")){
      if (_depthHoldEnabled) {
        _depthHoldEnabled = false;
        raw_lift = 0;
        target_depth = 0;

        int argsToSend[] = {1,0}; //include number of parms as last parm
        command.pushCommand("lift",argsToSend);
        Serial.println(F("log:depth_hold_disabled;"));

      } else {
        _depthHoldEnabled = true;
        if(command.args[0]==0){
          _depthHoldTarget = navdata::DEAP*100;  //casting to cm
        } else {
          _depthHoldTarget = command.args[1];
        }
        target_depth = _depthHoldTarget;
        Serial.print(F("log:depth_hold_enabled on="));
        Serial.print(target_depth);
        Serial.println(';');
      }
      Serial.print(F("targetDepth:"));
      if (_depthHoldEnabled) {
        Serial.print(target_depth);
      } else {
        Serial.print(DISABLED);
      }
      Serial.println(';');
    }

    if (pilotTimer.elapsed (50)) {

      // Autopilot Test #3 6 Jan 2014
      // Hold vehicle at arbitrary heading
      // Integer math; proportional control plus basic integrator
      // No hysteresis around 180 degree error

      // Check whether hold mode is on

      if (_depthHoldEnabled)
      {
        depth = navdata::DEAP*100;
        depth_Error = target_depth-depth;  //positive error = positive lift = go deaper.

        raw_lift = depth_Error * loop_Gain;
        lift = constrain(raw_lift, -50, 50);

        Serial.println(F("log:dhold pushing command;"));
        Serial.print(F("dp_er:"));
        Serial.print(depth_Error);
        Serial.println(';');
        int argsToSend[] = {1,lift}; //include number of parms as last parm
        command.pushCommand("lift",argsToSend);

      }

      if (_headingHoldEnabled)
      {

        // Code for hold mode here
        hdg = navdata::HDGD;

        // Calculate heading error

        hdg_Error = hdg - tgt_Hdg;

        if (hdg_Error > 180)
        {
        hdg_Error = hdg_Error - 360;
        }

        if (hdg_Error < -179)
        {
        hdg_Error = hdg_Error + 360;
        }

        // Run error accumulator (integrator)
        hdg_Error_Integral = hdg_Error_Integral + hdg_Error;

        // Calculator motor outputs
        raw_yaw = -1 * hdg_Error * loop_Gain;

        // raw_Left = raw_Left - (hdg_Error_Integral / integral_Divisor);
        // raw_Right = raw_Right + (hdg_Error_Integral / integral_Divisor);

        // Constrain and output to motors

        yaw = constrain(raw_yaw, -50, 50);
        Serial.println(F("log:hold pushing command;"));
        Serial.print(F("p_er:"));
        Serial.print(hdg_Error);
        Serial.println(';');

        int argsToSend[] = {1,yaw}; //include number of parms as last parm
        command.pushCommand("yaw",argsToSend);
      }

    }
}
#endif

<commit_msg>Revert "Fix spelling in Arduino 2"<commit_after>
#include "AConfig.h"
#if(HAS_STD_PILOT)
#include "Device.h"
#include "Pin.h"
#include "Pilot.h"
#include "Timer.h"

Timer pilotTimer;
bool _headingHoldEnabled = false;
int  _headingHoldTarget = 0;
int hdg = 0;
int hdg_Error;
int raw_Left, raw_Right;
int left, right;  // motor outputs in microseconds, +/-500
int loop_Gain = 1;
int integral_Divisor = 100;
long hdg_Error_Integral = 0;
int tgt_Hdg = 0;
bool _depthHoldEnabled = false;
int _depthHoldTarget = 0;
int depth = 0;
int depth_Error = 0;
int raw_lift =0;
int lift = 0;
int target_depth;
int raw_yaw, yaw;

void Pilot::device_setup(){
  pilotTimer.reset();
  Serial.println(F("log:pilot setup complete;"));
}

void Pilot::device_loop(Command command){
//intended to respond to fly by wire commands: MaintainHeading(); TurnTo(compassheading); DiveTo(depth);
    if( command.cmp("holdHeading_toggle")){
      if (_headingHoldEnabled) {
        _headingHoldEnabled = false;
        raw_Left = 0;
        raw_Right = 0;
        hdg_Error_Integral = 0;  // Reset error integrator
        tgt_Hdg = -500;  // -500 = system not in hdg hold

        int argsToSend[] = {1,00}; //include number of parms as last parm
        command.pushCommand("yaw",argsToSend);
        Serial.println(F("log:heading_hold_disabled;"));

      } else {
        _headingHoldEnabled = true;
        if(command.args[0]==0){
          _headingHoldTarget = navdata::HDGD;
        } else {
          _headingHoldTarget = command.args[1];
        }
        tgt_Hdg = _headingHoldTarget;
        Serial.print(F("log:heading_hold_enabled on="));
        Serial.print(tgt_Hdg);
        Serial.println(';');
      }
      Serial.print(F("targetHeading:"));
      if (_headingHoldEnabled) {
        Serial.print(tgt_Hdg);
      } else {
        Serial.print(DISABLED);
      }
      Serial.println(';');
    }

    if( command.cmp("holdDepth_toggle")){
      if (_depthHoldEnabled) {
        _depthHoldEnabled = false;
        raw_lift = 0;
        target_depth = 0;

        int argsToSend[] = {1,0}; //include number of parms as last parm
        command.pushCommand("lift",argsToSend);
        Serial.println(F("log:depth_hold_disabled;"));

      } else {
        _depthHoldEnabled = true;
        if(command.args[0]==0){
          _depthHoldTarget = navdata::DEAP*100;  //casting to cm
        } else {
          _depthHoldTarget = command.args[1];
        }
        target_depth = _depthHoldTarget;
        Serial.print(F("log:depth_hold_enabled on="));
        Serial.print(target_depth);
        Serial.println(';');
      }
      Serial.print(F("targetDepth:"));
      if (_depthHoldEnabled) {
        Serial.print(target_depth);
      } else {
        Serial.pitnt(DISABLED);
      }
      Serial.println(';');
    }

    if (pilotTimer.elapsed (50)) {

      // Autopilot Test #3 6 Jan 2014
      // Hold vehicle at arbitrary heading
      // Integer math; proportional control plus basic integrator
      // No hysteresis around 180 degree error

      // Check whether hold mode is on

      if (_depthHoldEnabled)
      {
        depth = navdata::DEAP*100;
        depth_Error = target_depth-depth;  //positive error = positive lift = go deaper.

        raw_lift = depth_Error * loop_Gain;
        lift = constrain(raw_lift, -50, 50);

        Serial.println(F("log:dhold pushing command;"));
        Serial.print(F("dp_er:"));
        Serial.print(depth_Error);
        Serial.println(';');
        int argsToSend[] = {1,lift}; //include number of parms as last parm
        command.pushCommand("lift",argsToSend);

      }

      if (_headingHoldEnabled)
      {

        // Code for hold mode here
        hdg = navdata::HDGD;

        // Calculate heading error

        hdg_Error = hdg - tgt_Hdg;

        if (hdg_Error > 180)
        {
        hdg_Error = hdg_Error - 360;
        }

        if (hdg_Error < -179)
        {
        hdg_Error = hdg_Error + 360;
        }

        // Run error accumulator (integrator)
        hdg_Error_Integral = hdg_Error_Integral + hdg_Error;

        // Calculator motor outputs
        raw_yaw = -1 * hdg_Error * loop_Gain;

        // raw_Left = raw_Left - (hdg_Error_Integral / integral_Divisor);
        // raw_Right = raw_Right + (hdg_Error_Integral / integral_Divisor);

        // Constrain and output to motors

        yaw = constrain(raw_yaw, -50, 50);
        Serial.println(F("log:hold pushing command;"));
        Serial.print(F("p_er:"));
        Serial.print(hdg_Error);
        Serial.println(';');

        int argsToSend[] = {1,yaw}; //include number of parms as last parm
        command.pushCommand("yaw",argsToSend);
      }

    }
}
#endif

<|endoftext|>


<commit_before>
#include "AConfig.h"
#if(HAS_STD_PILOT)
#include "Device.h"
#include "Pin.h"
#include "Pilot.h"
#include "Timer.h"

Timer pilotTimer;
bool _headingHoldEnabled = false;
int  _headingHoldTarget = 0;
int hdg = 0;
int hdg_Error;
int raw_Left, raw_Right;
int left, right;  // motor outputs in microseconds, +/-500
int loop_Gain = 1;
int integral_Divisor = 100;
long hdg_Error_Integral = 0;
int tgt_Hdg = 0;
bool _depthHoldEnabled = false;
int _depthHoldTarget = 0;
int depth = 0;
int depth_Error = 0;
int raw_lift =0;
int lift = 0;
int target_depth;
int raw_yaw, yaw;

void Pilot::device_setup(){
  pilotTimer.reset();
  Serial.println(F("log:pilot setup complete;"));
}

void Pilot::device_loop(Command command){
//intended to respond to fly by wire commands: MaintainHeading(); TurnTo(compassheading); DiveTo(depth);
    if( command.cmp("holdHeading_toggle")){
      if (_headingHoldEnabled) {
        _headingHoldEnabled = false;
        raw_Left = 0;
        raw_Right = 0;
        hdg_Error_Integral = 0;  // Reset error integrator
        tgt_Hdg = -500;  // -500 = system not in hdg hold

        int argsToSend[] = {1,00}; //include number of parms as last parm
        command.pushCommand("yaw",argsToSend);
        Serial.println(F("log:heading_hold_disabled;"));

      } else {
        _headingHoldEnabled = true;
        if(command.args[0]==0){
          _headingHoldTarget = navdata::HDGD;
        } else {
          _headingHoldTarget = command.args[1];
        }
        tgt_Hdg = _headingHoldTarget;
        Serial.print(F("log:heading_hold_enabled on="));
        Serial.print(tgt_Hdg);
        Serial.println(';');
      }
      Serial.print(F("targetHeading:"));
      if (_headingHoldEnabled) {
        Serial.print(tgt_Hdg);
      } else {
        Serial.print(DISABLED);
      }
      Serial.println(';');
    }

    if( command.cmp("holdDepth_toggle")){
      if (_depthHoldEnabled) {
        _depthHoldEnabled = false;
        raw_lift = 0;
        target_depth = 0;

        int argsToSend[] = {1,0}; //include number of parms as last parm
        command.pushCommand("lift",argsToSend);
        Serial.println(F("log:depth_hold_disabled;"));

      } else {
        _depthHoldEnabled = true;
        if(command.args[0]==0){
          _depthHoldTarget = navdata::DEAP*100;  //casting to cm
        } else {
          _depthHoldTarget = command.args[1];
        }
        target_depth = _depthHoldTarget;
        Serial.print(F("log:depth_hold_enabled on="));
        Serial.print(target_depth);
        Serial.println(';');
      }
      Serial.print(F("targetDepth:"));
      if (_depthHoldEnabled) {
        Serial.print(target_depth);
      } else {
        Serial.pitnt(DISABLED);
      }
      Serial.println(';');
    }

    if (pilotTimer.elapsed (50)) {

      // Autopilot Test #3 6 Jan 2014
      // Hold vehicle at arbitrary heading
      // Integer math; proportional control plus basic integrator
      // No hysteresis around 180 degree error

      // Check whether hold mode is on

      if (_depthHoldEnabled)
      {
        depth = navdata::DEAP*100;
        depth_Error = target_depth-depth;  //positive error = positive lift = go deaper.

        raw_lift = depth_Error * loop_Gain;
        lift = constrain(raw_lift, -50, 50);

        Serial.println(F("log:dhold pushing command;"));
        Serial.print(F("dp_er:"));
        Serial.print(depth_Error);
        Serial.println(';');
        int argsToSend[] = {1,lift}; //include number of parms as last parm
        command.pushCommand("lift",argsToSend);

      }

      if (_headingHoldEnabled)
      {

        // Code for hold mode here
        hdg = navdata::HDGD;

        // Calculate heading error

        hdg_Error = hdg - tgt_Hdg;

        if (hdg_Error > 180)
        {
        hdg_Error = hdg_Error - 360;
        }

        if (hdg_Error < -179)
        {
        hdg_Error = hdg_Error + 360;
        }

        // Run error accumulator (integrator)
        hdg_Error_Integral = hdg_Error_Integral + hdg_Error;

        // Calculator motor outputs
        raw_yaw = -1 * hdg_Error * loop_Gain;

        // raw_Left = raw_Left - (hdg_Error_Integral / integral_Divisor);
        // raw_Right = raw_Right + (hdg_Error_Integral / integral_Divisor);

        // Constrain and output to motors

        yaw = constrain(raw_yaw, -50, 50);
        Serial.println(F("log:hold pushing command;"));
        Serial.print(F("p_er:"));
        Serial.print(hdg_Error);
        Serial.println(';');

        int argsToSend[] = {1,yaw}; //include number of parms as last parm
        command.pushCommand("yaw",argsToSend);
      }

    }
}
#endif

<commit_msg>Fix spelling in Arduino 2<commit_after>
#include "AConfig.h"
#if(HAS_STD_PILOT)
#include "Device.h"
#include "Pin.h"
#include "Pilot.h"
#include "Timer.h"

Timer pilotTimer;
bool _headingHoldEnabled = false;
int  _headingHoldTarget = 0;
int hdg = 0;
int hdg_Error;
int raw_Left, raw_Right;
int left, right;  // motor outputs in microseconds, +/-500
int loop_Gain = 1;
int integral_Divisor = 100;
long hdg_Error_Integral = 0;
int tgt_Hdg = 0;
bool _depthHoldEnabled = false;
int _depthHoldTarget = 0;
int depth = 0;
int depth_Error = 0;
int raw_lift =0;
int lift = 0;
int target_depth;
int raw_yaw, yaw;

void Pilot::device_setup(){
  pilotTimer.reset();
  Serial.println(F("log:pilot setup complete;"));
}

void Pilot::device_loop(Command command){
//intended to respond to fly by wire commands: MaintainHeading(); TurnTo(compassheading); DiveTo(depth);
    if( command.cmp("holdHeading_toggle")){
      if (_headingHoldEnabled) {
        _headingHoldEnabled = false;
        raw_Left = 0;
        raw_Right = 0;
        hdg_Error_Integral = 0;  // Reset error integrator
        tgt_Hdg = -500;  // -500 = system not in hdg hold

        int argsToSend[] = {1,00}; //include number of parms as last parm
        command.pushCommand("yaw",argsToSend);
        Serial.println(F("log:heading_hold_disabled;"));

      } else {
        _headingHoldEnabled = true;
        if(command.args[0]==0){
          _headingHoldTarget = navdata::HDGD;
        } else {
          _headingHoldTarget = command.args[1];
        }
        tgt_Hdg = _headingHoldTarget;
        Serial.print(F("log:heading_hold_enabled on="));
        Serial.print(tgt_Hdg);
        Serial.println(';');
      }
      Serial.print(F("targetHeading:"));
      if (_headingHoldEnabled) {
        Serial.print(tgt_Hdg);
      } else {
        Serial.print(DISABLED);
      }
      Serial.println(';');
    }

    if( command.cmp("holdDepth_toggle")){
      if (_depthHoldEnabled) {
        _depthHoldEnabled = false;
        raw_lift = 0;
        target_depth = 0;

        int argsToSend[] = {1,0}; //include number of parms as last parm
        command.pushCommand("lift",argsToSend);
        Serial.println(F("log:depth_hold_disabled;"));

      } else {
        _depthHoldEnabled = true;
        if(command.args[0]==0){
          _depthHoldTarget = navdata::DEAP*100;  //casting to cm
        } else {
          _depthHoldTarget = command.args[1];
        }
        target_depth = _depthHoldTarget;
        Serial.print(F("log:depth_hold_enabled on="));
        Serial.print(target_depth);
        Serial.println(';');
      }
      Serial.print(F("targetDepth:"));
      if (_depthHoldEnabled) {
        Serial.print(target_depth);
      } else {
        Serial.print(DISABLED);
      }
      Serial.println(';');
    }

    if (pilotTimer.elapsed (50)) {

      // Autopilot Test #3 6 Jan 2014
      // Hold vehicle at arbitrary heading
      // Integer math; proportional control plus basic integrator
      // No hysteresis around 180 degree error

      // Check whether hold mode is on

      if (_depthHoldEnabled)
      {
        depth = navdata::DEAP*100;
        depth_Error = target_depth-depth;  //positive error = positive lift = go deaper.

        raw_lift = depth_Error * loop_Gain;
        lift = constrain(raw_lift, -50, 50);

        Serial.println(F("log:dhold pushing command;"));
        Serial.print(F("dp_er:"));
        Serial.print(depth_Error);
        Serial.println(';');
        int argsToSend[] = {1,lift}; //include number of parms as last parm
        command.pushCommand("lift",argsToSend);

      }

      if (_headingHoldEnabled)
      {

        // Code for hold mode here
        hdg = navdata::HDGD;

        // Calculate heading error

        hdg_Error = hdg - tgt_Hdg;

        if (hdg_Error > 180)
        {
        hdg_Error = hdg_Error - 360;
        }

        if (hdg_Error < -179)
        {
        hdg_Error = hdg_Error + 360;
        }

        // Run error accumulator (integrator)
        hdg_Error_Integral = hdg_Error_Integral + hdg_Error;

        // Calculator motor outputs
        raw_yaw = -1 * hdg_Error * loop_Gain;

        // raw_Left = raw_Left - (hdg_Error_Integral / integral_Divisor);
        // raw_Right = raw_Right + (hdg_Error_Integral / integral_Divisor);

        // Constrain and output to motors

        yaw = constrain(raw_yaw, -50, 50);
        Serial.println(F("log:hold pushing command;"));
        Serial.print(F("p_er:"));
        Serial.print(hdg_Error);
        Serial.println(';');

        int argsToSend[] = {1,yaw}; //include number of parms as last parm
        command.pushCommand("yaw",argsToSend);
      }

    }
}
#endif

<|endoftext|>


<commit_before>/*=========================================================================

Program:   BlueBerry Platform
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 "berryWorkbenchWindowAdvisor.h"

#include <Poco/Bugcheck.h>

#include <berryWorkbenchPreferenceConstants.h>
#include <berryObjects.h>
#include <berryIPreferences.h>

#include "../internal/berryWorkbenchWindowConfigurer.h"
#include "../internal/berryWorkbenchPlugin.h"

namespace berry
{

IWorkbenchWindowConfigurer::Pointer WorkbenchWindowAdvisor::GetWindowConfigurer()
{
  return windowConfigurer;
}

WorkbenchWindowAdvisor::WorkbenchWindowAdvisor(
    IWorkbenchWindowConfigurer::Pointer configurer)
{
  poco_assert(configurer.IsNotNull());
  this->windowConfigurer = configurer;
}

WorkbenchWindowAdvisor::~WorkbenchWindowAdvisor()
{
}

void WorkbenchWindowAdvisor::PreWindowOpen()
{
  // do nothing
}

ActionBarAdvisor::Pointer WorkbenchWindowAdvisor::CreateActionBarAdvisor(
    IActionBarConfigurer::Pointer configurer)
{
  ActionBarAdvisor::Pointer actionBarAdvisor(new ActionBarAdvisor(configurer));
  return actionBarAdvisor;
}

void WorkbenchWindowAdvisor::PostWindowRestore()
{
  // do nothing
}

void WorkbenchWindowAdvisor::OpenIntro()
{
  // TODO: Refactor this into an IIntroManager.openIntro(IWorkbenchWindow) call

  // introOpened flag needs to be global
  IWorkbenchConfigurer::Pointer wbConfig = GetWindowConfigurer()->GetWorkbenchConfigurer();
  std::string key = "introOpened"; //$NON-NLS-1$
  ObjectBool::Pointer introOpened = wbConfig->GetData(key).Cast<ObjectBool>();
  if (introOpened && introOpened->GetValue())
  {
    return;
  }

  wbConfig->SetData(key, ObjectBool::Pointer(new ObjectBool(true)));

  IPreferences::Pointer workbenchPrefs = WorkbenchPlugin::GetDefault()->GetPreferencesService()->GetSystemPreferences();

  bool showIntro = workbenchPrefs->GetBool(WorkbenchPreferenceConstants::SHOW_INTRO, true);

  IIntroManager* introManager = wbConfig->GetWorkbench()->GetIntroManager();

  bool hasIntro = introManager->HasIntro();
  bool isNewIntroContentAvailable = introManager->IsNewContentAvailable();

  if (hasIntro && (showIntro || isNewIntroContentAvailable))
  {
    introManager
    ->ShowIntro(GetWindowConfigurer()->GetWindow(), false);

    workbenchPrefs->PutBool(WorkbenchPreferenceConstants::SHOW_INTRO, false);
    workbenchPrefs->Flush();
  }
}

void WorkbenchWindowAdvisor::PostWindowCreate()
{
  // do nothing
}

void WorkbenchWindowAdvisor::PostWindowOpen()
{
  // do nothing
}

bool WorkbenchWindowAdvisor::PreWindowShellClose()
{
  // do nothing, but allow the close() to proceed
  return true;
}

void WorkbenchWindowAdvisor::PostWindowClose()
{
  // do nothing
}

void WorkbenchWindowAdvisor::CreateWindowContents(Shell::Pointer shell)
{
  this->GetWindowConfigurer().Cast<WorkbenchWindowConfigurer>()->CreateDefaultContents(shell);
}

void* WorkbenchWindowAdvisor::CreateEmptyWindowContents(void*  /*parent*/)
{
  return 0;
}

bool WorkbenchWindowAdvisor::SaveState(IMemento::Pointer  /*memento*/)
{
  // do nothing
  return true;
}

bool WorkbenchWindowAdvisor::RestoreState(IMemento::Pointer  /*memento*/)
{
  // do nothing
  return true;
}

}
<commit_msg>FIX (#5498): Now welcome screen is shown at every startup by standard. Only when it is closed explicitly (close view), it stops showing up. Help->Welcome brings it back.<commit_after>/*=========================================================================

Program:   BlueBerry Platform
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 "berryWorkbenchWindowAdvisor.h"

#include <Poco/Bugcheck.h>

#include <berryWorkbenchPreferenceConstants.h>
#include <berryObjects.h>
#include <berryIPreferences.h>

#include "../internal/berryWorkbenchWindowConfigurer.h"
#include "../internal/berryWorkbenchPlugin.h"

namespace berry
{

IWorkbenchWindowConfigurer::Pointer WorkbenchWindowAdvisor::GetWindowConfigurer()
{
  return windowConfigurer;
}

WorkbenchWindowAdvisor::WorkbenchWindowAdvisor(
    IWorkbenchWindowConfigurer::Pointer configurer)
{
  poco_assert(configurer.IsNotNull());
  this->windowConfigurer = configurer;
}

WorkbenchWindowAdvisor::~WorkbenchWindowAdvisor()
{
}

void WorkbenchWindowAdvisor::PreWindowOpen()
{
  // do nothing
}

ActionBarAdvisor::Pointer WorkbenchWindowAdvisor::CreateActionBarAdvisor(
    IActionBarConfigurer::Pointer configurer)
{
  ActionBarAdvisor::Pointer actionBarAdvisor(new ActionBarAdvisor(configurer));
  return actionBarAdvisor;
}

void WorkbenchWindowAdvisor::PostWindowRestore()
{
  // do nothing
}

void WorkbenchWindowAdvisor::OpenIntro()
{
  // TODO: Refactor this into an IIntroManager.openIntro(IWorkbenchWindow) call

  // introOpened flag needs to be global
  IWorkbenchConfigurer::Pointer wbConfig = GetWindowConfigurer()->GetWorkbenchConfigurer();
  std::string key = "introOpened"; //$NON-NLS-1$
  ObjectBool::Pointer introOpened = wbConfig->GetData(key).Cast<ObjectBool>();
  if (introOpened && introOpened->GetValue())
  {
    return;
  }

  wbConfig->SetData(key, ObjectBool::Pointer(new ObjectBool(true)));

  IPreferences::Pointer workbenchPrefs = WorkbenchPlugin::GetDefault()->GetPreferencesService()->GetSystemPreferences();

  bool showIntro = workbenchPrefs->GetBool(WorkbenchPreferenceConstants::SHOW_INTRO, true);

  IIntroManager* introManager = wbConfig->GetWorkbench()->GetIntroManager();

  bool hasIntro = introManager->HasIntro();
  bool isNewIntroContentAvailable = introManager->IsNewContentAvailable();

  if (hasIntro && (showIntro || isNewIntroContentAvailable))
  {
    introManager
    ->ShowIntro(GetWindowConfigurer()->GetWindow(), false);

   /* workbenchPrefs->PutBool(WorkbenchPreferenceConstants::SHOW_INTRO, false);
    workbenchPrefs->Flush();*/
  }
}

void WorkbenchWindowAdvisor::PostWindowCreate()
{
  // do nothing
}

void WorkbenchWindowAdvisor::PostWindowOpen()
{
  // do nothing
}

bool WorkbenchWindowAdvisor::PreWindowShellClose()
{
  // do nothing, but allow the close() to proceed
  return true;
}

void WorkbenchWindowAdvisor::PostWindowClose()
{
  // do nothing
}

void WorkbenchWindowAdvisor::CreateWindowContents(Shell::Pointer shell)
{
  this->GetWindowConfigurer().Cast<WorkbenchWindowConfigurer>()->CreateDefaultContents(shell);
}

void* WorkbenchWindowAdvisor::CreateEmptyWindowContents(void*  /*parent*/)
{
  return 0;
}

bool WorkbenchWindowAdvisor::SaveState(IMemento::Pointer  /*memento*/)
{
  // do nothing
  return true;
}

bool WorkbenchWindowAdvisor::RestoreState(IMemento::Pointer  /*memento*/)
{
  // do nothing
  return true;
}

}
<|endoftext|>