<commit_before>#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <sstream>

using namespace std;

vector<string> split(string str, char delimiter) {
	vector<string> internal;
	stringstream ss(str);
	string tok;

	while (getline(ss, tok, delimiter)) {
		internal.push_back(tok);
	}

	return internal;
}

int addIncludeHeader(string name, char* path) {
	ifstream iFile(path);
	string str;
	string fileContent = "";

	if (!iFile)
		return 1;

	while (!iFile.eof())
	{
		getline(iFile, str);

		str += "\n";
		fileContent += str;

		str = "";
	}

	iFile.close();

	vector<string> befor = split(fileContent, '\n');
	vector<string> after;

	for (unsigned int i = 0; i < befor.size(); i++) {
		after.push_back(befor.at(i));

		if (befor.at(i) == "//HEADER") {
			after.push_back("#include <scripts/" + name + ".hpp>");
		}
	}

	fileContent = "";

	for (unsigned int i = 0; i < after.size(); i++) {
		fileContent += after.at(i) + "\n";
	}

	//cout << fileContent << endl;

	ofstream oFile(path);

	oFile.write(fileContent.c_str(), fileContent.size());
	oFile.close();
	return 0;
}

int addEngineRegister(string name, char* path) {
	ifstream iFile(path);
	string str;
	string fileContent = "";

	if (!iFile)
		return 1;

	while (!iFile.eof())
	{
		getline(iFile, str);

		str += "\n";
		fileContent += str;

		str = "";
	}

	iFile.close();

	vector<string> befor = split(fileContent, '\n');
	vector<string> after;

	for (unsigned int i = 0; i < befor.size(); i++) {
		after.push_back(befor.at(i));

		if (befor.at(i) == "//ENGINE_REGISTER") {

			string lowerName = name;
			for (unsigned int i = 0; i < name.size(); i++)
				lowerName[i] = tolower(name[i]);

			after.push_back("	game::" + name + "* " + lowerName + " new game::" + name + "();");
			after.push_back("	fabric::Engine::vRegisteredGameObjects->push_back(" + lowerName + ");");
			after.push_back(" ");
		}
	}

	fileContent = "";

	for (unsigned int i = 0; i < after.size(); i++) {
		fileContent += after.at(i) + "\n";
	}

	//cout << fileContent;

	ofstream oFile(path);

	oFile.write(fileContent.c_str(), fileContent.size());
	oFile.close();
	return 0;
}

int addSourceFile(string name, string path) {
	ofstream oFile(path + name + ".cpp");

	string fileContent = "";

	fileContent += "#include <engine.hpp>\n";
	fileContent += "#include <gameobject.hpp>\n";
	fileContent += "#include <behavior.hpp>\n";
	fileContent += "\n";
	fileContent += "using namespace fabric;\n";
	fileContent += "\n";
	fileContent += "namespace game{\n";
	fileContent += "	class " + name + " : public GameObject{\n";
	fileContent += "	public:\n";
	fileContent += "		// Use for initialization\n";
	fileContent += "		void setup(){\n";
	fileContent += "\n";
	fileContent += "		}\n";
	fileContent += "\n";
	fileContent += "		// Use for frame by frame logic\n";
	fileContent += "		void update (){\n";
	fileContent += "\n";
	fileContent += "		}\n";
	fileContent += "	};\n";
	fileContent += "}";

	oFile.write(fileContent.c_str(), fileContent.size());
	oFile.close();

	return 0;
}

void waitForExit() {
	string input;

	do {
		cout << "Input anything to exit: ";
		cin >> input;
	} while (input == "");

}

int main() {
	string input;
	int lhs;

	cout << "Welcome to the automated script creation tool" << endl;
	cout << "Is this tool beeing ran from the 'tools' directory in your project or" << endl;
	cout << "has been launched from the editor? [yes | no]: ";

	cin >> input;
	if (input == "no") {
		cout << "Please launched the tool from the 'tools' directory or the editor" << endl;
		waitForExit();
		return 1;
	}

	cout << endl;
	cout << "Please enter the name of your script (no exstenion): ";
	cin >> input;
	cout << "Thank You";
	cout << endl;

	lhs = addIncludeHeader(input, "../../game/game.cpp");
	if (lhs == 0)
		cout << "... Include headers have been created in 'game.cpp'" << endl;
	else
		cout << "... Include header could not be written to 'game.cpp'" << endl;

	lhs = addEngineRegister(input, "../../game/game.cpp");
	if (lhs == 0)
		cout << "... Engine register have been created in 'game.cpp'" << endl;
	else
		cout << "... Engine register could not be written to 'game.cpp'" << endl;

	lhs = addSourceFile(input, "../../game/scripts/source/");
	if (lhs == 0)
		cout << "... .cpp file has been created in 'scripts/source'" << endl;
	else
		cout << "... .cpp file could not be created in'scripts/source'" << endl;

	cout << endl;
	cout << "Script has been added, your welcome" << endl;

	waitForExit();

	return 0;
}<commit_msg>Added automatic .hpp creation<commit_after>#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <sstream>

using namespace std;

vector<string> split(string str, char delimiter) {
	vector<string> internal;
	stringstream ss(str);
	string tok;

	while (getline(ss, tok, delimiter)) {
		internal.push_back(tok);
	}

	return internal;
}

int addIncludeHeader(string name, char* path) {
	ifstream iFile(path);
	string str;
	string fileContent = "";

	if (!iFile)
		return 1;

	while (!iFile.eof())
	{
		getline(iFile, str);

		str += "\n";
		fileContent += str;

		str = "";
	}

	iFile.close();

	vector<string> befor = split(fileContent, '\n');
	vector<string> after;

	for (unsigned int i = 0; i < befor.size(); i++) {
		after.push_back(befor.at(i));

		if (befor.at(i) == "//HEADER") {
			after.push_back("#include \"scripts/header/" + name + ".hpp\" ");
		}
	}

	fileContent = "";

	for (unsigned int i = 0; i < after.size(); i++) {
		fileContent += after.at(i) + "\n";
	}

	//cout << fileContent << endl;

	ofstream oFile(path);

	oFile.write(fileContent.c_str(), fileContent.size());
	oFile.close();
	return 0;
}

int addEngineRegister(string name, char* path) {
	ifstream iFile(path);
	string str;
	string fileContent = "";

	if (!iFile)
		return 1;

	while (!iFile.eof())
	{
		getline(iFile, str);

		str += "\n";
		fileContent += str;

		str = "";
	}

	iFile.close();

	vector<string> befor = split(fileContent, '\n');
	vector<string> after;

	for (unsigned int i = 0; i < befor.size(); i++) {
		after.push_back(befor.at(i));

		if (befor.at(i) == "//ENGINE_REGISTER") {

			string lowerName = name;
			for (unsigned int i = 0; i < name.size(); i++)
				lowerName[i] = tolower(name[i]);

			after.push_back("	game::" + name + "* " + lowerName + " = new game::" + name + "();");
			after.push_back("	fabric::Engine::vRegisteredGameObjects->push_back(" + lowerName + ");");
			after.push_back(" ");
		}
	}

	fileContent = "";

	for (unsigned int i = 0; i < after.size(); i++) {
		fileContent += after.at(i) + "\n";
	}

	//cout << fileContent;

	ofstream oFile(path);

	oFile.write(fileContent.c_str(), fileContent.size());
	oFile.close();
	return 0;
}

int addSourceFile(string name, string path) {
	ofstream oFile(path + name + ".cpp");

	if (!oFile)
		return 1;

	string fileContent;

	fileContent += "#include \"../header/" + name + ".hpp\"\n";
	fileContent += "#include <engine.hpp>\n";
	fileContent += "#include <gameobject.hpp>\n";
	fileContent += "#include <behavior.hpp>\n";
	fileContent += "\n";
	fileContent += "using namespace fabric;\n";
	fileContent += "\n";
	fileContent += "namespace game{\n";
	fileContent += "\n";

	fileContent += "void " + name + "::setup(){\n";
	fileContent += "	// Use this for inital setup\n";
	fileContent += "	}\n";

	fileContent += "void " + name + "::update(){\n";
	fileContent += "	// Use this for frame by frame logic\n";
	fileContent += "	}\n";
	fileContent += "}";

	oFile.write(fileContent.c_str(), fileContent.size());
	oFile.close();

	return 0;
}

int addHeaderFile(string name, string path) {
	ofstream oFile(path + name + ".hpp");

	if (!oFile)
		return 1;

	string upperName = name;
	for (unsigned int i = 0; i < name.size(); i++)
		upperName[i] = toupper(name[i]);

	string fileContent = "";

	fileContent += "#ifndef " + upperName + "_HPP" + "\n";
	fileContent += "#define " + upperName + "_HPP" + "\n";

	fileContent += "\n";

	fileContent += "#include <engine.hpp> \n";
	fileContent += "#include <gameobject.hpp>\n";
	fileContent += "#include <behavior.hpp>\n";
	fileContent += "\n";
	fileContent += "using namespace fabric;\n";
	fileContent += "\n";
	fileContent += "namespace game{\n";
	fileContent += "	class " + name + " : public GameObject{\n";
	fileContent += "	public:\n";
	fileContent += "		void setup();\n";
	fileContent += "		void update ();\n";
	fileContent += "	};\n";
	fileContent += "}\n";
	fileContent += "#endif";

	oFile.write(fileContent.c_str(), fileContent.size());
	oFile.close();

	return 0;
}

void waitForExit() {
	string input;

	do {
		cout << "Input anything to exit: ";
		cin >> input;
	} while (input == "");

}

int main() {
	string input;
	int lhs;

	cout << "Welcome to the automated script creation tool" << endl;
	cout << "Is this tool beeing ran from the 'tools' directory in your project or" << endl;
	cout << "has been launched from the editor? [yes | no]: ";

	cin >> input;
	if (input == "no") {
		cout << "Please launched the tool from the 'tools' directory or the editor" << endl;
		waitForExit();
		return 1;
	}

	cout << endl;
	cout << "Please enter the name of your script (no exstenion): ";
	cin >> input;
	cout << "Thank You";
	cout << endl;

	lhs = addIncludeHeader(input, "../../game/game.cpp");
	if (lhs == 0)
		cout << "... Include headers have been created in 'game.cpp'" << endl;
	else
		cout << "... Include header could not be written to 'game.cpp'" << endl;

	lhs = addEngineRegister(input, "../../game/game.cpp");
	if (lhs == 0)
		cout << "... Engine register have been created in 'game.cpp'" << endl;
	else
		cout << "... Engine register could not be written to 'game.cpp'" << endl;

	lhs = addSourceFile(input, "../../game/scripts/source/");
	if (lhs == 0)
		cout << "... .cpp file has been created in 'scripts/source'" << endl;
	else
		cout << "... .cpp file could not be created in'scripts/source'" << endl;

	lhs = addHeaderFile(input, "../../game/scripts/header/");
	if (lhs == 0)
		cout << "... .hpp file has been created in 'scripts/header'" << endl;
	else
		cout << "... .hpp file could not be created in'scripts/header'" << endl;

	cout << endl;
	cout << "Script has been added, your welcome" << endl;

	waitForExit();

	return 0;
}<|endoftext|>


<commit_before>/*  This file is part of the KDE project
    Copyright (C) 2005-2006 Matthias Kretz <kretz@kde.org>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License version 2 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
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.

*/

#include "abstractmediaproducer.h"
#include "abstractmediaproducer_p.h"
#include "factory.h"

#include "videopath.h"
#include "audiopath.h"

#include "mediaproducerinterface.h"

#include <QTimer>

#include <kdebug.h>
#include <QStringList>

#define PHONON_CLASSNAME AbstractMediaProducer
#define PHONON_INTERFACENAME MediaProducerInterface

namespace Phonon
{
PHONON_ABSTRACTBASE_IMPL

AbstractMediaProducer::~AbstractMediaProducer()
{
	K_D( AbstractMediaProducer );
	Phonon::State s = state();
	if( s != ErrorState || s != StoppedState || s != LoadingState )
		stop();
    foreach(VideoPath* vp, d->videoPaths)
        d->removeDestructionHandler(vp, d);
    foreach(AudioPath* ap, d->audioPaths)
        d->removeDestructionHandler(ap, d);
}

bool AbstractMediaProducer::addVideoPath( VideoPath* videoPath )
{
	K_D( AbstractMediaProducer );
	if( d->videoPaths.contains( videoPath ) )
		return false;

	if( iface() )
	{
		if( qobject_cast<MediaProducerInterface*>( d->backendObject )->addVideoPath( videoPath->iface() ) )
		{
            d->addDestructionHandler(videoPath, d);
			d->videoPaths.append( videoPath );
			return true;
		}
	}
	return false;
}

bool AbstractMediaProducer::addAudioPath( AudioPath* audioPath )
{
	K_D( AbstractMediaProducer );
	if( d->audioPaths.contains( audioPath ) )
		return false;

	if( iface() )
	{
		if( qobject_cast<MediaProducerInterface*>( d->backendObject )->addAudioPath( audioPath->iface() ) )
		{
            d->addDestructionHandler(audioPath, d);
			d->audioPaths.append( audioPath );
			return true;
		}
	}
	return false;
}

PHONON_INTERFACE_SETTER( setTickInterval, tickInterval, qint32 )
PHONON_INTERFACE_GETTER( qint32, tickInterval, d->tickInterval )
PHONON_INTERFACE_GETTER( Phonon::State, state, d->state )
PHONON_INTERFACE_GETTER( bool, hasVideo, false )
PHONON_INTERFACE_GETTER( bool, isSeekable, false )
PHONON_INTERFACE_GETTER( qint64, currentTime, d->currentTime )
PHONON_INTERFACE_GETTER1( QString, selectedAudioStream,    d->selectedAudioStream[    audioPath ], AudioPath*, audioPath )
PHONON_INTERFACE_GETTER1( QString, selectedVideoStream,    d->selectedVideoStream[    videoPath ], VideoPath*, videoPath )
PHONON_INTERFACE_GETTER1( QString, selectedSubtitleStream, d->selectedSubtitleStream[ videoPath ], VideoPath*, videoPath )
PHONON_INTERFACE_GETTER( QStringList, availableAudioStreams, QStringList() )
PHONON_INTERFACE_GETTER( QStringList, availableVideoStreams, QStringList() )
PHONON_INTERFACE_GETTER( QStringList, availableSubtitleStreams, QStringList() )

void AbstractMediaProducer::selectAudioStream( const QString& streamName, AudioPath* audioPath )
{
	K_D( AbstractMediaProducer );
	if( iface() )
        INTERFACE_CALL(selectAudioStream, (streamName, audioPath->iface()));
	else
		d->selectedAudioStream[ audioPath ] = streamName;
}

void AbstractMediaProducer::selectVideoStream( const QString& streamName, VideoPath* videoPath )
{
	K_D( AbstractMediaProducer );
	if( iface() )
        INTERFACE_CALL(selectVideoStream, (streamName, videoPath->iface()));
	else
		d->selectedVideoStream[ videoPath ] = streamName;
}

void AbstractMediaProducer::selectSubtitleStream( const QString& streamName, VideoPath* videoPath )
{
	K_D( AbstractMediaProducer );
	if( iface() )
        INTERFACE_CALL(selectSubtitleStream, (streamName, videoPath->iface()));
	else
		d->selectedSubtitleStream[ videoPath ] = streamName;
}

QList<VideoPath*> AbstractMediaProducer::videoPaths() const
{
	K_D( const AbstractMediaProducer );
	return d->videoPaths;
}

QList<AudioPath*> AbstractMediaProducer::audioPaths() const
{
	K_D( const AbstractMediaProducer );
	return d->audioPaths;
}

void AbstractMediaProducer::play()
{
	K_D( AbstractMediaProducer );
	if( iface() )
        INTERFACE_CALL(play, ());
}

void AbstractMediaProducer::pause()
{
	K_D( AbstractMediaProducer );
	if( iface() )
        INTERFACE_CALL(pause, ());
}

void AbstractMediaProducer::stop()
{
	K_D( AbstractMediaProducer );
	if( iface() )
	{
        INTERFACE_CALL(stop, ());
		if( tickInterval() > 0 )
			emit tick( 0 );
	}
}

void AbstractMediaProducer::seek( qint64 time )
{
	K_D( AbstractMediaProducer );
	State s = state();
	if( iface() && ( s == Phonon::PlayingState || s == Phonon::BufferingState || s == Phonon::PausedState ) )
        INTERFACE_CALL(seek, (time));
}

QString AbstractMediaProducer::errorString() const
{
    if (state() == Phonon::ErrorState) {
        K_D(const AbstractMediaProducer);
        return INTERFACE_CALL(errorString, ());
    }
    return QString();
}

ErrorType AbstractMediaProducer::errorType() const
{
    if (state() == Phonon::ErrorState) {
        K_D(const AbstractMediaProducer);
        return INTERFACE_CALL(errorType, ());
    }
    return Phonon::NoError;
}

bool AbstractMediaProducerPrivate::aboutToDeleteIface()
{
	//kDebug( 600 ) << k_funcinfo << endl;
	if( backendObject )
	{
		state = qobject_cast<MediaProducerInterface*>( backendObject )->state();
		currentTime = qobject_cast<MediaProducerInterface*>( backendObject )->currentTime();
		tickInterval = qobject_cast<MediaProducerInterface*>( backendObject )->tickInterval();
	}
	return true;
}

void AbstractMediaProducer::setupIface()
{
	K_D( AbstractMediaProducer );
	Q_ASSERT( d->backendObject );
	//kDebug( 600 ) << k_funcinfo << endl;

	connect( d->backendObject, SIGNAL( stateChanged( Phonon::State, Phonon::State ) ), SIGNAL( stateChanged( Phonon::State, Phonon::State ) ) );
	connect( d->backendObject, SIGNAL( tick( qint64 ) ), SIGNAL( tick( qint64 ) ) );
	connect( d->backendObject, SIGNAL( metaDataChanged( const QMultiMap<QString, QString>& ) ), SLOT( _k_metaDataChanged( const QMultiMap<QString, QString>& ) ) );
    connect(d->backendObject, SIGNAL(seekableChanged(bool)), SIGNAL(seekableChanged(bool)));

	// set up attributes
    INTERFACE_CALL(setTickInterval, (d->tickInterval));

	foreach( AudioPath* a, d->audioPaths )
	{
		if( !qobject_cast<MediaProducerInterface*>( d->backendObject )->addAudioPath( a->iface() ) )
			d->audioPaths.removeAll( a );
	}
	foreach( VideoPath* v, d->videoPaths )
	{
		if( !qobject_cast<MediaProducerInterface*>( d->backendObject )->addVideoPath( v->iface() ) )
			d->videoPaths.removeAll( v );
	}

	switch( d->state )
	{
		case LoadingState:
		case StoppedState:
		case ErrorState:
			break;
		case PlayingState:
		case BufferingState:
			QTimer::singleShot( 0, this, SLOT( _k_resumePlay() ) );
			break;
		case PausedState:
			QTimer::singleShot( 0, this, SLOT( _k_resumePause() ) );
			break;
	}
	d->state = qobject_cast<MediaProducerInterface*>( d->backendObject )->state();
}

void AbstractMediaProducerPrivate::_k_resumePlay()
{
	qobject_cast<MediaProducerInterface*>( backendObject )->play();
	if( currentTime > 0 )
		qobject_cast<MediaProducerInterface*>( backendObject )->seek( currentTime );
}

void AbstractMediaProducerPrivate::_k_resumePause()
{
	qobject_cast<MediaProducerInterface*>( backendObject )->play();
	if( currentTime > 0 )
		qobject_cast<MediaProducerInterface*>( backendObject )->seek( currentTime );
	qobject_cast<MediaProducerInterface*>( backendObject )->pause();
}

void AbstractMediaProducerPrivate::_k_metaDataChanged( const QMultiMap<QString, QString>& newMetaData )
{
	metaData = newMetaData;
	emit q_func()->metaDataChanged();
}

QStringList AbstractMediaProducer::metaDataKeys() const
{
	K_D( const AbstractMediaProducer );
	return d->metaData.keys();
}

QString AbstractMediaProducer::metaDataItem( const QString& key ) const
{
	K_D( const AbstractMediaProducer );
	return d->metaData.value( key );
}

QStringList AbstractMediaProducer::metaDataItems( const QString& key ) const
{
	K_D( const AbstractMediaProducer );
	return d->metaData.values( key );
}

void AbstractMediaProducerPrivate::phononObjectDestroyed( Base* o )
{
	// this method is called from Phonon::Base::~Base(), meaning the AudioPath
	// dtor has already been called, also virtual functions don't work anymore
	// (therefore qobject_cast can only downcast from Base)
	Q_ASSERT( o );
	AudioPath* audioPath = static_cast<AudioPath*>( o );
	VideoPath* videoPath = static_cast<VideoPath*>( o );
	if( audioPaths.contains( audioPath ) )
	{
		if( backendObject )
			qobject_cast<MediaProducerInterface*>( backendObject )->removeAudioPath( audioPath->iface() );
		audioPaths.removeAll( audioPath );
	}
	else if( videoPaths.contains( videoPath ) )
	{
		if( backendObject )
			qobject_cast<MediaProducerInterface*>( backendObject )->removeVideoPath( videoPath->iface() );
		videoPaths.removeAll( videoPath );
	}
}

} //namespace Phonon

#include "abstractmediaproducer.moc"
// vim: sw=4 ts=4 tw=80
<commit_msg>don't (re)create the backend object in the ctor<commit_after>/*  This file is part of the KDE project
    Copyright (C) 2005-2006 Matthias Kretz <kretz@kde.org>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License version 2 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
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.

*/

#include "abstractmediaproducer.h"
#include "abstractmediaproducer_p.h"
#include "factory.h"

#include "videopath.h"
#include "audiopath.h"

#include "mediaproducerinterface.h"

#include <QTimer>

#include <kdebug.h>
#include <QStringList>

#define PHONON_CLASSNAME AbstractMediaProducer
#define PHONON_INTERFACENAME MediaProducerInterface

namespace Phonon
{
PHONON_ABSTRACTBASE_IMPL

AbstractMediaProducer::~AbstractMediaProducer()
{
    K_D(AbstractMediaProducer);
    if (d->backendObject) {
        switch (state()) {
            case PlayingState:
            case BufferingState:
            case PausedState:
                stop();
                break;
            case ErrorState:
            case StoppedState:
            case LoadingState:
                break;
        }
    }
    foreach(VideoPath* vp, d->videoPaths)
        d->removeDestructionHandler(vp, d);
    foreach(AudioPath* ap, d->audioPaths)
        d->removeDestructionHandler(ap, d);
}

bool AbstractMediaProducer::addVideoPath( VideoPath* videoPath )
{
	K_D( AbstractMediaProducer );
	if( d->videoPaths.contains( videoPath ) )
		return false;

	if( iface() )
	{
		if( qobject_cast<MediaProducerInterface*>( d->backendObject )->addVideoPath( videoPath->iface() ) )
		{
            d->addDestructionHandler(videoPath, d);
			d->videoPaths.append( videoPath );
			return true;
		}
	}
	return false;
}

bool AbstractMediaProducer::addAudioPath( AudioPath* audioPath )
{
	K_D( AbstractMediaProducer );
	if( d->audioPaths.contains( audioPath ) )
		return false;

	if( iface() )
	{
		if( qobject_cast<MediaProducerInterface*>( d->backendObject )->addAudioPath( audioPath->iface() ) )
		{
            d->addDestructionHandler(audioPath, d);
			d->audioPaths.append( audioPath );
			return true;
		}
	}
	return false;
}

PHONON_INTERFACE_SETTER( setTickInterval, tickInterval, qint32 )
PHONON_INTERFACE_GETTER( qint32, tickInterval, d->tickInterval )
PHONON_INTERFACE_GETTER( Phonon::State, state, d->state )
PHONON_INTERFACE_GETTER( bool, hasVideo, false )
PHONON_INTERFACE_GETTER( bool, isSeekable, false )
PHONON_INTERFACE_GETTER( qint64, currentTime, d->currentTime )
PHONON_INTERFACE_GETTER1( QString, selectedAudioStream,    d->selectedAudioStream[    audioPath ], AudioPath*, audioPath )
PHONON_INTERFACE_GETTER1( QString, selectedVideoStream,    d->selectedVideoStream[    videoPath ], VideoPath*, videoPath )
PHONON_INTERFACE_GETTER1( QString, selectedSubtitleStream, d->selectedSubtitleStream[ videoPath ], VideoPath*, videoPath )
PHONON_INTERFACE_GETTER( QStringList, availableAudioStreams, QStringList() )
PHONON_INTERFACE_GETTER( QStringList, availableVideoStreams, QStringList() )
PHONON_INTERFACE_GETTER( QStringList, availableSubtitleStreams, QStringList() )

void AbstractMediaProducer::selectAudioStream( const QString& streamName, AudioPath* audioPath )
{
	K_D( AbstractMediaProducer );
	if( iface() )
        INTERFACE_CALL(selectAudioStream, (streamName, audioPath->iface()));
	else
		d->selectedAudioStream[ audioPath ] = streamName;
}

void AbstractMediaProducer::selectVideoStream( const QString& streamName, VideoPath* videoPath )
{
	K_D( AbstractMediaProducer );
	if( iface() )
        INTERFACE_CALL(selectVideoStream, (streamName, videoPath->iface()));
	else
		d->selectedVideoStream[ videoPath ] = streamName;
}

void AbstractMediaProducer::selectSubtitleStream( const QString& streamName, VideoPath* videoPath )
{
	K_D( AbstractMediaProducer );
	if( iface() )
        INTERFACE_CALL(selectSubtitleStream, (streamName, videoPath->iface()));
	else
		d->selectedSubtitleStream[ videoPath ] = streamName;
}

QList<VideoPath*> AbstractMediaProducer::videoPaths() const
{
	K_D( const AbstractMediaProducer );
	return d->videoPaths;
}

QList<AudioPath*> AbstractMediaProducer::audioPaths() const
{
	K_D( const AbstractMediaProducer );
	return d->audioPaths;
}

void AbstractMediaProducer::play()
{
	K_D( AbstractMediaProducer );
	if( iface() )
        INTERFACE_CALL(play, ());
}

void AbstractMediaProducer::pause()
{
	K_D( AbstractMediaProducer );
	if( iface() )
        INTERFACE_CALL(pause, ());
}

void AbstractMediaProducer::stop()
{
	K_D( AbstractMediaProducer );
	if( iface() )
	{
        INTERFACE_CALL(stop, ());
		if( tickInterval() > 0 )
			emit tick( 0 );
	}
}

void AbstractMediaProducer::seek( qint64 time )
{
	K_D( AbstractMediaProducer );
	State s = state();
	if( iface() && ( s == Phonon::PlayingState || s == Phonon::BufferingState || s == Phonon::PausedState ) )
        INTERFACE_CALL(seek, (time));
}

QString AbstractMediaProducer::errorString() const
{
    if (state() == Phonon::ErrorState) {
        K_D(const AbstractMediaProducer);
        return INTERFACE_CALL(errorString, ());
    }
    return QString();
}

ErrorType AbstractMediaProducer::errorType() const
{
    if (state() == Phonon::ErrorState) {
        K_D(const AbstractMediaProducer);
        return INTERFACE_CALL(errorType, ());
    }
    return Phonon::NoError;
}

bool AbstractMediaProducerPrivate::aboutToDeleteIface()
{
	//kDebug( 600 ) << k_funcinfo << endl;
	if( backendObject )
	{
		state = qobject_cast<MediaProducerInterface*>( backendObject )->state();
		currentTime = qobject_cast<MediaProducerInterface*>( backendObject )->currentTime();
		tickInterval = qobject_cast<MediaProducerInterface*>( backendObject )->tickInterval();
	}
	return true;
}

void AbstractMediaProducer::setupIface()
{
	K_D( AbstractMediaProducer );
	Q_ASSERT( d->backendObject );
	//kDebug( 600 ) << k_funcinfo << endl;

	connect( d->backendObject, SIGNAL( stateChanged( Phonon::State, Phonon::State ) ), SIGNAL( stateChanged( Phonon::State, Phonon::State ) ) );
	connect( d->backendObject, SIGNAL( tick( qint64 ) ), SIGNAL( tick( qint64 ) ) );
	connect( d->backendObject, SIGNAL( metaDataChanged( const QMultiMap<QString, QString>& ) ), SLOT( _k_metaDataChanged( const QMultiMap<QString, QString>& ) ) );
    connect(d->backendObject, SIGNAL(seekableChanged(bool)), SIGNAL(seekableChanged(bool)));

	// set up attributes
    INTERFACE_CALL(setTickInterval, (d->tickInterval));

	foreach( AudioPath* a, d->audioPaths )
	{
		if( !qobject_cast<MediaProducerInterface*>( d->backendObject )->addAudioPath( a->iface() ) )
			d->audioPaths.removeAll( a );
	}
	foreach( VideoPath* v, d->videoPaths )
	{
		if( !qobject_cast<MediaProducerInterface*>( d->backendObject )->addVideoPath( v->iface() ) )
			d->videoPaths.removeAll( v );
	}

	switch( d->state )
	{
		case LoadingState:
		case StoppedState:
		case ErrorState:
			break;
		case PlayingState:
		case BufferingState:
			QTimer::singleShot( 0, this, SLOT( _k_resumePlay() ) );
			break;
		case PausedState:
			QTimer::singleShot( 0, this, SLOT( _k_resumePause() ) );
			break;
	}
	d->state = qobject_cast<MediaProducerInterface*>( d->backendObject )->state();
}

void AbstractMediaProducerPrivate::_k_resumePlay()
{
	qobject_cast<MediaProducerInterface*>( backendObject )->play();
	if( currentTime > 0 )
		qobject_cast<MediaProducerInterface*>( backendObject )->seek( currentTime );
}

void AbstractMediaProducerPrivate::_k_resumePause()
{
	qobject_cast<MediaProducerInterface*>( backendObject )->play();
	if( currentTime > 0 )
		qobject_cast<MediaProducerInterface*>( backendObject )->seek( currentTime );
	qobject_cast<MediaProducerInterface*>( backendObject )->pause();
}

void AbstractMediaProducerPrivate::_k_metaDataChanged( const QMultiMap<QString, QString>& newMetaData )
{
	metaData = newMetaData;
	emit q_func()->metaDataChanged();
}

QStringList AbstractMediaProducer::metaDataKeys() const
{
	K_D( const AbstractMediaProducer );
	return d->metaData.keys();
}

QString AbstractMediaProducer::metaDataItem( const QString& key ) const
{
	K_D( const AbstractMediaProducer );
	return d->metaData.value( key );
}

QStringList AbstractMediaProducer::metaDataItems( const QString& key ) const
{
	K_D( const AbstractMediaProducer );
	return d->metaData.values( key );
}

void AbstractMediaProducerPrivate::phononObjectDestroyed( Base* o )
{
	// this method is called from Phonon::Base::~Base(), meaning the AudioPath
	// dtor has already been called, also virtual functions don't work anymore
	// (therefore qobject_cast can only downcast from Base)
	Q_ASSERT( o );
	AudioPath* audioPath = static_cast<AudioPath*>( o );
	VideoPath* videoPath = static_cast<VideoPath*>( o );
	if( audioPaths.contains( audioPath ) )
	{
		if( backendObject )
			qobject_cast<MediaProducerInterface*>( backendObject )->removeAudioPath( audioPath->iface() );
		audioPaths.removeAll( audioPath );
	}
	else if( videoPaths.contains( videoPath ) )
	{
		if( backendObject )
			qobject_cast<MediaProducerInterface*>( backendObject )->removeVideoPath( videoPath->iface() );
		videoPaths.removeAll( videoPath );
	}
}

} //namespace Phonon

#include "abstractmediaproducer.moc"
// vim: sw=4 ts=4 tw=80
<|endoftext|>


<commit_before>#ifndef LUA_FUNCTION_H
#include "LuaFunction.hpp"
#endif

LuaFunction::LuaFunction(LuaAdapter &lua) : Lua{lua.GetLuaState()} {}

LuaFunction::LuaFunction(lua_State *const lua) : Lua{lua} {}

LuaFunction::~LuaFunction() {}

bool LuaFunction::Call(const char *functionName, const unsigned short int argc,
                       const int args[], int &result) {
  if (!this->Lua) {
    return false;
  }
  lua_getglobal(this->Lua, functionName);

  for (unsigned char i = 0; i < argc; i++)
    if (args + i)
      lua_pushnumber(this->Lua, args[i]);
  if (this->pcall(argc, 1, 0) == false) {
    return false;
  }

  if (lua_isnumber(this->Lua, -1)) {
    result = lua_tointeger(this->Lua, -1);
  }
  lua_pop(this->Lua, 1);
  return true;
}

bool LuaFunction::Call(const char *functionName, const char *const string,
                       const size_t length) {
  if (!this->Lua) {
    return false;
  }
  lua_getglobal(this->Lua, functionName);
  lua_pushlstring(this->Lua, string, length);
  if (this->pcall(1, 1, 0) == false){
    return false;
  }
  //lua_pop(this->Lua, 1);
  return true;
}

bool LuaFunction::Call(const char *functionName) {
  if (!this->Lua) {
    return false;
  }
  lua_getglobal(this->Lua, functionName);
  if (this->pcall(0, 0, 0) == false) {
    return false;
  }
  //lua_pop(this->Lua, 1);
  return true;
}

bool LuaFunction::Call(const char *functionName, const char *const string,
                       size_t &length, std::string &result) {
  if (!this->Lua) {
    return false;
  }
  lua_getglobal(this->Lua, functionName);
  lua_pushlstring(this->Lua, string, length);

  if (this->pcall(1, 1, 0) == false){
    return false;
  }
  if  (lua_isstring(this->Lua, -1) == false) {
    lua_pop(this->Lua, 1);
    return false;
  }
  size_t l{0};
  const char *buffer{lua_tolstring(this->Lua, -1, &l)};
  if ((!buffer) || (l == 0)) {
    lua_pop(this->Lua, 1);
    return false;
  }
  length = l;
  result = std::string{buffer, length};
  lua_pop(this->Lua, 1);
  return true;
}

bool LuaFunction::Call(const char *functionName, const std::string arg,
                       std::string &result) {
  if (!this->Lua) {
    return false;
  }
  lua_getglobal(this->Lua, functionName);
  lua_pushlstring(this->Lua, arg.c_str(), arg.length());

  if (this->pcall(1, 1, 0) == false){
    return false;
  }
  if  (lua_isstring(this->Lua, -1) == false) {
    lua_pop(this->Lua, 1);
    return false;
  }
  result = lua_tostring(this->Lua, -1);
  lua_pop(this->Lua, 1);
  return true;
}

bool LuaFunction::Call(const char *functionName, double &result) {
  if (!this->Lua) {
    return false;
  }
  lua_getglobal(this->Lua, functionName);

  if (this->pcall(0, 1, 0) == false)
    return false;
  if (lua_isnumber(this->Lua, -1) == false) {
    lua_pop(this->Lua, 1);
    return false;
  }
  result = lua_tonumber(this->Lua, -1);
  lua_pop(this->Lua, 1);
  return true;
}

bool LuaFunction::Push(Lua_callback_function function,
                       const char *functionName) {
  if (!this->Lua)
    return false;

  lua_pushcfunction(this->Lua, function);
  lua_setglobal(this->Lua, functionName);
  return true;
}

bool LuaFunction::pcall(int nargs, int nresults, int msgh){
  //luaL_traceback(this->Lua, this->Lua, nullptr, 0);

  const int call {lua_pcall(this->Lua, nargs, nresults, msgh)};
  if (call == LUA_OK){
    return true;
  }
 //std::cerr << "\tTraceback: " << lua_tostring(this->Lua, -1);
 // lua_pop(this->Lua, 1);
  std::cerr << LUA_PREFIX << "Error: pcall failed. Code: ";
  std::cerr << call;
  std::cerr << ", '" << lua_tostring(this->Lua, -1) << "'\n";
  lua_pop(this->Lua, 1);
  return false;
}<commit_msg>Added proper pcall-function for error-outputs<commit_after>#ifndef LUA_FUNCTION_H
#include "LuaFunction.hpp"
#endif

LuaFunction::LuaFunction(LuaAdapter &lua) : Lua{lua.GetLuaState()} {}

LuaFunction::LuaFunction(lua_State *const lua) : Lua{lua} {}

LuaFunction::~LuaFunction() {}

bool LuaFunction::Call(const char *functionName, const unsigned short int argc,
                       const int args[], int &result) {
  if (!this->Lua) {
    return false;
  }
  lua_getglobal(this->Lua, functionName);

  for (unsigned char i = 0; i < argc; i++)
    if (args + i)
      lua_pushnumber(this->Lua, args[i]);
  if (this->pcall(argc, 1, 0) == false) {
    return false;
  }

  if (lua_isnumber(this->Lua, -1)) {
    result = lua_tointeger(this->Lua, -1);
  }
  lua_pop(this->Lua, 1);
  return true;
}

bool LuaFunction::Call(const char *functionName, const char *const string,
                       const size_t length) {
  if (!this->Lua) {
    return false;
  }
  lua_getglobal(this->Lua, functionName);
  lua_pushlstring(this->Lua, string, length);
  if (this->pcall(1, 1, 0) == false){
    return false;
  }
  //lua_pop(this->Lua, 1);
  return true;
}

bool LuaFunction::Call(const char *functionName) {
  if (!this->Lua) {
    return false;
  }
  lua_getglobal(this->Lua, functionName);
  if (this->pcall(0, 0, 0) == false) {
    return false;
  }
  //lua_pop(this->Lua, 1);
  return true;
}

bool LuaFunction::Call(const char *functionName, const char *const string,
                       size_t &length, std::string &result) {
  if (!this->Lua) {
    return false;
  }
  lua_getglobal(this->Lua, functionName);
  lua_pushlstring(this->Lua, string, length);

  if (this->pcall(1, 1, 0) == false){
    return false;
  }
  if  (lua_isstring(this->Lua, -1) == false) {
    lua_pop(this->Lua, 1);
    return false;
  }
  size_t l{0};
  const char *buffer{lua_tolstring(this->Lua, -1, &l)};
  if ((!buffer) || (l == 0)) {
    lua_pop(this->Lua, 1);
    return false;
  }
  length = l;
  result = std::string{buffer, length};
  lua_pop(this->Lua, 1);
  return true;
}

bool LuaFunction::Call(const char *functionName, const std::string arg,
                       std::string &result) {
  if (!this->Lua) {
    return false;
  }
  lua_getglobal(this->Lua, functionName);
  lua_pushlstring(this->Lua, arg.c_str(), arg.length());

  if (this->pcall(1, 1, 0) == false){
    return false;
  }
  if  (lua_isstring(this->Lua, -1) == false) {
    lua_pop(this->Lua, 1);
    return false;
  }
  result = lua_tostring(this->Lua, -1);
  lua_pop(this->Lua, 1);
  return true;
}

bool LuaFunction::Call(const char *functionName, double &result) {
  if (!this->Lua) {
    return false;
  }
  lua_getglobal(this->Lua, functionName);

  if (this->pcall(0, 1, 0) == false)
    return false;
  if (lua_isnumber(this->Lua, -1) == false) {
    lua_pop(this->Lua, 1);
    return false;
  }
  result = lua_tonumber(this->Lua, -1);
  lua_pop(this->Lua, 1);
  return true;
}

bool LuaFunction::Push(Lua_callback_function function,
                       const char *functionName) {
  if (!this->Lua)
    return false;

  lua_pushcfunction(this->Lua, function);
  lua_setglobal(this->Lua, functionName);
  return true;
}

bool LuaFunction::pcall(int nargs, int nresults, int msgh){
  const int call {lua_pcall(this->Lua, nargs, nresults, msgh)};
  if (call == LUA_OK){
    return true;
  }
  std::cerr << LUA_PREFIX << "Error: pcall failed. Code: ";
  std::cerr << call;
  std::cerr << ", '" << lua_tostring(this->Lua, -1) << "'\n";
  lua_pop(this->Lua, 1);
  return false;
}<|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

#include <AEEStdDef.h>
#include <AEEStdErr.h>
#include <remote.h>
#include <rpcmem.h>

#include <algorithm>
#include <ios>
#include <iostream>
#include <string>
#include <vector>

#include "launcher_core.h"
#include "launcher_rpc.h"

AEEResult enable_unsigned_pd(bool enable) {
  remote_rpc_control_unsigned_module data{static_cast<int>(enable), CDSP_DOMAIN_ID};
  AEEResult rc = remote_session_control(DSPRPC_CONTROL_UNSIGNED_MODULE, &data, sizeof(data));
  if (rc != AEE_SUCCESS) {
    std::cout << "error " << (enable ? "enabling" : "disabling") << " unsigned PD\n";
  }
  return rc;
}

AEEResult set_remote_stack_size(int size) {
  remote_rpc_thread_params th_data{CDSP_DOMAIN_ID, -1, size};
  AEEResult rc = remote_session_control(FASTRPC_THREAD_PARAMS, &th_data, sizeof(th_data));
  if (rc != AEE_SUCCESS) {
    std::cout << "error setting remote stack size: " << std::hex << rc << '\n';
  }
  return rc;
}

struct RPCChannel : public ExecutionSession {
  explicit RPCChannel(const std::string& uri) {
    enable_unsigned_pd(true);
    set_remote_stack_size(128 * 1024);

    int rc = launcher_rpc_open(uri.c_str(), &handle);
    if (rc != AEE_SUCCESS) {
      handle = -1;
    }
  }

  ~RPCChannel() {
    if (handle == -1) {
      return;
    }

    for (void* ptr : allocations) {
      rpcmem_free(ptr);
    }
    if (model_loaded) {
      unload_model();
    }
    launcher_rpc_close(handle);
    handle = -1;
  }

  void* alloc_mem(size_t nbytes, size_t align) override {
    void* host_ptr = rpcmem_alloc(RPCMEM_HEAP_ID_SYSTEM, RPCMEM_DEFAULT_FLAGS, nbytes);
    if (host_ptr != nullptr) {
      allocations.push_back(host_ptr);
    }
    return host_ptr;
  }

  void free_mem(void* addr) override {
    auto f = std::find(allocations.begin(), allocations.end(), addr);
    if (f != allocations.end()) {
      allocations.erase(f);
      rpcmem_free(addr);
    }
  }

  bool load_model(const std::string& model_path, const std::string& model_json) override {
    AEEResult rc = launcher_rpc_load(handle, model_path.c_str(), model_json.c_str());
    if (rc != AEE_SUCCESS) {
      std::cout << "error loading graph module: " << std::hex << rc << '\n';
    } else {
      model_loaded = true;
    }
    return rc == AEE_SUCCESS;
  }

  bool unload_model() override {
    AEEResult rc = launcher_rpc_unload(handle);
    if (rc != AEE_SUCCESS) {
      std::cout << "error unloading model: " << std::hex << rc << '\n';
    }
    model_loaded = false;
    return rc == AEE_SUCCESS;
  }

  bool set_input(int input_idx, const tensor_meta* input_meta, const void* input_data) override {
    AEEResult rc = launcher_rpc_set_input(
        handle, input_idx, reinterpret_cast<const unsigned char*>(input_meta),
        input_meta->meta_size(), reinterpret_cast<const unsigned char*>(input_data),
        input_meta->data_size());
    if (rc != AEE_SUCCESS) {
      std::cout << "error setting model input no." << input_idx << ": " << std::hex << rc << '\n';
    }
    return rc == AEE_SUCCESS;
  }

  bool run(uint64_t* pcycles, uint64_t* usecs) override {
    AEEResult rc = launcher_rpc_run(handle, pcycles, usecs);
    if (rc != AEE_SUCCESS) {
      std::cout << "error running model: " << std::hex << rc << '\n';
    }
    return rc == AEE_SUCCESS;
  }

  bool get_num_outputs(int* num_outputs) override {
    AEEResult rc = launcher_rpc_get_num_outputs(handle, num_outputs);
    if (rc != AEE_SUCCESS) {
      std::cout << "error getting number of outputs: " << std::hex << rc << '\n';
    }
    return rc == AEE_SUCCESS;
  }

  bool get_output(int output_idx, tensor_meta* output_meta, int meta_size, void* output_data,
                  int data_size) override {
    AEEResult rc = launcher_rpc_get_output(
        handle, output_idx, reinterpret_cast<unsigned char*>(output_meta), meta_size,
        reinterpret_cast<unsigned char*>(output_data), data_size);
    if (rc != AEE_SUCCESS) {
      std::cout << "error getting output no." << output_idx << ": " << std::hex << rc << '\n';
    }
    return rc == AEE_SUCCESS;
  }

  bool model_loaded = false;
  remote_handle64 handle = -1;
  std::vector<void*> allocations;
};

ExecutionSession* create_execution_session() {
  auto* session = new RPCChannel(launcher_rpc_URI CDSP_DOMAIN);
  if (session->handle == -1) {
    delete session;
    session = nullptr;
    std::cout << "Error opening FastRPC channel\n";
  }
  return session;
}
<commit_msg>[Hexagon] Don't use {} initialization with FastRPC structures (#9033)<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

#include <AEEStdDef.h>
#include <AEEStdErr.h>
#include <remote.h>
#include <rpcmem.h>

#include <algorithm>
#include <ios>
#include <iostream>
#include <string>
#include <vector>

#include "launcher_core.h"
#include "launcher_rpc.h"

AEEResult enable_unsigned_pd(bool enable) {
  remote_rpc_control_unsigned_module data;
  data.domain = CDSP_DOMAIN_ID;
  data.enable = static_cast<int>(enable);
  AEEResult rc = remote_session_control(DSPRPC_CONTROL_UNSIGNED_MODULE, &data, sizeof(data));
  if (rc != AEE_SUCCESS) {
    std::cout << "error " << (enable ? "enabling" : "disabling") << " unsigned PD\n";
  }
  return rc;
}

AEEResult set_remote_stack_size(int size) {
  remote_rpc_thread_params data;
  data.domain = CDSP_DOMAIN_ID;
  data.prio = -1;
  data.stack_size = size;
  AEEResult rc = remote_session_control(FASTRPC_THREAD_PARAMS, &data, sizeof(data));
  if (rc != AEE_SUCCESS) {
    std::cout << "error setting remote stack size: " << std::hex << rc << '\n';
  }
  return rc;
}

struct RPCChannel : public ExecutionSession {
  explicit RPCChannel(const std::string& uri) {
    enable_unsigned_pd(true);
    set_remote_stack_size(128 * 1024);

    int rc = launcher_rpc_open(uri.c_str(), &handle);
    if (rc != AEE_SUCCESS) {
      handle = -1;
    }
  }

  ~RPCChannel() {
    if (handle == -1) {
      return;
    }

    for (void* ptr : allocations) {
      rpcmem_free(ptr);
    }
    if (model_loaded) {
      unload_model();
    }
    launcher_rpc_close(handle);
    handle = -1;
  }

  void* alloc_mem(size_t nbytes, size_t align) override {
    void* host_ptr = rpcmem_alloc(RPCMEM_HEAP_ID_SYSTEM, RPCMEM_DEFAULT_FLAGS, nbytes);
    if (host_ptr != nullptr) {
      allocations.push_back(host_ptr);
    }
    return host_ptr;
  }

  void free_mem(void* addr) override {
    auto f = std::find(allocations.begin(), allocations.end(), addr);
    if (f != allocations.end()) {
      allocations.erase(f);
      rpcmem_free(addr);
    }
  }

  bool load_model(const std::string& model_path, const std::string& model_json) override {
    AEEResult rc = launcher_rpc_load(handle, model_path.c_str(), model_json.c_str());
    if (rc != AEE_SUCCESS) {
      std::cout << "error loading graph module: " << std::hex << rc << '\n';
    } else {
      model_loaded = true;
    }
    return rc == AEE_SUCCESS;
  }

  bool unload_model() override {
    AEEResult rc = launcher_rpc_unload(handle);
    if (rc != AEE_SUCCESS) {
      std::cout << "error unloading model: " << std::hex << rc << '\n';
    }
    model_loaded = false;
    return rc == AEE_SUCCESS;
  }

  bool set_input(int input_idx, const tensor_meta* input_meta, const void* input_data) override {
    AEEResult rc = launcher_rpc_set_input(
        handle, input_idx, reinterpret_cast<const unsigned char*>(input_meta),
        input_meta->meta_size(), reinterpret_cast<const unsigned char*>(input_data),
        input_meta->data_size());
    if (rc != AEE_SUCCESS) {
      std::cout << "error setting model input no." << input_idx << ": " << std::hex << rc << '\n';
    }
    return rc == AEE_SUCCESS;
  }

  bool run(uint64_t* pcycles, uint64_t* usecs) override {
    AEEResult rc = launcher_rpc_run(handle, pcycles, usecs);
    if (rc != AEE_SUCCESS) {
      std::cout << "error running model: " << std::hex << rc << '\n';
    }
    return rc == AEE_SUCCESS;
  }

  bool get_num_outputs(int* num_outputs) override {
    AEEResult rc = launcher_rpc_get_num_outputs(handle, num_outputs);
    if (rc != AEE_SUCCESS) {
      std::cout << "error getting number of outputs: " << std::hex << rc << '\n';
    }
    return rc == AEE_SUCCESS;
  }

  bool get_output(int output_idx, tensor_meta* output_meta, int meta_size, void* output_data,
                  int data_size) override {
    AEEResult rc = launcher_rpc_get_output(
        handle, output_idx, reinterpret_cast<unsigned char*>(output_meta), meta_size,
        reinterpret_cast<unsigned char*>(output_data), data_size);
    if (rc != AEE_SUCCESS) {
      std::cout << "error getting output no." << output_idx << ": " << std::hex << rc << '\n';
    }
    return rc == AEE_SUCCESS;
  }

  bool model_loaded = false;
  remote_handle64 handle = -1;
  std::vector<void*> allocations;
};

ExecutionSession* create_execution_session() {
  auto* session = new RPCChannel(launcher_rpc_URI CDSP_DOMAIN);
  if (session->handle == -1) {
    delete session;
    session = nullptr;
    std::cout << "Error opening FastRPC channel\n";
  }
  return session;
}
<|endoftext|>


<commit_before>/*
 * RenderItemDistanceMetric.h
 *
 *  Created on: Feb 16, 2009
 *      Author: struktured
 */

#ifndef RenderItemDISTANCEMETRIC_H_
#define RenderItemDISTANCEMETRIC_H_

#include "Common.hpp"
#include "Renderable.hpp"
#include <limits>
#include <functional>
#include <map>

struct TypeIdPair {
	TypeIdPair(const std::type_info & info1, const std::type_info & info2): id1(info1.name()), id2(info2.name()) {}
	TypeIdPair(const std::string & id1, const std::string & id2): id1(id1), id2(id2) {}
	std::string id1;
	std::string id2;
	inline bool operator<(const TypeIdPair & rhs) const {
		return this->id1 < rhs.id1 || (this->id1 == rhs.id1 && this->id2 < rhs.id2);
	}

	inline bool operator>(const TypeIdPair & rhs) const {
		return !operator<(rhs) && !operator==(rhs);
	}

	inline bool operator==(const TypeIdPair & rhs) const {
			return this->id1 == rhs.id1 && this->id2 == rhs.id2;
	}
};

/// Compares two render items and returns zero if they are virtually equivalent and large values
/// when they are dissimilar. If two render items cannot be compared, NOT_COMPARABLE_VALUE is returned.
class RenderItemDistanceMetric : public std::binary_function<const RenderItem*, const RenderItem*, double> {
public:
  const static double NOT_COMPARABLE_VALUE;
  virtual double operator()(const RenderItem * r1, const RenderItem * r2) const = 0;
  virtual TypeIdPair typeIdPair() const = 0;
};

// A base class to construct render item distance metrics. Just specify your two concrete
// render item types as template parameters and override the computeDistance() function.
template <class R1, class R2>
class RenderItemDistance : public RenderItemDistanceMetric {

protected:
// Override to create your own distance metric for your specified custom types.
virtual double computeDistance(const R1 * r1, const R2 * r2) const = 0;

public:

inline virtual double operator()(const RenderItem * r1, const RenderItem * r2) const {
	if (supported(r1, r2))
		return computeDistance(dynamic_cast<const R1*>(r1), dynamic_cast<const R2*>(r2));
	else if (supported(r2,r1))
		return computeDistance(dynamic_cast<const R2*>(r2), dynamic_cast<const R2*>(r1));
	else
		return NOT_COMPARABLE_VALUE;
}

// Returns true if and only if r1 and r2 are of type R1 and R2 respectively.
inline bool supported(const RenderItem * r1, const RenderItem * r2) const {
	return typeid(r1) == typeid(const R1 *) && typeid(r2) == typeid(const R2 *);
}

inline TypeIdPair typeIdPair() const {
	return TypeIdPair(typeid(const R1*).name(), typeid(const R2*).name());
}

};

class RTIRenderItemDistance : public RenderItemDistance<RenderItem, RenderItem> {
public:

	RTIRenderItemDistance() {}
	virtual ~RTIRenderItemDistance() {}

protected:
	virtual inline double computeDistance(const RenderItem * lhs, const RenderItem * rhs) const {
		if (typeid(lhs) == typeid(rhs))
			return 0.0;
		else
			return NOT_COMPARABLE_VALUE;
	}

};

class ShapeXYDistance : public RenderItemDistance<Shape, Shape> {

public:

	ShapeXYDistance() {}
	virtual ~ShapeXYDistance() {}

protected:

	virtual inline double computeDistance(const Shape * lhs, const Shape * rhs) const {
			return (meanSquaredError(lhs->x, rhs->x) + meanSquaredError(lhs->y, rhs->y)) / 2;
	}

};

class MasterRenderItemDistance : public RenderItemDistance<RenderItem, RenderItem> {

typedef std::map<TypeIdPair, RenderItemDistanceMetric*> DistanceMetricMap;
public:

	MasterRenderItemDistance() {}
	virtual ~MasterRenderItemDistance() {}

	inline void addMetric(RenderItemDistanceMetric * fun) {
		_distanceMetricMap[fun->typeIdPair()] = fun;
	}

protected:
	virtual inline double computeDistance(const RenderItem * lhs, const RenderItem * rhs) const {

		RenderItemDistanceMetric * metric;

		TypeIdPair pair(typeid(lhs), typeid(rhs));
		if (_distanceMetricMap.count(pair)) {
			metric = _distanceMetricMap[pair];
		} else if (_distanceMetricMap.count(pair = TypeIdPair(typeid(lhs), typeid(rhs)))) {
			metric = _distanceMetricMap[pair];
		} else {
			metric  = 0;
		}

		// If specialized metric exists, use it to get higher granularity
		// of correctness
		if (metric)
			return (*metric)(lhs, rhs);
		else // Failing that, use rtti and return 0 if they match, max value otherwise
			return _rttiDistance(lhs,rhs);
	}

private:
	mutable RTIRenderItemDistance _rttiDistance;
	mutable DistanceMetricMap _distanceMetricMap;
};

#endif /* RenderItemDISTANCEMETRIC_H_ */
<commit_msg>bug fix<commit_after>/*
 * RenderItemDistanceMetric.h
 *
 *  Created on: Feb 16, 2009
 *      Author: struktured
 */

#ifndef RenderItemDISTANCEMETRIC_H_
#define RenderItemDISTANCEMETRIC_H_

#include "Common.hpp"
#include "Renderable.hpp"
#include <limits>
#include <functional>
#include <map>

struct TypeIdPair {
	TypeIdPair(const std::type_info & info1, const std::type_info & info2): id1(info1.name()), id2(info2.name()) {}
	TypeIdPair(const std::string & id1, const std::string & id2): id1(id1), id2(id2) {}
	std::string id1;
	std::string id2;
	inline bool operator<(const TypeIdPair & rhs) const {
		return this->id1 < rhs.id1 || (this->id1 == rhs.id1 && this->id2 < rhs.id2);
	}

	inline bool operator>(const TypeIdPair & rhs) const {
		return !operator<(rhs) && !operator==(rhs);
	}

	inline bool operator==(const TypeIdPair & rhs) const {
			return this->id1 == rhs.id1 && this->id2 == rhs.id2;
	}
};

/// Compares two render items and returns zero if they are virtually equivalent and large values
/// when they are dissimilar. If two render items cannot be compared, NOT_COMPARABLE_VALUE is returned.
class RenderItemDistanceMetric : public std::binary_function<const RenderItem*, const RenderItem*, double> {
public:
  const static double NOT_COMPARABLE_VALUE;
  virtual double operator()(const RenderItem * r1, const RenderItem * r2) const = 0;
  virtual TypeIdPair typeIdPair() const = 0;
};

// A base class to construct render item distance metrics. Just specify your two concrete
// render item types as template parameters and override the computeDistance() function.
template <class R1, class R2>
class RenderItemDistance : public RenderItemDistanceMetric {

protected:
// Override to create your own distance metric for your specified custom types.
virtual double computeDistance(const R1 * r1, const R2 * r2) const = 0;

public:

inline virtual double operator()(const RenderItem * r1, const RenderItem * r2) const {
	if (supported(r1, r2))
		return computeDistance(dynamic_cast<const R1*>(r1), dynamic_cast<const R2*>(r2));
	else if (supported(r2,r1))
		return computeDistance(dynamic_cast<const R2*>(r2), dynamic_cast<const R2*>(r1));
	else
		return NOT_COMPARABLE_VALUE;
}

// Returns true if and only if r1 and r2 are of type R1 and R2 respectively.
inline bool supported(const RenderItem * r1, const RenderItem * r2) const {
	return typeid(r1) == typeid(const R1 *) && typeid(r2) == typeid(const R2 *);
}

inline TypeIdPair typeIdPair() const {
	return TypeIdPair(typeid(const R1*).name(), typeid(const R2*).name());
}

};

class RTIRenderItemDistance : public RenderItemDistance<RenderItem, RenderItem> {
public:

	RTIRenderItemDistance() {}
	virtual ~RTIRenderItemDistance() {}

protected:
	virtual inline double computeDistance(const RenderItem * lhs, const RenderItem * rhs) const {
		if (typeid(lhs) == typeid(rhs))
			return 0.0;
		else
			return NOT_COMPARABLE_VALUE;
	}

};

class ShapeXYDistance : public RenderItemDistance<Shape, Shape> {

public:

	ShapeXYDistance() {}
	virtual ~ShapeXYDistance() {}

protected:

	virtual inline double computeDistance(const Shape * lhs, const Shape * rhs) const {
			return (meanSquaredError(lhs->x, rhs->x) + meanSquaredError(lhs->y, rhs->y)) / 2;
	}

};

class MasterRenderItemDistance : public RenderItemDistance<RenderItem, RenderItem> {

typedef std::map<TypeIdPair, RenderItemDistanceMetric*> DistanceMetricMap;
public:

	MasterRenderItemDistance() {}
	virtual ~MasterRenderItemDistance() {}

	inline void addMetric(RenderItemDistanceMetric * fun) {
		_distanceMetricMap[fun->typeIdPair()] = fun;
	}

protected:
	virtual inline double computeDistance(const RenderItem * lhs, const RenderItem * rhs) const {

		RenderItemDistanceMetric * metric;

		TypeIdPair pair(typeid(lhs), typeid(rhs));
		if (_distanceMetricMap.count(pair)) {
			metric = _distanceMetricMap[pair];
		} else if (_distanceMetricMap.count(pair = TypeIdPair(typeid(rhs), typeid(lhs)))) {
			metric = _distanceMetricMap[pair];
		} else {
			metric  = 0;
		}

		// If specialized metric exists, use it to get higher granularity
		// of correctness
		if (metric)
			return (*metric)(lhs, rhs);
		else // Failing that, use rtti and return 0 if they match, max value otherwise
			return _rttiDistance(lhs,rhs);
	}

private:
	mutable RTIRenderItemDistance _rttiDistance;
	mutable DistanceMetricMap _distanceMetricMap;
};

#endif /* RenderItemDISTANCEMETRIC_H_ */
<|endoftext|>


<commit_before>#include "Logger.h"
#include <sstream>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

Logger* Logger::logger_instance = NULL;

Logger::Logger(): nivelDeLog(LOG_DEBUG) {
	string timeStamp = "output.html";
	struct stat buffer;
	if (stat(timeStamp.c_str(), &buffer)) {
		archivoLog.open( timeStamp.c_str() );
		archivoLog << "  Fecha y  hora\t\t" << " Tipo\t\t" << "Lugar del mensaje\t\t\t" << "Mensaje" << endl ;
	} else {
		archivoLog.open(timeStamp.c_str(), std::ofstream::app);
	}
	lock = new LockFile(timeStamp.c_str());
}

Logger& Logger::instance() {
	if (!logger_instance) {
		logger_instance = new Logger();
	}
	return *logger_instance;
}

void Logger::close() {
	if (logger_instance)
		delete logger_instance;
	logger_instance = NULL;
}

Logger::~Logger() {
	delete lock;
}

void Logger::warn(const string& tag, const string& msg){
	if ((nivelDeLog & LOG_WARN) == 0)
		return;

	log(tag, msg, LOG_WARN);
}

void Logger::error(const string& tag, const string& msg) {
	if ((nivelDeLog & LOG_ERROR) == 0)
		return;

	log(tag, msg, LOG_ERROR);
}

void Logger::debug(const string& tag, const string& msg) {
	if (nivelDeLog != LOG_DEBUG)
		return;
	log(tag, msg, LOG_DEBUG);
}

void Logger::info(const string& tag, const string& msg) {
	if ((nivelDeLog & LOG_INFO) == 0)
		return;

	log(tag, msg, LOG_INFO);
}

void Logger::fatal(const string& tag, const string& msg) {
	if ((nivelDeLog & LOG_FATAL) == 0)
		return;
	log(tag, msg, LOG_FATAL);
}

void Logger::log(const string& tag, const string& msg, int level) {
	lock->tomarLock();
	struct tm *p_local_t;
	time_t t = time(NULL);
	p_local_t = localtime(&t);

	string sNivel("[INFO]\t");
	switch (level) {
	case LOG_FATAL:
		sNivel = "[FATAL]\t";
		break;
	case LOG_ERROR:
		sNivel = "[ERROR]\t";
		break;
	case LOG_WARN:
		sNivel = "[WARN]\t";
		break;
	case LOG_INFO:
		sNivel = "[INFO]\t";
		break;
	case LOG_DEBUG:
		sNivel = "[DEBUG]\t";
		break;
	default:
		break;
	}
	std::stringstream str;
	str << "[" << p_local_t->tm_mday << "-" << 1 + p_local_t->tm_mon
			<< "-" << 1900 + p_local_t->tm_year << " "
			<< p_local_t->tm_hour << ":" << p_local_t->tm_min
			<< ":" << p_local_t->tm_sec << "]";
	std::string fecha;
	str >> fecha;
	printMessageFormatted(fecha, sNivel, tag, msg);
	archivoLog.flush();
	lock->liberarLock();
}

void Logger::clear() {
	lock->tomarLock();
	string timeStamp = "output.html";
	archivoLog.close();
	archivoLog.open(timeStamp.c_str());
	printHeader();
	lock->liberarLock();
}

void Logger::setLogLevel(int nivelLog){
	lock->tomarLock();
	nivelDeLog = nivelLog;
	lock->liberarLock();
}

void Logger::printHeader() {
	archivoLog << "
" << std::endl;
	archivoLog << "
Fecha y  hora	Tipo	Lugar del mensaje	Mensaje
" << std::endl;
}

void Logger::printMessageFormatted(const std::string& fecha, const std::string& level,
		const std::string& tag, const std::string& message) {
	archivoLog << "
" << std::endl;
	archivoLog << "" << fecha << "	"<<std::endl;
	archivoLog << "" << level << "	"<<std::endl;
	archivoLog << "" << tag << "	" <<std::endl;
	archivoLog << "" << message << "	" <<std::endl;
	archivoLog << "
" << std::endl;
}
<commit_msg>logger html<commit_after>#include "Logger.h"
#include <sstream>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

Logger* Logger::logger_instance = NULL;

Logger::Logger(): nivelDeLog(LOG_DEBUG) {
	string timeStamp = "output.html";
	struct stat buffer;
	if (stat(timeStamp.c_str(), &buffer)) {
		archivoLog.open( timeStamp.c_str() );
		archivoLog << "  Fecha y  hora\t\t" << " Tipo\t\t" << "Lugar del mensaje\t\t\t" << "Mensaje" << endl ;
	} else {
		archivoLog.open(timeStamp.c_str(), std::ofstream::app);
	}
	lock = new LockFile(timeStamp.c_str());
}

Logger& Logger::instance() {
	if (!logger_instance) {
		logger_instance = new Logger();
	}
	return *logger_instance;
}

void Logger::close() {
	if (logger_instance)
		delete logger_instance;
	logger_instance = NULL;
}

Logger::~Logger() {
	delete lock;
}

void Logger::warn(const string& tag, const string& msg){
	if ((nivelDeLog & LOG_WARN) == 0)
		return;

	log(tag, msg, LOG_WARN);
}

void Logger::error(const string& tag, const string& msg) {
	if ((nivelDeLog & LOG_ERROR) == 0)
		return;

	log(tag, msg, LOG_ERROR);
}

void Logger::debug(const string& tag, const string& msg) {
	if (nivelDeLog != LOG_DEBUG)
		return;
	log(tag, msg, LOG_DEBUG);
}

void Logger::info(const string& tag, const string& msg) {
	if ((nivelDeLog & LOG_INFO) == 0)
		return;

	log(tag, msg, LOG_INFO);
}

void Logger::fatal(const string& tag, const string& msg) {
	if ((nivelDeLog & LOG_FATAL) == 0)
		return;
	log(tag, msg, LOG_FATAL);
}

void Logger::log(const string& tag, const string& msg, int level) {
	lock->tomarLock();
	struct tm *p_local_t;
	time_t t = time(NULL);
	p_local_t = localtime(&t);

	string sNivel("[INFO]\t");
	switch (level) {
	case LOG_FATAL:
		sNivel = "[FATAL]\t";
		break;
	case LOG_ERROR:
		sNivel = "[ERROR]\t";
		break;
	case LOG_WARN:
		sNivel = "[WARN]\t";
		break;
	case LOG_INFO:
		sNivel = "[INFO]\t";
		break;
	case LOG_DEBUG:
		sNivel = "[DEBUG]\t";
		break;
	default:
		break;
	}
	std::stringstream str;
	str << p_local_t->tm_mday << "-" << 1 + p_local_t->tm_mon
			<< "-" << 1900 + p_local_t->tm_year << " "
			<< p_local_t->tm_hour << ":" << p_local_t->tm_min
			<< ":" << p_local_t->tm_sec << "]";
	std::string fecha;
	str >> fecha;
	printMessageFormatted(fecha, sNivel, tag, msg);
	archivoLog.flush();
	lock->liberarLock();
}

void Logger::clear() {
	lock->tomarLock();
	string timeStamp = "output.html";
	archivoLog.close();
	archivoLog.open(timeStamp.c_str());
	printHeader();
	lock->liberarLock();
}

void Logger::setLogLevel(int nivelLog){
	lock->tomarLock();
	nivelDeLog = nivelLog;
	lock->liberarLock();
}

void Logger::printHeader() {
	archivoLog << "
" << std::endl;
	archivoLog << "
Fecha y  hora	Tipo	Lugar del mensaje	Mensaje
" << std::endl;
}

void Logger::printMessageFormatted(const std::string& fecha, const std::string& level,
		const std::string& tag, const std::string& message) {
	archivoLog << "
" << std::endl;
	archivoLog << "" << fecha << "	"<<std::endl;
	archivoLog << "" << level << "	"<<std::endl;
	archivoLog << "" << tag << "	" <<std::endl;
	archivoLog << "" << message << "	" <<std::endl;
	archivoLog << "
" << std::endl;
}
<|endoftext|>


<commit_before>#include <test/utility.hpp>
#include <gtest/gtest.h>
#include <fstream>
#include <string>
#include <stdexcept>

using cmdstan::test::convert_model_path;
using cmdstan::test::multiple_command_separator;
using cmdstan::test::run_command;
using cmdstan::test::run_command_output;

class CmdStan : public testing::Test {
 public:
  void SetUp() {
    model_path = {"src", "test", "test-models", "gq_model"};
    data_file_path = {"src", "test", "test-models", "gq_model.data.json"};
    model_path_2 = {"src", "test", "test-models", "test_model"};
    model_path_non_scalar_gq = {"src", "test", "test-models", "gq_non_scalar"};
    output_file_path = {"/dev", "null"};
    fitted_params_file_path
        = {"src", "test", "test-models", "gq_model_output.csv"};
    fitted_params_file_path_2
        = {"src", "test", "test-models", "test_model_output.csv"};
    fitted_params_file_path_empty = {"src", "test", "test-models", "empty.csv"};
    fitted_params_non_scalar_gq
        = {"src", "test", "test-models", "gq_non_scalar.csv"};
    default_file_path = {"src", "test", "test-models", "output.csv"};
  }

  std::vector<std::string> model_path;
  std::vector<std::string> data_file_path;
  std::vector<std::string> model_path_2;
  std::vector<std::string> model_path_non_scalar_gq;
  std::vector<std::string> output_file_path;
  std::vector<std::string> fitted_params_file_path;
  std::vector<std::string> fitted_params_file_path_2;
  std::vector<std::string> fitted_params_file_path_empty;
  std::vector<std::string> fitted_params_non_scalar_gq;
  std::vector<std::string> default_file_path;
};

TEST_F(CmdStan, generate_quantities_good) {
  std::stringstream ss;
  ss << convert_model_path(model_path)
     << " data file=" << convert_model_path(data_file_path)
     << " output file=" << convert_model_path(output_file_path)
     << " method=generate_quantities fitted_params="
     << convert_model_path(fitted_params_file_path);
  std::string cmd = ss.str();
  run_command_output out = run_command(cmd);
  ASSERT_FALSE(out.hasError);
}

TEST_F(CmdStan, generate_quantities_non_scalar_good) {
  std::stringstream ss;
  ss << convert_model_path(model_path_non_scalar_gq)
     << " output file=" << convert_model_path(output_file_path)
     << " method=generate_quantities fitted_params="
     << convert_model_path(fitted_params_non_scalar_gq);
  std::string cmd = ss.str();
  run_command_output out = run_command(cmd);
  ASSERT_FALSE(out.hasError);
}

TEST_F(CmdStan, generate_quantities_bad_nodata) {
  std::stringstream ss;
  ss << convert_model_path(model_path)
     << " output file=" << convert_model_path(output_file_path)
     << " method=generate_quantities fitted_params="
     << convert_model_path(fitted_params_file_path_empty) << " 2>&1";
  std::string cmd = ss.str();
  run_command_output out = run_command(cmd);
  ASSERT_TRUE(out.hasError);
}

TEST_F(CmdStan, generate_quantities_bad_no_gqs) {
  std::stringstream ss;
  ss << convert_model_path(model_path_2)
     << " output file=" << convert_model_path(output_file_path)
     << " method=generate_quantities "
     << " fitted_params=" << convert_model_path(fitted_params_file_path_2)
     << " 2>&1";
  std::string cmd = ss.str();
  run_command_output out = run_command(cmd);
  ASSERT_TRUE(out.hasError);
}

TEST_F(CmdStan, generate_quantities_wrong_csv) {
  std::stringstream ss;
  ss << convert_model_path(model_path)
     << " data file=" << convert_model_path(data_file_path)
     << " output file=" << convert_model_path(output_file_path)
     << " method=generate_quantities fitted_params="
     << convert_model_path(fitted_params_file_path_2) << " 2>&1";
  std::string cmd = ss.str();
  run_command_output out = run_command(cmd);
  ASSERT_TRUE(out.hasError);
}

TEST_F(CmdStan, generate_quantities_wrong_csv_2) {
  std::stringstream ss;
  ss << convert_model_path(model_path_2)
     << " data file=" << convert_model_path(data_file_path)
     << " output file=" << convert_model_path(output_file_path)
     << " method=generate_quantities fitted_params="
     << convert_model_path(fitted_params_file_path) << " 2>&1";
  std::string cmd = ss.str();
  run_command_output out = run_command(cmd);
  ASSERT_TRUE(out.hasError);
}

TEST_F(CmdStan, generate_quantities_csv_conflict) {
  std::stringstream ss;
  ss << convert_model_path(model_path)
     << " data file=" << convert_model_path(data_file_path)
     << " output file=" << convert_model_path(default_file_path)
     << " method=generate_quantities fitted_params="
     << convert_model_path(default_file_path); // << " 2>&1";
  std::string cmd = ss.str();
  run_command_output out = run_command(cmd);
  ASSERT_TRUE(out.hasError);
}
<commit_msg>[Jenkins] auto-formatting by clang-format version 6.0.0-1ubuntu2 (tags/RELEASE_600/final)<commit_after>#include <test/utility.hpp>
#include <gtest/gtest.h>
#include <fstream>
#include <string>
#include <stdexcept>

using cmdstan::test::convert_model_path;
using cmdstan::test::multiple_command_separator;
using cmdstan::test::run_command;
using cmdstan::test::run_command_output;

class CmdStan : public testing::Test {
 public:
  void SetUp() {
    model_path = {"src", "test", "test-models", "gq_model"};
    data_file_path = {"src", "test", "test-models", "gq_model.data.json"};
    model_path_2 = {"src", "test", "test-models", "test_model"};
    model_path_non_scalar_gq = {"src", "test", "test-models", "gq_non_scalar"};
    output_file_path = {"/dev", "null"};
    fitted_params_file_path
        = {"src", "test", "test-models", "gq_model_output.csv"};
    fitted_params_file_path_2
        = {"src", "test", "test-models", "test_model_output.csv"};
    fitted_params_file_path_empty = {"src", "test", "test-models", "empty.csv"};
    fitted_params_non_scalar_gq
        = {"src", "test", "test-models", "gq_non_scalar.csv"};
    default_file_path = {"src", "test", "test-models", "output.csv"};
  }

  std::vector<std::string> model_path;
  std::vector<std::string> data_file_path;
  std::vector<std::string> model_path_2;
  std::vector<std::string> model_path_non_scalar_gq;
  std::vector<std::string> output_file_path;
  std::vector<std::string> fitted_params_file_path;
  std::vector<std::string> fitted_params_file_path_2;
  std::vector<std::string> fitted_params_file_path_empty;
  std::vector<std::string> fitted_params_non_scalar_gq;
  std::vector<std::string> default_file_path;
};

TEST_F(CmdStan, generate_quantities_good) {
  std::stringstream ss;
  ss << convert_model_path(model_path)
     << " data file=" << convert_model_path(data_file_path)
     << " output file=" << convert_model_path(output_file_path)
     << " method=generate_quantities fitted_params="
     << convert_model_path(fitted_params_file_path);
  std::string cmd = ss.str();
  run_command_output out = run_command(cmd);
  ASSERT_FALSE(out.hasError);
}

TEST_F(CmdStan, generate_quantities_non_scalar_good) {
  std::stringstream ss;
  ss << convert_model_path(model_path_non_scalar_gq)
     << " output file=" << convert_model_path(output_file_path)
     << " method=generate_quantities fitted_params="
     << convert_model_path(fitted_params_non_scalar_gq);
  std::string cmd = ss.str();
  run_command_output out = run_command(cmd);
  ASSERT_FALSE(out.hasError);
}

TEST_F(CmdStan, generate_quantities_bad_nodata) {
  std::stringstream ss;
  ss << convert_model_path(model_path)
     << " output file=" << convert_model_path(output_file_path)
     << " method=generate_quantities fitted_params="
     << convert_model_path(fitted_params_file_path_empty) << " 2>&1";
  std::string cmd = ss.str();
  run_command_output out = run_command(cmd);
  ASSERT_TRUE(out.hasError);
}

TEST_F(CmdStan, generate_quantities_bad_no_gqs) {
  std::stringstream ss;
  ss << convert_model_path(model_path_2)
     << " output file=" << convert_model_path(output_file_path)
     << " method=generate_quantities "
     << " fitted_params=" << convert_model_path(fitted_params_file_path_2)
     << " 2>&1";
  std::string cmd = ss.str();
  run_command_output out = run_command(cmd);
  ASSERT_TRUE(out.hasError);
}

TEST_F(CmdStan, generate_quantities_wrong_csv) {
  std::stringstream ss;
  ss << convert_model_path(model_path)
     << " data file=" << convert_model_path(data_file_path)
     << " output file=" << convert_model_path(output_file_path)
     << " method=generate_quantities fitted_params="
     << convert_model_path(fitted_params_file_path_2) << " 2>&1";
  std::string cmd = ss.str();
  run_command_output out = run_command(cmd);
  ASSERT_TRUE(out.hasError);
}

TEST_F(CmdStan, generate_quantities_wrong_csv_2) {
  std::stringstream ss;
  ss << convert_model_path(model_path_2)
     << " data file=" << convert_model_path(data_file_path)
     << " output file=" << convert_model_path(output_file_path)
     << " method=generate_quantities fitted_params="
     << convert_model_path(fitted_params_file_path) << " 2>&1";
  std::string cmd = ss.str();
  run_command_output out = run_command(cmd);
  ASSERT_TRUE(out.hasError);
}

TEST_F(CmdStan, generate_quantities_csv_conflict) {
  std::stringstream ss;
  ss << convert_model_path(model_path)
     << " data file=" << convert_model_path(data_file_path)
     << " output file=" << convert_model_path(default_file_path)
     << " method=generate_quantities fitted_params="
     << convert_model_path(default_file_path);  // << " 2>&1";
  std::string cmd = ss.str();
  run_command_output out = run_command(cmd);
  ASSERT_TRUE(out.hasError);
}
<|endoftext|>


<commit_before>/**************************************************************************
**
** This file is part of Doxygen plugin for Qt Creator
**
** Copyright (c) 2009 Kevin Tanguy (kofee@kofee.org).
** Copyright (c) 2015 Fabien Poussin (fabien.poussin@gmail.com).
**
** This plugin 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 plugin 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 General Public License
** along with Doxygen Plugin. If not, see <http://www.gnu.org/licenses/>.
**/

#include "doxygensettingswidget.h"
#include "ui_doxygensettingswidget.h"

DoxygenSettingsWidget::DoxygenSettingsWidget(QWidget* parent)
    : QWidget(parent)
    , ui(new Ui::DoxygenSettingsWidget)
{
    ui->setupUi(this);
    ui->pathChooser_doxygen->setExpectedKind(Utils::PathChooser::Command);
    ui->pathChooser_doxygen->setPromptDialogTitle(tr("Doxygen Command"));
    ui->pathChooser_wizard->setExpectedKind(Utils::PathChooser::Command);
    ui->pathChooser_wizard->setPromptDialogTitle(tr("DoxyWizard Command"));
    // Why do I *have* to call processEvents() to get my QComboBox display the right value?!
    qApp->processEvents();
    connect(ui->styleChooser, SIGNAL(currentIndexChanged(int)), this, SLOT(updateCustomWidgetPart(int)));
}

DoxygenSettingsWidget::~DoxygenSettingsWidget()
{
    delete ui;
}

void DoxygenSettingsWidget::changeEvent(QEvent* e)
{
    QWidget::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

DoxygenSettingsStruct DoxygenSettingsWidget::settings() const
{
    DoxygenSettingsStruct rc;
    rc.doxygenCommand = ui->pathChooser_doxygen->path();
    rc.doxyfileFileName = ui->edit_doxyfileName->text();
    rc.doxywizardCommand = ui->pathChooser_wizard->path();
    rc.style = DoxygenStyle(ui->styleChooser->currentIndex());
    rc.fcomment = Files2Comment(ui->fcommentChooser->currentIndex());
    rc.printBrief = ui->printBriefTag->isChecked();
    rc.shortVarDoc = ui->shortVariableDoc->isChecked();
    rc.verbosePrinting = ui->verbosePrinting->isChecked();
    rc.customBegin = QString(ui->edit_beginTag->text()).replace("\\n", "\n");
    rc.customBrief = QString(ui->edit_briefTag->text()).replace("\\n", "\n");
    rc.customEmptyLine = QString(ui->edit_emptyLineTag->text()).replace("\\n", "\n");
    rc.customEnding = QString(ui->edit_endTag->text()).replace("\\n", "\n");
    rc.customNewLine = QString(ui->edit_newLine->text()).replace("\\n", "\n");
    rc.customShortDoc = QString(ui->edit_shortTag->text()).replace("\\n", "\n");
    rc.customShortDocEnd = QString(ui->edit_shortTagEnd->text()).replace("\\\n", "\n");
    rc.fileComment = ui->fileCommentText->toPlainText();
    rc.fileCommentHeaders = ui->commentHeaderFiles->isChecked();
    rc.fileCommentImpl = ui->commentImplementationFiles->isChecked();
    rc.fileCommentsEnabled = ui->fileComments->isChecked();
    rc.automaticReturnType = ui->autoAddReturnTypes->isChecked();
    return rc;
}

void DoxygenSettingsWidget::setSettings(const DoxygenSettingsStruct& s)
{
    ui->pathChooser_doxygen->setPath(s.doxygenCommand);
    ui->pathChooser_wizard->setPath(s.doxywizardCommand);
    ui->edit_doxyfileName->setText(s.doxyfileFileName);
    ui->styleChooser->setCurrentIndex(s.style);
    ui->fcommentChooser->setCurrentIndex(s.fcomment);
    ui->printBriefTag->setChecked(s.printBrief);
    ui->shortVariableDoc->setChecked(s.shortVarDoc);
    ui->verbosePrinting->setChecked(s.verbosePrinting);
    ui->edit_beginTag->setText(QString(s.customBegin).replace("\n", "\\n"));
    ui->edit_briefTag->setText(QString(s.customBrief).replace("\n", "\\n"));
    ui->edit_emptyLineTag->setText(QString(s.customEmptyLine).replace("\n", "\\n"));
    ui->edit_endTag->setText(QString(s.customEnding).replace("\n", "\\n"));
    ui->edit_newLine->setText(QString(s.customNewLine).replace("\n", "\\n"));
    ui->edit_shortTag->setText(QString(s.customShortDoc).replace("\n", "\\n"));
    ui->edit_shortTagEnd->setText(QString(s.customShortDocEnd).replace("\n", "\\n"));
    ui->fileCommentText->setPlainText(s.fileComment);
    ui->fileComments->setChecked(s.fileCommentsEnabled);
    ui->commentHeaderFiles->setChecked(s.fileCommentHeaders);
    ui->commentImplementationFiles->setChecked(s.fileCommentImpl);
    ui->autoAddReturnTypes->setChecked(s.automaticReturnType);

    updateCustomWidgetPart(s.style);
    on_fileComments_clicked(s.fileCommentsEnabled);
}

void DoxygenSettingsWidget::updateCustomWidgetPart(int index)
{
    ui->customCommentsSettings->setEnabled(index == customDoc);
}

void DoxygenSettingsWidget::on_fileComments_clicked(bool checked)
{
    Files2Comment toComment = Files2Comment(ui->fcommentChooser->currentIndex());
    ui->fileCommentText->setEnabled(checked);
    if (checked == false || toComment == all) {
        checked = false;
        ui->label_filecommentHeaders->setVisible(checked);
        ui->label_filecommentImpl->setVisible(checked);
        ui->commentHeaderFiles->setVisible(checked);
        ui->commentImplementationFiles->setVisible(checked);
    } else if (toComment == headers) {
        ui->label_filecommentHeaders->setVisible(false);
        ui->label_filecommentImpl->setVisible(true);

        ui->commentHeaderFiles->setVisible(false);
        ui->commentImplementationFiles->setVisible(true);
    } else if (toComment == implementations) {
        ui->label_filecommentHeaders->setVisible(true);
        ui->label_filecommentImpl->setVisible(false);
        ui->commentHeaderFiles->setVisible(true);
        ui->commentImplementationFiles->setVisible(false);
    }
}

void DoxygenSettingsWidget::on_fcommentChooser_currentIndexChanged(int index)
{
    Q_UNUSED(index)
    on_fileComments_clicked(ui->fileComments->isChecked());
}
<commit_msg>fixed typo in rc.customShortDocEnd definition<commit_after>/**************************************************************************
**
** This file is part of Doxygen plugin for Qt Creator
**
** Copyright (c) 2009 Kevin Tanguy (kofee@kofee.org).
** Copyright (c) 2015 Fabien Poussin (fabien.poussin@gmail.com).
**
** This plugin 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 plugin 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 General Public License
** along with Doxygen Plugin. If not, see <http://www.gnu.org/licenses/>.
**/

#include "doxygensettingswidget.h"
#include "ui_doxygensettingswidget.h"

DoxygenSettingsWidget::DoxygenSettingsWidget(QWidget* parent)
    : QWidget(parent)
    , ui(new Ui::DoxygenSettingsWidget)
{
    ui->setupUi(this);
    ui->pathChooser_doxygen->setExpectedKind(Utils::PathChooser::Command);
    ui->pathChooser_doxygen->setPromptDialogTitle(tr("Doxygen Command"));
    ui->pathChooser_wizard->setExpectedKind(Utils::PathChooser::Command);
    ui->pathChooser_wizard->setPromptDialogTitle(tr("DoxyWizard Command"));
    // Why do I *have* to call processEvents() to get my QComboBox display the right value?!
    qApp->processEvents();
    connect(ui->styleChooser, SIGNAL(currentIndexChanged(int)), this, SLOT(updateCustomWidgetPart(int)));
}

DoxygenSettingsWidget::~DoxygenSettingsWidget()
{
    delete ui;
}

void DoxygenSettingsWidget::changeEvent(QEvent* e)
{
    QWidget::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

DoxygenSettingsStruct DoxygenSettingsWidget::settings() const
{
    DoxygenSettingsStruct rc;
    rc.doxygenCommand = ui->pathChooser_doxygen->path();
    rc.doxyfileFileName = ui->edit_doxyfileName->text();
    rc.doxywizardCommand = ui->pathChooser_wizard->path();
    rc.style = DoxygenStyle(ui->styleChooser->currentIndex());
    rc.fcomment = Files2Comment(ui->fcommentChooser->currentIndex());
    rc.printBrief = ui->printBriefTag->isChecked();
    rc.shortVarDoc = ui->shortVariableDoc->isChecked();
    rc.verbosePrinting = ui->verbosePrinting->isChecked();
    rc.customBegin = QString(ui->edit_beginTag->text()).replace("\\n", "\n");
    rc.customBrief = QString(ui->edit_briefTag->text()).replace("\\n", "\n");
    rc.customEmptyLine = QString(ui->edit_emptyLineTag->text()).replace("\\n", "\n");
    rc.customEnding = QString(ui->edit_endTag->text()).replace("\\n", "\n");
    rc.customNewLine = QString(ui->edit_newLine->text()).replace("\\n", "\n");
    rc.customShortDoc = QString(ui->edit_shortTag->text()).replace("\\n", "\n");
    rc.customShortDocEnd = QString(ui->edit_shortTagEnd->text()).replace("\\n", "\n");
    rc.fileComment = ui->fileCommentText->toPlainText();
    rc.fileCommentHeaders = ui->commentHeaderFiles->isChecked();
    rc.fileCommentImpl = ui->commentImplementationFiles->isChecked();
    rc.fileCommentsEnabled = ui->fileComments->isChecked();
    rc.automaticReturnType = ui->autoAddReturnTypes->isChecked();
    return rc;
}

void DoxygenSettingsWidget::setSettings(const DoxygenSettingsStruct& s)
{
    ui->pathChooser_doxygen->setPath(s.doxygenCommand);
    ui->pathChooser_wizard->setPath(s.doxywizardCommand);
    ui->edit_doxyfileName->setText(s.doxyfileFileName);
    ui->styleChooser->setCurrentIndex(s.style);
    ui->fcommentChooser->setCurrentIndex(s.fcomment);
    ui->printBriefTag->setChecked(s.printBrief);
    ui->shortVariableDoc->setChecked(s.shortVarDoc);
    ui->verbosePrinting->setChecked(s.verbosePrinting);
    ui->edit_beginTag->setText(QString(s.customBegin).replace("\n", "\\n"));
    ui->edit_briefTag->setText(QString(s.customBrief).replace("\n", "\\n"));
    ui->edit_emptyLineTag->setText(QString(s.customEmptyLine).replace("\n", "\\n"));
    ui->edit_endTag->setText(QString(s.customEnding).replace("\n", "\\n"));
    ui->edit_newLine->setText(QString(s.customNewLine).replace("\n", "\\n"));
    ui->edit_shortTag->setText(QString(s.customShortDoc).replace("\n", "\\n"));
    ui->edit_shortTagEnd->setText(QString(s.customShortDocEnd).replace("\n", "\\n"));
    ui->fileCommentText->setPlainText(s.fileComment);
    ui->fileComments->setChecked(s.fileCommentsEnabled);
    ui->commentHeaderFiles->setChecked(s.fileCommentHeaders);
    ui->commentImplementationFiles->setChecked(s.fileCommentImpl);
    ui->autoAddReturnTypes->setChecked(s.automaticReturnType);

    updateCustomWidgetPart(s.style);
    on_fileComments_clicked(s.fileCommentsEnabled);
}

void DoxygenSettingsWidget::updateCustomWidgetPart(int index)
{
    ui->customCommentsSettings->setEnabled(index == customDoc);
}

void DoxygenSettingsWidget::on_fileComments_clicked(bool checked)
{
    Files2Comment toComment = Files2Comment(ui->fcommentChooser->currentIndex());
    ui->fileCommentText->setEnabled(checked);
    if (checked == false || toComment == all) {
        checked = false;
        ui->label_filecommentHeaders->setVisible(checked);
        ui->label_filecommentImpl->setVisible(checked);
        ui->commentHeaderFiles->setVisible(checked);
        ui->commentImplementationFiles->setVisible(checked);
    } else if (toComment == headers) {
        ui->label_filecommentHeaders->setVisible(false);
        ui->label_filecommentImpl->setVisible(true);

        ui->commentHeaderFiles->setVisible(false);
        ui->commentImplementationFiles->setVisible(true);
    } else if (toComment == implementations) {
        ui->label_filecommentHeaders->setVisible(true);
        ui->label_filecommentImpl->setVisible(false);
        ui->commentHeaderFiles->setVisible(true);
        ui->commentImplementationFiles->setVisible(false);
    }
}

void DoxygenSettingsWidget::on_fcommentChooser_currentIndexChanged(int index)
{
    Q_UNUSED(index)
    on_fileComments_clicked(ui->fileComments->isChecked());
}
<|endoftext|>


<commit_before>#include "GliderManipulator.h"
#include <osg/Notify>

using namespace osg;
using namespace osgGA;

GliderManipulator::GliderManipulator()
{
    _modelScale = 0.01f;
    _velocity = 0.0f;
    _yawMode = YAW_AUTOMATICALLY_WHEN_BANKED;

    _distance = 1.0f;
}

GliderManipulator::~GliderManipulator()
{
}

void GliderManipulator::setNode(osg::Node* node)
{
    _node = node;
    if (_node.get())
    {
        const osg::BoundingSphere& boundingSphere=_node->getBound();
        _modelScale = boundingSphere._radius;
    }
}

const osg::Node* GliderManipulator::getNode() const
{
    return _node.get();
}

osg::Node* GliderManipulator::getNode()
{
    return _node.get();
}

void GliderManipulator::home(const GUIEventAdapter& ea,GUIActionAdapter& us)
{
    if(_node.get())
    {

        const osg::BoundingSphere& boundingSphere=_node->getBound();

        osg::Vec3 eye = boundingSphere._center+osg::Vec3(-boundingSphere._radius*0.25f,-boundingSphere._radius*0.25f,-boundingSphere._radius*0.03f);

        computePosition(eye,
            osg::Vec3(1.0f,1.0f,-0.1f),
            osg::Vec3(0.0f,0.0f,1.0f));

        _velocity = boundingSphere._radius*0.01f;

        us.requestRedraw();

        us.requestWarpPointer((ea.getXmin()+ea.getXmax())/2.0f,(ea.getYmin()+ea.getYmax())/2.0f);

        flushMouseEventStack();

    }

}

void GliderManipulator::init(const GUIEventAdapter& ea,GUIActionAdapter& us)
{
    flushMouseEventStack();

    us.requestContinuousUpdate(false);

    _velocity = 0.0f;

    if (ea.getEventType()!=GUIEventAdapter::RESIZE)
    {
        us.requestWarpPointer((ea.getXmin()+ea.getXmax())/2.0f,(ea.getYmin()+ea.getYmax())/2.0f);
    }
}

bool GliderManipulator::handle(const GUIEventAdapter& ea,GUIActionAdapter& us)
{
    switch(ea.getEventType())
    {
        case(GUIEventAdapter::PUSH):
        {

            addMouseEvent(ea);
            us.requestContinuousUpdate(true);
            if (calcMovement()) us.requestRedraw();
            return true;
        }

        case(GUIEventAdapter::RELEASE):
        {

            addMouseEvent(ea);
            us.requestContinuousUpdate(true);
            if (calcMovement()) us.requestRedraw();
            return true;
        }

        case(GUIEventAdapter::DRAG):
        {

            addMouseEvent(ea);
            us.requestContinuousUpdate(true);
            if (calcMovement()) us.requestRedraw();
            return true;
        }

        case(GUIEventAdapter::MOVE):
        {

            addMouseEvent(ea);
            us.requestContinuousUpdate(true);
            if (calcMovement()) us.requestRedraw();

            return true;
        }

        case(GUIEventAdapter::KEYDOWN):
            if (ea.getKey()==' ')
            {
                flushMouseEventStack();
                home(ea,us);
                us.requestRedraw();
                us.requestContinuousUpdate(false);
                return true;
            }
            else if (ea.getKey()=='q')
            {
                _yawMode = YAW_AUTOMATICALLY_WHEN_BANKED;
                return true;
            }
            else if (ea.getKey()=='a')
            {
                _yawMode = NO_AUTOMATIC_YAW;
                return true;
            }
            return false;

        case(GUIEventAdapter::FRAME):
            addMouseEvent(ea);
            if (calcMovement()) us.requestRedraw();
            return true;

        case(GUIEventAdapter::RESIZE):
            init(ea,us);
            us.requestRedraw();
            return true;

        default:
            return false;
    }
}

void GliderManipulator::getUsage(osg::ApplicationUsage& usage) const
{
    usage.addKeyboardMouseBinding("Flight: Space","Reset the viewing position to home");
    usage.addKeyboardMouseBinding("Flight: q","Automatically yaw when banked (default)");
    usage.addKeyboardMouseBinding("Flight: a","No yaw when banked");
}

void GliderManipulator::flushMouseEventStack()
{
    _ga_t1 = NULL;
    _ga_t0 = NULL;
}

void GliderManipulator::addMouseEvent(const GUIEventAdapter& ea)
{
    _ga_t1 = _ga_t0;
    _ga_t0 = &ea;
}

void GliderManipulator::setByMatrix(const osg::Matrixd& matrix)
{
    _eye = matrix.getTrans();
    matrix.get(_rotation);
    _distance = 1.0f;
}

osg::Matrixd GliderManipulator::getMatrix() const
{
    return osg::Matrixd::rotate(_rotation)*osg::Matrixd::translate(_eye);
}

osg::Matrixd GliderManipulator::getInverseMatrix() const
{
    return osg::Matrixd::translate(-_eye)*osg::Matrixd::rotate(_rotation.inverse());
}

void GliderManipulator::computePosition(const osg::Vec3& eye,const osg::Vec3& lv,const osg::Vec3& up)
{
    osg::Vec3 f(lv);
    f.normalize();
    osg::Vec3 s(f^up);
    s.normalize();
    osg::Vec3 u(s^f);
    u.normalize();

    osg::Matrixd rotation_matrix(s[0],     u[0],     -f[0],     0.0f,
                                s[1],     u[1],     -f[1],     0.0f,
                                s[2],     u[2],     -f[2],     0.0f,
                                0.0f,     0.0f,     0.0f,      1.0f);

    _eye = eye;
    _distance = lv.length();
    rotation_matrix.get(_rotation);
    _rotation = _rotation.inverse();
}

bool GliderManipulator::calcMovement()
{
    //_camera->setFusionDistanceMode(osg::Camera::PROPORTIONAL_TO_SCREEN_DISTANCE);

    // return if less then two events have been added.
    if (_ga_t0.get()==NULL || _ga_t1.get()==NULL) return false;

    double dt = _ga_t0->time()-_ga_t1->time();

    if (dt<0.0f)
    {
        notify(WARN) << "warning dt = "<<dt<< std::endl;
        dt = 0.0f;
    }

    unsigned int buttonMask = _ga_t1->getButtonMask();
    if (buttonMask==GUIEventAdapter::LEFT_MOUSE_BUTTON)
    {
        // pan model.

        _velocity += dt*_modelScale*0.05f;

    }
    else if (buttonMask==GUIEventAdapter::MIDDLE_MOUSE_BUTTON ||
        buttonMask==(GUIEventAdapter::LEFT_MOUSE_BUTTON|GUIEventAdapter::RIGHT_MOUSE_BUTTON))
    {

        _velocity = 0.0f;

    }
    else if (buttonMask==GUIEventAdapter::RIGHT_MOUSE_BUTTON)
    {

        _velocity -= dt*_modelScale*0.05f;

    }

    float dx = _ga_t0->getXnormalized();
    float dy = _ga_t0->getYnormalized();

    osg::Matrixd rotation_matrix;
    rotation_matrix.makeRotate(_rotation);

    osg::Vec3 up = osg::Vec3(0.0f,1.0f,0.0) * rotation_matrix;
    osg::Vec3 lv = osg::Vec3(0.0f,0.0f,-1.0f) * rotation_matrix;

    osg::Vec3 sv = lv^up;
    sv.normalize();

    float pitch = -inDegrees(dy*75.0f*dt);
    float roll = inDegrees(dx*50.0f*dt);

    osg::Quat delta_rotate;

    osg::Quat roll_rotate;
    osg::Quat pitch_rotate;

    pitch_rotate.makeRotate(pitch,sv.x(),sv.y(),sv.z());
    roll_rotate.makeRotate(roll,lv.x(),lv.y(),lv.z());

    delta_rotate = pitch_rotate*roll_rotate;

    if (_yawMode==YAW_AUTOMATICALLY_WHEN_BANKED)
    {
        float bank = asinf(sv.z());
        float yaw = inRadians(bank)*dt;

        osg::Quat yaw_rotate;
        yaw_rotate.makeRotate(yaw,0.0f,0.0f,1.0f);

        delta_rotate = delta_rotate*yaw_rotate;
    }

    lv *= (_velocity*dt);

    _eye += lv;
    _rotation = _rotation*delta_rotate;

    return true;
}
<commit_msg>Maded debugging output write out at INFO level<commit_after>#include "GliderManipulator.h"
#include <osg/Notify>

using namespace osg;
using namespace osgGA;

GliderManipulator::GliderManipulator()
{
    _modelScale = 0.01f;
    _velocity = 0.0f;
    _yawMode = YAW_AUTOMATICALLY_WHEN_BANKED;

    _distance = 1.0f;
}

GliderManipulator::~GliderManipulator()
{
}

void GliderManipulator::setNode(osg::Node* node)
{
    _node = node;
    if (_node.get())
    {
        const osg::BoundingSphere& boundingSphere=_node->getBound();
        _modelScale = boundingSphere._radius;
    }
}

const osg::Node* GliderManipulator::getNode() const
{
    return _node.get();
}

osg::Node* GliderManipulator::getNode()
{
    return _node.get();
}

void GliderManipulator::home(const GUIEventAdapter& ea,GUIActionAdapter& us)
{
    if(_node.get())
    {

        const osg::BoundingSphere& boundingSphere=_node->getBound();

        osg::Vec3 eye = boundingSphere._center+osg::Vec3(-boundingSphere._radius*0.25f,-boundingSphere._radius*0.25f,-boundingSphere._radius*0.03f);

        computePosition(eye,
            osg::Vec3(1.0f,1.0f,-0.1f),
            osg::Vec3(0.0f,0.0f,1.0f));

        _velocity = boundingSphere._radius*0.01f;

        us.requestRedraw();

        us.requestWarpPointer((ea.getXmin()+ea.getXmax())/2.0f,(ea.getYmin()+ea.getYmax())/2.0f);

        flushMouseEventStack();

    }

}

void GliderManipulator::init(const GUIEventAdapter& ea,GUIActionAdapter& us)
{
    flushMouseEventStack();

    us.requestContinuousUpdate(false);

    _velocity = 0.0f;

    if (ea.getEventType()!=GUIEventAdapter::RESIZE)
    {
        us.requestWarpPointer((ea.getXmin()+ea.getXmax())/2.0f,(ea.getYmin()+ea.getYmax())/2.0f);
    }
}

bool GliderManipulator::handle(const GUIEventAdapter& ea,GUIActionAdapter& us)
{
    switch(ea.getEventType())
    {
        case(GUIEventAdapter::PUSH):
        {

            addMouseEvent(ea);
            us.requestContinuousUpdate(true);
            if (calcMovement()) us.requestRedraw();
            return true;
        }

        case(GUIEventAdapter::RELEASE):
        {

            addMouseEvent(ea);
            us.requestContinuousUpdate(true);
            if (calcMovement()) us.requestRedraw();
            return true;
        }

        case(GUIEventAdapter::DRAG):
        {

            addMouseEvent(ea);
            us.requestContinuousUpdate(true);
            if (calcMovement()) us.requestRedraw();
            return true;
        }

        case(GUIEventAdapter::MOVE):
        {

            addMouseEvent(ea);
            us.requestContinuousUpdate(true);
            if (calcMovement()) us.requestRedraw();

            return true;
        }

        case(GUIEventAdapter::KEYDOWN):
            if (ea.getKey()==' ')
            {
                flushMouseEventStack();
                home(ea,us);
                us.requestRedraw();
                us.requestContinuousUpdate(false);
                return true;
            }
            else if (ea.getKey()=='q')
            {
                _yawMode = YAW_AUTOMATICALLY_WHEN_BANKED;
                return true;
            }
            else if (ea.getKey()=='a')
            {
                _yawMode = NO_AUTOMATIC_YAW;
                return true;
            }
            return false;

        case(GUIEventAdapter::FRAME):
            addMouseEvent(ea);
            if (calcMovement()) us.requestRedraw();
            return true;

        case(GUIEventAdapter::RESIZE):
            init(ea,us);
            us.requestRedraw();
            return true;

        default:
            return false;
    }
}

void GliderManipulator::getUsage(osg::ApplicationUsage& usage) const
{
    usage.addKeyboardMouseBinding("Flight: Space","Reset the viewing position to home");
    usage.addKeyboardMouseBinding("Flight: q","Automatically yaw when banked (default)");
    usage.addKeyboardMouseBinding("Flight: a","No yaw when banked");
}

void GliderManipulator::flushMouseEventStack()
{
    _ga_t1 = NULL;
    _ga_t0 = NULL;
}

void GliderManipulator::addMouseEvent(const GUIEventAdapter& ea)
{
    _ga_t1 = _ga_t0;
    _ga_t0 = &ea;
}

void GliderManipulator::setByMatrix(const osg::Matrixd& matrix)
{
    _eye = matrix.getTrans();
    matrix.get(_rotation);
    _distance = 1.0f;
}

osg::Matrixd GliderManipulator::getMatrix() const
{
    return osg::Matrixd::rotate(_rotation)*osg::Matrixd::translate(_eye);
}

osg::Matrixd GliderManipulator::getInverseMatrix() const
{
    return osg::Matrixd::translate(-_eye)*osg::Matrixd::rotate(_rotation.inverse());
}

void GliderManipulator::computePosition(const osg::Vec3& eye,const osg::Vec3& lv,const osg::Vec3& up)
{
    osg::Vec3 f(lv);
    f.normalize();
    osg::Vec3 s(f^up);
    s.normalize();
    osg::Vec3 u(s^f);
    u.normalize();

    osg::Matrixd rotation_matrix(s[0],     u[0],     -f[0],     0.0f,
                                s[1],     u[1],     -f[1],     0.0f,
                                s[2],     u[2],     -f[2],     0.0f,
                                0.0f,     0.0f,     0.0f,      1.0f);

    _eye = eye;
    _distance = lv.length();
    rotation_matrix.get(_rotation);
    _rotation = _rotation.inverse();
}

bool GliderManipulator::calcMovement()
{
    //_camera->setFusionDistanceMode(osg::Camera::PROPORTIONAL_TO_SCREEN_DISTANCE);

    // return if less then two events have been added.
    if (_ga_t0.get()==NULL || _ga_t1.get()==NULL) return false;

    double dt = _ga_t0->time()-_ga_t1->time();

    if (dt<0.0f)
    {
        notify(INFO) << "warning dt = "<<dt<< std::endl;
        dt = 0.0f;
    }

    unsigned int buttonMask = _ga_t1->getButtonMask();
    if (buttonMask==GUIEventAdapter::LEFT_MOUSE_BUTTON)
    {
        // pan model.

        _velocity += dt*_modelScale*0.05f;

    }
    else if (buttonMask==GUIEventAdapter::MIDDLE_MOUSE_BUTTON ||
        buttonMask==(GUIEventAdapter::LEFT_MOUSE_BUTTON|GUIEventAdapter::RIGHT_MOUSE_BUTTON))
    {

        _velocity = 0.0f;

    }
    else if (buttonMask==GUIEventAdapter::RIGHT_MOUSE_BUTTON)
    {

        _velocity -= dt*_modelScale*0.05f;

    }

    float dx = _ga_t0->getXnormalized();
    float dy = _ga_t0->getYnormalized();

    osg::Matrixd rotation_matrix;
    rotation_matrix.makeRotate(_rotation);

    osg::Vec3 up = osg::Vec3(0.0f,1.0f,0.0) * rotation_matrix;
    osg::Vec3 lv = osg::Vec3(0.0f,0.0f,-1.0f) * rotation_matrix;

    osg::Vec3 sv = lv^up;
    sv.normalize();

    float pitch = -inDegrees(dy*75.0f*dt);
    float roll = inDegrees(dx*50.0f*dt);

    osg::Quat delta_rotate;

    osg::Quat roll_rotate;
    osg::Quat pitch_rotate;

    pitch_rotate.makeRotate(pitch,sv.x(),sv.y(),sv.z());
    roll_rotate.makeRotate(roll,lv.x(),lv.y(),lv.z());

    delta_rotate = pitch_rotate*roll_rotate;

    if (_yawMode==YAW_AUTOMATICALLY_WHEN_BANKED)
    {
        float bank = asinf(sv.z());
        float yaw = inRadians(bank)*dt;

        osg::Quat yaw_rotate;
        yaw_rotate.makeRotate(yaw,0.0f,0.0f,1.0f);

        delta_rotate = delta_rotate*yaw_rotate;
    }

    lv *= (_velocity*dt);

    _eye += lv;
    _rotation = _rotation*delta_rotate;

    return true;
}
<|endoftext|>