<commit_before>#include "ResourceList.hpp"

#include <Engine/Geometry/Model.hpp>
#include <Engine/Texture/TextureAsset.hpp>
#include <Engine/Audio/SoundBuffer.hpp>
#include <Engine/Script/ScriptFile.hpp>
#include <Engine/Util/FileSystem.hpp>
#include <Editor/Util/EditorSettings.hpp>
#include <Engine/Hymn.hpp>
#include <Engine/Entity/Entity.hpp>
#include <Engine/MainWindow.hpp>
#include <imgui.h>
#include <limits>
#include "../ImGui/Splitter.hpp"

using namespace GUI;

void ResourceList::Show() {
    ImVec2 size(MainWindow::GetInstance()->GetSize().x, MainWindow::GetInstance()->GetSize().y);

    // Splitter.
    ImGui::VerticalSplitter(ImVec2(sceneWidth, size.y - resourceHeight), size.x - sceneWidth - editorWidth, splitterSize, resourceHeight, resourceResize, 20, size.y - 20);
    if (resourceResize)
        resourceHeight = size.y - resourceHeight;

    ImGui::SetNextWindowPos(ImVec2(sceneWidth, size.y - resourceHeight));
    ImGui::SetNextWindowSize(ImVec2(size.x - sceneWidth - editorWidth, resourceHeight));

    ImGui::Begin("Resources", nullptr, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_ShowBorders);

    // Scenes.
    if (ImGui::TreeNode("Scenes")) {
        if (ImGui::Button("Add scene"))
            Hymn().scenes.push_back("Scene #" + std::to_string(Hymn().scenes.size()));

        for (std::size_t i = 0; i < Hymn().scenes.size(); ++i) {
            size_t activeScene = Hymn().activeScene;
            if (ImGui::Selectable(Hymn().scenes[i].c_str())) {
                changeScene = true;
                sceneIndex = i;
                savePromptWindow.SetTitle("Save before you switch scene?");
            }

            if (ImGui::BeginPopupContextItem(Hymn().scenes[i].c_str())) {
                if (ImGui::Selectable("Delete")) {
                    Hymn().scenes.erase(Hymn().scenes.begin() + i);
                    ImGui::EndPopup();

                    if (Hymn().activeScene >= i) {
                        if (Hymn().activeScene > 0)
                            Hymn().activeScene = Hymn().activeScene - 1;

                        sceneEditor.SetScene(Hymn().activeScene);
                    }
                    break;
                }
                ImGui::EndPopup();
            }
        }
        ImGui::TreePop();

        if (changeScene) {

            if (Hymn().GetPath() != "") {

                savePromptWindow.SetVisible(true);
                savePromptWindow.Show();

                switch (savePromptWindow.GetDecision())
                {
                case 0:
                    sceneEditor.Save();
                    sceneEditor.SetVisible(true);
                    sceneEditor.SetScene(sceneIndex);
                    Hymn().activeScene = sceneIndex;
                    sceneEditor.entityEditor.SetVisible(false);
                    Hymn().world.Clear();
                    Hymn().world.Load(Hymn().GetPath() + FileSystem::DELIMITER + "Scenes" + FileSystem::DELIMITER + Hymn().scenes[sceneIndex] + ".json");
                    changeScene = false;
                    savePromptWindow.SetVisible(false);
                    savePromptWindow.ResetDecision();
                    break;

                case 1:
                    sceneEditor.SetVisible(true);
                    sceneEditor.SetScene(sceneIndex);
                    Hymn().activeScene = sceneIndex;
                    sceneEditor.entityEditor.SetVisible(false);
                    Hymn().world.Clear();
                    Hymn().world.Load(Hymn().GetPath() + FileSystem::DELIMITER + "Scenes" + FileSystem::DELIMITER + Hymn().scenes[sceneIndex] + ".json");
                    changeScene = false;
                    savePromptWindow.SetVisible(false);
                    savePromptWindow.ResetDecision();
                    break;

                default:
                    break;
                }

            }

        }

    }

    // Models.
    bool modelPressed = false;
    if (ImGui::TreeNode("Models")) {
        if (ImGui::Button("Add model")) {
            Geometry::Model* model = new Geometry::Model();
            model->name = "Model #" + std::to_string(Hymn().modelNumber++);
            Hymn().models.push_back(model);
        }

        for (auto it = Hymn().models.begin(); it != Hymn().models.end(); ++it) {
            Geometry::Model* model = *it;
            if (ImGui::Selectable(model->name.c_str())) {
                modelPressed = true;
                modelEditor.SetModel(model);
            }

            if (ImGui::BeginPopupContextItem(model->name.c_str())) {
                if (ImGui::Selectable("Delete")) {
                    if (modelEditor.GetModel() == model)
                        modelEditor.SetVisible(false);

                    delete model;
                    Hymn().models.erase(it);
                    ImGui::EndPopup();
                    break;
                }
                ImGui::EndPopup();
            }
        }
        ImGui::TreePop();
    }

    // Textures.
    bool texturePressed = false;
    if (ImGui::TreeNode("Textures")) {
        if (ImGui::Button("Add texture")) {
            TextureAsset* texture = new TextureAsset();
            texture->name = "Texture #" + std::to_string(Hymn().textureNumber++);
            Hymn().textures.push_back(texture);
        }

        for (auto it = Hymn().textures.begin(); it != Hymn().textures.end(); ++it) {
            TextureAsset* texture = *it;
            if (ImGui::Selectable(texture->name.c_str())) {
                texturePressed = true;
                textureEditor.SetTexture(texture);
            }

            if (ImGui::BeginPopupContextItem(texture->name.c_str())) {
                if (ImGui::Selectable("Delete")) {
                    if (textureEditor.GetTexture() == texture)
                        textureEditor.SetVisible(false);

                    delete texture;
                    Hymn().textures.erase(it);
                    ImGui::EndPopup();
                    break;
                }
                ImGui::EndPopup();
            }
        }

        ImGui::TreePop();
    }

    // Scripts.
    bool scriptPressed = false;
    if (ImGui::TreeNode("Scripts")) {
        if (ImGui::Button("Add script")) {
            ScriptFile* scriptFile = new ScriptFile();
            scriptFile->name = "Script #" + std::to_string(Hymn().scriptNumber++);
            Hymn().scripts.push_back(scriptFile);
        }

        for (auto it = Hymn().scripts.begin(); it != Hymn().scripts.end(); ++it) {
            ScriptFile* script = *it;
            std::string name = script->name;

            if (ImGui::Selectable(name.c_str())) {
                scriptPressed = true;
                scriptEditor.SetScript(script);
            }

            if (ImGui::BeginPopupContextItem(name.c_str())) {
                if (ImGui::Selectable("Delete")) {
                    if (scriptEditor.GetScript() == script)
                        scriptEditor.SetVisible(false);

                    delete script;
                    Hymn().scripts.erase(it);
                    ImGui::EndPopup();
                    break;
                }
                ImGui::EndPopup();
            }
        }

        ImGui::TreePop();
    }

    // Sounds.
    bool soundPressed = false;
    if (ImGui::TreeNode("Sounds")) {
        if (ImGui::Button("Add sound")) {
            Audio::SoundBuffer* sound = new Audio::SoundBuffer();
            sound->name = "Sound #" + std::to_string(Hymn().soundNumber++);
            Hymn().sounds.push_back(sound);
        }

        for (auto it = Hymn().sounds.begin(); it != Hymn().sounds.end(); ++it) {
            Audio::SoundBuffer* sound = *it;
            if (ImGui::Selectable(sound->name.c_str())) {
                soundPressed = true;
                soundEditor.SetSound(sound);
            }

            if (ImGui::BeginPopupContextItem(sound->name.c_str())) {
                if (ImGui::Selectable("Delete")) {
                    if (soundEditor.GetSound() == sound)
                        soundEditor.SetVisible(false);

                    delete sound;
                    Hymn().sounds.erase(it);
                    ImGui::EndPopup();
                    break;
                }
                ImGui::EndPopup();
            }
        }

        ImGui::TreePop();
    }

    if (sceneEditor.entityPressed || scriptPressed || texturePressed || modelPressed || soundPressed) {
        sceneEditor.entityEditor.SetVisible(sceneEditor.entityPressed);
        scriptEditor.SetVisible(scriptPressed);
        textureEditor.SetVisible(texturePressed);
        modelEditor.SetVisible(modelPressed);
        soundEditor.SetVisible(soundPressed);
    }

    if (sceneEditor.IsVisible()) {
        ImGui::HorizontalSplitter(ImVec2(sceneWidth, 20), size.y - 20, splitterSize, sceneWidth, sceneResize, 20, size.x - editorWidth - 20);
        ImGui::SetNextWindowPos(ImVec2(0, 20));
        ImGui::SetNextWindowSize(ImVec2(sceneWidth, size.y - 20));
        sceneEditor.Show();
    }

    if (sceneEditor.entityEditor.IsVisible() || scriptEditor.IsVisible() || textureEditor.IsVisible() || modelEditor.IsVisible() || soundEditor.IsVisible()) {
        editorWidth = size.x - editorWidth;
        ImGui::HorizontalSplitter(ImVec2(editorWidth, 20), size.y - 20, splitterSize, editorWidth, editorResize, sceneWidth + 20, size.x - 20);
        editorWidth = size.x - editorWidth;

        ImGui::SetNextWindowPos(ImVec2(size.x - editorWidth, 20));
        ImGui::SetNextWindowSize(ImVec2(editorWidth, size.y - 20));
    }

    if (sceneEditor.entityEditor.IsVisible())
        sceneEditor.entityEditor.Show();
    if (scriptEditor.IsVisible())
        scriptEditor.Show();
    if (textureEditor.IsVisible())
        textureEditor.Show();
    if (modelEditor.IsVisible())
        modelEditor.Show();
    if (soundEditor.IsVisible())
        soundEditor.Show();

    ImGui::End();
}

bool ResourceList::IsVisible() const {
    return visible;
}

void ResourceList::SetVisible(bool visible) {
    this->visible = visible;
}

void ResourceList::HideEditors() {
    sceneEditor.SetVisible(false);
    sceneEditor.entityEditor.SetVisible(false);
    scriptEditor.SetVisible(false);
    modelEditor.SetVisible(false);
    textureEditor.SetVisible(false);
    soundEditor.SetVisible(false);
}

void ResourceList::SaveScene() const {
    sceneEditor.Save();
}

#undef max
void ResourceList::ResetScene() {
    sceneEditor.SetScene(std::numeric_limits<std::size_t>::max());
    sceneEditor.SetVisible(false);
}

SceneEditor& ResourceList::GetScene() {
    return sceneEditor;
}
<commit_msg>Removed uneccessary space<commit_after>#include "ResourceList.hpp"

#include <Engine/Geometry/Model.hpp>
#include <Engine/Texture/TextureAsset.hpp>
#include <Engine/Audio/SoundBuffer.hpp>
#include <Engine/Script/ScriptFile.hpp>
#include <Engine/Util/FileSystem.hpp>
#include <Editor/Util/EditorSettings.hpp>
#include <Engine/Hymn.hpp>
#include <Engine/Entity/Entity.hpp>
#include <Engine/MainWindow.hpp>
#include <imgui.h>
#include <limits>
#include "../ImGui/Splitter.hpp"

using namespace GUI;

void ResourceList::Show() {
    ImVec2 size(MainWindow::GetInstance()->GetSize().x, MainWindow::GetInstance()->GetSize().y);

    // Splitter.
    ImGui::VerticalSplitter(ImVec2(sceneWidth, size.y - resourceHeight), size.x - sceneWidth - editorWidth, splitterSize, resourceHeight, resourceResize, 20, size.y - 20);
    if (resourceResize)
        resourceHeight = size.y - resourceHeight;

    ImGui::SetNextWindowPos(ImVec2(sceneWidth, size.y - resourceHeight));
    ImGui::SetNextWindowSize(ImVec2(size.x - sceneWidth - editorWidth, resourceHeight));

    ImGui::Begin("Resources", nullptr, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_ShowBorders);

    // Scenes.
    if (ImGui::TreeNode("Scenes")) {
        if (ImGui::Button("Add scene"))
            Hymn().scenes.push_back("Scene #" + std::to_string(Hymn().scenes.size()));

        for (std::size_t i = 0; i < Hymn().scenes.size(); ++i) {
            size_t activeScene = Hymn().activeScene;
            if (ImGui::Selectable(Hymn().scenes[i].c_str())) {
                changeScene = true;
                sceneIndex = i;
                savePromptWindow.SetTitle("Save before you switch scene?");
            }

            if (ImGui::BeginPopupContextItem(Hymn().scenes[i].c_str())) {
                if (ImGui::Selectable("Delete")) {
                    Hymn().scenes.erase(Hymn().scenes.begin() + i);
                    ImGui::EndPopup();

                    if (Hymn().activeScene >= i) {
                        if (Hymn().activeScene > 0)
                            Hymn().activeScene = Hymn().activeScene - 1;

                        sceneEditor.SetScene(Hymn().activeScene);
                    }
                    break;
                }
                ImGui::EndPopup();
            }
        }
        ImGui::TreePop();

        if (changeScene) {

            if (Hymn().GetPath() != "") {

                savePromptWindow.SetVisible(true);
                savePromptWindow.Show();

                switch (savePromptWindow.GetDecision())
                {
                case 0:
                    sceneEditor.Save();
                    sceneEditor.SetVisible(true);
                    sceneEditor.SetScene(sceneIndex);
                    Hymn().activeScene = sceneIndex;
                    sceneEditor.entityEditor.SetVisible(false);
                    Hymn().world.Clear();
                    Hymn().world.Load(Hymn().GetPath() + FileSystem::DELIMITER + "Scenes" + FileSystem::DELIMITER + Hymn().scenes[sceneIndex] + ".json");
                    changeScene = false;
                    savePromptWindow.SetVisible(false);
                    savePromptWindow.ResetDecision();
                    break;

                case 1:
                    sceneEditor.SetVisible(true);
                    sceneEditor.SetScene(sceneIndex);
                    Hymn().activeScene = sceneIndex;
                    sceneEditor.entityEditor.SetVisible(false);
                    Hymn().world.Clear();
                    Hymn().world.Load(Hymn().GetPath() + FileSystem::DELIMITER + "Scenes" + FileSystem::DELIMITER + Hymn().scenes[sceneIndex] + ".json");
                    changeScene = false;
                    savePromptWindow.SetVisible(false);
                    savePromptWindow.ResetDecision();
                    break;

                default:
                    break;
                }
            }
        }
    }

    // Models.
    bool modelPressed = false;
    if (ImGui::TreeNode("Models")) {
        if (ImGui::Button("Add model")) {
            Geometry::Model* model = new Geometry::Model();
            model->name = "Model #" + std::to_string(Hymn().modelNumber++);
            Hymn().models.push_back(model);
        }

        for (auto it = Hymn().models.begin(); it != Hymn().models.end(); ++it) {
            Geometry::Model* model = *it;
            if (ImGui::Selectable(model->name.c_str())) {
                modelPressed = true;
                modelEditor.SetModel(model);
            }

            if (ImGui::BeginPopupContextItem(model->name.c_str())) {
                if (ImGui::Selectable("Delete")) {
                    if (modelEditor.GetModel() == model)
                        modelEditor.SetVisible(false);

                    delete model;
                    Hymn().models.erase(it);
                    ImGui::EndPopup();
                    break;
                }
                ImGui::EndPopup();
            }
        }
        ImGui::TreePop();
    }

    // Textures.
    bool texturePressed = false;
    if (ImGui::TreeNode("Textures")) {
        if (ImGui::Button("Add texture")) {
            TextureAsset* texture = new TextureAsset();
            texture->name = "Texture #" + std::to_string(Hymn().textureNumber++);
            Hymn().textures.push_back(texture);
        }

        for (auto it = Hymn().textures.begin(); it != Hymn().textures.end(); ++it) {
            TextureAsset* texture = *it;
            if (ImGui::Selectable(texture->name.c_str())) {
                texturePressed = true;
                textureEditor.SetTexture(texture);
            }

            if (ImGui::BeginPopupContextItem(texture->name.c_str())) {
                if (ImGui::Selectable("Delete")) {
                    if (textureEditor.GetTexture() == texture)
                        textureEditor.SetVisible(false);

                    delete texture;
                    Hymn().textures.erase(it);
                    ImGui::EndPopup();
                    break;
                }
                ImGui::EndPopup();
            }
        }

        ImGui::TreePop();
    }

    // Scripts.
    bool scriptPressed = false;
    if (ImGui::TreeNode("Scripts")) {
        if (ImGui::Button("Add script")) {
            ScriptFile* scriptFile = new ScriptFile();
            scriptFile->name = "Script #" + std::to_string(Hymn().scriptNumber++);
            Hymn().scripts.push_back(scriptFile);
        }

        for (auto it = Hymn().scripts.begin(); it != Hymn().scripts.end(); ++it) {
            ScriptFile* script = *it;
            std::string name = script->name;

            if (ImGui::Selectable(name.c_str())) {
                scriptPressed = true;
                scriptEditor.SetScript(script);
            }

            if (ImGui::BeginPopupContextItem(name.c_str())) {
                if (ImGui::Selectable("Delete")) {
                    if (scriptEditor.GetScript() == script)
                        scriptEditor.SetVisible(false);

                    delete script;
                    Hymn().scripts.erase(it);
                    ImGui::EndPopup();
                    break;
                }
                ImGui::EndPopup();
            }
        }

        ImGui::TreePop();
    }

    // Sounds.
    bool soundPressed = false;
    if (ImGui::TreeNode("Sounds")) {
        if (ImGui::Button("Add sound")) {
            Audio::SoundBuffer* sound = new Audio::SoundBuffer();
            sound->name = "Sound #" + std::to_string(Hymn().soundNumber++);
            Hymn().sounds.push_back(sound);
        }

        for (auto it = Hymn().sounds.begin(); it != Hymn().sounds.end(); ++it) {
            Audio::SoundBuffer* sound = *it;
            if (ImGui::Selectable(sound->name.c_str())) {
                soundPressed = true;
                soundEditor.SetSound(sound);
            }

            if (ImGui::BeginPopupContextItem(sound->name.c_str())) {
                if (ImGui::Selectable("Delete")) {
                    if (soundEditor.GetSound() == sound)
                        soundEditor.SetVisible(false);

                    delete sound;
                    Hymn().sounds.erase(it);
                    ImGui::EndPopup();
                    break;
                }
                ImGui::EndPopup();
            }
        }

        ImGui::TreePop();
    }

    if (sceneEditor.entityPressed || scriptPressed || texturePressed || modelPressed || soundPressed) {
        sceneEditor.entityEditor.SetVisible(sceneEditor.entityPressed);
        scriptEditor.SetVisible(scriptPressed);
        textureEditor.SetVisible(texturePressed);
        modelEditor.SetVisible(modelPressed);
        soundEditor.SetVisible(soundPressed);
    }

    if (sceneEditor.IsVisible()) {
        ImGui::HorizontalSplitter(ImVec2(sceneWidth, 20), size.y - 20, splitterSize, sceneWidth, sceneResize, 20, size.x - editorWidth - 20);
        ImGui::SetNextWindowPos(ImVec2(0, 20));
        ImGui::SetNextWindowSize(ImVec2(sceneWidth, size.y - 20));
        sceneEditor.Show();
    }

    if (sceneEditor.entityEditor.IsVisible() || scriptEditor.IsVisible() || textureEditor.IsVisible() || modelEditor.IsVisible() || soundEditor.IsVisible()) {
        editorWidth = size.x - editorWidth;
        ImGui::HorizontalSplitter(ImVec2(editorWidth, 20), size.y - 20, splitterSize, editorWidth, editorResize, sceneWidth + 20, size.x - 20);
        editorWidth = size.x - editorWidth;

        ImGui::SetNextWindowPos(ImVec2(size.x - editorWidth, 20));
        ImGui::SetNextWindowSize(ImVec2(editorWidth, size.y - 20));
    }

    if (sceneEditor.entityEditor.IsVisible())
        sceneEditor.entityEditor.Show();
    if (scriptEditor.IsVisible())
        scriptEditor.Show();
    if (textureEditor.IsVisible())
        textureEditor.Show();
    if (modelEditor.IsVisible())
        modelEditor.Show();
    if (soundEditor.IsVisible())
        soundEditor.Show();

    ImGui::End();
}

bool ResourceList::IsVisible() const {
    return visible;
}

void ResourceList::SetVisible(bool visible) {
    this->visible = visible;
}

void ResourceList::HideEditors() {
    sceneEditor.SetVisible(false);
    sceneEditor.entityEditor.SetVisible(false);
    scriptEditor.SetVisible(false);
    modelEditor.SetVisible(false);
    textureEditor.SetVisible(false);
    soundEditor.SetVisible(false);
}

void ResourceList::SaveScene() const {
    sceneEditor.Save();
}

#undef max
void ResourceList::ResetScene() {
    sceneEditor.SetScene(std::numeric_limits<std::size_t>::max());
    sceneEditor.SetVisible(false);
}

SceneEditor& ResourceList::GetScene() {
    return sceneEditor;
}
<|endoftext|>


<commit_before>/*
    Kopete Latex Plugin

    Copyright (c) 2004 by Duncan Mac-Vicar Prett   <duncan@kde.org>
    Copyright (c) 2004-2005 by Olivier Goffart  <ogoffart@kde. org>

    Kopete    (c) 2001-2004 by the Kopete developers  <kopete-devel@kde.org>

    *************************************************************************
    *                                                                       *
    * This program is free software; you can redistribute it and/or modify  *
    * it under the terms of the GNU General Public License as published by  *
    * the Free Software Foundation; either version 2 of the License, or     *
    * (at your option) any later version.                                   *
    *                                                                       *
    *************************************************************************
*/

#include <qregexp.h>
#include <qimage.h>
#include <qbuffer.h>
#include <QTextDocument>

#include <kgenericfactory.h>
#include <kdebug.h>
#include <kstandarddirs.h>
#include <kprocess.h>
#include <ktemporaryfile.h>
#include <kcodecs.h>
#include <kmessagebox.h>

#include "kopetechatsessionmanager.h"
#include "kopeteuiglobal.h"

#include "latexplugin.h"
#include "latexconfig.h"
#include "latexguiclient.h"

#define ENCODED_IMAGE_MODE 0

K_PLUGIN_FACTORY(LatexPluginFactory, registerPlugin<LatexPlugin>();)
K_EXPORT_PLUGIN(LatexPluginFactory( "kopete_latex" ))

LatexPlugin::LatexPlugin( QObject *parent, const QVariantList &/*args*/ )
: Kopete::Plugin( LatexPluginFactory::componentData(), parent )
{
//	kDebug(14317) ;
	if( !s_pluginStatic )
		s_pluginStatic = this;

	mMagickNotFoundShown = false;
	connect( Kopete::ChatSessionManager::self(), SIGNAL( aboutToDisplay( Kopete::Message & ) ), SLOT( slotMessageAboutToShow( Kopete::Message & ) ) );
	connect( Kopete::ChatSessionManager::self(), SIGNAL( aboutToSend(Kopete::Message& )  ), this,  SLOT(slotMessageAboutToSend(Kopete::Message& )  ) );
	connect( Kopete::ChatSessionManager::self(), SIGNAL( chatSessionCreated( Kopete::ChatSession * ) ),
			 this, SLOT( slotNewChatSession( Kopete::ChatSession * ) ) );

	m_convScript = KStandardDirs::findExe("kopete_latexconvert.sh");

		//Add GUI action to all already existing kmm (if the plugin is launched when kopete already rining)
	QList<Kopete::ChatSession*> sessions = Kopete::ChatSessionManager::self()->sessions();
	foreach( Kopete::ChatSession* cs, sessions )
		slotNewChatSession( cs );
}

LatexPlugin::~LatexPlugin()
{
	qDeleteAll( m_tempFiles );
	s_pluginStatic = 0L;
}

LatexPlugin* LatexPlugin::plugin()
{
	return s_pluginStatic ;
}

LatexPlugin* LatexPlugin::s_pluginStatic = 0L;

void LatexPlugin::slotNewChatSession( Kopete::ChatSession *KMM )
{
	new LatexGUIClient( KMM );
}

void LatexPlugin::slotMessageAboutToShow( Kopete::Message& msg )
{
	QString mMagick = KStandardDirs::findExe("convert");
	if ( mMagick.isEmpty() )
	{
		// show just once
		if (  !mMagickNotFoundShown )
		{
			KMessageBox::queuedMessageBox(
			    Kopete::UI::Global::mainWidget(),
			    KMessageBox::Error, i18n("Cannot find the Magick 'convert' program.\nconvert is required to render the LaTeX formulae.\nPlease get the software from www.imagemagick.org or from your distribution's package manager.")
			);
			mMagickNotFoundShown = true;
		}
		// don't try to parse if convert is not installed
		return;
	}

	QString messageText = msg.plainBody();
	if( !messageText.contains("$$"))
		return;

	//kDebug(14317) << " Using converter: " << m_convScript;

	// /\[([^]]).*?\[/$1\]/
	// \$\$.+?\$\$

	// this searches for $$formula$$
	QRegExp rg("\\$\\$.+\\$\\$");
	rg.setMinimal(true);
	// this searches for [latex]formula[/latex]
	//QRegExp rg("\\[([^]\]).*?\\[/$1\\]");

	int pos = 0;

	QMap<QString, QString> replaceMap;
	while (pos >= 0 && pos < messageText.length())
	{
//		kDebug(14317) << " searching pos: " << pos;
		pos = rg.indexIn(messageText, pos);

		if (pos >= 0 )
		{
			QString match = rg.cap(0);
			pos += rg.matchedLength();

			QString formul=match;
			if(!securityCheck(formul))
				continue;

			QString fileName=handleLatex(formul.replace("$$",""));

			// get the image and encode it with base64
			#if ENCODED_IMAGE_MODE
			QImage renderedImage( fileName );
			imagePxWidth = renderedImage.width();
			imagePxHeight = renderedImage.height();
			if ( !renderedImage.isNull() )
			{
				QByteArray ba;
				QBuffer buffer( ba );
				buffer.open( QIODevice::WriteOnly );
				renderedImage.save( &buffer, "PNG" );
				QString imageURL = QString::fromLatin1("data:image/png;base64,%1").arg( KCodecs::base64Encode( ba ) );
				replaceMap[match] = imageURL;
			}
			#else
			replaceMap[match] = fileName;
			#endif
		}
	}

	if(replaceMap.isEmpty()) //we haven't found any LaTeX strings
		return;

	messageText= msg.escapedBody();

	int imagePxWidth,imagePxHeight;
	for (QMap<QString,QString>::ConstIterator it = replaceMap.begin(); it != replaceMap.end(); ++it)
	{
		QImage theImage(*it);
		if(theImage.isNull())
			continue;
		imagePxWidth = theImage.width();
		imagePxHeight = theImage.height();
		QString escapedLATEX=Qt::escape(it.key()).replace("\"",""");  //we need  the escape quotes because that string will be in a title="" argument, but not the \n
		messageText.replace(Kopete::Message::escape(it.key()), "  ");
	}

	msg.setHtmlBody( messageText );
}

void LatexPlugin::slotMessageAboutToSend( Kopete::Message& msg)
{
	Q_UNUSED(msg)
	//disabled because to work correctly, we need to find what special has the gif we can send over MSN
#if 0
	KSharedConfig::Ptr config = KGlobal::config();
	config->setGroup("Latex Plugin");

	if(!config->readEntry("ParseOutgoing", false))
		return;

	QString messageText = msg.plainBody();
	if( !messageText.contains("$$"))
		return;
/*	if( msg.from()->protocol()->pluginId()!="MSNProtocol" )
	return;*/

	// this searches for $$formula$$
	QRegExp rg("^\\s*\\$\\$([^$]+)\\$\\$\\s*$");

	if( rg.search(messageText) != -1 )
	{
		QString latexFormula = rg.cap(1);
		if(!securityCheck( latexFormula ))
			return;

		QString url = handleLatex(latexFormula);

		if(!url.isNull())
		{
			QString escapedLATEX= Qt::escape(messageText).replace("\"",""");
			QString messageText="";
			msg.setBody( messageText, Kopete::Message::RichText );
		}
	}
#endif
}

QString LatexPlugin::handleLatex(const QString &latexFormula)
{
	KTemporaryFile *tempFile=new KTemporaryFile();
	tempFile->setPrefix("kopetelatex-");
	tempFile->setSuffix(".png");
	tempFile->open();
	m_tempFiles.append(tempFile);
	QString fileName = tempFile->fileName();

	KProcess p;

	QString argumentRes = QString("-r %1x%2").arg(LatexConfig::horizontalDPI()).arg(LatexConfig::verticalDPI());
	QString argumentOut = QString("-o %1").arg(fileName);
	QString argumentInclude ("-x %1");
	//QString argumentFormat = "-fgif";  //we uses gif format because MSN only handle gif
	LatexConfig::self()->readConfig();
	QString includePath = LatexConfig::latexIncludeFile();
	if (!includePath.isNull())
		p << m_convScript <<  argumentRes << argumentOut /*<< argumentFormat*/ << argumentInclude.arg(includePath) << latexFormula;
	else
		p << m_convScript <<  argumentRes << argumentOut /*<< argumentFormat*/ << latexFormula;

	kDebug(14317) << "Rendering" << m_convScript << argumentRes << argumentOut << argumentInclude << latexFormula ;

	// FIXME our sucky sync filter API limitations :-)
	p.execute();
	return fileName;
}

bool LatexPlugin::securityCheck(const QString &latexFormula)
{
	return !latexFormula.contains(QRegExp("\\\\(def|let|futurelet|newcommand|renewcomment|else|fi|write|input|include"
			"|chardef|catcode|makeatletter|noexpand|toksdef|every|errhelp|errorstopmode|scrollmode|nonstopmode|batchmode"
			"|read|csname|newhelp|relax|afterground|afterassignment|expandafter|noexpand|special|command|loop|repeat|toks"
			"|output|line|mathcode|name|item|section|mbox|DeclareRobustCommand)[^a-zA-Z]"));

}

#include "latexplugin.moc"

// vim: set noet ts=4 sts=4 sw=4:

<commit_msg>Align formulas (images rendered by latex) vertically centered. BUG: 161575<commit_after>/*
    Kopete Latex Plugin

    Copyright (c) 2004 by Duncan Mac-Vicar Prett   <duncan@kde.org>
    Copyright (c) 2004-2005 by Olivier Goffart  <ogoffart@kde. org>

    Kopete    (c) 2001-2004 by the Kopete developers  <kopete-devel@kde.org>

    *************************************************************************
    *                                                                       *
    * This program is free software; you can redistribute it and/or modify  *
    * it under the terms of the GNU General Public License as published by  *
    * the Free Software Foundation; either version 2 of the License, or     *
    * (at your option) any later version.                                   *
    *                                                                       *
    *************************************************************************
*/

#include <qregexp.h>
#include <qimage.h>
#include <qbuffer.h>
#include <QTextDocument>

#include <kgenericfactory.h>
#include <kdebug.h>
#include <kstandarddirs.h>
#include <kprocess.h>
#include <ktemporaryfile.h>
#include <kcodecs.h>
#include <kmessagebox.h>

#include "kopetechatsessionmanager.h"
#include "kopeteuiglobal.h"

#include "latexplugin.h"
#include "latexconfig.h"
#include "latexguiclient.h"

#define ENCODED_IMAGE_MODE 0

K_PLUGIN_FACTORY(LatexPluginFactory, registerPlugin<LatexPlugin>();)
K_EXPORT_PLUGIN(LatexPluginFactory( "kopete_latex" ))

LatexPlugin::LatexPlugin( QObject *parent, const QVariantList &/*args*/ )
: Kopete::Plugin( LatexPluginFactory::componentData(), parent )
{
//	kDebug(14317) ;
	if( !s_pluginStatic )
		s_pluginStatic = this;

	mMagickNotFoundShown = false;
	connect( Kopete::ChatSessionManager::self(), SIGNAL( aboutToDisplay( Kopete::Message & ) ), SLOT( slotMessageAboutToShow( Kopete::Message & ) ) );
	connect( Kopete::ChatSessionManager::self(), SIGNAL( aboutToSend(Kopete::Message& )  ), this,  SLOT(slotMessageAboutToSend(Kopete::Message& )  ) );
	connect( Kopete::ChatSessionManager::self(), SIGNAL( chatSessionCreated( Kopete::ChatSession * ) ),
			 this, SLOT( slotNewChatSession( Kopete::ChatSession * ) ) );

	m_convScript = KStandardDirs::findExe("kopete_latexconvert.sh");

		//Add GUI action to all already existing kmm (if the plugin is launched when kopete already rining)
	QList<Kopete::ChatSession*> sessions = Kopete::ChatSessionManager::self()->sessions();
	foreach( Kopete::ChatSession* cs, sessions )
		slotNewChatSession( cs );
}

LatexPlugin::~LatexPlugin()
{
	qDeleteAll( m_tempFiles );
	s_pluginStatic = 0L;
}

LatexPlugin* LatexPlugin::plugin()
{
	return s_pluginStatic ;
}

LatexPlugin* LatexPlugin::s_pluginStatic = 0L;

void LatexPlugin::slotNewChatSession( Kopete::ChatSession *KMM )
{
	new LatexGUIClient( KMM );
}

void LatexPlugin::slotMessageAboutToShow( Kopete::Message& msg )
{
	QString mMagick = KStandardDirs::findExe("convert");
	if ( mMagick.isEmpty() )
	{
		// show just once
		if (  !mMagickNotFoundShown )
		{
			KMessageBox::queuedMessageBox(
			    Kopete::UI::Global::mainWidget(),
			    KMessageBox::Error, i18n("Cannot find the Magick 'convert' program.\nconvert is required to render the LaTeX formulae.\nPlease get the software from www.imagemagick.org or from your distribution's package manager.")
			);
			mMagickNotFoundShown = true;
		}
		// don't try to parse if convert is not installed
		return;
	}

	QString messageText = msg.plainBody();
	if( !messageText.contains("$$"))
		return;

	//kDebug(14317) << " Using converter: " << m_convScript;

	// /\[([^]]).*?\[/$1\]/
	// \$\$.+?\$\$

	// this searches for $$formula$$
	QRegExp rg("\\$\\$.+\\$\\$");
	rg.setMinimal(true);
	// this searches for [latex]formula[/latex]
	//QRegExp rg("\\[([^]\]).*?\\[/$1\\]");

	int pos = 0;

	QMap<QString, QString> replaceMap;
	while (pos >= 0 && pos < messageText.length())
	{
//		kDebug(14317) << " searching pos: " << pos;
		pos = rg.indexIn(messageText, pos);

		if (pos >= 0 )
		{
			QString match = rg.cap(0);
			pos += rg.matchedLength();

			QString formul=match;
			if(!securityCheck(formul))
				continue;

			QString fileName=handleLatex(formul.replace("$$",""));

			// get the image and encode it with base64
			#if ENCODED_IMAGE_MODE
			QImage renderedImage( fileName );
			imagePxWidth = renderedImage.width();
			imagePxHeight = renderedImage.height();
			if ( !renderedImage.isNull() )
			{
				QByteArray ba;
				QBuffer buffer( ba );
				buffer.open( QIODevice::WriteOnly );
				renderedImage.save( &buffer, "PNG" );
				QString imageURL = QString::fromLatin1("data:image/png;base64,%1").arg( KCodecs::base64Encode( ba ) );
				replaceMap[match] = imageURL;
			}
			#else
			replaceMap[match] = fileName;
			#endif
		}
	}

	if(replaceMap.isEmpty()) //we haven't found any LaTeX strings
		return;

	messageText= msg.escapedBody();

	int imagePxWidth,imagePxHeight;
	for (QMap<QString,QString>::ConstIterator it = replaceMap.begin(); it != replaceMap.end(); ++it)
	{
		QImage theImage(*it);
		if(theImage.isNull())
			continue;
		imagePxWidth = theImage.width();
		imagePxHeight = theImage.height();
		QString escapedLATEX=Qt::escape(it.key()).replace("\"",""");  //we need  the escape quotes because that string will be in a title="" argument, but not the \n
		messageText.replace(Kopete::Message::escape(it.key()), "  ");
	}

	msg.setHtmlBody( messageText );
}

void LatexPlugin::slotMessageAboutToSend( Kopete::Message& msg)
{
	Q_UNUSED(msg)
	//disabled because to work correctly, we need to find what special has the gif we can send over MSN
#if 0
	KSharedConfig::Ptr config = KGlobal::config();
	config->setGroup("Latex Plugin");

	if(!config->readEntry("ParseOutgoing", false))
		return;

	QString messageText = msg.plainBody();
	if( !messageText.contains("$$"))
		return;
/*	if( msg.from()->protocol()->pluginId()!="MSNProtocol" )
	return;*/

	// this searches for $$formula$$
	QRegExp rg("^\\s*\\$\\$([^$]+)\\$\\$\\s*$");

	if( rg.search(messageText) != -1 )
	{
		QString latexFormula = rg.cap(1);
		if(!securityCheck( latexFormula ))
			return;

		QString url = handleLatex(latexFormula);

		if(!url.isNull())
		{
			QString escapedLATEX= Qt::escape(messageText).replace("\"",""");
			QString messageText="";
			msg.setBody( messageText, Kopete::Message::RichText );
		}
	}
#endif
}

QString LatexPlugin::handleLatex(const QString &latexFormula)
{
	KTemporaryFile *tempFile=new KTemporaryFile();
	tempFile->setPrefix("kopetelatex-");
	tempFile->setSuffix(".png");
	tempFile->open();
	m_tempFiles.append(tempFile);
	QString fileName = tempFile->fileName();

	KProcess p;

	QString argumentRes = QString("-r %1x%2").arg(LatexConfig::horizontalDPI()).arg(LatexConfig::verticalDPI());
	QString argumentOut = QString("-o %1").arg(fileName);
	QString argumentInclude ("-x %1");
	//QString argumentFormat = "-fgif";  //we uses gif format because MSN only handle gif
	LatexConfig::self()->readConfig();
	QString includePath = LatexConfig::latexIncludeFile();
	if (!includePath.isNull())
		p << m_convScript <<  argumentRes << argumentOut /*<< argumentFormat*/ << argumentInclude.arg(includePath) << latexFormula;
	else
		p << m_convScript <<  argumentRes << argumentOut /*<< argumentFormat*/ << latexFormula;

	kDebug(14317) << "Rendering" << m_convScript << argumentRes << argumentOut << argumentInclude << latexFormula ;

	// FIXME our sucky sync filter API limitations :-)
	p.execute();
	return fileName;
}

bool LatexPlugin::securityCheck(const QString &latexFormula)
{
	return !latexFormula.contains(QRegExp("\\\\(def|let|futurelet|newcommand|renewcomment|else|fi|write|input|include"
			"|chardef|catcode|makeatletter|noexpand|toksdef|every|errhelp|errorstopmode|scrollmode|nonstopmode|batchmode"
			"|read|csname|newhelp|relax|afterground|afterassignment|expandafter|noexpand|special|command|loop|repeat|toks"
			"|output|line|mathcode|name|item|section|mbox|DeclareRobustCommand)[^a-zA-Z]"));

}

#include "latexplugin.moc"

// vim: set noet ts=4 sts=4 sw=4:

<|endoftext|>


<commit_before>#include "Vision/RTSVisionManager.h"

#include "EngineUtils.h"
#include "Engine/World.h"
#include "Kismet/GameplayStatics.h"

#include "RTSGameMode.h"
#include "RTSLog.h"
#include "RTSOwnerComponent.h"
#include "RTSPlayerState.h"
#include "RTSTeamInfo.h"
#include "Vision/RTSFogOfWarActor.h"
#include "Vision/RTSVisibleActor.h"
#include "Vision/RTSVisibleComponent.h"
#include "Vision/RTSVisionComponent.h"
#include "Vision/RTSVisionInfo.h"
#include "Vision/RTSVisionVolume.h"

ARTSVisionManager::ARTSVisionManager(const FObjectInitializer& ObjectInitializer /*= FObjectInitializer::Get()*/)
    : Super(ObjectInitializer)
{
    PrimaryActorTick.bCanEverTick = true;
    PrimaryActorTick.bStartWithTickEnabled = true;
}

void ARTSVisionManager::Initialize()
{
    UWorld* World = GetWorld();

    // Find manager and info actors.
    for (TActorIterator<AActor> It(World); It; ++It)
    {
        AActor* Actor = *It;

        if (IsValid(Actor))
        {
            if (Actor->IsA(ARTSFogOfWarActor::StaticClass()))
            {
                FogOfWarActor = Cast<ARTSFogOfWarActor>(Actor);
            }
            else if (Actor->IsA(ARTSVisionInfo::StaticClass()))
            {
                ARTSVisionInfo* VisionInfo = Cast<ARTSVisionInfo>(Actor);
                VisionInfos.Add(VisionInfo);
            }
            else if (Actor->IsA(ARTSVisionVolume::StaticClass()))
            {
                VisionVolume = Cast<ARTSVisionVolume>(Actor);
            }
        }
    }

    if (IsValid(VisionVolume))
    {
        VisionVolume->Initialize();
    }

    for (ARTSVisionInfo* VisionInfo : VisionInfos)
    {
        VisionInfo->Initialize(VisionVolume);
    }

    if (IsValid(FogOfWarActor))
    {
        FogOfWarActor->Initialize(VisionVolume);
    }

    // Discover initial vision actors.
    for (TActorIterator<AActor> It(GetWorld()); It; ++It)
    {
        AActor* Actor = *It;

        if (!IsValid(Actor))
        {
            continue;
        }

        URTSVisibleComponent* VisibleComponent = Actor->FindComponentByClass<URTSVisibleComponent>();

        if (IsValid(VisibleComponent))
        {
            AddVisibleActor(Actor);
        }

        URTSVisionComponent* VisionComponent = Actor->FindComponentByClass<URTSVisionComponent>();

        if (IsValid(VisionComponent))
        {
            AddVisionActor(Actor);
        }
    }
}

void ARTSVisionManager::Tick(float DeltaSeconds)
{
    Super::Tick(DeltaSeconds);

    // Update unit vision.
    for (FRTSVisionActor& VisionActor : VisionActors)
    {
        UpdateVisionActor(VisionActor);
    }

    // Update unit visibility.
    for (FRTSVisibleActor& VisibleActor : VisibleActors)
    {
        if (!VisibleActor.IsActorValid())
        {
            continue;
        }

        FIntVector TileLocation;

        if (IsValid(VisibleActor.VisionComponent))
        {
            TileLocation = VisibleActor.VisionComponent->ActorLocationTile;
        }
        else
        {
            TileLocation = IsValid(VisionVolume)
                ? VisionVolume->WorldToTile(VisibleActor.Actor->GetActorLocation())
                : FIntVector::ZeroValue;
        }

        if (GetNetMode() <= NM_ListenServer)
        {
            ARTSGameMode* GameMode = Cast<ARTSGameMode>(UGameplayStatics::GetGameMode(this));

            // Update server vision.
            for (ARTSTeamInfo* Team : GameMode->GetTeams())
            {
                // If friendly, always visible.
                if (VisibleActor.OwnerComponent && VisibleActor.OwnerComponent->GetPlayerOwner() &&
                    VisibleActor.OwnerComponent->GetPlayerOwner()->GetTeam() == Team)
                {
                    for (AController* Player : Team->GetTeamMembers())
                    {
                        // Set visibility according to team vision.
                        VisibleActor.VisibleComponent->SetVisionStateForPlayer(Player, ERTSVisionState::VISION_Visible);
                    }

                    continue;
                }

                // Get matching vision info.
                if (VisionInfos.IsValidIndex(Team->GetTeamIndex()))
                {
                    ARTSVisionInfo* TeamVision = VisionInfos[Team->GetTeamIndex()];
                    ERTSVisionState NewVision = TeamVision->GetVision(TileLocation.X, TileLocation.Y);

                    for (AController* Player : Team->GetTeamMembers())
                    {
                        // Set visibility according to team vision.
                        VisibleActor.VisibleComponent->SetVisionStateForPlayer(Player, NewVision);
                    }
                }
                else
                {
                    UE_LOG(LogRTS, Warning, TEXT("No vision info available for team %i."), Team->GetTeamIndex());
                }

            }
        }

        if (GetNetMode() >= NM_ListenServer)
        {
            // Update client vision.
            ERTSVisionState NewVision = IsValid(LocalVisionInfo)
                ? LocalVisionInfo->GetVision(TileLocation.X, TileLocation.Y)
                : ERTSVisionState::VISION_Visible;

            VisibleActor.VisibleComponent->SetClientVisionState(NewVision);
        }
    }
}

void ARTSVisionManager::SetLocalPlayerState(ARTSPlayerState* InLocalPlayerState)
{
    LocalPlayerState = InLocalPlayerState;
}

void ARTSVisionManager::SetLocalVisionInfo(ARTSVisionInfo* InLocalVisionInfo)
{
    LocalVisionInfo = InLocalVisionInfo;

    if (!VisionInfos.Contains(LocalVisionInfo))
    {
        // It seems like this has been replicated after our initialization.
        VisionInfos.Add(LocalVisionInfo);
        LocalVisionInfo->Initialize(VisionVolume);
    }

    if (IsValid(FogOfWarActor))
    {
        FogOfWarActor->SetupVisionInfo(LocalVisionInfo);
    }

    if (IsValid(LocalVisionInfo))
    {
        UE_LOG(LogRTS, Log, TEXT("Using local vision info %s."), *LocalVisionInfo->GetName());
    }
}

void ARTSVisionManager::AddVisibleActor(AActor* Actor)
{
    for (int32 Index = 0; Index < VisibleActors.Num(); ++Index)
    {
        if (VisibleActors[Index].Actor == Actor)
        {
            // Already added.
            return;
        }
    }

    FRTSVisibleActor VisibleActor(Actor);

    if (!VisibleActor.IsActorValid())
    {
        return;
    }

    VisibleActors.Add(VisibleActor);
}

void ARTSVisionManager::RemoveVisibleActor(AActor* Actor)
{
    int32 IndexToRemove = -1;

    for (int32 Index = 0; Index < VisibleActors.Num(); ++Index)
    {
        if (VisibleActors[Index].Actor == Actor)
        {
            IndexToRemove = Index;
            break;
        }
    }

    if (VisibleActors.IsValidIndex(IndexToRemove))
    {
        VisibleActors.RemoveAt(IndexToRemove);
    }
}

void ARTSVisionManager::AddVisionActor(AActor* Actor)
{
    for (int32 Index = 0; Index < VisionActors.Num(); ++Index)
    {
        if (VisionActors[Index].Actor == Actor)
        {
            // Already added.
            return;
        }
    }

    FRTSVisionActor VisionActor(Actor);

    if (!VisionActor.IsActorValid())
    {
        return;
    }

    VisionActors.Add(VisionActor);
}

void ARTSVisionManager::RemoveVisionActor(AActor* Actor)
{
    int32 IndexToRemove = -1;

    for (int32 Index = 0; Index < VisionActors.Num(); ++Index)
    {
        if (VisionActors[Index].Actor == Actor)
        {
            IndexToRemove = Index;
            break;
        }
    }

    if (VisionActors.IsValidIndex(IndexToRemove))
    {
        ResetVisionForActor(VisionActors[IndexToRemove]);
        VisionActors.RemoveAt(IndexToRemove);
    }
}

void ARTSVisionManager::UpdateVisionActor(const FRTSVisionActor& VisionActor)
{
    if (VisionInfos.Num() == 0)
    {
        return;
    }

    if (!IsValid(LocalPlayerState))
    {
        return;
    }

    for (ARTSVisionInfo* VisionInfo : VisionInfos)
    {
        if (!VisionInfo->IsInitialized())
        {
            return;
        }
    }

    // We only need to update vision for actors who have moved onto a new tile.
    if (!VisionActor.IsActorValid())
    {
        return;
    }

    FVector ActorLocationWorld = VisionActor.Actor->GetActorLocation();
    FIntVector ActorLocationTile = VisionVolume->WorldToTile(ActorLocationWorld);
    int32 ActorLocationHeightLevel = VisionVolume->GetTileHeight(ActorLocationTile);

    if (VisionActor.VisionComponent->ActorLocationTile.X == ActorLocationTile.X &&
        VisionActor.VisionComponent->ActorLocationTile.Y == ActorLocationTile.Y &&
        VisionActor.VisionComponent->ActorLocationTile.Z == ActorLocationHeightLevel)
    {
        // Hasn't moved.
        return;
    }
    else
    {
        // Moved to new grid cell.
        VisionActor.VisionComponent->ActorLocationTile = ActorLocationTile;
        VisionActor.VisionComponent->ActorLocationTile.Z = ActorLocationHeightLevel;
    }

    ResetVisionForActor(VisionActor);

    // Apply vision.
    TArray<int32> CachedVisionTiles;

    for (ARTSVisionInfo* VisionInfo : VisionInfos)
    {
        VisionInfo->ApplyVisionForActor(VisionActor.Actor, CachedVisionTiles);
    }
}

void ARTSVisionManager::ResetVisionForActor(const FRTSVisionActor& VisionActor)
{
    if (!VisionActor.IsActorValid())
    {
        return;
    }

    // Reset vision.
    for (const FRTSVisionInfoTileList& VisionInfoTileList : VisionActor.VisionComponent->VisibleTiles)
    {
        VisionInfoTileList.VisionInfo->ResetVisionForActor(VisionActor.Actor);
    }

    VisionActor.VisionComponent->VisibleTiles.Empty();
}
<commit_msg>Make sure to wait for full initialization on standalone before applying vision.<commit_after>#include "Vision/RTSVisionManager.h"

#include "EngineUtils.h"
#include "Engine/GameInstance.h"
#include "Engine/World.h"
#include "GameFramework/PlayerController.h"
#include "Kismet/GameplayStatics.h"

#include "RTSGameMode.h"
#include "RTSLog.h"
#include "RTSOwnerComponent.h"
#include "RTSPlayerState.h"
#include "RTSTeamInfo.h"
#include "Vision/RTSFogOfWarActor.h"
#include "Vision/RTSVisibleActor.h"
#include "Vision/RTSVisibleComponent.h"
#include "Vision/RTSVisionComponent.h"
#include "Vision/RTSVisionInfo.h"
#include "Vision/RTSVisionVolume.h"

ARTSVisionManager::ARTSVisionManager(const FObjectInitializer& ObjectInitializer /*= FObjectInitializer::Get()*/)
    : Super(ObjectInitializer)
{
    PrimaryActorTick.bCanEverTick = true;
    PrimaryActorTick.bStartWithTickEnabled = true;
}

void ARTSVisionManager::Initialize()
{
    UWorld* World = GetWorld();

    // Find local player.
    APlayerController* FirstLocalPlayerController = GetGameInstance()->GetFirstLocalPlayerController();

    if (IsValid(FirstLocalPlayerController))
    {
        SetLocalPlayerState(FirstLocalPlayerController->GetPlayerState<ARTSPlayerState>());
    }

    // Find manager and info actors.
    for (TActorIterator<AActor> It(World); It; ++It)
    {
        AActor* Actor = *It;

        if (IsValid(Actor))
        {
            if (Actor->IsA(ARTSFogOfWarActor::StaticClass()))
            {
                FogOfWarActor = Cast<ARTSFogOfWarActor>(Actor);
            }
            else if (Actor->IsA(ARTSVisionInfo::StaticClass()))
            {
                ARTSVisionInfo* VisionInfo = Cast<ARTSVisionInfo>(Actor);
                VisionInfos.Add(VisionInfo);
            }
            else if (Actor->IsA(ARTSVisionVolume::StaticClass()))
            {
                VisionVolume = Cast<ARTSVisionVolume>(Actor);
            }
        }
    }

    if (IsValid(VisionVolume))
    {
        VisionVolume->Initialize();
    }

    for (ARTSVisionInfo* VisionInfo : VisionInfos)
    {
        VisionInfo->Initialize(VisionVolume);
    }

    if (IsValid(FogOfWarActor))
    {
        FogOfWarActor->Initialize(VisionVolume);
    }

    // Discover initial vision actors.
    for (TActorIterator<AActor> It(GetWorld()); It; ++It)
    {
        AActor* Actor = *It;

        if (!IsValid(Actor))
        {
            continue;
        }

        URTSVisibleComponent* VisibleComponent = Actor->FindComponentByClass<URTSVisibleComponent>();

        if (IsValid(VisibleComponent))
        {
            AddVisibleActor(Actor);
        }

        URTSVisionComponent* VisionComponent = Actor->FindComponentByClass<URTSVisionComponent>();

        if (IsValid(VisionComponent))
        {
            AddVisionActor(Actor);
        }
    }
}

void ARTSVisionManager::Tick(float DeltaSeconds)
{
    Super::Tick(DeltaSeconds);

    // Update unit vision.
    for (FRTSVisionActor& VisionActor : VisionActors)
    {
        UpdateVisionActor(VisionActor);
    }

    // Update unit visibility.
    for (FRTSVisibleActor& VisibleActor : VisibleActors)
    {
        if (!VisibleActor.IsActorValid())
        {
            continue;
        }

        FIntVector TileLocation;

        if (IsValid(VisibleActor.VisionComponent))
        {
            TileLocation = VisibleActor.VisionComponent->ActorLocationTile;
        }
        else
        {
            TileLocation = IsValid(VisionVolume)
                ? VisionVolume->WorldToTile(VisibleActor.Actor->GetActorLocation())
                : FIntVector::ZeroValue;
        }

        if (GetNetMode() <= NM_ListenServer)
        {
            ARTSGameMode* GameMode = Cast<ARTSGameMode>(UGameplayStatics::GetGameMode(this));

            // Update server vision.
            for (ARTSTeamInfo* Team : GameMode->GetTeams())
            {
                // If friendly, always visible.
                if (VisibleActor.OwnerComponent && VisibleActor.OwnerComponent->GetPlayerOwner() &&
                    VisibleActor.OwnerComponent->GetPlayerOwner()->GetTeam() == Team)
                {
                    for (AController* Player : Team->GetTeamMembers())
                    {
                        // Set visibility according to team vision.
                        VisibleActor.VisibleComponent->SetVisionStateForPlayer(Player, ERTSVisionState::VISION_Visible);
                    }

                    continue;
                }

                // Get matching vision info.
                if (VisionInfos.IsValidIndex(Team->GetTeamIndex()))
                {
                    ARTSVisionInfo* TeamVision = VisionInfos[Team->GetTeamIndex()];
                    ERTSVisionState NewVision = TeamVision->GetVision(TileLocation.X, TileLocation.Y);

                    for (AController* Player : Team->GetTeamMembers())
                    {
                        // Set visibility according to team vision.
                        VisibleActor.VisibleComponent->SetVisionStateForPlayer(Player, NewVision);
                    }
                }
                else
                {
                    UE_LOG(LogRTS, Warning, TEXT("No vision info available for team %i."), Team->GetTeamIndex());
                }

            }
        }

        if (GetNetMode() >= NM_ListenServer)
        {
            // Update client vision.
            ERTSVisionState NewVision = IsValid(LocalVisionInfo)
                ? LocalVisionInfo->GetVision(TileLocation.X, TileLocation.Y)
                : ERTSVisionState::VISION_Visible;

            VisibleActor.VisibleComponent->SetClientVisionState(NewVision);
        }
    }
}

void ARTSVisionManager::SetLocalPlayerState(ARTSPlayerState* InLocalPlayerState)
{
    LocalPlayerState = InLocalPlayerState;

    if (IsValid(InLocalPlayerState))
    {
        UE_LOG(LogRTS, Log, TEXT("Using local player state %s."), *InLocalPlayerState->GetName());
    }
}

void ARTSVisionManager::SetLocalVisionInfo(ARTSVisionInfo* InLocalVisionInfo)
{
    LocalVisionInfo = InLocalVisionInfo;

    if (!VisionInfos.Contains(LocalVisionInfo))
    {
        // It seems like this has been replicated after our initialization.
        VisionInfos.Add(LocalVisionInfo);
        LocalVisionInfo->Initialize(VisionVolume);
    }

    if (IsValid(FogOfWarActor))
    {
        FogOfWarActor->SetupVisionInfo(LocalVisionInfo);
    }

    if (IsValid(LocalVisionInfo))
    {
        UE_LOG(LogRTS, Log, TEXT("Using local vision info %s."), *LocalVisionInfo->GetName());
    }
}

void ARTSVisionManager::AddVisibleActor(AActor* Actor)
{
    for (int32 Index = 0; Index < VisibleActors.Num(); ++Index)
    {
        if (VisibleActors[Index].Actor == Actor)
        {
            // Already added.
            return;
        }
    }

    FRTSVisibleActor VisibleActor(Actor);

    if (!VisibleActor.IsActorValid())
    {
        return;
    }

    VisibleActors.Add(VisibleActor);
}

void ARTSVisionManager::RemoveVisibleActor(AActor* Actor)
{
    int32 IndexToRemove = -1;

    for (int32 Index = 0; Index < VisibleActors.Num(); ++Index)
    {
        if (VisibleActors[Index].Actor == Actor)
        {
            IndexToRemove = Index;
            break;
        }
    }

    if (VisibleActors.IsValidIndex(IndexToRemove))
    {
        VisibleActors.RemoveAt(IndexToRemove);
    }
}

void ARTSVisionManager::AddVisionActor(AActor* Actor)
{
    for (int32 Index = 0; Index < VisionActors.Num(); ++Index)
    {
        if (VisionActors[Index].Actor == Actor)
        {
            // Already added.
            return;
        }
    }

    FRTSVisionActor VisionActor(Actor);

    if (!VisionActor.IsActorValid())
    {
        return;
    }

    VisionActors.Add(VisionActor);
}

void ARTSVisionManager::RemoveVisionActor(AActor* Actor)
{
    int32 IndexToRemove = -1;

    for (int32 Index = 0; Index < VisionActors.Num(); ++Index)
    {
        if (VisionActors[Index].Actor == Actor)
        {
            IndexToRemove = Index;
            break;
        }
    }

    if (VisionActors.IsValidIndex(IndexToRemove))
    {
        ResetVisionForActor(VisionActors[IndexToRemove]);
        VisionActors.RemoveAt(IndexToRemove);
    }
}

void ARTSVisionManager::UpdateVisionActor(const FRTSVisionActor& VisionActor)
{
    if (VisionInfos.Num() == 0)
    {
        return;
    }

    if (!IsValid(LocalPlayerState))
    {
        return;
    }

    for (ARTSVisionInfo* VisionInfo : VisionInfos)
    {
        if (!VisionInfo->IsInitialized())
        {
            return;
        }
    }

    // We only need to update vision for actors who have moved onto a new tile.
    if (!VisionActor.IsActorValid())
    {
        return;
    }

    FVector ActorLocationWorld = VisionActor.Actor->GetActorLocation();
    FIntVector ActorLocationTile = VisionVolume->WorldToTile(ActorLocationWorld);
    int32 ActorLocationHeightLevel = VisionVolume->GetTileHeight(ActorLocationTile);

    if (VisionActor.VisionComponent->ActorLocationTile.X == ActorLocationTile.X &&
        VisionActor.VisionComponent->ActorLocationTile.Y == ActorLocationTile.Y &&
        VisionActor.VisionComponent->ActorLocationTile.Z == ActorLocationHeightLevel)
    {
        // Hasn't moved.
        return;
    }
    else
    {
        // Moved to new grid cell.
        VisionActor.VisionComponent->ActorLocationTile = ActorLocationTile;
        VisionActor.VisionComponent->ActorLocationTile.Z = ActorLocationHeightLevel;
    }

    ResetVisionForActor(VisionActor);

    // Apply vision.
    TArray<int32> CachedVisionTiles;

    for (ARTSVisionInfo* VisionInfo : VisionInfos)
    {
        VisionInfo->ApplyVisionForActor(VisionActor.Actor, CachedVisionTiles);
    }
}

void ARTSVisionManager::ResetVisionForActor(const FRTSVisionActor& VisionActor)
{
    if (!VisionActor.IsActorValid())
    {
        return;
    }

    // Reset vision.
    for (const FRTSVisionInfoTileList& VisionInfoTileList : VisionActor.VisionComponent->VisibleTiles)
    {
        VisionInfoTileList.VisionInfo->ResetVisionForActor(VisionActor.Actor);
    }

    VisionActor.VisionComponent->VisibleTiles.Empty();
}
<|endoftext|>


<commit_before>/*
 * D-Bus AT-SPI, Qt Adaptor
 *
 * Copyright 2008, 2009      Nokia.
 * Copyright 2008, 2009      Codethink Ltd.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */

#include <QApplication>
#include <QObject>
#include <QWidget>
#include <QWidgetList>
#include <QApplication>
#include <QStackedWidget>

#include "cache.h"
#include "object.h"
#include "adaptor.h"
#include "accessible.h"

#include "generated/cache_adaptor.h"

#define QSPI_OBJECT_PATH_CACHE "/org/a11y/atspi/cache"

/*---------------------------------------------------------------------------*/

QSpiAccessibleCache::QSpiAccessibleCache(QObject *root, QDBusConnection c)
    : dbusConnection(c)
{
    CacheAdaptor *adaptor;

    //QApplication::instance()->installEventFilter(this);

    rootObject = root;
    cache.insert(root, new QSpiApplication(this, QAccessible::queryAccessibleInterface(root), dbusConnection));
    registerChildren(QAccessible::queryAccessibleInterface(root));

    adaptor = new CacheAdaptor(this);
    c.registerObject(QSPI_OBJECT_PATH_CACHE, this, QDBusConnection::ExportAdaptors);

    connect (this, SIGNAL(AddAccessible(QSpiAccessibleCacheItem)),
             adaptor, SIGNAL(AddAccessible(QSpiAccessibleCacheItem)));
    connect (this, SIGNAL(RemoveAccessible(QSpiObjectReference)),
             adaptor, SIGNAL(RemoveAccessible(QSpiObjectReference)));
}

/*---------------------------------------------------------------------------*/

QObject *QSpiAccessibleCache::getRoot ()
{
    return rootObject;
}

/*---------------------------------------------------------------------------*/

//bool QSpiAccessibleCache::eventFilter(QObject *obj, QEvent *event)
//{
//    QSpiObject *accessible = NULL;

//    switch (event->type ())
//    {
//        case QEvent::Show:
//        {
//            accessible = objectToAccessible (obj);
//            break;
//        }
//        /*
//         * FIXME: No Idea what to do here, the ChildAdded signal is BROKEN
//         * for accessibility as the accessible interface is not ready when this signal
//         * is emmited.
//         */
//#if 0
//        case QEvent::ChildAdded:
//        {
//            QList <QSpiObject *> children;
//            QObject *child = static_cast<QChildEvent *>(event)->child();

//            qDebug ("QSpiAccessibleBridge : childAdded.\n\t%s\n\t%s\n\t%s\n",
//                    qPrintable(accessible->getReference().path()),
//                    qPrintable(accessible->getParentPath().path()),
//                    qPrintable (accessible->getInterface().text(QAccessible::Name, 0))
//                   );

//            children = accessible->getChildren();
//            foreach (QSpiObject *chld, children)
//            {
//                qDebug ("\t\t%s", qPrintable(chld->getReference().path()));
//            }

//            registerChildren(child);
//            emit accessibleUpdated (accessible);
//            break;
//            // TODO
//            Emit the child added signal
//        }
//#endif
//        default:
//            break;
//    }
//    /* Think false is the right thing to do, no need to block these events here. */
//    return false;
//}

/*---------------------------------------------------------------------------*/

//void QSpiAccessibleCache::objectDestroyed (QObject *obj)
//{
//    if (cache.contains (obj))
//    {
//        QSpiObject *accessible = cache.take (obj);
//#if 0
//        qDebug("QSpiAccessibleBridge : Object Destroyed\n\t%s\n",
//               qPrintable(accessible->getReference().path()));
//#endif
//        emit RemoveAccessible (accessible->getReference());
//        delete accessible;
//    }
//}

/*
 * Registers all descendants of the given accessible interface with the cache.
 *
 * No Idea about the threading implications here.
 * What is the equivalent of the GDK lock?
 */
void QSpiAccessibleCache::registerChildren(QAccessibleInterface *interface)
{
    qDebug() << "QSpiAccessibleCache::registerChildren";

    QAccessibleInterface *current;
    QSpiObject *accessible = NULL;
    QStack <QAccessibleInterface *> stack;

    if (interface == NULL || interface->object() == NULL)
        return;

    /* Depth first iteration over all un-registered objects */
    stack.push (interface);
    while (!stack.empty())
    {
        current = stack.pop();
        accessible = objectToAccessible(current->object());

        for (int i = 1; i <= current->childCount (); i++)
        {
            QAccessibleInterface *child = NULL;
            current->navigate(QAccessible::Child, i, &child);
            if (child)
            {
                stack.push (child);
            }
        }
    }
}

QSpiObject *QSpiAccessibleCache::objectToAccessible(QObject *obj)
{
    if (cache.contains(obj)) {
        return cache.value(obj);
    } else {
        QAccessibleInterface *interface = QAccessible::queryAccessibleInterface(obj);
        if (interface)
        {
            QSpiObject *accessible = new QSpiAccessible(this, interface, dbusConnection);

            cache.insert(interface->object(), accessible);

#if 0
            qDebug ("QSpiAccessibleBridge : accessibleRegistered.\n\t%s\n\t%s\n\t%s\n",
                     qPrintable(accessible->getReference().path()),
                     qPrintable(accessible->getParentPath().path()),
                     qPrintable (accessible->getInterface().text(QAccessible::Name, 0))
                   );
#endif

            qDebug() << "QSpiAccessibleCache::objectToAccessible AddAccessible";
            emit AddAccessible(accessible->getCacheItem()); // this one actually works!!!
            return accessible;
        }
    }
    return 0;
}

/* AT-SPI Cache interface ---------------------------------------------------*/

QSpiAccessibleCacheArray QSpiAccessibleCache::GetItems()
{
    QList <QSpiAccessibleCacheItem> cacheArray;

    foreach (QSpiObject *obj, cache.values())
    {
        cacheArray << obj->getCacheItem();
    }
    return cacheArray;
}

/*END------------------------------------------------------------------------*/
<commit_msg>Only emit AddAccessible once.<commit_after>/*
 * D-Bus AT-SPI, Qt Adaptor
 *
 * Copyright 2008, 2009      Nokia.
 * Copyright 2008, 2009      Codethink Ltd.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */

#include <QApplication>
#include <QObject>
#include <QWidget>
#include <QWidgetList>
#include <QApplication>
#include <QStackedWidget>

#include "cache.h"
#include "object.h"
#include "adaptor.h"
#include "accessible.h"

#include "generated/cache_adaptor.h"

#define QSPI_OBJECT_PATH_CACHE "/org/a11y/atspi/cache"

/*---------------------------------------------------------------------------*/

QSpiAccessibleCache::QSpiAccessibleCache(QObject *root, QDBusConnection c)
    : dbusConnection(c)
{
    CacheAdaptor *adaptor;

    //QApplication::instance()->installEventFilter(this);

    rootObject = root;
    cache.insert(root, new QSpiApplication(this, QAccessible::queryAccessibleInterface(root), dbusConnection));
    registerChildren(QAccessible::queryAccessibleInterface(root));

    adaptor = new CacheAdaptor(this);
    c.registerObject(QSPI_OBJECT_PATH_CACHE, this, QDBusConnection::ExportAdaptors);
}

/*---------------------------------------------------------------------------*/

QObject *QSpiAccessibleCache::getRoot ()
{
    return rootObject;
}

/*---------------------------------------------------------------------------*/

//bool QSpiAccessibleCache::eventFilter(QObject *obj, QEvent *event)
//{
//    QSpiObject *accessible = NULL;

//    switch (event->type ())
//    {
//        case QEvent::Show:
//        {
//            accessible = objectToAccessible (obj);
//            break;
//        }
//        /*
//         * FIXME: No Idea what to do here, the ChildAdded signal is BROKEN
//         * for accessibility as the accessible interface is not ready when this signal
//         * is emmited.
//         */
//#if 0
//        case QEvent::ChildAdded:
//        {
//            QList <QSpiObject *> children;
//            QObject *child = static_cast<QChildEvent *>(event)->child();

//            qDebug ("QSpiAccessibleBridge : childAdded.\n\t%s\n\t%s\n\t%s\n",
//                    qPrintable(accessible->getReference().path()),
//                    qPrintable(accessible->getParentPath().path()),
//                    qPrintable (accessible->getInterface().text(QAccessible::Name, 0))
//                   );

//            children = accessible->getChildren();
//            foreach (QSpiObject *chld, children)
//            {
//                qDebug ("\t\t%s", qPrintable(chld->getReference().path()));
//            }

//            registerChildren(child);
//            emit accessibleUpdated (accessible);
//            break;
//            // TODO
//            Emit the child added signal
//        }
//#endif
//        default:
//            break;
//    }
//    /* Think false is the right thing to do, no need to block these events here. */
//    return false;
//}

/*---------------------------------------------------------------------------*/

//void QSpiAccessibleCache::objectDestroyed (QObject *obj)
//{
//    if (cache.contains (obj))
//    {
//        QSpiObject *accessible = cache.take (obj);
//#if 0
//        qDebug("QSpiAccessibleBridge : Object Destroyed\n\t%s\n",
//               qPrintable(accessible->getReference().path()));
//#endif
//        emit RemoveAccessible (accessible->getReference());
//        delete accessible;
//    }
//}

/*
 * Registers all descendants of the given accessible interface with the cache.
 *
 * No Idea about the threading implications here.
 * What is the equivalent of the GDK lock?
 */
void QSpiAccessibleCache::registerChildren(QAccessibleInterface *interface)
{
    qDebug() << "QSpiAccessibleCache::registerChildren";

    QAccessibleInterface *current;
    QSpiObject *accessible = NULL;
    QStack <QAccessibleInterface *> stack;

    if (interface == NULL || interface->object() == NULL)
        return;

    /* Depth first iteration over all un-registered objects */
    stack.push (interface);
    while (!stack.empty())
    {
        current = stack.pop();
        accessible = objectToAccessible(current->object());

        for (int i = 1; i <= current->childCount (); i++)
        {
            QAccessibleInterface *child = NULL;
            current->navigate(QAccessible::Child, i, &child);
            if (child)
            {
                stack.push (child);
            }
        }
    }
}

QSpiObject *QSpiAccessibleCache::objectToAccessible(QObject *obj)
{
    if (cache.contains(obj)) {
        return cache.value(obj);
    } else {
        QAccessibleInterface *interface = QAccessible::queryAccessibleInterface(obj);
        if (interface)
        {
            QSpiObject *accessible = new QSpiAccessible(this, interface, dbusConnection);

            cache.insert(interface->object(), accessible);

#if 0
            qDebug ("QSpiAccessibleBridge : accessibleRegistered.\n\t%s\n\t%s\n\t%s\n",
                     qPrintable(accessible->getReference().path()),
                     qPrintable(accessible->getParentPath().path()),
                     qPrintable (accessible->getInterface().text(QAccessible::Name, 0))
                   );
#endif

            qDebug() << "QSpiAccessibleCache::objectToAccessible AddAccessible";
            emit AddAccessible(accessible->getCacheItem()); // this one actually works!!!
            return accessible;
        }
    }
    return 0;
}

/* AT-SPI Cache interface ---------------------------------------------------*/

QSpiAccessibleCacheArray QSpiAccessibleCache::GetItems()
{
    QList <QSpiAccessibleCacheItem> cacheArray;

    foreach (QSpiObject *obj, cache.values())
    {
        cacheArray << obj->getCacheItem();
    }
    return cacheArray;
}

/*END------------------------------------------------------------------------*/
<|endoftext|>


<commit_before>/*=========================================================================
 *
 *  Copyright RTK Consortium
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 *  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 "rtkramp_ggo.h"
#include "rtkMacro.h"

#include "rtkProjectionsReader.h"
#include "rtkFFTRampImageFilter.h"
#include "rtkConfiguration.h"
#if CUDA_FOUND
#  include "rtkCudaFFTRampImageFilter.h"
#endif

#include <itkImageFileWriter.h>
#include <itkRegularExpressionSeriesFileNames.h>
#include <itkStreamingImageFilter.h>
#include <itkTimeProbe.h>

int main(int argc, char * argv[])
{
  GGO(rtkramp, args_info);

  typedef float OutputPixelType;
  const unsigned int Dimension = 3;

  typedef itk::Image< OutputPixelType, Dimension > OutputImageType;

  // Generate file names
  itk::RegularExpressionSeriesFileNames::Pointer names = itk::RegularExpressionSeriesFileNames::New();
  names->SetDirectory(args_info.path_arg);
  names->SetNumericSort(false);
  names->SetRegularExpression(args_info.regexp_arg);
  names->SetSubMatch(0);

  // Projections reader
  typedef rtk::ProjectionsReader< OutputImageType > ReaderType;
  ReaderType::Pointer reader = ReaderType::New();
  reader->SetFileNames( names->GetFileNames() );

  TRY_AND_EXIT_ON_ITK_EXCEPTION( reader->Update() )

  // Ramp filter
  typedef rtk::FFTRampImageFilter<OutputImageType, OutputImageType, float > rampFilterType;
  rampFilterType::Pointer rampFilter;
  if( !strcmp(args_info.hardware_arg, "cuda") )
    {
#if CUDA_FOUND
    rampFilter = rtk::CudaFFTRampImageFilter::New();
#else
    std::cerr << "The program has not been compiled with cuda option" << std::endl;
    return EXIT_FAILURE;
#endif
    }
     rampFilter = rtk::CudaFFTRampImageFilter::New();
  else
    rampFilter = rampFilterType::New();
  rampFilter->SetInput( reader->GetOutput() );
  rampFilter->SetTruncationCorrection(args_info.pad_arg);
  rampFilter->SetHannCutFrequency(args_info.hann_arg);
  rampFilter->SetHannCutFrequencyY(args_info.hannY_arg);

  // Streaming filter
  typedef itk::StreamingImageFilter<OutputImageType, OutputImageType> StreamerType;
  StreamerType::Pointer streamer = StreamerType::New();
  streamer->SetInput( rampFilter->GetOutput() );
  streamer->SetNumberOfStreamDivisions( 1 + reader->GetOutput()->GetLargestPossibleRegion().GetNumberOfPixels() / (1024*1024*4) );

  itk::TimeProbe probe;
  probe.Start();
  TRY_AND_EXIT_ON_ITK_EXCEPTION( streamer->Update() )
  probe.Stop();
  std::cout << "The streamed ramp filter update took "
            << probe.GetMean()
            << probe.GetUnit()
            << std::endl;

  // Write
  typedef itk::ImageFileWriter<  OutputImageType > WriterType;
  WriterType::Pointer writer = WriterType::New();
  writer->SetFileName( args_info.output_arg );
  writer->SetInput( streamer->GetOutput() );
  writer->UpdateOutputInformation();

  TRY_AND_EXIT_ON_ITK_EXCEPTION( writer->Update() )

  return EXIT_SUCCESS;
}
<commit_msg>Compilation error<commit_after>/*=========================================================================
 *
 *  Copyright RTK Consortium
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 *  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 "rtkramp_ggo.h"
#include "rtkMacro.h"

#include "rtkProjectionsReader.h"
#include "rtkFFTRampImageFilter.h"
#include "rtkConfiguration.h"
#if CUDA_FOUND
#  include "rtkCudaFFTRampImageFilter.h"
#endif

#include <itkImageFileWriter.h>
#include <itkRegularExpressionSeriesFileNames.h>
#include <itkStreamingImageFilter.h>
#include <itkTimeProbe.h>

int main(int argc, char * argv[])
{
  GGO(rtkramp, args_info);

  typedef float OutputPixelType;
  const unsigned int Dimension = 3;

  typedef itk::Image< OutputPixelType, Dimension > OutputImageType;

  // Generate file names
  itk::RegularExpressionSeriesFileNames::Pointer names = itk::RegularExpressionSeriesFileNames::New();
  names->SetDirectory(args_info.path_arg);
  names->SetNumericSort(false);
  names->SetRegularExpression(args_info.regexp_arg);
  names->SetSubMatch(0);

  // Projections reader
  typedef rtk::ProjectionsReader< OutputImageType > ReaderType;
  ReaderType::Pointer reader = ReaderType::New();
  reader->SetFileNames( names->GetFileNames() );

  TRY_AND_EXIT_ON_ITK_EXCEPTION( reader->Update() )

  // Ramp filter
  typedef rtk::FFTRampImageFilter<OutputImageType, OutputImageType, float > rampFilterType;
  rampFilterType::Pointer rampFilter;
  if( !strcmp(args_info.hardware_arg, "cuda") )
    {
#if CUDA_FOUND
    rampFilter = rtk::CudaFFTRampImageFilter::New();
#else
    std::cerr << "The program has not been compiled with cuda option" << std::endl;
    return EXIT_FAILURE;
#endif
    }
  else
    rampFilter = rampFilterType::New();
  rampFilter->SetInput( reader->GetOutput() );
  rampFilter->SetTruncationCorrection(args_info.pad_arg);
  rampFilter->SetHannCutFrequency(args_info.hann_arg);
  rampFilter->SetHannCutFrequencyY(args_info.hannY_arg);

  // Streaming filter
  typedef itk::StreamingImageFilter<OutputImageType, OutputImageType> StreamerType;
  StreamerType::Pointer streamer = StreamerType::New();
  streamer->SetInput( rampFilter->GetOutput() );
  streamer->SetNumberOfStreamDivisions( 1 + reader->GetOutput()->GetLargestPossibleRegion().GetNumberOfPixels() / (1024*1024*4) );

  itk::TimeProbe probe;
  probe.Start();
  TRY_AND_EXIT_ON_ITK_EXCEPTION( streamer->Update() )
  probe.Stop();
  std::cout << "The streamed ramp filter update took "
            << probe.GetMean()
            << probe.GetUnit()
            << std::endl;

  // Write
  typedef itk::ImageFileWriter<  OutputImageType > WriterType;
  WriterType::Pointer writer = WriterType::New();
  writer->SetFileName( args_info.output_arg );
  writer->SetInput( streamer->GetOutput() );
  writer->UpdateOutputInformation();

  TRY_AND_EXIT_ON_ITK_EXCEPTION( writer->Update() )

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>
#include "config.h"

// boost
#include <boost/filesystem.hpp>

// dune-common
#include <dune/common/exceptions.hh>
#include <dune/common/mpihelper.hh>
#include <dune/common/timer.hh>

// dune-fem
#include <dune/fem/misc/mpimanager.hh>

// dune-grid-multiscale
#include <dune/grid/part/leaf.hh>

// dune-stuff
#include <dune/stuff/common/parameter/tree.hh>
#include <dune/stuff/common/logging.hh>
#include <dune/stuff/grid/provider/cube.hh>
#include <dune/stuff/grid/boundaryinfo.hh>

// dune-detailed-solvers
#include <dune/detailed/solvers/stationary/linear/elliptic/model/default.hh>
#include <dune/detailed/solvers/stationary/linear/elliptic/continuousgalerkin/dune-detailed-discretizations.hh>

#ifdef POLORDER
const int polOrder = POLORDER;
#else
const int polOrder = 1;
#endif

const std::string id = "stationary.linear.elliptic.cg.ddd";

/**
  \brief      Creates a parameter file if it does not exist.

              Nothing is done if the file already exists. If not, a parameter file will be created with all neccessary
              keys and values.
  \param[in]  filename
              (Relative) path to the file.
  **/
void ensureParamFile(std::string filename)
{
  // only write param file if there is none
  if (!boost::filesystem::exists(filename)) {
    std::ofstream file;
    file.open(filename);
    file << "[stuff.grid.provider.cube]" << std::endl;
    file << "level = 4" << std::endl;
    file << "filename = " << id << ".grid" << std::endl;
    file << "[detailed.solvers.stationary.linear.elliptic.model.default]" << std::endl;
    file << "diffusion.order = 0"  << std::endl;
    file << "diffusion.variable = x" << std::endl;
    file << "diffusion.expression.0 = 1.0"  << std::endl;
    file << "diffusion.expression.1 = 1.0"  << std::endl;
    file << "diffusion.expression.2 = 1.0"  << std::endl;
    file << "force.order = 0"  << std::endl;
    file << "force.variable = x" << std::endl;
    file << "force.expression.0 = 1.0"  << std::endl;
    file << "force.expression.1 = 1.0"  << std::endl;
    file << "force.expression.2 = 1.0"  << std::endl;
    file << "dirichlet.order = 0"  << std::endl;
    file << "dirichlet.variable = x" << std::endl;
    file << "dirichlet.expression.0 = 0.0"  << std::endl;
    file << "dirichlet.expression.1 = 0.0"  << std::endl;
    file << "dirichlet.expression.2 = 0.0"  << std::endl;
    file << "[detailed.solvers.stationary.linear.elliptic.continuousgalerkin]" << std::endl;
    file << "solve.type = eigen.bicgstab.incompletelut" << std::endl;
    file << "solve.maxIter = 5000"  << std::endl;
    file << "solve.precision = 1e-12"  << std::endl;
    file << "visualize.filename = " << id << ".solution"  << std::endl;
    file << "visualize.name = solution"  << std::endl;
    file.close();
  } // only write param file if there is none
} // void ensureParamFile()

int main(int argc, char** argv)
{
  try {
    // mpi
    Dune::MPIManager::initialize(argc, argv);

    // parameter
    const std::string filename = id + ".param";
    ensureParamFile(filename);
    Dune::Stuff::Common::ExtendedParameterTree paramTree(argc, argv, filename);

    // logger
    Dune::Stuff::Common::Logger().create(Dune::Stuff::Common::LOG_INFO |
                                         Dune::Stuff::Common::LOG_CONSOLE |
                                         Dune::Stuff::Common::LOG_DEBUG);
    Dune::Stuff::Common::LogStream& info = Dune::Stuff::Common::Logger().info();
//    std::ostream& info = std::cout;
    Dune::Stuff::Common::LogStream& debug = Dune::Stuff::Common::Logger().debug();

    // timer
    Dune::Timer timer;

    // grid
    info << "setting up grid: " << std::endl;
    debug.suspend();
    typedef Dune::Stuff::Grid::Provider::UnitCube<> GridProviderType;
    paramTree.assertSub(GridProviderType::id, id);
    const GridProviderType gridProvider(paramTree.sub(GridProviderType::id));
    typedef GridProviderType::GridType GridType;
    const Dune::shared_ptr< const GridType > grid = gridProvider.gridPtr();
    typedef Dune::grid::Part::Leaf::Const< GridType > GridPartType;
    const Dune::shared_ptr< const GridPartType > gridPart(new GridPartType(*grid));
    info << "  took " << timer.elapsed()
         << " sec, has " << grid->size(0) << " elements" << std::endl;
    info << "visualizing grid... " << std::flush;
    timer.reset();
    gridProvider.visualize(paramTree.sub(GridProviderType::id).get("filename", id + "_grid"));
    info << " done (took " << timer.elapsed() << " sek)" << std::endl;
    debug.resume();

    // model
    info << "setting up model... " << std::flush;
    timer.reset();
    const unsigned int DUNE_UNUSED(dimDomain) = GridProviderType::dim;
    const unsigned int DUNE_UNUSED(dimRange) = 1;
    typedef GridProviderType::CoordinateType::value_type DomainFieldType;
    typedef DomainFieldType RangeFieldType;
    typedef Dune::Detailed::Solvers::Stationary::Linear::Elliptic::Model::Default< DomainFieldType, dimDomain, RangeFieldType, dimRange > ModelType;
    paramTree.assertSub(ModelType::id, id);
    const Dune::shared_ptr< const ModelType > model(new ModelType(paramTree.sub(ModelType::id)));
    typedef Dune::Stuff::Grid::BoundaryInfo::AllDirichlet BoundaryInfoType;
    const Dune::shared_ptr< const BoundaryInfoType > boundaryInfo(new BoundaryInfoType());
    info << "done (took " << timer.elapsed() << " sec)" << std::endl;

    // solver
    info << "initializing solver:" << std::endl;
//    timer.reset();
    typedef Dune::Detailed::Solvers::Stationary::Linear::Elliptic::ContinuousGalerkin::DuneDetailedDiscretizations< ModelType,
                                                                                GridPartType,
                                                                                BoundaryInfoType,
                                                                                polOrder > SolverType;
    paramTree.assertSub(SolverType::id, id);
    SolverType solver(model, gridPart, boundaryInfo);
    solver.init("  ", info);
//    info << "done (took " << timer.elapsed() << " sec)" << std::endl;

    info << "solving:" << std::endl;
//    timer.reset();
    typedef SolverType::VectorBackendType DofVectorType;
    Dune::shared_ptr< DofVectorType > solution = solver.createVector();
    solver.solve(*solution, paramTree.sub(SolverType::id).sub("solve"), "  ", info);
//    info << "done (took " << timer.elapsed() << " sec)" << std::endl;

    info << "postprocessing:" << std::endl;
//    timer.reset();
    solver.visualize(*solution,
                     paramTree.sub(SolverType::id).sub("visualize").get("filename", id + "_solution"),
                     paramTree.sub(SolverType::id).sub("visualize").get("name", "solution"),
                     "  ",
                     info);
//    info << "done (took " << timer.elapsed() << " sec)" << std::endl;

    // if we came that far we can as well be happy about it
    return 0;
  } catch(Dune::Exception& e) {
    std::cerr << "Dune reported error: " << e.what() << std::endl;
  } catch(std::exception& e) {
    std::cerr << e.what() << std::endl;
  } catch( ... ) {
    std::cerr << "Unknown exception thrown!" << std::endl;
  } // try
} // main
<commit_msg>[examples...continuousgalerkin...] make use of the new model<commit_after>
#include "config.h"

// system
#include <sstream>

// boost
#include <boost/filesystem.hpp>

// dune-common
#include <dune/common/exceptions.hh>
#include <dune/common/mpihelper.hh>
#include <dune/common/timer.hh>

// dune-fem
#include <dune/fem/misc/mpimanager.hh>

// dune-grid-multiscale
#include <dune/grid/part/leaf.hh>

// dune-stuff
#include <dune/stuff/common/parameter/tree.hh>
#include <dune/stuff/common/logging.hh>
#include <dune/stuff/grid/provider/cube.hh>
#include <dune/stuff/grid/boundaryinfo.hh>

// dune-detailed-solvers
#include <dune/detailed/solvers/stationary/linear/elliptic/model/default.hh>
#include <dune/detailed/solvers/stationary/linear/elliptic/continuousgalerkin/dune-detailed-discretizations.hh>

#ifdef POLORDER
const int polOrder = POLORDER;
#else
const int polOrder = 1;
#endif

const std::string id = "stationary.linear.elliptic.cg.ddd";

/**
  \brief      Creates a parameter file if it does not exist.

              Nothing is done if the file already exists. If not, a parameter file will be created with all neccessary
              keys and values.
  \param[in]  filename
              (Relative) path to the file.
  **/
void ensureParamFile(std::string filename)
{
  // only write param file if there is none
  if (!boost::filesystem::exists(filename)) {
    std::ofstream file;
    file.open(filename);
    file << "[stationary.linear.elliptic.cg.ddd]" << std::endl;
    file << "model = detailed.solvers.stationary.linear.elliptic.model.default" << std::endl;
    file << "[stuff.grid.provider.cube]" << std::endl;
    file << "level = 4" << std::endl;
    file << "filename = " << id << ".grid" << std::endl;
    file << "[detailed.solvers.stationary.linear.elliptic.model.default]" << std::endl;
    file << "diffusion.order = 0"  << std::endl;
    file << "diffusion.variable = x" << std::endl;
    file << "diffusion.expression.0 = 1.0"  << std::endl;
    file << "diffusion.expression.1 = 1.0"  << std::endl;
    file << "diffusion.expression.2 = 1.0"  << std::endl;
    file << "force.order = 0"  << std::endl;
    file << "force.variable = x" << std::endl;
    file << "force.expression.0 = 1.0"  << std::endl;
    file << "force.expression.1 = 1.0"  << std::endl;
    file << "force.expression.2 = 1.0"  << std::endl;
    file << "dirichlet.order = 0"  << std::endl;
    file << "dirichlet.variable = x" << std::endl;
    file << "dirichlet.expression.0 = 0.0"  << std::endl;
    file << "dirichlet.expression.1 = 0.0"  << std::endl;
    file << "dirichlet.expression.2 = 0.0"  << std::endl;
    file << "[detailed.solvers.stationary.linear.elliptic.continuousgalerkin]" << std::endl;
    file << "solve.type = eigen.bicgstab.incompletelut" << std::endl;
    file << "solve.maxIter = 5000"  << std::endl;
    file << "solve.precision = 1e-12"  << std::endl;
    file << "visualize.filename = " << id << ".solution"  << std::endl;
    file << "visualize.name = solution"  << std::endl;
    file.close();
  } // only write param file if there is none
} // void ensureParamFile()

template< class DomainFieldType, int dimDomain, class RangeFieldType, int dimRange >
Dune::shared_ptr< Dune::Detailed::Solvers::Stationary::Linear::Elliptic::Model::Interface< DomainFieldType, dimDomain, RangeFieldType, dimRange > >
  createModel(const Dune::Stuff::Common::ExtendedParameterTree& paramTree)
{
  // prepare
  paramTree.assertKey(id + ".model");
  const std::string modelId = paramTree.sub(id).get("model", "default_value");
  typedef Dune::Detailed::Solvers::Stationary::Linear::Elliptic::Model::Interface< DomainFieldType, dimDomain, RangeFieldType, dimRange > ModelInterfaceType;
  // chosse model
  if (modelId == "detailed.solvers.stationary.linear.elliptic.model.default") {
    typedef Dune::Detailed::Solvers::Stationary::Linear::Elliptic::Model::Default< DomainFieldType, dimDomain, RangeFieldType, dimRange > ModelType;
    paramTree.assertSub(ModelType::id, id);
    Dune::shared_ptr< ModelInterfaceType > model(new ModelType(paramTree.sub(ModelType::id)));
    return model;
  } else {
    std::stringstream msg;
    msg << std::endl << "Error in " << id << ": unknown model ('" << modelId << "') given in the following Dune::Parametertree" << std::endl;
    paramTree.report(msg);
    DUNE_THROW(Dune::InvalidStateException, msg.str());
  } // chosse model
} // ... createModel(...)

int main(int argc, char** argv)
{
  try {
    // mpi
    Dune::MPIManager::initialize(argc, argv);

    // parameter
    const std::string filename = id + ".param";
    ensureParamFile(filename);
    Dune::Stuff::Common::ExtendedParameterTree paramTree(argc, argv, filename);

    // logger
    Dune::Stuff::Common::Logger().create(Dune::Stuff::Common::LOG_INFO |
                                         Dune::Stuff::Common::LOG_CONSOLE |
                                         Dune::Stuff::Common::LOG_DEBUG);
    Dune::Stuff::Common::LogStream& info = Dune::Stuff::Common::Logger().info();
//    std::ostream& info = std::cout;
    Dune::Stuff::Common::LogStream& debug = Dune::Stuff::Common::Logger().debug();

    // timer
    Dune::Timer timer;

    // grid
    info << "setting up grid: " << std::endl;
    debug.suspend();
    typedef Dune::Stuff::Grid::Provider::UnitCube<> GridProviderType;
    paramTree.assertSub(GridProviderType::id, id);
    const GridProviderType gridProvider(paramTree.sub(GridProviderType::id));
    typedef GridProviderType::GridType GridType;
    const Dune::shared_ptr< const GridType > grid = gridProvider.gridPtr();
    typedef Dune::grid::Part::Leaf::Const< GridType > GridPartType;
    const Dune::shared_ptr< const GridPartType > gridPart(new GridPartType(*grid));
    info << "  took " << timer.elapsed()
         << " sec, has " << grid->size(0) << " elements" << std::endl;
    info << "visualizing grid... " << std::flush;
    timer.reset();
    gridProvider.visualize(paramTree.sub(GridProviderType::id).get("filename", id + "_grid"));
    info << " done (took " << timer.elapsed() << " sek)" << std::endl;
    debug.resume();

    // model
    info << "setting up model... " << std::flush;
    timer.reset();
    const unsigned int DUNE_UNUSED(dimDomain) = GridProviderType::dim;
    const unsigned int DUNE_UNUSED(dimRange) = 1;
    typedef GridProviderType::CoordinateType::value_type DomainFieldType;
    typedef DomainFieldType RangeFieldType;
    paramTree.assertSub(id, id);
    typedef Dune::Detailed::Solvers::Stationary::Linear::Elliptic::Model::Interface< DomainFieldType, dimDomain, RangeFieldType, dimRange > ModelType;
    const Dune::shared_ptr< const ModelType > model = createModel< DomainFieldType, dimDomain, RangeFieldType, dimRange >(paramTree);
    typedef Dune::Stuff::Grid::BoundaryInfo::AllDirichlet BoundaryInfoType;
    const Dune::shared_ptr< const BoundaryInfoType > boundaryInfo(new BoundaryInfoType());
    info << "done (took " << timer.elapsed() << " sec)" << std::endl;

    // solver
    info << "initializing solver:" << std::endl;
//    timer.reset();
    typedef Dune::Detailed::Solvers::Stationary::Linear::Elliptic::ContinuousGalerkin::DuneDetailedDiscretizations< ModelType,
                                                                                GridPartType,
                                                                                BoundaryInfoType,
                                                                                polOrder > SolverType;
    paramTree.assertSub(SolverType::id, id);
    SolverType solver(model, gridPart, boundaryInfo);
    solver.init("  ", info);
//    info << "done (took " << timer.elapsed() << " sec)" << std::endl;

    info << "solving:" << std::endl;
//    timer.reset();
    typedef SolverType::VectorBackendType DofVectorType;
    Dune::shared_ptr< DofVectorType > solution = solver.createVector();
    solver.solve(*solution, paramTree.sub(SolverType::id).sub("solve"), "  ", info);
//    info << "done (took " << timer.elapsed() << " sec)" << std::endl;

    info << "postprocessing:" << std::endl;
//    timer.reset();
    solver.visualize(*solution,
                     paramTree.sub(SolverType::id).sub("visualize").get("filename", id + "_solution"),
                     paramTree.sub(SolverType::id).sub("visualize").get("name", "solution"),
                     "  ",
                     info);
//    info << "done (took " << timer.elapsed() << " sec)" << std::endl;

    // if we came that far we can as well be happy about it
    return 0;
  } catch(Dune::Exception& e) {
    std::cerr << "Dune reported error: " << e.what() << std::endl;
  } catch(std::exception& e) {
    std::cerr << e.what() << std::endl;
  } catch( ... ) {
    std::cerr << "Unknown exception thrown!" << std::endl;
  } // try
} // main
<|endoftext|>