<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: setaccess.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 03:20:15 $
 *
 *  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 CONFIGMGR_API_SETACCESS_HXX_
#define CONFIGMGR_API_SETACCESS_HXX_

#ifndef _COM_SUN_STAR_CONTAINER_XHIERARCHICALNAME_HPP_
#include <com/sun/star/container/XHierarchicalName.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XHIERARCHICALNAMEACCESS_HPP_
#include <com/sun/star/container/XHierarchicalNameAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XCONTAINER_HPP_
#include <com/sun/star/container/XContainer.hpp>
#endif
#ifndef _COM_SUN_STAR_CONFIGURATION_XTEMPLATECONTAINER_HPP_
#include <com/sun/star/configuration/XTemplateContainer.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XEXACTNAME_HPP_
#include <com/sun/star/beans/XExactName.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTY_HPP_
#include <com/sun/star/beans/XProperty.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSETINFO_HPP_
#include <com/sun/star/beans/XPropertySetInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XSTRINGESCAPE_HPP_
#include <com/sun/star/util/XStringEscape.hpp>
#endif

#ifndef _CPPUHELPER_IMPLBASE9_HXX_
#include <cppuhelper/implbase9.hxx>
#endif

namespace configmgr
{
    namespace css = ::com::sun::star;
    namespace uno = ::com::sun::star::uno;
    using rtl::OUString;

    namespace configapi { class NodeSetInfoAccess; }

    /** implements the (read-only) interfaces supported by a set node
        within the configuration tree.

 Is an interface adapter around <type scope='configmgr::configapi'>NodeAccess</type>.

    */
    class BasicSetAccess
    : public ::cppu::ImplHelper9
                < css::container::XNameAccess
                , css::container::XHierarchicalName
                , css::container::XHierarchicalNameAccess
                , css::container::XContainer
                , css::beans::XExactName
                , css::beans::XProperty
                , css::beans::XPropertySetInfo
                , css::configuration::XTemplateContainer
                , css::util::XStringEscape
                >
    {
    protected:
    // Destructors
        virtual ~BasicSetAccess() {}

    public:
    // Interface methods
        // XHierarchicalName
        virtual OUString SAL_CALL
            getHierarchicalName(  )
                throw(uno::RuntimeException);

        virtual OUString SAL_CALL
            composeHierarchicalName( const OUString& aRelativeName )
                throw(css::lang::IllegalArgumentException, css::lang::NoSupportException,
                        uno::RuntimeException);

        // XElementAccess, base class of XNameAccess
        virtual uno::Type SAL_CALL
            getElementType(  )
                throw(uno::RuntimeException);

        virtual sal_Bool SAL_CALL
            hasElements(  )
                throw(uno::RuntimeException);

        // XNameAccess
        virtual uno::Any SAL_CALL
            getByName( const OUString& aName )
                throw(css::container::NoSuchElementException, css::lang::WrappedTargetException,
                         uno::RuntimeException);

        virtual uno::Sequence< OUString > SAL_CALL
            getElementNames(  )
                throw( uno::RuntimeException);

        virtual sal_Bool SAL_CALL
            hasByName( const OUString& aName )
                throw(uno::RuntimeException);

        // XHierarchicalNameAccess
        virtual uno::Any SAL_CALL
            getByHierarchicalName( const OUString& aName )
                throw(css::container::NoSuchElementException, uno::RuntimeException);

        virtual sal_Bool SAL_CALL
            hasByHierarchicalName( const OUString& aName )
                throw(uno::RuntimeException);

        // XContainer
        virtual void SAL_CALL
            addContainerListener( const uno::Reference< css::container::XContainerListener >& xListener )
                throw(uno::RuntimeException);

        virtual void SAL_CALL
            removeContainerListener( const uno::Reference< css::container::XContainerListener >& xListener )
                throw(uno::RuntimeException);

        // XExactName
        virtual OUString SAL_CALL
            getExactName( const OUString& aApproximateName )
                throw(uno::RuntimeException);

        // XProperty
        virtual css::beans::Property SAL_CALL
            getAsProperty(  )
                throw(uno::RuntimeException);

        // XPropertySetInfo
        virtual uno::Sequence< css::beans::Property > SAL_CALL
            getProperties(  )
                throw (uno::RuntimeException);

        virtual css::beans::Property SAL_CALL
            getPropertyByName( const OUString& aName )
                throw (css::beans::UnknownPropertyException, uno::RuntimeException);

        virtual sal_Bool SAL_CALL
            hasPropertyByName( const OUString& Name )
                throw (uno::RuntimeException);

        // XTemplateContainer
        OUString SAL_CALL
            getElementTemplateName(  )
                throw(uno::RuntimeException);

        // XStringEscape
        OUString SAL_CALL
            escapeString( const OUString& aString )
                throw(css::lang::IllegalArgumentException, uno::RuntimeException);

        OUString SAL_CALL
            unescapeString( const OUString& aEscapedString )
                throw(css::lang::IllegalArgumentException, uno::RuntimeException);

    protected:
        virtual configapi::NodeSetInfoAccess& getNode() = 0;
    };

}
#endif // CONFIGMGR_API_SETACCESS_HXX_

<commit_msg>INTEGRATION: CWS changefileheader (1.3.130); FILE MERGED 2008/04/01 15:06:33 thb 1.3.130.3: #i85898# Stripping all external header guards 2008/04/01 12:27:14 thb 1.3.130.2: #i85898# Stripping all external header guards 2008/03/31 12:22:38 rt 1.3.130.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: setaccess.hxx,v $
 * $Revision: 1.4 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef CONFIGMGR_API_SETACCESS_HXX_
#define CONFIGMGR_API_SETACCESS_HXX_

#include <com/sun/star/container/XHierarchicalName.hpp>
#include <com/sun/star/container/XNameAccess.hpp>
#include <com/sun/star/container/XHierarchicalNameAccess.hpp>
#include <com/sun/star/container/XContainer.hpp>
#include <com/sun/star/configuration/XTemplateContainer.hpp>
#include <com/sun/star/beans/XExactName.hpp>
#include <com/sun/star/beans/XProperty.hpp>
#include <com/sun/star/beans/XPropertySetInfo.hpp>
#include <com/sun/star/util/XStringEscape.hpp>
#include <cppuhelper/implbase9.hxx>

namespace configmgr
{
    namespace css = ::com::sun::star;
    namespace uno = ::com::sun::star::uno;
    using rtl::OUString;

    namespace configapi { class NodeSetInfoAccess; }

    /** implements the (read-only) interfaces supported by a set node
        within the configuration tree.

 Is an interface adapter around <type scope='configmgr::configapi'>NodeAccess</type>.

    */
    class BasicSetAccess
    : public ::cppu::ImplHelper9
                < css::container::XNameAccess
                , css::container::XHierarchicalName
                , css::container::XHierarchicalNameAccess
                , css::container::XContainer
                , css::beans::XExactName
                , css::beans::XProperty
                , css::beans::XPropertySetInfo
                , css::configuration::XTemplateContainer
                , css::util::XStringEscape
                >
    {
    protected:
    // Destructors
        virtual ~BasicSetAccess() {}

    public:
    // Interface methods
        // XHierarchicalName
        virtual OUString SAL_CALL
            getHierarchicalName(  )
                throw(uno::RuntimeException);

        virtual OUString SAL_CALL
            composeHierarchicalName( const OUString& aRelativeName )
                throw(css::lang::IllegalArgumentException, css::lang::NoSupportException,
                        uno::RuntimeException);

        // XElementAccess, base class of XNameAccess
        virtual uno::Type SAL_CALL
            getElementType(  )
                throw(uno::RuntimeException);

        virtual sal_Bool SAL_CALL
            hasElements(  )
                throw(uno::RuntimeException);

        // XNameAccess
        virtual uno::Any SAL_CALL
            getByName( const OUString& aName )
                throw(css::container::NoSuchElementException, css::lang::WrappedTargetException,
                         uno::RuntimeException);

        virtual uno::Sequence< OUString > SAL_CALL
            getElementNames(  )
                throw( uno::RuntimeException);

        virtual sal_Bool SAL_CALL
            hasByName( const OUString& aName )
                throw(uno::RuntimeException);

        // XHierarchicalNameAccess
        virtual uno::Any SAL_CALL
            getByHierarchicalName( const OUString& aName )
                throw(css::container::NoSuchElementException, uno::RuntimeException);

        virtual sal_Bool SAL_CALL
            hasByHierarchicalName( const OUString& aName )
                throw(uno::RuntimeException);

        // XContainer
        virtual void SAL_CALL
            addContainerListener( const uno::Reference< css::container::XContainerListener >& xListener )
                throw(uno::RuntimeException);

        virtual void SAL_CALL
            removeContainerListener( const uno::Reference< css::container::XContainerListener >& xListener )
                throw(uno::RuntimeException);

        // XExactName
        virtual OUString SAL_CALL
            getExactName( const OUString& aApproximateName )
                throw(uno::RuntimeException);

        // XProperty
        virtual css::beans::Property SAL_CALL
            getAsProperty(  )
                throw(uno::RuntimeException);

        // XPropertySetInfo
        virtual uno::Sequence< css::beans::Property > SAL_CALL
            getProperties(  )
                throw (uno::RuntimeException);

        virtual css::beans::Property SAL_CALL
            getPropertyByName( const OUString& aName )
                throw (css::beans::UnknownPropertyException, uno::RuntimeException);

        virtual sal_Bool SAL_CALL
            hasPropertyByName( const OUString& Name )
                throw (uno::RuntimeException);

        // XTemplateContainer
        OUString SAL_CALL
            getElementTemplateName(  )
                throw(uno::RuntimeException);

        // XStringEscape
        OUString SAL_CALL
            escapeString( const OUString& aString )
                throw(css::lang::IllegalArgumentException, uno::RuntimeException);

        OUString SAL_CALL
            unescapeString( const OUString& aEscapedString )
                throw(css::lang::IllegalArgumentException, uno::RuntimeException);

    protected:
        virtual configapi::NodeSetInfoAccess& getNode() = 0;
    };

}
#endif // CONFIGMGR_API_SETACCESS_HXX_

<|endoftext|>


<commit_before>/**
* C S O U N D   V S T
*
* A VST plugin version of Csound, with Python scripting.
*
* L I C E N S E
*
* This software 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 software 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 software; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/
#ifndef MIDIFILE_H
#define MIDIFILE_H
#ifdef SWIG
%module CsoundVST
%{
#include <algorithm>
#include <fstream>
#include <iostream>
#include <map>
#include <string>
#include <vector>
%}
%template(IntToDoubleMap) std::map<int, double>;
#else
#include <algorithm>
#include <fstream>
#include <iostream>
#include <map>
#include <string>
#include <vector>
#endif

namespace csound
{
	class MidiFile;

	class Chunk
	{
	public:
		int id;
		int chunkSize;
		int chunkSizePosition;
		int chunkStart;
		int chunkEnd;
		Chunk(const char *_id);
		virtual ~Chunk(void);
		virtual void read(std::istream &stream);
		virtual void write(std::ostream &stream);
		virtual void markChunkSize(std::ostream &stream);
		virtual void markChunkStart(std::ostream &stream);
		virtual void markChunkEnd(std::ostream &stream);
	};

	class MidiHeader : public Chunk
	{
	public:
		short type;
		short trackCount;
		short timeFormat;
		MidiHeader(void);
		virtual ~MidiHeader(void);
		virtual void clear(void);
		virtual void read(std::istream &stream);
		virtual void write(std::ostream &stream);
	};

	/**
	* This class is used to store ALL Midi messages.
	*/
	class MidiEvent : public std::vector<unsigned char>
	{
	public:
		int ticks;
		double time;
		MidiEvent(void);
		virtual ~MidiEvent(void);
		virtual void read(std::istream &stream, MidiFile &midiFile);
		virtual void write(std::ostream &stream, MidiFile &midiFile, int lastTick);
		virtual int getStatus(void);
		virtual int getStatusNybble(void);
		virtual int getChannelNybble(void);
		virtual int getKey(void);
		virtual int getVelocity(void);
		virtual int getMetaType(void);
		virtual unsigned char getMetaData(int i);
		virtual size_t getMetaSize(void);
		virtual unsigned char read(std::istream &stream);
		virtual bool isChannelVoiceMessage();
		virtual bool isNoteOn(void);
		virtual bool isNoteOff(void);
		virtual bool isMatchingNoteOff(MidiEvent &offEvent);
		friend bool operator < (const MidiEvent &a, MidiEvent &b);
	};

	class MidiTrack : public Chunk, public std::vector<MidiEvent>
	{
	public:
		MidiTrack(void);
		virtual ~MidiTrack(void);
		virtual void read(std::istream &stream, MidiFile &midiFile);
		virtual void write(std::ostream &stream, MidiFile &midiFile);
		virtual void sort(void);
	};

	class TempoMap : public std::map<int, double>
	{
	public:
		double getCurrentSecondsPerTick(int tick);
	};

	/**
	* Reads and writes format 0 and format 1 standard MIDI files.
	*/
	class MidiFile
	{
	public:
		typedef enum {
			CHANNEL_NOTE_OFF = 0x80,
			CHANNEL_NOTE_ON = 0x90,
			CHANNEL_KEY_PRESSURE = 0xa0,
			CHANNEL_CONTROL_CHANGE = 0xb0,
			CHANNEL_PROGRAM_CHANGE = 0xc0,
			CHANNEL_AFTER_TOUCH = 0xd0,
			CHANNEL_PITCH_BEND = 0xe0,
			SYSTEM_EXCLUSIVE = 0xf0,
			SYSTEM_MIDI_TIME_CODE = 0xf1,
			SYSTEM_SONG_POSITION_POINTER = 0xf2,
			SYSTEM_SONG_SELECT = 0xf3,
			SYSTEM_TUNE_REQUEST = 0xf6,
			SYSTEM_END_OF_EXCLUSIVE = 0xf7,
			SYSTEM_TIMING_CLOCK = 0xf8,
			SYSTEM_START = 0xfa,
			SYSTEM_CONTINUE = 0xfb,
			SYSTEM_STOP = 0xfc,
			SYSTEM_ACTIVE_SENSING = 0xfe,
			META_EVENT = 0xff,
		} MidiEventTypes;
		typedef enum {
			META_SEQUENCE_NUMBER = 0x00,
			META_TEXT_EVENT = 0x01,
			META_COPYRIGHT_NOTICE = 0x02,
			META_SEQUENCE_NAME = 0x03,
			META_INSTRUMENT_NAME = 0x04,
			META_LYRIC = 0x05,
			META_MARKER = 0x06,
			META_CUE_POINT = 0x07,
			META_CHANNEL_PREFIX = 0x20,
			META_END_OF_TRACK = 0x2f,
			META_SET_TEMPO = 0x51,
			META_SMPTE_OFFSET = 0x54,
			META_TIME_SIGNATURE = 0x58,
			META_KEY_SIGNATURE = 0x59,
			META_SEQUENCER_SPECIFIC = 0x74,
		} MetaEventTypes;
		typedef enum {
			CONTROLLER_MOD_WHEEL = 1,
			CONTROLLER_BREATH = 2,
			CONTROLLER_FOOT = 4,
			CONTROLLER_BALANCE = 8,
			CONTROLLER_PAN = 10,
			CONTROLLER_EXPRESSION = 11,
			/* 7 bit controllers */
			CONTROLLER_DAMPER_PEDAL = 0x40,
			CONTROLLER_PORTAMENTO = 0x41,
			CONTROLLER_SOSTENUTO = 0x42,
			CONTROLLER_SOFT_PEDAL = 0x43,
			CONTROLLER_GENERAL_4 = 0x44,
			CONTROLLER_HOLD_2 = 0x45,
			CONTROLLER_7GENERAL_5 = 0x50,
			CONTROLLER_GENERAL_6 = 0x51,
			CONTROLLER_GENERAL_7 = 0x52,
			CONTROLLER_GENERAL_8 = 0x53,
			CONTROLLER_TREMOLO_DEPTH = 0x5c,
			CONTROLLER_CHORUS_DEPTH = 0x5d,
			CONTROLLER_DETUNE = 0x5e,
			CONTROLLER_PHASER_DEPTH = 0x5f,
			/* parameter values */
			CONTROLLER_DATA_INC = 0x60,
			CONTROLLER_DATA_DEC = 0x61,
			/* parameter selection */
			CONTROLLER_NON_REG_LSB = 0x62,
			CONTROLLER_NON_REG_MSB = 0x63,
			CONTROLLER_REG_LSB = 0x64,
			CONTROLLER_REG_MSG = 0x65,
			CONTROLLER_CONTINUOUS_AFTERTOUCH = 128,
		} MidiControllers;
		static int readVariableLength(std::istream &stream);
		static void writeVariableLength(std::ostream &stream, int value);
		static int toInt(int c1, int c2, int c3, int c4);
		static short toShort(int c1, int c2);
		static int readInt(std::istream &stream);
		static void writeInt(std::ostream &stream, int value);
		static short readShort(std::istream &stream);
		static void writeShort(std::ostream &stream, short value);
		static int chunkName(int a, int b, int c, int d);
		void computeTimes(void);
		int currentTick;
		double currentTime;
		double currentSecondsPerTick;
		double microsecondsPerQuarterNote;
		unsigned char lastStatus;
		MidiHeader midiHeader;
		TempoMap tempoMap;
		std::vector<MidiTrack> midiTracks;
		MidiFile(void);
		virtual ~MidiFile(void);
		virtual void clear(void);
		virtual void read(std::istream &stream);
		virtual void write(std::ostream &stream);
		virtual void load(std::string filename);
		virtual void save(std::string filename);
		virtual void dump(std::ostream &stream);
		virtual void sort(void);
	};

	bool operator < (const MidiEvent &a, MidiEvent &b);
}
#endif
<commit_msg>Fixed typedefs and template declarations for MinGW.<commit_after>/**
* C S O U N D   V S T
*
* A VST plugin version of Csound, with Python scripting.
*
* L I C E N S E
*
* This software 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 software 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 software; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/
#ifndef MIDIFILE_H
#define MIDIFILE_H
#ifdef SWIG
%module CsoundVST
%{
#include <algorithm>
#include <fstream>
#include <iostream>
#include <map>
#include <string>
#include <vector>
%}
%template(IntToDoubleMap) std::map<int, double>;
%template(MidiByteVector) std::vector<unsigned char>;
#else
#include <algorithm>
#include <fstream>
#include <iostream>
#include <map>
#include <string>
#include <vector>
#endif

namespace csound
{
    typedef unsigned char csound_u_char;
	class MidiFile;

	class Chunk
	{
	public:
		int id;
		int chunkSize;
		int chunkSizePosition;
		int chunkStart;
		int chunkEnd;
		Chunk(const char *_id);
		virtual ~Chunk(void);
		virtual void read(std::istream &stream);
		virtual void write(std::ostream &stream);
		virtual void markChunkSize(std::ostream &stream);
		virtual void markChunkStart(std::ostream &stream);
		virtual void markChunkEnd(std::ostream &stream);
	};

	class MidiHeader : public Chunk
	{
	public:
		short type;
		short trackCount;
		short timeFormat;
		MidiHeader(void);
		virtual ~MidiHeader(void);
		virtual void clear(void);
		virtual void read(std::istream &stream);
		virtual void write(std::ostream &stream);
	};

	/**
	* This class is used to store ALL Midi messages.
	*/
	class MidiEvent : public std::vector<csound_u_char>
	{
	public:
		int ticks;
		double time;
		MidiEvent(void);
		virtual ~MidiEvent(void);
		virtual void read(std::istream &stream, MidiFile &midiFile);
		virtual void write(std::ostream &stream, MidiFile &midiFile, int lastTick);
		virtual int getStatus(void);
		virtual int getStatusNybble(void);
		virtual int getChannelNybble(void);
		virtual int getKey(void);
		virtual int getVelocity(void);
		virtual int getMetaType(void);
		virtual unsigned char getMetaData(int i);
		virtual size_t getMetaSize(void);
		virtual unsigned char read(std::istream &stream);
		virtual bool isChannelVoiceMessage();
		virtual bool isNoteOn(void);
		virtual bool isNoteOff(void);
		virtual bool isMatchingNoteOff(MidiEvent &offEvent);
		friend bool operator < (const MidiEvent &a, MidiEvent &b);
	};

	class MidiTrack : public Chunk, public std::vector<MidiEvent>
	{
	public:
		MidiTrack(void);
		virtual ~MidiTrack(void);
		virtual void read(std::istream &stream, MidiFile &midiFile);
		virtual void write(std::ostream &stream, MidiFile &midiFile);
		virtual void sort(void);
	};

	class TempoMap : public std::map<int, double>
	{
	public:
		double getCurrentSecondsPerTick(int tick);
	};

	/**
	* Reads and writes format 0 and format 1 standard MIDI files.
	*/
	class MidiFile
	{
	public:
		typedef enum {
			CHANNEL_NOTE_OFF = 0x80,
			CHANNEL_NOTE_ON = 0x90,
			CHANNEL_KEY_PRESSURE = 0xa0,
			CHANNEL_CONTROL_CHANGE = 0xb0,
			CHANNEL_PROGRAM_CHANGE = 0xc0,
			CHANNEL_AFTER_TOUCH = 0xd0,
			CHANNEL_PITCH_BEND = 0xe0,
			SYSTEM_EXCLUSIVE = 0xf0,
			SYSTEM_MIDI_TIME_CODE = 0xf1,
			SYSTEM_SONG_POSITION_POINTER = 0xf2,
			SYSTEM_SONG_SELECT = 0xf3,
			SYSTEM_TUNE_REQUEST = 0xf6,
			SYSTEM_END_OF_EXCLUSIVE = 0xf7,
			SYSTEM_TIMING_CLOCK = 0xf8,
			SYSTEM_START = 0xfa,
			SYSTEM_CONTINUE = 0xfb,
			SYSTEM_STOP = 0xfc,
			SYSTEM_ACTIVE_SENSING = 0xfe,
			META_EVENT = 0xff,
		} MidiEventTypes;
		typedef enum {
			META_SEQUENCE_NUMBER = 0x00,
			META_TEXT_EVENT = 0x01,
			META_COPYRIGHT_NOTICE = 0x02,
			META_SEQUENCE_NAME = 0x03,
			META_INSTRUMENT_NAME = 0x04,
			META_LYRIC = 0x05,
			META_MARKER = 0x06,
			META_CUE_POINT = 0x07,
			META_CHANNEL_PREFIX = 0x20,
			META_END_OF_TRACK = 0x2f,
			META_SET_TEMPO = 0x51,
			META_SMPTE_OFFSET = 0x54,
			META_TIME_SIGNATURE = 0x58,
			META_KEY_SIGNATURE = 0x59,
			META_SEQUENCER_SPECIFIC = 0x74,
		} MetaEventTypes;
		typedef enum {
			CONTROLLER_MOD_WHEEL = 1,
			CONTROLLER_BREATH = 2,
			CONTROLLER_FOOT = 4,
			CONTROLLER_BALANCE = 8,
			CONTROLLER_PAN = 10,
			CONTROLLER_EXPRESSION = 11,
			/* 7 bit controllers */
			CONTROLLER_DAMPER_PEDAL = 0x40,
			CONTROLLER_PORTAMENTO = 0x41,
			CONTROLLER_SOSTENUTO = 0x42,
			CONTROLLER_SOFT_PEDAL = 0x43,
			CONTROLLER_GENERAL_4 = 0x44,
			CONTROLLER_HOLD_2 = 0x45,
			CONTROLLER_7GENERAL_5 = 0x50,
			CONTROLLER_GENERAL_6 = 0x51,
			CONTROLLER_GENERAL_7 = 0x52,
			CONTROLLER_GENERAL_8 = 0x53,
			CONTROLLER_TREMOLO_DEPTH = 0x5c,
			CONTROLLER_CHORUS_DEPTH = 0x5d,
			CONTROLLER_DETUNE = 0x5e,
			CONTROLLER_PHASER_DEPTH = 0x5f,
			/* parameter values */
			CONTROLLER_DATA_INC = 0x60,
			CONTROLLER_DATA_DEC = 0x61,
			/* parameter selection */
			CONTROLLER_NON_REG_LSB = 0x62,
			CONTROLLER_NON_REG_MSB = 0x63,
			CONTROLLER_REG_LSB = 0x64,
			CONTROLLER_REG_MSG = 0x65,
			CONTROLLER_CONTINUOUS_AFTERTOUCH = 128,
		} MidiControllers;
		static int readVariableLength(std::istream &stream);
		static void writeVariableLength(std::ostream &stream, int value);
		static int toInt(int c1, int c2, int c3, int c4);
		static short toShort(int c1, int c2);
		static int readInt(std::istream &stream);
		static void writeInt(std::ostream &stream, int value);
		static short readShort(std::istream &stream);
		static void writeShort(std::ostream &stream, short value);
		static int chunkName(int a, int b, int c, int d);
		void computeTimes(void);
		int currentTick;
		double currentTime;
		double currentSecondsPerTick;
		double microsecondsPerQuarterNote;
		unsigned char lastStatus;
		MidiHeader midiHeader;
		TempoMap tempoMap;
		std::vector<MidiTrack> midiTracks;
		MidiFile(void);
		virtual ~MidiFile(void);
		virtual void clear(void);
		virtual void read(std::istream &stream);
		virtual void write(std::ostream &stream);
		virtual void load(std::string filename);
		virtual void save(std::string filename);
		virtual void dump(std::ostream &stream);
		virtual void sort(void);
	};

	bool operator < (const MidiEvent &a, MidiEvent &b);
}
#endif
<|endoftext|>


<commit_before>#include "SimObservable.h"
#include "SimObserver.h"
#include "json/json.h"
#include "schema.h"
#include "../Validator/ObjectRequirement.h"
#include "../Validator/ArrayRequirement.h"
#include "SimException.h"
#include "../Observers/DLMFileObserver.h"
#include "../Observers/JSONObserver.h"
#include "../Observers/XYZObserver.h"

using namespace Json;

namespace SAPHRON
{
	// Initialized SimFlags based on (pre-validated) JSON.
	SimFlags InitFlags(const Value& json)
	{
		SimFlags flags;

		flags.iteration = json.get("iteration", 0).asUInt();
		flags.move_acceptances = json.get("move_acceptances", 0).asUInt();
		flags.dos_factor = json.get("dos_factor", 0).asUInt();
		flags.dos_flatness = json.get("dos_flatness", 0).asUInt();
		flags.world_pressure = json.get("world_pressure", 0).asUInt();
		flags.world_volume = json.get("world_volume", 0).asUInt();
		flags.world_density = json.get("world_density", 0).asUInt();
		flags.world_temperature = json.get("world_temperature", 0).asUInt();
		flags.world_composition = json.get("world_composition", 0).asUInt();
		flags.world_energy = json.get("world_energy", 0).asUInt();
		flags.world_chem_pot = json.get("world_chem_pot", 0).asUInt();
		flags.eintervdw = json.get("energy_intervdw", 0).asUInt();
		flags.eintravdw = json.get("energy_intravdw", 0).asUInt();
		flags.einterelect = json.get("energy_interelect", 0).asUInt();
		flags.eintraelect = json.get("energy_intraelect", 0).asUInt();
		flags.ebonded = json.get("energy_bonded", 0).asUInt();
		flags.econnectivity = json.get("energy_connectivity", 0).asUInt();
		flags.pideal = json.get("pressure_ideal", 0).asUInt();
		flags.pxx = json.get("pressure_pxx", 0).asUInt();
		flags.pxy = json.get("pressure_pxy", 0).asUInt();
		flags.pxz = json.get("pressure_pxz", 0).asUInt();
		flags.pyy = json.get("pressure_pyy", 0).asUInt();
		flags.pyz = json.get("pressure_pyz", 0).asUInt();
		flags.pzz = json.get("pressure_pzz", 0).asUInt();
		flags.ptail = json.get("pressure_tail", 0).asUInt();
		flags.hist_interval = json.get("hist_interval", 0).asUInt();
		flags.hist_bin_count = json.get("hist_bin_count", 0).asUInt();
		flags.hist_lower_outliers = json.get("hist_lower_outliers", 0).asUInt();
		flags.hist_upper_outliers = json.get("hist_upper_outliers", 0).asUInt();
		flags.hist_values = json.get("hist_values", 0).asUInt();
		flags.hist_counts = json.get("hist_counts", 0).asUInt();
		flags.particle_id = json.get("particle_id", 0).asUInt();
		flags.particle_species = json.get("particle_species", 0).asUInt();
		flags.particle_parent_id = json.get("particle_parent_id", 0).asUInt();
		flags.particle_parent_species = json.get("particle_parent_species", 0).asUInt();
		flags.particle_position = json.get("particle_position", 0).asUInt();
		flags.particle_director = json.get("particle_director", 0).asUInt();
		flags.particle_neighbors = json.get("particles_neighbors", 0).asUInt();

		// Masks.
		int simulation = json.get("simulation", 0).asInt();
		int world = json.get("world", 0).asInt();
		int energy_components = json.get("energy_components", 0).asInt();
		int pressure_tensor = json.get("pressure_tensor", 0).asInt();
		int histogram = json.get("histogram", 0).asInt();
		int particle = json.get("particle", 0).asInt();

		if(simulation)
			flags.simulation_on();
		if(world)
			flags.world_on();
		if(energy_components)
			flags.energy_on();
		if(pressure_tensor)
			flags.pressure_on();
		if(histogram)
			flags.histogram_on();
		if(particle)
			flags.particle_on();

		return flags;
	}

	void SimObserver::Update(const SimEvent& e)
	{
		// Only lock and proceed if we have to.
		if(e.GetIteration() % _frequency == 0 || e.ForceObserve())
		{
			_mutex.lock();
			_event = e;
			PreVisit();
			_event.GetObservable()->AcceptVisitor(*this);
			PostVisit();
			_mutex.unlock();
		}
	};

	SimObserver* SimObserver::BuildObserver(const Value &json)
	{
		return BuildObserver(json, "#/observers");
	}
	SimObserver* SimObserver::BuildObserver(const Value &json, const std::string& path)
	{
		ObjectRequirement validator;
		Value schema;
		Reader reader;

		SimObserver* obs = nullptr;

		auto type = json.get("type", "none").asString();

		if(type == "DLMFile")
		{
			reader.parse(JsonSchema::DLMFileObserver, schema);
			validator.Parse(schema, path);

			// Validate inputs.
			validator.Validate(json, path);
			if(validator.HasErrors())
				throw BuildException(validator.GetErrors());

			// Initialize flags.
			SimFlags flags = InitFlags(json["flags"]);

			// Initialize DLM specific options.
			auto prefix = json.get("prefix", "unnamed").asString();
			auto frequency = json.get("frequency", 1).asInt();
			auto colwidth = json.get("colwidth", 15).asInt();
			auto fixedw = json.get("fixedwmode", true).asBool();
			auto delimiter = json.get("delimiter", " ").asString();
			auto extension = json.get("extension", ".dat").asString();

			auto* dlm = new DLMFileObserver(prefix, flags, frequency);
			dlm->SetWidth(colwidth);
			dlm->SetFixedWidthMode(fixedw);
			dlm->SetDelimiter(delimiter);
			dlm->SetExtension(extension);
			obs = static_cast<SimObserver*>(dlm);
		}
		else if(type == "JSON")
		{
			reader.parse(JsonSchema::JSONObserver, schema);
			validator.Parse(schema, path);

			// Validate inputs.
			validator.Validate(json, path);
			if(validator.HasErrors())
				throw BuildException(validator.GetErrors());

			// Initialize flags.
			SimFlags flags;

			// Initialize JSON specific options.
			auto prefix = json.get("prefix", "unnamed").asString();
			auto frequency = json.get("frequency", 1).asInt();

			auto* dlm = new JSONObserver(prefix, flags, frequency);
			obs = static_cast<SimObserver*>(dlm);
		}
		else if(type == "XYZ")
		{
			reader.parse(JsonSchema::XYZObserver, schema);
			validator.Parse(schema, path);

			// Validate inputs.
			if(validator.HasErrors())
				throw BuildException(validator.GetErrors());

			// Initialize flags.
			SimFlags flags;

			// Initialize JSON specific options.
			auto prefix = json.get("prefix", "unnamed").asString();
			auto frequency = json.get("frequency", 1).asInt();

			auto* dlm = new XYZObserver(prefix, flags, frequency);
			obs = static_cast<SimObserver*>(dlm);
		}
		else
		{
			throw BuildException({path + ": Unknown observer type specified."});
		}

		return obs;
	}

	void SimObserver::BuildObservers(const Json::Value &json, ObserverList &ol)
	{
		ArrayRequirement validator;
		Value schema;
		Reader reader;

		reader.parse(JsonSchema::Observers, schema);
		validator.Parse(schema, "#/observers");

		// Validate high level schema.
		validator.Validate(json, "#/observers");
		if(validator.HasErrors())
			throw BuildException(validator.GetErrors());

		// Loop through observers.
		int i = 0;
		for(auto& obs : json)
		{
			ol.push_back(BuildObserver(obs, "#/observers/" + std::to_string(i)));
			++i;
		}
	}
}
<commit_msg>Minor adjustments to flags in SimObserver<commit_after>#include "SimObservable.h"
#include "SimObserver.h"
#include "json/json.h"
#include "schema.h"
#include "../Validator/ObjectRequirement.h"
#include "../Validator/ArrayRequirement.h"
#include "SimException.h"
#include "../Observers/DLMFileObserver.h"
#include "../Observers/JSONObserver.h"
#include "../Observers/XYZObserver.h"

using namespace Json;

namespace SAPHRON
{
	// Initialized SimFlags based on (pre-validated) JSON.
	SimFlags InitFlags(const Value& json)
	{
		SimFlags flags;

		flags.iteration = json.get("iteration", 0).asUInt();
		flags.move_acceptances = json.get("move_acceptances", 0).asUInt();
		flags.dos_factor = json.get("dos_factor", 0).asUInt();
		flags.dos_flatness = json.get("dos_flatness", 0).asUInt();
		flags.world_pressure = json.get("world_pressure", 0).asUInt();
		flags.world_volume = json.get("world_volume", 0).asUInt();
		flags.world_density = json.get("world_density", 0).asUInt();
		flags.world_temperature = json.get("world_temperature", 0).asUInt();
		flags.world_composition = json.get("world_composition", 0).asUInt();
		flags.world_energy = json.get("world_energy", 0).asUInt();
		flags.world_chem_pot = json.get("world_chem_pot", 0).asUInt();
		flags.eintervdw = json.get("energy_intervdw", 0).asUInt();
		flags.eintravdw = json.get("energy_intravdw", 0).asUInt();
		flags.einterelect = json.get("energy_interelect", 0).asUInt();
		flags.eintraelect = json.get("energy_intraelect", 0).asUInt();
		flags.ebonded = json.get("energy_bonded", 0).asUInt();
		flags.econnectivity = json.get("energy_connectivity", 0).asUInt();
		flags.pideal = json.get("pressure_ideal", 0).asUInt();
		flags.pxx = json.get("pressure_pxx", 0).asUInt();
		flags.pxy = json.get("pressure_pxy", 0).asUInt();
		flags.pxz = json.get("pressure_pxz", 0).asUInt();
		flags.pyy = json.get("pressure_pyy", 0).asUInt();
		flags.pyz = json.get("pressure_pyz", 0).asUInt();
		flags.pzz = json.get("pressure_pzz", 0).asUInt();
		flags.ptail = json.get("pressure_tail", 0).asUInt();
		flags.hist_interval = json.get("hist_interval", 0).asUInt();
		flags.hist_bin_count = json.get("hist_bin_count", 0).asUInt();
		flags.hist_lower_outliers = json.get("hist_lower_outliers", 0).asUInt();
		flags.hist_upper_outliers = json.get("hist_upper_outliers", 0).asUInt();
		flags.hist_values = json.get("hist_values", 0).asUInt();
		flags.hist_counts = json.get("hist_counts", 0).asUInt();
		flags.particle_id = json.get("particle_id", 0).asUInt();
		flags.particle_species = json.get("particle_species", 0).asUInt();
		flags.particle_parent_id = json.get("particle_parent_id", 0).asUInt();
		flags.particle_parent_species = json.get("particle_parent_species", 0).asUInt();
		flags.particle_position = json.get("particle_position", 0).asUInt();
		flags.particle_director = json.get("particle_director", 0).asUInt();
		flags.particle_charge = json.get("particle_charge", 0).asUInt();

		// Masks.
		int simulation = json.get("simulation", 0).asInt();
		int world = json.get("world", 0).asInt();
		int energy_components = json.get("energy_components", 0).asInt();
		int pressure_tensor = json.get("pressure_tensor", 0).asInt();
		int histogram = json.get("histogram", 0).asInt();
		int particle = json.get("particle", 0).asInt();

		if(simulation)
			flags.simulation_on();
		if(world)
			flags.world_on();
		if(energy_components)
			flags.energy_on();
		if(pressure_tensor)
			flags.pressure_on();
		if(histogram)
			flags.histogram_on();
		if(particle)
			flags.particle_on();

		flags.particle_neighbors = json.get("particles_neighbors", 0).asUInt();

		return flags;
	}

	void SimObserver::Update(const SimEvent& e)
	{
		// Only lock and proceed if we have to.
		if(e.GetIteration() % _frequency == 0 || e.ForceObserve())
		{
			_mutex.lock();
			_event = e;
			PreVisit();
			_event.GetObservable()->AcceptVisitor(*this);
			PostVisit();
			_mutex.unlock();
		}
	};

	SimObserver* SimObserver::BuildObserver(const Value &json)
	{
		return BuildObserver(json, "#/observers");
	}
	SimObserver* SimObserver::BuildObserver(const Value &json, const std::string& path)
	{
		ObjectRequirement validator;
		Value schema;
		Reader reader;

		SimObserver* obs = nullptr;

		auto type = json.get("type", "none").asString();

		if(type == "DLMFile")
		{
			reader.parse(JsonSchema::DLMFileObserver, schema);
			validator.Parse(schema, path);

			// Validate inputs.
			validator.Validate(json, path);
			if(validator.HasErrors())
				throw BuildException(validator.GetErrors());

			// Initialize flags.
			SimFlags flags = InitFlags(json["flags"]);

			// Initialize DLM specific options.
			auto prefix = json.get("prefix", "unnamed").asString();
			auto frequency = json.get("frequency", 1).asInt();
			auto colwidth = json.get("colwidth", 15).asInt();
			auto fixedw = json.get("fixedwmode", true).asBool();
			auto delimiter = json.get("delimiter", " ").asString();
			auto extension = json.get("extension", ".dat").asString();

			auto* dlm = new DLMFileObserver(prefix, flags, frequency);
			dlm->SetWidth(colwidth);
			dlm->SetFixedWidthMode(fixedw);
			dlm->SetDelimiter(delimiter);
			dlm->SetExtension(extension);
			obs = static_cast<SimObserver*>(dlm);
		}
		else if(type == "JSON")
		{
			reader.parse(JsonSchema::JSONObserver, schema);
			validator.Parse(schema, path);

			// Validate inputs.
			validator.Validate(json, path);
			if(validator.HasErrors())
				throw BuildException(validator.GetErrors());

			// Initialize flags.
			SimFlags flags;

			// Initialize JSON specific options.
			auto prefix = json.get("prefix", "unnamed").asString();
			auto frequency = json.get("frequency", 1).asInt();

			auto* dlm = new JSONObserver(prefix, flags, frequency);
			obs = static_cast<SimObserver*>(dlm);
		}
		else if(type == "XYZ")
		{
			reader.parse(JsonSchema::XYZObserver, schema);
			validator.Parse(schema, path);

			// Validate inputs.
			if(validator.HasErrors())
				throw BuildException(validator.GetErrors());

			// Initialize flags.
			SimFlags flags;

			// Initialize JSON specific options.
			auto prefix = json.get("prefix", "unnamed").asString();
			auto frequency = json.get("frequency", 1).asInt();

			auto* dlm = new XYZObserver(prefix, flags, frequency);
			obs = static_cast<SimObserver*>(dlm);
		}
		else
		{
			throw BuildException({path + ": Unknown observer type specified."});
		}

		return obs;
	}

	void SimObserver::BuildObservers(const Json::Value &json, ObserverList &ol)
	{
		ArrayRequirement validator;
		Value schema;
		Reader reader;

		reader.parse(JsonSchema::Observers, schema);
		validator.Parse(schema, "#/observers");

		// Validate high level schema.
		validator.Validate(json, "#/observers");
		if(validator.HasErrors())
			throw BuildException(validator.GetErrors());

		// Loop through observers.
		int i = 0;
		for(auto& obs : json)
		{
			ol.push_back(BuildObserver(obs, "#/observers/" + std::to_string(i)));
			++i;
		}
	}
}
<|endoftext|>


<commit_before>// Copyright (c) 2010-2022, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.

#ifndef MFEM_LIBCEED_INTERFACE
#define MFEM_LIBCEED_INTERFACE

// Object wrapping a CeedOperator in a mfem::Operator.
#include "operator.hpp"
// Functions to initialize CeedBasis objects.
#include "basis.hpp"
// Functions to initialize CeedRestriction objects.
#include "restriction.hpp"
// Functions to initialize coefficients.
#include "coefficient.hpp"
// PA or MF Operator using libCEED.
#include "integrator.hpp"
// Utility functions
#include "util.hpp"
// Wrapper to include <ceed.h>
#include "ceed.hpp"

namespace mfem
{

namespace ceed
{

} // namespace ceed

} // namespace mfem

#endif // MFEM_LIBCEED_INTERFACE
<commit_msg>Remove unused namespace.<commit_after>// Copyright (c) 2010-2022, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.

#ifndef MFEM_LIBCEED_INTERFACE
#define MFEM_LIBCEED_INTERFACE

// Object wrapping a CeedOperator in a mfem::Operator.
#include "operator.hpp"
// Functions to initialize CeedBasis objects.
#include "basis.hpp"
// Functions to initialize CeedRestriction objects.
#include "restriction.hpp"
// Functions to initialize coefficients.
#include "coefficient.hpp"
// PA or MF Operator using libCEED.
#include "integrator.hpp"
// Utility functions
#include "util.hpp"
// Wrapper to include <ceed.h>
#include "ceed.hpp"

#endif // MFEM_LIBCEED_INTERFACE
<|endoftext|>


<commit_before>#include "tangram_bam.h"
#include <stdio.h>
#include <limits.h>
#include <getopt.h>

#include <vector>
#include <string>
#include <iostream>

#include "api/BamReader.h"
#include "api/BamWriter.h"
#include "../OutSources/fasta/Fasta.h"
#include "../OutSources/stripedSW/ssw_cpp.h"

using namespace std;

void ShowHelp() {
  fprintf(stderr, "Usage: tangram_bam <in_bam> <ref_fa> <out_bam>\n\n");
  fprintf(stderr, "tangram_bam will generate ZA tags for bams");
  fprintf(stderr, " that are not generated by MOSAIK.\n");

  fprintf(stderr, "<ref_fa> is a fasta file containing insertion sequences\n");
  fprintf(stderr, " that we are going to detect them.\n");
}

bool OpenBams(
    const string& infilename,
    const string& outfilename,
    const string& command_line,
    BamTools::BamReader* reader,
    BamTools::BamWriter* writer) {

  reader->Open(infilename);
  if (!reader->IsOpen()) {
    fprintf(stderr, "ERROR: The bam file, %s, cannot be open\n", infilename.c_str());
    return false;
  }

  // Load header and ref
  string header = reader->GetHeaderText();
  size_t pos1 = header.find("SO:");
  if (pos1 != string::npos) {
    size_t pos2 = header.find("SO:queryname");
    if (pos2 != string::npos) header.replace(pos2, 12, "SO:unsorted");
    pos2 = header.find("SO:coordinate");
    if (pos2 != string::npos) header.replace(pos2, 13, "SO:unsorted");
  }
  header += "@PG\tID:tangram_bam\tCL:";
  header += (command_line + '\n');
  BamTools::RefVector ref = reader->GetReferenceData();

  if (!writer->Open(outfilename, header, ref)) {
    fprintf(stderr, "ERROR: The bam file, %s, cannot be open\n", outfilename.c_str());
    reader->Close();
    return false;
  }

  return true;
}

inline bool LoadReference(const char* fa, FastaReference* fasta) {
  string filename = fa;
  fasta->open(filename);

  return true;
}

bool ConcatenateSpecialReference(
    FastaReference* fasta,
    SpecialReference* s_ref) {
  int total_len = 0;
  for (vector<string>::const_iterator ite = fasta->index->sequenceNames.begin();
       ite != fasta->index->sequenceNames.end(); ++ite) {
    s_ref->concatnated += fasta->getSequence(*ite).c_str();
    s_ref->ref_lens.push_back(fasta->sequenceLength(*ite));
    s_ref->ref_names.push_back(*ite);
    total_len += fasta->sequenceLength(*ite);
  }

  s_ref->concatnated_len = total_len;

  return true;
}

void GetReverseComplement(const string& query, string* reverse) {
  reverse->clear();

  for (string::const_reverse_iterator ite = query.rbegin(); ite != query.rend(); ++ite) {
    switch(*ite) {
      case 'A': *reverse += 'T'; break;
      case 'C': *reverse += 'G'; break;
      case 'G': *reverse += 'C'; break;
      case 'T': *reverse += 'A'; break;
      default: *reverse += 'N';
    }
  }
}

void Align(
    const string& query,
    const StripedSmithWaterman::Aligner& aligner,
    StripedSmithWaterman::Alignment* alignment) {

    alignment->Clear();
    aligner.Align(query.c_str(), kFilter, alignment);
}

void GetZa(const Alignment& al, const Alignment& mate, string* za) {
  const bool mate1 = al.bam_alignment.IsFirstMate();
  Alignment const *mate1_ptr, *mate2_ptr;

  if (mate1) {
    *za = "<@;";
    mate1_ptr = &al;
    mate2_ptr = &mate;
  } else {
    *za = "<&;";
    mate1_ptr = &mate;
    mate2_ptr = &al;
  }

  *za += (std::to_string(mate1_ptr->bam_alignment.MapQuality) + ";;"
          + (mate1_ptr->hit_insertion ? mate1_ptr->ins_prefix : "")
	  + ";1;");

  if (mate1) {
    *za += ";><&;";
  } else {
    *za += ";><@;";
  }

  *za += (std::to_string(mate2_ptr->bam_alignment.MapQuality) + ";;"
          + (mate2_ptr->hit_insertion ? mate2_ptr->ins_prefix : "")
	  + ";1;;>");

}

void WriteAlignment(
    const bool& add_za,
    const Alignment& mate,
    Alignment* al,
    BamTools::BamWriter* writer) {

  if (add_za) {
    string za;
    GetZa(*al, mate, &za);
    al->bam_alignment.AddTag("ZA","Z",za);
  }

  writer->SaveAlignment(al->bam_alignment);
}

void WriteAlignment(const bool& add_za,
                    map<string, Alignment>* al_map_ite,
                    BamTools::BamWriter* writer) {

  for (map<string, Alignment>::iterator ite = al_map_ite->begin();
       ite != al_map_ite->end(); ++ite) {
    Alignment* al = &(ite->second);
    if (add_za) {
      string za;
      if (al->bam_alignment.IsPaired()) { // paired-end read
        if (al->bam_alignment.IsFirstMate()) {
          za = "<@;" + std::to_string(al->bam_alignment.MapQuality) + ";;"
               + (al->hit_insertion ? al->ins_prefix : "") + ";1;;>"
	       + "<&;0;;;0;;>";
        } else {
          za = "<&;0;;;0;;><@;" + std::to_string(al->bam_alignment.MapQuality) + ";;"
               + (al->hit_insertion ? al->ins_prefix : "") + ";1;;>";
        }
      } else { // sinle-end read
        za = "<@;" + std::to_string(al->bam_alignment.MapQuality) + ";;"
             + (al->hit_insertion ? al->ins_prefix : "") + ";1;;>";
      }

      al->bam_alignment.AddTag("ZA","Z",za);
    }

    writer->SaveAlignment(al->bam_alignment);
  }
}

// Return true if an alignment contains too many soft clips
inline bool IsTooManyClips (const BamTools::BamAlignment& al) {
  if (al.CigarData.empty()) return true;

  int clip = 0;
  if ((al.CigarData.begin())->Type == 'S') clip += (al.CigarData.begin())->Length;
  if ((al.CigarData.rbegin())->Type == 'S') clip += (al.CigarData.rbegin())->Length;

  if (clip > (al.Length * kSoftClipRate)) return true;
  else return false;
}

inline void MarkAsUnmapped (BamTools::BamAlignment* al, BamTools::BamAlignment* mate) {
  const bool al_unmapped   = IsTooManyClips(*al);
  const bool mate_unmapped = IsTooManyClips(*mate);

  if (!al_unmapped && !mate_unmapped) {
    // nothing
  } else {
    al->SetIsMapped(!al_unmapped);
    mate->SetIsMapped(!mate_unmapped);
    al->SetIsMateMapped(!mate_unmapped);
    mate->SetIsMateMapped(!al_unmapped);
  }
}

void StoreAlignment(
    const bool& add_za,
    Alignment* al,
    map<string, Alignment> *al_map_cur,
    map<string, Alignment> *al_map_pre,
    BamTools::BamWriter* writer) {
  // Clear up the buffers once the al_map_cur buffer is full
  // 1. Clear up al_map_pre
  // 2. move al_map_cur to al_map_pre
  if ((static_cast<int>(al_map_cur->size()) > kAlignmentMapSize)) {
    WriteAlignment(add_za, al_map_pre, writer);
    al_map_pre->clear();
    map<string, Alignment> *tmp = al_map_pre;
    al_map_pre = al_map_cur;
    al_map_cur = tmp;
  }

  map<string, Alignment>::iterator ite_cur = al_map_cur->find(al->bam_alignment.Name);
  if (ite_cur == al_map_cur->end()) {
    if (!al_map_pre) {
      map<string, Alignment>::iterator ite_pre = al_map_pre->find(al->bam_alignment.Name);
      if (ite_pre == al_map_pre->end()) { // al is not found in cur or pre either
        (*al_map_cur)[al->bam_alignment.Name] = *al;
      } else { // find the mate in al_map_pre
        MarkAsUnmapped(&(al->bam_alignment), &(ite_pre->second.bam_alignment));
	WriteAlignment(add_za, ite_pre->second, al, writer);
        WriteAlignment(add_za, *al, &(ite_pre->second), writer);
        al_map_pre->erase(ite_pre);
      }
    } else { // al is not found in cur and pre is NULL
      (*al_map_cur)[al->bam_alignment.Name] = *al;
    }
  } else { // find the mate in al_map_cur
    MarkAsUnmapped(&(al->bam_alignment), &(ite_cur->second.bam_alignment));
    WriteAlignment(add_za, ite_cur->second, al, writer);
    WriteAlignment(add_za, *al, &(ite_cur->second), writer);
    al_map_cur->erase(ite_cur);
  }

}

bool ParseArguments(const int argc, char* const * argv, Param* param) {
  if (argc == 1) { // no argument
    ShowHelp();
    return false;
  }

  // record command line
  param->command_line = argv[0];
  for ( int i = 1; i < argc; ++i ) {
    param->command_line += " ";
    param->command_line += argv[i];
  }

  const char *short_option = "hi:o:r:z";
  const struct option long_option[] = {
    {"help", no_argument, NULL, 'h'},
    {"input", required_argument, NULL, 'i'},
    {"output", required_argument, NULL, 'o'},
    {"ref", required_argument, NULL, 'r'},
    {"no-za-add", no_argument, NULL, 'z'},

    {0, 0, 0, 0}
  };

  int c = 0;
  bool show_help = false;
  while (true) {
    int option_index = 0;
    c = getopt_long(argc, argv, short_option, long_option, &option_index);

    if (c == -1) // end of options
      break;

    switch (c) {
      case 'h': show_help = true; break;
      case 'i': param->in_bam = optarg; break;
      case 'o': param->out_bam = optarg; break;
      case 'r': param->ref_fasta = optarg; break;
      case 'z': param->za_add = false; break;
    }
  }

  if (show_help || param->in_bam.empty()
   || param->out_bam.empty() || param->ref_fasta.empty()) {
    ShowHelp();
    return false;
  }

  return true;
}

int PickBestAlignment(const int& request_score,
                      const StripedSmithWaterman::Alignment& alignment,
		      const SpecialReference& s_ref) {
  if (alignment.sw_score < request_score) {
    return -1; // no proper alignment is found
  } else {
    int accu_len = 0;
    for (unsigned int i = 0; i < s_ref.ref_lens.size(); ++i) {
      accu_len += s_ref.ref_lens[i];
      if (alignment.ref_begin < accu_len) {
        if (alignment.ref_end < accu_len) return i;
	else return -1;
      }
    }
  }

  return -1;
}

int main(int argc, char** argv) {
  Param param;

  if (!ParseArguments(argc, argv, &param)) return 1;

  // Open input bam
  string infilename = param.in_bam;
  string outfilename = param.out_bam;
  BamTools::BamReader reader;
  BamTools::BamWriter writer;
  if (!OpenBams(infilename, outfilename, param.command_line, &reader, &writer)) return 1;

  // Open fasta
  FastaReference fasta;
  LoadReference(param.ref_fasta.c_str(), &fasta);

  // Build SSW aligners for every reference in fasta
  SpecialReference s_ref;
  ConcatenateSpecialReference(&fasta, &s_ref);

  // Build SSW aligner
  StripedSmithWaterman::Aligner aligner;
  aligner.SetReferenceSequence(s_ref.concatnated.c_str(), s_ref.concatnated_len);

  // CORE ALGORITHM
  BamTools::BamAlignment bam_alignment;
  map<string, Alignment> al_map1, al_map2;
  map<string, Alignment> *al_map_cur = &al_map1, *al_map_pre = &al_map2;
  StripedSmithWaterman::Alignment alignment;
  Alignment al;
  while (reader.GetNextAlignment(bam_alignment)) {
    int index = -1;
    if (param.za_add) {
      Align(bam_alignment.QueryBases, aligner, &alignment);
      index = PickBestAlignment(bam_alignment.Length, alignment, s_ref);
      if (index == -1) { // try the reverse complement sequences
        string reverse;
        GetReverseComplement(bam_alignment.QueryBases, &reverse);
        Align(reverse, aligner, &alignment);
        index = PickBestAlignment(bam_alignment.Length, alignment, s_ref);
      }
    }
    al.Clear();
    al.bam_alignment = bam_alignment;
    al.hit_insertion = (index == -1) ? false: true;
    al.ins_prefix    = (index == -1) ? "" : s_ref.ref_names[index].substr(8,2);
    StoreAlignment(param.za_add, &al, al_map_cur, al_map_pre, &writer);
  }

  // Close
  WriteAlignment(param.za_add, &al_map1, &writer);
  WriteAlignment(param.za_add, &al_map2, &writer);
  al_map1.clear();
  al_map2.clear();
  reader.Close();
  writer.Close();
}
<commit_msg>Shrink tangram_bam pool; decrease the number of reads for SSW<commit_after>#include "tangram_bam.h"
#include <stdio.h>
#include <limits.h>
#include <getopt.h>

#include <vector>
#include <string>
#include <iostream>

#include "api/BamReader.h"
#include "api/BamWriter.h"
#include "../OutSources/fasta/Fasta.h"
#include "../OutSources/stripedSW/ssw_cpp.h"

using namespace std;

void ShowHelp() {
  fprintf(stderr, "Usage: tangram_bam <in_bam> <ref_fa> <out_bam>\n\n");
  fprintf(stderr, "tangram_bam will generate ZA tags for bams");
  fprintf(stderr, " that are not generated by MOSAIK.\n");

  fprintf(stderr, "<ref_fa> is a fasta file containing insertion sequences\n");
  fprintf(stderr, " that we are going to detect them.\n");
}

bool OpenBams(
    const string& infilename,
    const string& outfilename,
    const string& command_line,
    BamTools::BamReader* reader,
    BamTools::BamWriter* writer) {

  reader->Open(infilename);
  if (!reader->IsOpen()) {
    fprintf(stderr, "ERROR: The bam file, %s, cannot be open\n", infilename.c_str());
    return false;
  }

  // Load header and ref
  string header = reader->GetHeaderText();
  size_t pos1 = header.find("SO:");
  if (pos1 != string::npos) {
    size_t pos2 = header.find("SO:queryname");
    if (pos2 != string::npos) header.replace(pos2, 12, "SO:unsorted");
    pos2 = header.find("SO:coordinate");
    if (pos2 != string::npos) header.replace(pos2, 13, "SO:unsorted");
  }
  header += "@PG\tID:tangram_bam\tCL:";
  header += (command_line + '\n');
  BamTools::RefVector ref = reader->GetReferenceData();

  if (!writer->Open(outfilename, header, ref)) {
    fprintf(stderr, "ERROR: The bam file, %s, cannot be open\n", outfilename.c_str());
    reader->Close();
    return false;
  }

  return true;
}

inline bool LoadReference(const char* fa, FastaReference* fasta) {
  string filename = fa;
  fasta->open(filename);

  return true;
}

bool ConcatenateSpecialReference(
    FastaReference* fasta,
    SpecialReference* s_ref) {
  int total_len = 0;
  for (vector<string>::const_iterator ite = fasta->index->sequenceNames.begin();
       ite != fasta->index->sequenceNames.end(); ++ite) {
    s_ref->concatnated += fasta->getSequence(*ite).c_str();
    s_ref->ref_lens.push_back(fasta->sequenceLength(*ite));
    s_ref->ref_names.push_back(*ite);
    total_len += fasta->sequenceLength(*ite);
  }

  s_ref->concatnated_len = total_len;

  return true;
}

void GetReverseComplement(const string& query, string* reverse) {
  reverse->clear();

  for (string::const_reverse_iterator ite = query.rbegin(); ite != query.rend(); ++ite) {
    switch(*ite) {
      case 'A': *reverse += 'T'; break;
      case 'C': *reverse += 'G'; break;
      case 'G': *reverse += 'C'; break;
      case 'T': *reverse += 'A'; break;
      default: *reverse += 'N';
    }
  }
}

void Align(
    const string& query,
    const StripedSmithWaterman::Aligner& aligner,
    StripedSmithWaterman::Alignment* alignment) {

    alignment->Clear();
    aligner.Align(query.c_str(), kFilter, alignment);
}

void GetZa(const Alignment& al, const Alignment& mate, string* za) {
  const bool mate1 = al.bam_alignment.IsFirstMate();
  Alignment const *mate1_ptr, *mate2_ptr;

  if (mate1) {
    *za = "<@;";
    mate1_ptr = &al;
    mate2_ptr = &mate;
  } else {
    *za = "<&;";
    mate1_ptr = &mate;
    mate2_ptr = &al;
  }

  *za += (std::to_string(mate1_ptr->bam_alignment.MapQuality) + ";;"
          + (mate1_ptr->hit_insertion ? mate1_ptr->ins_prefix : "")
	  + ";1;");

  if (mate1) {
    *za += ";><&;";
  } else {
    *za += ";><@;";
  }

  *za += (std::to_string(mate2_ptr->bam_alignment.MapQuality) + ";;"
          + (mate2_ptr->hit_insertion ? mate2_ptr->ins_prefix : "")
	  + ";1;;>");

}

void WriteAlignment(
    const bool& add_za,
    const Alignment& mate,
    Alignment* al,
    BamTools::BamWriter* writer) {

  if (add_za) {
    string za;
    GetZa(*al, mate, &za);
    al->bam_alignment.AddTag("ZA","Z",za);
  }

  writer->SaveAlignment(al->bam_alignment);
}

void WriteAlignment(const bool& add_za,
                    map<string, Alignment>* al_map_ite,
                    BamTools::BamWriter* writer) {

  for (map<string, Alignment>::iterator ite = al_map_ite->begin();
       ite != al_map_ite->end(); ++ite) {
    Alignment* al = &(ite->second);
    if (add_za) {
      string za;
      if (al->bam_alignment.IsPaired()) { // paired-end read
        if (al->bam_alignment.IsFirstMate()) {
          za = "<@;" + std::to_string(al->bam_alignment.MapQuality) + ";;"
               + (al->hit_insertion ? al->ins_prefix : "") + ";1;;>"
	       + "<&;0;;;0;;>";
        } else {
          za = "<&;0;;;0;;><@;" + std::to_string(al->bam_alignment.MapQuality) + ";;"
               + (al->hit_insertion ? al->ins_prefix : "") + ";1;;>";
        }
      } else { // sinle-end read
        za = "<@;" + std::to_string(al->bam_alignment.MapQuality) + ";;"
             + (al->hit_insertion ? al->ins_prefix : "") + ";1;;>";
      }

      al->bam_alignment.AddTag("ZA","Z",za);
    }

    writer->SaveAlignment(al->bam_alignment);
  }
}

// Return true if an alignment contains too many soft clips
inline bool IsTooManyClips (const BamTools::BamAlignment& al) {
  if (al.CigarData.empty()) return true;

  int clip = 0;
  if ((al.CigarData.begin())->Type == 'S') clip += (al.CigarData.begin())->Length;
  if ((al.CigarData.rbegin())->Type == 'S') clip += (al.CigarData.rbegin())->Length;

  if (clip > (al.Length * kSoftClipRate)) return true;
  else return false;
}

inline void MarkAsUnmapped (BamTools::BamAlignment* al, BamTools::BamAlignment* mate) {
  const bool al_unmapped   = IsTooManyClips(*al);
  const bool mate_unmapped = IsTooManyClips(*mate);

  if (!al_unmapped && !mate_unmapped) {
    // nothing
  } else {
    al->SetIsMapped(!al_unmapped);
    mate->SetIsMapped(!mate_unmapped);
    al->SetIsMateMapped(!mate_unmapped);
    mate->SetIsMateMapped(!al_unmapped);
  }
}

void StoreAlignment(
    const bool& add_za,
    Alignment* al,
    map<string, Alignment> *al_map_cur,
    map<string, Alignment> *al_map_pre,
    BamTools::BamWriter* writer) {
  // Clear up the buffers once the al_map_cur buffer is full
  // 1. Clear up al_map_pre
  // 2. move al_map_cur to al_map_pre
  if ((static_cast<int>(al_map_cur->size()) > kAlignmentMapSize)) {
    WriteAlignment(add_za, al_map_pre, writer);
    al_map_pre->clear();
    map<string, Alignment> *tmp = al_map_pre;
    al_map_pre = al_map_cur;
    al_map_cur = tmp;
  }

  map<string, Alignment>::iterator ite_cur = al_map_cur->find(al->bam_alignment.Name);
  if (ite_cur == al_map_cur->end()) {
    if (!al_map_pre) {
      map<string, Alignment>::iterator ite_pre = al_map_pre->find(al->bam_alignment.Name);
      if (ite_pre == al_map_pre->end()) { // al is not found in cur or pre either
        (*al_map_cur)[al->bam_alignment.Name] = *al;
      } else { // find the mate in al_map_pre
        MarkAsUnmapped(&(al->bam_alignment), &(ite_pre->second.bam_alignment));
	WriteAlignment(add_za, ite_pre->second, al, writer);
        WriteAlignment(add_za, *al, &(ite_pre->second), writer);
        al_map_pre->erase(ite_pre);
      }
    } else { // al is not found in cur and pre is NULL
      (*al_map_cur)[al->bam_alignment.Name] = *al;
    }
  } else { // find the mate in al_map_cur
    MarkAsUnmapped(&(al->bam_alignment), &(ite_cur->second.bam_alignment));
    WriteAlignment(add_za, ite_cur->second, al, writer);
    WriteAlignment(add_za, *al, &(ite_cur->second), writer);
    al_map_cur->erase(ite_cur);
  }

}

bool ParseArguments(const int argc, char* const * argv, Param* param) {
  if (argc == 1) { // no argument
    ShowHelp();
    return false;
  }

  // record command line
  param->command_line = argv[0];
  for ( int i = 1; i < argc; ++i ) {
    param->command_line += " ";
    param->command_line += argv[i];
  }

  const char *short_option = "hi:o:r:z";
  const struct option long_option[] = {
    {"help", no_argument, NULL, 'h'},
    {"input", required_argument, NULL, 'i'},
    {"output", required_argument, NULL, 'o'},
    {"ref", required_argument, NULL, 'r'},
    {"no-za-add", no_argument, NULL, 'z'},

    {0, 0, 0, 0}
  };

  int c = 0;
  bool show_help = false;
  while (true) {
    int option_index = 0;
    c = getopt_long(argc, argv, short_option, long_option, &option_index);

    if (c == -1) // end of options
      break;

    switch (c) {
      case 'h': show_help = true; break;
      case 'i': param->in_bam = optarg; break;
      case 'o': param->out_bam = optarg; break;
      case 'r': param->ref_fasta = optarg; break;
      case 'z': param->za_add = false; break;
    }
  }

  if (show_help || param->in_bam.empty()
   || param->out_bam.empty() || param->ref_fasta.empty()) {
    ShowHelp();
    return false;
  }

  return true;
}

int PickBestAlignment(const int& request_score,
                      const StripedSmithWaterman::Alignment& alignment,
		      const SpecialReference& s_ref) {
  if (alignment.sw_score < request_score) {
    return -1; // no proper alignment is found
  } else {
    int accu_len = 0;
    for (unsigned int i = 0; i < s_ref.ref_lens.size(); ++i) {
      accu_len += s_ref.ref_lens[i];
      if (alignment.ref_begin < accu_len) {
        if (alignment.ref_end < accu_len) return i;
	else return -1;
      }
    }
  }

  return -1;
}

bool IsProblematicAlignment(const BamTools::BamAlignment& al) {
  if (!al.IsMapped()) return true;
  if (al.RefID != al.MateRefID) return true;
  if (al.CigarData.size() > 5) return true;
  if (IsTooManyClips(al)) return true;

  return false;
}

int main(int argc, char** argv) {
  Param param;

  if (!ParseArguments(argc, argv, &param)) return 1;

  // Open input bam
  string infilename = param.in_bam;
  string outfilename = param.out_bam;
  BamTools::BamReader reader;
  BamTools::BamWriter writer;
  if (!OpenBams(infilename, outfilename, param.command_line, &reader, &writer)) return 1;

  // Get the ID of target chromosome

  // Open fasta
  FastaReference fasta;
  LoadReference(param.ref_fasta.c_str(), &fasta);

  // Build SSW aligners for every reference in fasta
  SpecialReference s_ref;
  ConcatenateSpecialReference(&fasta, &s_ref);

  // Build SSW aligner
  StripedSmithWaterman::Aligner aligner;
  aligner.SetReferenceSequence(s_ref.concatnated.c_str(), s_ref.concatnated_len);

  // CORE ALGORITHM
  BamTools::BamAlignment bam_alignment;
  map<string, Alignment> al_map1, al_map2;
  map<string, Alignment> *al_map_cur = &al_map1, *al_map_pre = &al_map2;
  StripedSmithWaterman::Alignment alignment;
  Alignment al;
  while (reader.GetNextAlignment(bam_alignment)) {
    int index = -1;
    if (param.za_add && IsProblematicAlignment(bam_alignment)) {
      Align(bam_alignment.QueryBases, aligner, &alignment);
      index = PickBestAlignment(bam_alignment.Length, alignment, s_ref);
      if (index == -1) { // try the reverse complement sequences
        string reverse;
        GetReverseComplement(bam_alignment.QueryBases, &reverse);
        Align(reverse, aligner, &alignment);
        index = PickBestAlignment(bam_alignment.Length, alignment, s_ref);
      }
    }
    al.Clear();
    al.bam_alignment = bam_alignment;
    al.hit_insertion = (index == -1) ? false: true;
    al.ins_prefix    = (index == -1) ? "" : s_ref.ref_names[index].substr(8,2);
    StoreAlignment(param.za_add, &al, al_map_cur, al_map_pre, &writer);
  }

  // Close
  WriteAlignment(param.za_add, &al_map1, &writer);
  WriteAlignment(param.za_add, &al_map2, &writer);
  al_map1.clear();
  al_map2.clear();
  reader.Close();
  writer.Close();
}
<|endoftext|>


<commit_before>//! @file
//! @copyright See LICENSE.txt.

#pragma once

#include "bounded/static.hpp"
#include "quantities/wall_time.hpp"
#include "rsrc/fonts.hpp"
#include "utility/reference.hpp"
#include "utility/simple_moving_average.hpp"

#include <SFML/Graphics.hpp>

#include <deque>

namespace ql {
	struct widget;

	//! Represents an instance of the game Questless.
	struct game {
		//! @param fullscreen Whether to run the game in fullscreen mode.
		game(bool fullscreen);

		~game();

		//! Runs a new game of Questless.
		auto run() -> void;

	private:
		sf::RenderWindow _window;

		rsrc::fonts _fonts;

		uptr<widget> _root;

		// Timing

		//! The last time the game updated.
		clock::time_point _last_update_time = clock::now();

		//! Time debt is nonnegative.
		static constexpr sec min_time_debt = 0.0_s;
		//! Capped to prevent too much "fast-forwarding".
		static constexpr sec max_time_debt = 1.0_s;
		//! How far behind the target frame duration the scene is.
		static_bounded<sec, min_time_debt, max_time_debt> _time_debt = 0.0_s;

		static constexpr size_t _fps_buffer_size = 25;
		simple_moving_average<per_sec, _fps_buffer_size> _avg_fps;

		//! Tries to keep the scene running at the target frame rate.
		//! @return The duration of the last frame.
		auto regulate_timing() -> sec;

		//! Draws the FPS counter.
		auto draw_fps() -> void;

		//! Inform the root element that the user is trying to quit.
		auto request_quit() -> void;
	};
}
<commit_msg>Seems redundant to give this template parameter a named value just because.<commit_after>//! @file
//! @copyright See LICENSE.txt.

#pragma once

#include "bounded/static.hpp"
#include "quantities/wall_time.hpp"
#include "rsrc/fonts.hpp"
#include "utility/reference.hpp"
#include "utility/simple_moving_average.hpp"

#include <SFML/Graphics.hpp>

#include <deque>

namespace ql {
	struct widget;

	//! Represents an instance of the game Questless.
	struct game {
		//! @param fullscreen Whether to run the game in fullscreen mode.
		game(bool fullscreen);

		~game();

		//! Runs a new game of Questless.
		auto run() -> void;

	private:
		sf::RenderWindow _window;

		rsrc::fonts _fonts;

		uptr<widget> _root;

		// Timing

		//! The last time the game updated.
		clock::time_point _last_update_time = clock::now();

		//! Time debt is nonnegative.
		static constexpr sec min_time_debt = 0.0_s;
		//! Capped to prevent too much "fast-forwarding".
		static constexpr sec max_time_debt = 1.0_s;
		//! How far behind the target frame duration the scene is.
		static_bounded<sec, min_time_debt, max_time_debt> _time_debt = 0.0_s;

		simple_moving_average<per_sec, 25> _avg_fps;

		//! Tries to keep the scene running at the target frame rate.
		//! @return The duration of the last frame.
		auto regulate_timing() -> sec;

		//! Draws the FPS counter.
		auto draw_fps() -> void;

		//! Inform the root element that the user is trying to quit.
		auto request_quit() -> void;
	};
}
<|endoftext|>


<commit_before>/*
    Copyright(c) Microsoft Open Technologies, Inc. All rights reserved.

    The MIT License(MIT)

    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.
*/

//
// MainPage.xaml.cpp
// Implementation of the MainPage class.
//

#include "pch.h"
#include "MainPage.xaml.h"
#include <string>

using namespace BlinkyCpp;

using namespace Platform;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Controls::Primitives;
using namespace Windows::UI::Xaml::Data;
using namespace Windows::UI::Xaml::Input;
using namespace Windows::UI::Xaml::Media;
using namespace Windows::UI::Xaml::Navigation;
using namespace Windows::Devices::Enumeration;
using namespace Windows::Devices::Gpio;
using namespace concurrency;

MainPage::MainPage()
{
    InitializeComponent();

    InitGPIO();

    timer_ = ref new DispatcherTimer();
    TimeSpan interval;
    interval.Duration = 500 * 1000 * 10;
    timer_->Interval = interval;
    timer_->Tick += ref new EventHandler<Object ^>(this, &MainPage::OnTick);
    timer_->Start();
}

void MainPage::InitGPIO()
{
	auto gpio = GpioController::GetDefault();

	if (gpio == nullptr)
	{
		pin_ = nullptr;
		GpioStatus->Text = "There is no GPIO controller on this device.";
		return;
	}

	pin_ = gpio->OpenPin(LED_PIN);
	pin_->Write(GpioPinValue::High);
	pin_->SetDriveMode(GpioPinDriveMode::Output);

	GpioStatus->Text = "GPIO pin initialized correctly.";
}

void MainPage::FlipLED()
{
    if (LEDStatus_ == 0)
    {
        LEDStatus_ = 1;
        if (pin_ != nullptr)
        {
            pin_->Write(GpioPinValue::High);
        }
        LED->Fill = redBrush_;
    }
    else
    {
        LEDStatus_ = 0;
        if (pin_ != nullptr)
        {
            pin_->Write(GpioPinValue::Low);
        }
        LED->Fill = grayBrush_;
    }
}

void MainPage::TurnOffLED()
{
    if (LEDStatus_ == 1)
    {
        FlipLED();
    }
}

void MainPage::OnTick(Object ^sender, Object ^args)
{
    FlipLED();
}

void MainPage::Delay_ValueChanged(Object^ sender, RangeBaseValueChangedEventArgs^ e)
{
    if (timer_ == nullptr)
    {
        return;
    }
    if (e->NewValue == Delay->Minimum)
    {
        DelayText->Text = "Stopped";
        timer_->Stop();
        TurnOffLED();
    }
    else
    {
        long delay = static_cast<long>(e->NewValue);
        auto txt = std::to_wstring(delay) + L"ms";
        DelayText->Text = ref new String(txt.c_str());
        TimeSpan interval;
        interval.Duration = delay * 1000 * 10;
        timer_->Interval = interval;
        timer_->Start();
    }

}
<commit_msg>Blinky cpp gpio logic corrected. Matches correct CS code.<commit_after>/*
    Copyright(c) Microsoft Open Technologies, Inc. All rights reserved.

    The MIT License(MIT)

    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.
*/

//
// MainPage.xaml.cpp
// Implementation of the MainPage class.
//

#include "pch.h"
#include "MainPage.xaml.h"
#include <string>

using namespace BlinkyCpp;

using namespace Platform;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Controls::Primitives;
using namespace Windows::UI::Xaml::Data;
using namespace Windows::UI::Xaml::Input;
using namespace Windows::UI::Xaml::Media;
using namespace Windows::UI::Xaml::Navigation;
using namespace Windows::Devices::Enumeration;
using namespace Windows::Devices::Gpio;
using namespace concurrency;

MainPage::MainPage()
{
    InitializeComponent();

    InitGPIO();

    timer_ = ref new DispatcherTimer();
    TimeSpan interval;
    interval.Duration = 500 * 1000 * 10;
    timer_->Interval = interval;
    timer_->Tick += ref new EventHandler<Object ^>(this, &MainPage::OnTick);
    timer_->Start();
}

void MainPage::InitGPIO()
{
	auto gpio = GpioController::GetDefault();

	if (gpio == nullptr)
	{
		pin_ = nullptr;
		GpioStatus->Text = "There is no GPIO controller on this device.";
		return;
	}

	pin_ = gpio->OpenPin(LED_PIN);
	pin_->Write(GpioPinValue::High);
	pin_->SetDriveMode(GpioPinDriveMode::Output);

	GpioStatus->Text = "GPIO pin initialized correctly.";
}

void MainPage::FlipLED()
{
    if (LEDStatus_ == 0)
    {
        LEDStatus_ = 1;
        if (pin_ != nullptr)
        {
            pin_->Write(GpioPinValue::Low);
        }
        LED->Fill = redBrush_;
    }
    else
    {
        LEDStatus_ = 0;
        if (pin_ != nullptr)
        {
            pin_->Write(GpioPinValue::High);
        }
        LED->Fill = grayBrush_;
    }
}

void MainPage::TurnOffLED()
{
    if (LEDStatus_ == 1)
    {
        FlipLED();
    }
}

void MainPage::OnTick(Object ^sender, Object ^args)
{
    FlipLED();
}

void MainPage::Delay_ValueChanged(Object^ sender, RangeBaseValueChangedEventArgs^ e)
{
    if (timer_ == nullptr)
    {
        return;
    }
    if (e->NewValue == Delay->Minimum)
    {
        DelayText->Text = "Stopped";
        timer_->Stop();
        TurnOffLED();
    }
    else
    {
        long delay = static_cast<long>(e->NewValue);
        auto txt = std::to_wstring(delay) + L"ms";
        DelayText->Text = ref new String(txt.c_str());
        TimeSpan interval;
        interval.Duration = delay * 1000 * 10;
        timer_->Interval = interval;
        timer_->Start();
    }

}
<|endoftext|>