<commit_before>#include "ResourceView.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 <Engine/Hymn.hpp>
#include <DefaultAlbedo.png.hpp>
#include <Engine/MainWindow.hpp>
#include <imgui.h>
#include <limits>
#include "../ImGui/Splitter.hpp"
#include <Engine/Manager/Managers.hpp>
#include <Engine/Manager/ResourceManager.hpp>
#include <cstdio>
#include <Utility/Log.hpp>

using namespace GUI;
using namespace std;

ResourceView::ResourceView() {
    folderNameWindow.SetClosedCallback(std::bind(&ResourceView::FileNameWindowClosed, this, placeholders::_1));
}

void ResourceView::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);

    // Show resources.
    scriptPressed = false;
    texturePressed = false;
    modelPressed = false;
    soundPressed = false;

    ShowResourceFolder(Resources().resourceFolder, Resources().resourceFolder.name);

    // Change scene.
    if (changeScene) {
        if (Hymn().GetPath() != "") {
            savePromptWindow.SetVisible(true);
            savePromptWindow.Show();

            switch (savePromptWindow.GetDecision()) {
            case 0:
                sceneEditor.Save();
                sceneEditor.SetVisible(true);
                sceneEditor.SetScene(resourcePath, scene);
                Resources().activeScene = resourcePath + "/" + *scene;
                sceneEditor.entityEditor.SetVisible(false);
                Hymn().world.Clear();
                Hymn().world.Load(Hymn().GetPath() + "/" + Resources().activeScene + ".json");
                changeScene = false;
                savePromptWindow.SetVisible(false);
                savePromptWindow.ResetDecision();
                break;

            case 1:
                sceneEditor.SetVisible(true);
                sceneEditor.SetScene(resourcePath, scene);
                Resources().activeScene = resourcePath + "/" + *scene;
                sceneEditor.entityEditor.SetVisible(false);
                Hymn().world.Clear();
                Hymn().world.Load(Hymn().GetPath() + "/" + Resources().activeScene + ".json");
                changeScene = false;
                savePromptWindow.SetVisible(false);
                savePromptWindow.ResetDecision();
                break;

            case 2:
                changeScene = false;
                savePromptWindow.ResetDecision();
                savePromptWindow.SetVisible(false);
                break;

            default:
                break;
            }
        }
    }

    // Create folder.
    if (folderNameWindow.IsVisible())
        folderNameWindow.Show();

    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 ResourceView::IsVisible() const {
    return visible;
}

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

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

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

#undef max
void ResourceView::ResetScene() {
    sceneEditor.SetScene("", nullptr);
    sceneEditor.SetVisible(false);
}

SceneEditor& ResourceView::GetScene() {
    return sceneEditor;
}

void ResourceView::ShowResourceFolder(ResourceList::ResourceFolder& folder, const std::string& path) {
    bool opened = ImGui::TreeNode(folder.name.c_str());

    if (ImGui::BeginPopupContextItem(folder.name.c_str())) {
        // Add subfolder.
        if (ImGui::Selectable("Add folder")) {
            resourcePath = path;
            parentFolder = &folder;
            folderNameWindow.SetVisible(true);
            return;
        }

        // Add scene.
        if (ImGui::Selectable("Add scene")) {
            ResourceList::Resource resource;
            resource.type = ResourceList::Resource::SCENE;
            resource.scene = "Scene #" + std::to_string(Resources().sceneNumber++);
            folder.resources.push_back(resource);
            return;
        }

        // Add model.
        if (ImGui::Selectable("Add model")) {
            ResourceList::Resource resource;
            resource.type = ResourceList::Resource::MODEL;
            resource.model = new Geometry::Model();
            resource.model->name = "Model #" + std::to_string(Resources().modelNumber++);
            folder.resources.push_back(resource);
            return;
        }

        // Add texture.
        if (ImGui::Selectable("Add texture")) {
            ResourceList::Resource resource;
            resource.type = ResourceList::Resource::TEXTURE;
            string name = path + "/Texture #" + std::to_string(Resources().textureNumber++);
            resource.texture = Managers().resourceManager->CreateTextureAsset(name, Managers().resourceManager->CreateTexture2D(DEFAULTALBEDO_PNG, DEFAULTALBEDO_PNG_LENGTH));
            folder.resources.push_back(resource);
            return;
        }

        // Add script.
        if (ImGui::Selectable("Add script")) {
            ResourceList::Resource resource;
            resource.type = ResourceList::Resource::SCRIPT;
            resource.script = new ScriptFile();
            resource.script->path = path + "/";
            resource.script->name = "Script #" + std::to_string(Hymn().scriptNumber++);
            Hymn().scripts.push_back(resource.script);
            folder.resources.push_back(resource);
            return;
        }

        /// @todo Add sound.
        if (ImGui::Selectable("Add sound")) {

        }

        /// @todo Remove folder.

        ImGui::EndPopup();
    }

    if (opened) {
        // Show subfolders.
        for (ResourceList::ResourceFolder& subfolder : folder.subfolders) {
            ShowResourceFolder(subfolder, path + "/" + subfolder.name);
        }

        // Show resources.
        for (auto it = folder.resources.begin(); it != folder.resources.end(); ++it) {
            if (ShowResource(*it, path)) {
                folder.resources.erase(it);
                return;
            }
        }

        ImGui::TreePop();
    }
}

bool ResourceView::ShowResource(ResourceList::Resource& resource, const std::string& path) {
    // Scene.
    if (resource.type == ResourceList::Resource::SCENE) {
        if (ImGui::Selectable(resource.scene.c_str())) {
            // Sets to don't save when opening first scene.
            if (scene == nullptr) {
                changeScene = true;
                resourcePath = path;
                scene = &resource.scene;
                savePromptWindow.SetVisible(false);
                savePromptWindow.SetDecision(1);
            } else {
                // Does so that the prompt window won't show if you select active scene.
                if (resource.scene != Resources().activeScene) {
                    changeScene = true;
                    resourcePath = path;
                    scene = &resource.scene;
                    savePromptWindow.SetTitle("Save before you switch scene?");
                }
            }
        }

        // Delete scene.
        if (ImGui::BeginPopupContextItem(resource.scene.c_str())) {
            if (ImGui::Selectable("Delete")) {
                if (Resources().activeScene == resource.scene) {
                    Resources().activeScene = "";
                    sceneEditor.SetScene("", nullptr);
                }

                ImGui::EndPopup();

                return true;
            }
            ImGui::EndPopup();
        }
    }

    /*
    // Models.
    bool modelPressed = false;
    if (ImGui::TreeNode("Models")) {
        for (auto it = Resources().models.begin(); it != Resources().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;
                    Resources().models.erase(it);
                    ImGui::EndPopup();
                    break;
                }
                ImGui::EndPopup();
            }
        }
        ImGui::TreePop();
    }

    // Textures.
    bool texturePressed = false;
    if (ImGui::TreeNode("Textures")) {
        for (auto it = Resources().textures.begin(); it != Resources().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 (Managers().resourceManager->GetTextureAssetInstanceCount(texture) > 1) {
                        Log() << "This texture is in use. Remove all references to the texture first.\n";
                    } else {
                        if (textureEditor.GetTexture() == texture)
                            textureEditor.SetVisible(false);

                        // Remove files.
                        remove((Hymn().GetPath() + FileSystem::DELIMITER + "Textures" + FileSystem::DELIMITER + texture->name + ".png").c_str());
                        remove((Hymn().GetPath() + FileSystem::DELIMITER + "Textures" + FileSystem::DELIMITER + texture->name + ".json").c_str());

                        Managers().resourceManager->FreeTextureAsset(texture);
                        Resources().textures.erase(it);
                    }
                    ImGui::EndPopup();
                    break;
                }
                ImGui::EndPopup();
            }
        }

        ImGui::TreePop();
    }

    // Scripts.
    bool scriptPressed = false;
    if (ImGui::TreeNode("Scripts")) {
        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(Resources().soundNumber++);
            Resources().sounds.push_back(sound);
        }

        for (auto it = Resources().sounds.begin(); it != Resources().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;
                    Resources().sounds.erase(it);
                    ImGui::EndPopup();
                    break;
                }
                ImGui::EndPopup();
            }
        }

        ImGui::TreePop();
    }*/

    return false;
}

void ResourceView::FileNameWindowClosed(const std::string& name) {
    if (!name.empty()) {
        ResourceList::ResourceFolder folder;
        folder.name = name;
        parentFolder->subfolders.push_back(folder);

        FileSystem::CreateDirectory((Hymn().GetPath() + "/" + resourcePath + "/" + name).c_str());
    }
}
<commit_msg>Add sound<commit_after>#include "ResourceView.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 <Engine/Hymn.hpp>
#include <DefaultAlbedo.png.hpp>
#include <Engine/MainWindow.hpp>
#include <imgui.h>
#include <limits>
#include "../ImGui/Splitter.hpp"
#include <Engine/Manager/Managers.hpp>
#include <Engine/Manager/ResourceManager.hpp>
#include <cstdio>
#include <Utility/Log.hpp>

using namespace GUI;
using namespace std;

ResourceView::ResourceView() {
    folderNameWindow.SetClosedCallback(std::bind(&ResourceView::FileNameWindowClosed, this, placeholders::_1));
}

void ResourceView::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);

    // Show resources.
    scriptPressed = false;
    texturePressed = false;
    modelPressed = false;
    soundPressed = false;

    ShowResourceFolder(Resources().resourceFolder, Resources().resourceFolder.name);

    // Change scene.
    if (changeScene) {
        if (Hymn().GetPath() != "") {
            savePromptWindow.SetVisible(true);
            savePromptWindow.Show();

            switch (savePromptWindow.GetDecision()) {
            case 0:
                sceneEditor.Save();
                sceneEditor.SetVisible(true);
                sceneEditor.SetScene(resourcePath, scene);
                Resources().activeScene = resourcePath + "/" + *scene;
                sceneEditor.entityEditor.SetVisible(false);
                Hymn().world.Clear();
                Hymn().world.Load(Hymn().GetPath() + "/" + Resources().activeScene + ".json");
                changeScene = false;
                savePromptWindow.SetVisible(false);
                savePromptWindow.ResetDecision();
                break;

            case 1:
                sceneEditor.SetVisible(true);
                sceneEditor.SetScene(resourcePath, scene);
                Resources().activeScene = resourcePath + "/" + *scene;
                sceneEditor.entityEditor.SetVisible(false);
                Hymn().world.Clear();
                Hymn().world.Load(Hymn().GetPath() + "/" + Resources().activeScene + ".json");
                changeScene = false;
                savePromptWindow.SetVisible(false);
                savePromptWindow.ResetDecision();
                break;

            case 2:
                changeScene = false;
                savePromptWindow.ResetDecision();
                savePromptWindow.SetVisible(false);
                break;

            default:
                break;
            }
        }
    }

    // Create folder.
    if (folderNameWindow.IsVisible())
        folderNameWindow.Show();

    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 ResourceView::IsVisible() const {
    return visible;
}

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

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

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

#undef max
void ResourceView::ResetScene() {
    sceneEditor.SetScene("", nullptr);
    sceneEditor.SetVisible(false);
}

SceneEditor& ResourceView::GetScene() {
    return sceneEditor;
}

void ResourceView::ShowResourceFolder(ResourceList::ResourceFolder& folder, const std::string& path) {
    bool opened = ImGui::TreeNode(folder.name.c_str());

    if (ImGui::BeginPopupContextItem(folder.name.c_str())) {
        // Add subfolder.
        if (ImGui::Selectable("Add folder")) {
            resourcePath = path;
            parentFolder = &folder;
            folderNameWindow.SetVisible(true);
            return;
        }

        // Add scene.
        if (ImGui::Selectable("Add scene")) {
            ResourceList::Resource resource;
            resource.type = ResourceList::Resource::SCENE;
            resource.scene = "Scene #" + std::to_string(Resources().sceneNumber++);
            folder.resources.push_back(resource);
            return;
        }

        // Add model.
        if (ImGui::Selectable("Add model")) {
            ResourceList::Resource resource;
            resource.type = ResourceList::Resource::MODEL;
            resource.model = new Geometry::Model();
            resource.model->path = path + "/";
            resource.model->name = "Model #" + std::to_string(Resources().modelNumber++);
            folder.resources.push_back(resource);
            return;
        }

        // Add texture.
        if (ImGui::Selectable("Add texture")) {
            ResourceList::Resource resource;
            resource.type = ResourceList::Resource::TEXTURE;
            string name = path + "/Texture #" + std::to_string(Resources().textureNumber++);
            resource.texture = Managers().resourceManager->CreateTextureAsset(name, Managers().resourceManager->CreateTexture2D(DEFAULTALBEDO_PNG, DEFAULTALBEDO_PNG_LENGTH));
            folder.resources.push_back(resource);
            return;
        }

        // Add script.
        if (ImGui::Selectable("Add script")) {
            ResourceList::Resource resource;
            resource.type = ResourceList::Resource::SCRIPT;
            resource.script = new ScriptFile();
            resource.script->path = path + "/";
            resource.script->name = "Script #" + std::to_string(Hymn().scriptNumber++);
            Hymn().scripts.push_back(resource.script);
            folder.resources.push_back(resource);
            return;
        }

        // Add sound.
        if (ImGui::Selectable("Add sound")) {
            ResourceList::Resource resource;
            resource.type = ResourceList::Resource::SOUND;
            resource.sound = new Audio::SoundBuffer();
            resource.sound->path = path + "/";
            resource.sound->name = "Sound #" + std::to_string(Resources().soundNumber++);
            folder.resources.push_back(resource);
            return;
        }

        /// @todo Remove folder.

        ImGui::EndPopup();
    }

    if (opened) {
        // Show subfolders.
        for (ResourceList::ResourceFolder& subfolder : folder.subfolders) {
            ShowResourceFolder(subfolder, path + "/" + subfolder.name);
        }

        // Show resources.
        for (auto it = folder.resources.begin(); it != folder.resources.end(); ++it) {
            if (ShowResource(*it, path)) {
                folder.resources.erase(it);
                return;
            }
        }

        ImGui::TreePop();
    }
}

bool ResourceView::ShowResource(ResourceList::Resource& resource, const std::string& path) {
    // Scene.
    if (resource.type == ResourceList::Resource::SCENE) {
        if (ImGui::Selectable(resource.scene.c_str())) {
            // Sets to don't save when opening first scene.
            if (scene == nullptr) {
                changeScene = true;
                resourcePath = path;
                scene = &resource.scene;
                savePromptWindow.SetVisible(false);
                savePromptWindow.SetDecision(1);
            } else {
                // Does so that the prompt window won't show if you select active scene.
                if (resource.scene != Resources().activeScene) {
                    changeScene = true;
                    resourcePath = path;
                    scene = &resource.scene;
                    savePromptWindow.SetTitle("Save before you switch scene?");
                }
            }
        }

        // Delete scene.
        if (ImGui::BeginPopupContextItem(resource.scene.c_str())) {
            if (ImGui::Selectable("Delete")) {
                if (Resources().activeScene == resource.scene) {
                    Resources().activeScene = "";
                    sceneEditor.SetScene("", nullptr);
                }

                ImGui::EndPopup();

                return true;
            }
            ImGui::EndPopup();
        }
    }

    /*
    // Models.
    bool modelPressed = false;
    if (ImGui::TreeNode("Models")) {
        for (auto it = Resources().models.begin(); it != Resources().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;
                    Resources().models.erase(it);
                    ImGui::EndPopup();
                    break;
                }
                ImGui::EndPopup();
            }
        }
        ImGui::TreePop();
    }

    // Textures.
    bool texturePressed = false;
    if (ImGui::TreeNode("Textures")) {
        for (auto it = Resources().textures.begin(); it != Resources().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 (Managers().resourceManager->GetTextureAssetInstanceCount(texture) > 1) {
                        Log() << "This texture is in use. Remove all references to the texture first.\n";
                    } else {
                        if (textureEditor.GetTexture() == texture)
                            textureEditor.SetVisible(false);

                        // Remove files.
                        remove((Hymn().GetPath() + FileSystem::DELIMITER + "Textures" + FileSystem::DELIMITER + texture->name + ".png").c_str());
                        remove((Hymn().GetPath() + FileSystem::DELIMITER + "Textures" + FileSystem::DELIMITER + texture->name + ".json").c_str());

                        Managers().resourceManager->FreeTextureAsset(texture);
                        Resources().textures.erase(it);
                    }
                    ImGui::EndPopup();
                    break;
                }
                ImGui::EndPopup();
            }
        }

        ImGui::TreePop();
    }

    // Scripts.
    bool scriptPressed = false;
    if (ImGui::TreeNode("Scripts")) {
        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")) {
        for (auto it = Resources().sounds.begin(); it != Resources().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;
                    Resources().sounds.erase(it);
                    ImGui::EndPopup();
                    break;
                }
                ImGui::EndPopup();
            }
        }

        ImGui::TreePop();
    }*/

    return false;
}

void ResourceView::FileNameWindowClosed(const std::string& name) {
    if (!name.empty()) {
        ResourceList::ResourceFolder folder;
        folder.name = name;
        parentFolder->subfolders.push_back(folder);

        FileSystem::CreateDirectory((Hymn().GetPath() + "/" + resourcePath + "/" + name).c_str());
    }
}
<|endoftext|>


<commit_before>/*
 * Copyright 2011 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "gm.h"
#include "SkCanvas.h"
#include "SkColorPriv.h"
#include "SkShader.h"

/*
 *  Want to ensure that our bitmap sampler (in bitmap shader) keeps plenty of
 *  precision when scaling very large images (where the dx might get very small.
 */

#define W   256
#define H   160

class GiantBitmapGM : public skiagm::GM {
    SkBitmap* fBM;
    SkShader::TileMode fMode;
    bool fDoFilter;
    bool fDoRotate;

    const SkBitmap& getBitmap() {
        if (NULL == fBM) {
            fBM = new SkBitmap;
            fBM->setConfig(SkBitmap::kARGB_8888_Config, W, H);
            fBM->allocPixels();
            fBM->eraseColor(SK_ColorWHITE);

            const SkColor colors[] = {
                SK_ColorBLUE, SK_ColorRED, SK_ColorBLACK, SK_ColorGREEN
            };

            SkCanvas canvas(*fBM);
            SkPaint paint;
            paint.setAntiAlias(true);
            paint.setStrokeWidth(SkIntToScalar(30));
            for (int y = -H*2; y < H; y += 80) {
                SkScalar yy = SkIntToScalar(y);
                paint.setColor(colors[y/80 & 0x3]);
                canvas.drawLine(0, yy, SkIntToScalar(W), yy + SkIntToScalar(W),
                                paint);
            }
        }
        return *fBM;
    }

public:
    GiantBitmapGM(SkShader::TileMode mode, bool doFilter, bool doRotate) : fBM(NULL) {
        fMode = mode;
        fDoFilter = doFilter;
        fDoRotate = doRotate;
    }

    virtual ~GiantBitmapGM() {
        SkDELETE(fBM);
    }

protected:
    virtual SkString onShortName() {
        SkString str("giantbitmap_");
        switch (fMode) {
            case SkShader::kClamp_TileMode:
                str.append("clamp");
                break;
            case SkShader::kRepeat_TileMode:
                str.append("repeat");
                break;
            case SkShader::kMirror_TileMode:
                str.append("mirror");
                break;
            default:
                break;
        }
        str.append(fDoFilter ? "_bilerp" : "_point");
        str.append(fDoRotate ? "_rotate" : "_scale");
        return str;
    }

    virtual SkISize onISize() { return SkISize::Make(640, 480); }

    virtual void onDraw(SkCanvas* canvas) {
        SkPaint paint;
        SkShader* s = SkShader::CreateBitmapShader(getBitmap(), fMode, fMode);

        SkMatrix m;
        if (fDoRotate) {
//            m.setRotate(SkIntToScalar(30), 0, 0);
            m.setSkew(SK_Scalar1, 0, 0, 0);
            m.postScale(2*SK_Scalar1/3, 2*SK_Scalar1/3);
        } else {
            m.setScale(2*SK_Scalar1/3, 2*SK_Scalar1/3);
        }
        s->setLocalMatrix(m);

        paint.setShader(s)->unref();
        paint.setFilterBitmap(fDoFilter);

        canvas->translate(SkIntToScalar(50), SkIntToScalar(50));
        canvas->drawPaint(paint);
    }

private:
    typedef GM INHERITED;
};

///////////////////////////////////////////////////////////////////////////////

static skiagm::GM* G000(void*) { return new GiantBitmapGM(SkShader::kClamp_TileMode, false, false); }
static skiagm::GM* G100(void*) { return new GiantBitmapGM(SkShader::kRepeat_TileMode, false, false); }
static skiagm::GM* G200(void*) { return new GiantBitmapGM(SkShader::kMirror_TileMode, false, false); }
static skiagm::GM* G010(void*) { return new GiantBitmapGM(SkShader::kClamp_TileMode, true, false); }
static skiagm::GM* G110(void*) { return new GiantBitmapGM(SkShader::kRepeat_TileMode, true, false); }
static skiagm::GM* G210(void*) { return new GiantBitmapGM(SkShader::kMirror_TileMode, true, false); }

static skiagm::GM* G001(void*) { return new GiantBitmapGM(SkShader::kClamp_TileMode, false, true); }
static skiagm::GM* G101(void*) { return new GiantBitmapGM(SkShader::kRepeat_TileMode, false, true); }
static skiagm::GM* G201(void*) { return new GiantBitmapGM(SkShader::kMirror_TileMode, false, true); }
static skiagm::GM* G011(void*) { return new GiantBitmapGM(SkShader::kClamp_TileMode, true, true); }
static skiagm::GM* G111(void*) { return new GiantBitmapGM(SkShader::kRepeat_TileMode, true, true); }
static skiagm::GM* G211(void*) { return new GiantBitmapGM(SkShader::kMirror_TileMode, true, true); }

static skiagm::GMRegistry reg000(G000);
static skiagm::GMRegistry reg100(G100);
static skiagm::GMRegistry reg200(G200);
static skiagm::GMRegistry reg010(G010);
static skiagm::GMRegistry reg110(G110);
static skiagm::GMRegistry reg210(G210);

static skiagm::GMRegistry reg001(G001);
static skiagm::GMRegistry reg101(G101);
static skiagm::GMRegistry reg201(G201);
static skiagm::GMRegistry reg011(G011);
static skiagm::GMRegistry reg111(G111);
static skiagm::GMRegistry reg211(G211);

<commit_msg>update test<commit_after>/*
 * Copyright 2011 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "gm.h"
#include "SkCanvas.h"
#include "SkColorPriv.h"
#include "SkShader.h"

/*
 *  Want to ensure that our bitmap sampler (in bitmap shader) keeps plenty of
 *  precision when scaling very large images (where the dx might get very small.
 */

#define W   257
#define H   161

class GiantBitmapGM : public skiagm::GM {
    SkBitmap* fBM;
    SkShader::TileMode fMode;
    bool fDoFilter;
    bool fDoRotate;

    const SkBitmap& getBitmap() {
        if (NULL == fBM) {
            fBM = new SkBitmap;
            fBM->setConfig(SkBitmap::kARGB_8888_Config, W, H);
            fBM->allocPixels();
            fBM->eraseColor(SK_ColorWHITE);

            const SkColor colors[] = {
                SK_ColorBLUE, SK_ColorRED, SK_ColorBLACK, SK_ColorGREEN
            };

            SkCanvas canvas(*fBM);
            SkPaint paint;
            paint.setAntiAlias(true);
            paint.setStrokeWidth(SkIntToScalar(20));

#if 0
            for (int y = -H*2; y < H; y += 50) {
                SkScalar yy = SkIntToScalar(y);
                paint.setColor(colors[y/50 & 0x3]);
                canvas.drawLine(0, yy, SkIntToScalar(W), yy + SkIntToScalar(W),
                                paint);
            }
#else
            for (int x = -W; x < W; x += 60) {
                paint.setColor(colors[x/60 & 0x3]);

                SkScalar xx = SkIntToScalar(x);
                canvas.drawLine(xx, 0, xx, SkIntToScalar(H),
                                paint);
            }
#endif
        }
        return *fBM;
    }

public:
    GiantBitmapGM(SkShader::TileMode mode, bool doFilter, bool doRotate) : fBM(NULL) {
        fMode = mode;
        fDoFilter = doFilter;
        fDoRotate = doRotate;
    }

    virtual ~GiantBitmapGM() {
        SkDELETE(fBM);
    }

protected:
    virtual SkString onShortName() {
        SkString str("giantbitmap_");
        switch (fMode) {
            case SkShader::kClamp_TileMode:
                str.append("clamp");
                break;
            case SkShader::kRepeat_TileMode:
                str.append("repeat");
                break;
            case SkShader::kMirror_TileMode:
                str.append("mirror");
                break;
            default:
                break;
        }
        str.append(fDoFilter ? "_bilerp" : "_point");
        str.append(fDoRotate ? "_rotate" : "_scale");
        return str;
    }

    virtual SkISize onISize() { return SkISize::Make(640, 480); }

    virtual void onDraw(SkCanvas* canvas) {
        SkPaint paint;
        SkShader* s = SkShader::CreateBitmapShader(getBitmap(), fMode, fMode);

        SkMatrix m;
        if (fDoRotate) {
//            m.setRotate(SkIntToScalar(30), 0, 0);
            m.setSkew(SK_Scalar1, 0, 0, 0);
//            m.postScale(2*SK_Scalar1/3, 2*SK_Scalar1/3);
        } else {
            SkScalar scale = 11*SK_Scalar1/12;
            m.setScale(scale, scale);
        }
        s->setLocalMatrix(m);

        paint.setShader(s)->unref();
        paint.setFilterBitmap(fDoFilter);

        canvas->translate(SkIntToScalar(50), SkIntToScalar(50));

        SkRect r = SkRect::MakeXYWH(-50, -50, 32, 16);
//        canvas->drawRect(r, paint); return;
        canvas->drawPaint(paint);
    }

private:
    typedef GM INHERITED;
};

///////////////////////////////////////////////////////////////////////////////

static skiagm::GM* G000(void*) { return new GiantBitmapGM(SkShader::kClamp_TileMode, false, false); }
static skiagm::GM* G100(void*) { return new GiantBitmapGM(SkShader::kRepeat_TileMode, false, false); }
static skiagm::GM* G200(void*) { return new GiantBitmapGM(SkShader::kMirror_TileMode, false, false); }
static skiagm::GM* G010(void*) { return new GiantBitmapGM(SkShader::kClamp_TileMode, true, false); }
static skiagm::GM* G110(void*) { return new GiantBitmapGM(SkShader::kRepeat_TileMode, true, false); }
static skiagm::GM* G210(void*) { return new GiantBitmapGM(SkShader::kMirror_TileMode, true, false); }

static skiagm::GM* G001(void*) { return new GiantBitmapGM(SkShader::kClamp_TileMode, false, true); }
static skiagm::GM* G101(void*) { return new GiantBitmapGM(SkShader::kRepeat_TileMode, false, true); }
static skiagm::GM* G201(void*) { return new GiantBitmapGM(SkShader::kMirror_TileMode, false, true); }
static skiagm::GM* G011(void*) { return new GiantBitmapGM(SkShader::kClamp_TileMode, true, true); }
static skiagm::GM* G111(void*) { return new GiantBitmapGM(SkShader::kRepeat_TileMode, true, true); }
static skiagm::GM* G211(void*) { return new GiantBitmapGM(SkShader::kMirror_TileMode, true, true); }

static skiagm::GMRegistry reg000(G000);
static skiagm::GMRegistry reg100(G100);
static skiagm::GMRegistry reg200(G200);
static skiagm::GMRegistry reg010(G010);
static skiagm::GMRegistry reg110(G110);
static skiagm::GMRegistry reg210(G210);

static skiagm::GMRegistry reg001(G001);
static skiagm::GMRegistry reg101(G101);
static skiagm::GMRegistry reg201(G201);
static skiagm::GMRegistry reg011(G011);
static skiagm::GMRegistry reg111(G111);
static skiagm::GMRegistry reg211(G211);

<|endoftext|>


<commit_before>//
//  File:       PBody.cpp
//  Class:      PBody
//  Author:     Jesper Persson
//              All code is my own except where credited to others.
//
//	Copyright (c) 2012 by Catch22. All Rights Reserved.
//  Date: 		29/09-2012
//

#include "PBody.hpp"
#include "../../Helper/Logger.hpp"
#include "../../Math/Math.hpp"

PBody::PBody(Vector2dArray* vectorArray, Vector2d* centerOfMassOffset, bool affectedByGravity, bool stationaryObject, bool rotatableObject, PBodyType tag)
{
    m_vectorArray = vectorArray;
    m_centerOfMassOffset = centerOfMassOffset;
    m_affectedByGravity = affectedByGravity;
    m_stationaryObject = stationaryObject;
    m_rotatableObject = rotatableObject;

    m_movementVector = new Vector2d(0,0);
    m_tag = tag;
}
PBody::PBody(Vector2dArray* vectorArray, bool affectedByGravity, bool stationaryObject, bool rotatableObject, PBodyType tag)
{
    m_vectorArray = vectorArray;
    m_centerOfMassOffset = new Vector2d(0,0);
    m_affectedByGravity = affectedByGravity;
    m_stationaryObject = stationaryObject;
    m_rotatableObject = rotatableObject;

    m_movementVector = new Vector2d(0,0);
    m_tag = tag;
}
PBody::PBody(Vector2dArray* vectorArray, bool stationaryObject, PBodyType tag)
{
    m_vectorArray = vectorArray;
    m_centerOfMassOffset = new Vector2d(0,0);
    m_affectedByGravity = !stationaryObject;
    m_stationaryObject = stationaryObject;
    m_rotatableObject = !stationaryObject;

    m_movementVector = new Vector2d(0,0);
    m_tag = tag;
}
PBody::PBody(Vector2d* position, Vector2d* size, bool affectedByGravity, bool stationaryObject, bool rotatableObject, PBodyType tag)
{
    Vector2d** vArr = new Vector2d*[4];
    vArr[0] = new Vector2d(position->m_x, position->m_y);
    vArr[1] = new Vector2d(position->m_x, position->m_y + size->m_y);
    vArr[2] = new Vector2d(position->m_x + size->m_x, position->m_y + size->m_y);
    vArr[3] = new Vector2d(position->m_x + size->m_x, position->m_y);

    m_vectorArray = new Vector2dArray(vArr, 4);
    m_centerOfMassOffset = new Vector2d(0,0);
    m_affectedByGravity = affectedByGravity;
    m_stationaryObject = stationaryObject;
    m_rotatableObject = rotatableObject;

    m_movementVector = new Vector2d(0,0);
    m_tag = tag;
}

PBody::~PBody()
{

    delete m_centerOfMassOffset;
    delete m_movementVector;
    delete m_vectorArray;
}

void PBody::applyForce(float dt)
{
    for (int i = 0; i < m_vectorArray->m_size; i++) {
        m_vectorArray->m_vectors[i]->m_x += (m_movementVector->m_x * dt);
        m_vectorArray->m_vectors[i]->m_y += (m_movementVector->m_y * dt);
    }
}
void PBody::revertForce(float dt)
{
    for (int i = 0; i < m_vectorArray->m_size; i++) {
        m_vectorArray->m_vectors[i]->m_x -= (m_movementVector->m_x * dt);
        m_vectorArray->m_vectors[i]->m_y -= (m_movementVector->m_y * dt);
    }
}
void PBody::applyForceWithMask(Vector2d* mask, float dt)
{
    for (int i = 0; i < m_vectorArray->m_size; i++) {
        m_vectorArray->m_vectors[i]->m_x += ((m_movementVector->m_x * mask->m_x) * dt);
        m_vectorArray->m_vectors[i]->m_y += ((m_movementVector->m_y * mask->m_y) * dt);
    }
}
void PBody::revertForceWithMask(Vector2d* mask, float dt)
{
    for (int i = 0; i < m_vectorArray->m_size; i++) {
        m_vectorArray->m_vectors[i]->m_x -= ((m_movementVector->m_x * mask->m_x) * dt);
        m_vectorArray->m_vectors[i]->m_y -= ((m_movementVector->m_y * mask->m_y) * dt);
    }
}
void PBody::addVector(Vector2d* vector)
{
    *m_movementVector += *vector;
}
void PBody::removeVector(Vector2d* vector)
{
    *m_movementVector -= vector;
}
void PBody::resetMovementVector()
{
    m_movementVector = new Vector2d(0,0);
}
void PBody::maskMovementVector(float x, float y)
{
    this->m_movementVector->m_x *= x;
    this->m_movementVector->m_y *= y;
}
void PBody::rotateAround(Vector2d* pivotPoint, float degrees)
{
    // Implement me plxzz
}
void PBody::translateBy(Vector2d* vector)
{
    // Implement me plxzz
}

Vector2dArray* PBody::getVectorArray()
{
    return m_vectorArray;
}

bool PBody::isAffectedByGravity()
{
    return m_affectedByGravity;
}
bool PBody::isStationary()
{
    return m_stationaryObject;
}
bool PBody::isCollidingWithBody(PBody* otherBody)
{

    Vector2d** axes1 = this->getAxes();
    Vector2d** axes2 = otherBody->getAxes();

    for (int a = 0; a < this->m_vectorArray->m_size; a++) {
        Vector2d* axis = axes1[a];

        Vector2d* proj1 = this->projectionOnVector(axis);
        Vector2d* proj2 = otherBody->projectionOnVector(axis);

        if (proj1->m_x < proj2->m_x && proj1->m_y < proj2->m_x)
            return false;
        if (proj2->m_x < proj1->m_x && proj2->m_y < proj1->m_x)
            return false;
    }

    for (int a = 0; a < otherBody->m_vectorArray->m_size; a++) {
        Vector2d* axis = axes2[a];

        Vector2d* proj1 = this->projectionOnVector(axis);
        Vector2d* proj2 = otherBody->projectionOnVector(axis);

        if (proj1->m_x < proj2->m_x && proj1->m_y < proj2->m_x)
            return false;
        if (proj2->m_x < proj1->m_x && proj2->m_y < proj1->m_x)
            return false;
    }

    return true;
}
PBodyType PBody::getTag()
{
    return m_tag;
}
Vector2d* PBody::getSize()
{
    double xmin = this->m_vectorArray->m_size > 0 ? this->m_vectorArray->m_vectors[0]->m_x : 0;
    double xmax = this->m_vectorArray->m_size > 0 ? this->m_vectorArray->m_vectors[0]->m_x : 0;
    double ymin = this->m_vectorArray->m_size > 0 ? this->m_vectorArray->m_vectors[0]->m_y : 0;
    double ymax = this->m_vectorArray->m_size > 0 ? this->m_vectorArray->m_vectors[0]->m_y : 0;

    for (int i = 0; i < this->m_vectorArray->m_size; i++) {
        xmin = this->m_vectorArray->m_vectors[i]->m_x < xmin ? this->m_vectorArray->m_vectors[i]->m_x : xmin;
        ymin = this->m_vectorArray->m_vectors[i]->m_y < ymin ? this->m_vectorArray->m_vectors[i]->m_y : ymin;

        xmax = this->m_vectorArray->m_vectors[i]->m_x > xmax ? this->m_vectorArray->m_vectors[i]->m_x : xmax;
        ymax = this->m_vectorArray->m_vectors[i]->m_y > ymax ? this->m_vectorArray->m_vectors[i]->m_y : ymax;
    }

    return new Vector2d(xmax - xmin, ymax - ymin);
}
Vector2d* PBody::getPosition()
{
    double x = this->m_vectorArray->m_size > 0 ? this->m_vectorArray->m_vectors[0]->m_x : 0;
    double y = this->m_vectorArray->m_size > 0 ? this->m_vectorArray->m_vectors[0]->m_y : 0;

    for (int i = 0; i < this->m_vectorArray->m_size; i++) {
        x = this->m_vectorArray->m_vectors[i]->m_x < x ? this->m_vectorArray->m_vectors[i]->m_x : x;
        y = this->m_vectorArray->m_vectors[i]->m_y < y ? this->m_vectorArray->m_vectors[i]->m_y : y;
    }

    return new Vector2d(x, y);
}

Vector2d** PBody::getAxes()
{
    Vector2d** edges = this->getEdges();
    Vector2d** axes = new Vector2d*[this->m_vectorArray->m_size];

    for (int i = 0; i < this->m_vectorArray->m_size; i++) {
        axes[i] = new Vector2d(edges[i]->m_y, -edges[i]->m_x);
    }

    delete [] edges;

    return axes;
}

Vector2d** PBody::getEdges()
{
    Vector2d** edges = new Vector2d*[this->m_vectorArray->m_size];

    for (int a = 0; a < this->m_vectorArray->m_size; a++) {
        Vector2d* p1 = this->m_vectorArray->m_vectors[a];
        Vector2d* p2 = this->m_vectorArray->m_vectors[a + 1 == this->m_vectorArray->m_size ? 0 : a + 1];

        edges[a] = new Vector2d(p1->m_x - p2->m_x, p1->m_y - p2->m_y);
    }

    return edges;
}
Vector2d* PBody::projectionOnVector(Vector2d* axis)
{
    double min = this->m_vectorArray->m_vectors[0]->m_x*axis->m_x + this->m_vectorArray->m_vectors[0]->m_y*axis->m_y;
    double max = min;

    for (int i = 0; i < this->m_vectorArray->m_size; i++) {
        double dot = this->m_vectorArray->m_vectors[i]->m_x*axis->m_x + this->m_vectorArray->m_vectors[i]->m_y*axis->m_y;

        min = min < dot ? min : dot;
        max = max < dot ? dot : max;
    }
    return new Vector2d(min, max);
}
<commit_msg>Expanded how the collision detection works.<commit_after>//
//  File:       PBody.cpp
//  Class:      PBody
//  Author:     Jesper Persson
//              All code is my own except where credited to others.
//
//	Copyright (c) 2012 by Catch22. All Rights Reserved.
//  Date: 		29/09-2012
//

#include "PBody.hpp"
#include "../../Helper/Logger.hpp"
#include "../../Math/Math.hpp"

PBody::PBody(Vector2dArray* vectorArray, Vector2d* centerOfMassOffset, bool affectedByGravity, bool stationaryObject, bool rotatableObject, PBodyType tag)
{
    m_vectorArray = vectorArray;
    m_centerOfMassOffset = centerOfMassOffset;
    m_affectedByGravity = affectedByGravity;
    m_stationaryObject = stationaryObject;
    m_rotatableObject = rotatableObject;

    m_movementVector = new Vector2d(0.0,0.0);
    m_tag = tag;
}
PBody::PBody(Vector2dArray* vectorArray, bool affectedByGravity, bool stationaryObject, bool rotatableObject, PBodyType tag)
{
    m_vectorArray = vectorArray;
    m_centerOfMassOffset = new Vector2d(0.0,0.0);
    m_affectedByGravity = affectedByGravity;
    m_stationaryObject = stationaryObject;
    m_rotatableObject = rotatableObject;

    m_movementVector = new Vector2d(0.0,0.0);
    m_tag = tag;
}
PBody::PBody(Vector2dArray* vectorArray, bool stationaryObject, PBodyType tag)
{
    m_vectorArray = vectorArray;
    m_centerOfMassOffset = new Vector2d(0.0,0.0);
    m_affectedByGravity = !stationaryObject;
    m_stationaryObject = stationaryObject;
    m_rotatableObject = !stationaryObject;

    m_movementVector = new Vector2d(0.0,0.0);
    m_tag = tag;
}
PBody::PBody(Vector2d* position, Vector2d* size, bool affectedByGravity, bool stationaryObject, bool rotatableObject, PBodyType tag)
{
    Vector2d** vArr = new Vector2d*[4];
    vArr[0] = new Vector2d(position->m_x, position->m_y);
    vArr[1] = new Vector2d(position->m_x, position->m_y + size->m_y);
    vArr[2] = new Vector2d(position->m_x + size->m_x, position->m_y + size->m_y);
    vArr[3] = new Vector2d(position->m_x + size->m_x, position->m_y);

    m_vectorArray = new Vector2dArray(vArr, 4);
    m_centerOfMassOffset = new Vector2d(0.0,0.0);
    m_affectedByGravity = affectedByGravity;
    m_stationaryObject = stationaryObject;
    m_rotatableObject = rotatableObject;

    m_movementVector = new Vector2d(0.0,0.0);
    m_tag = tag;
}

PBody::~PBody()
{

    delete m_centerOfMassOffset;
    delete m_movementVector;
    delete m_vectorArray;
}

void PBody::applyForce(float dt)
{
    for (int i = 0; i < m_vectorArray->m_size; i++) {
        m_vectorArray->m_vectors[i]->m_x += (m_movementVector->m_x * dt);
        m_vectorArray->m_vectors[i]->m_y += (m_movementVector->m_y * dt);
    }

    Log(LOG_INFO, "PBody", generateCString("Applying force: %d,%d", this->m_movementVector->m_x, this->m_movementVector->m_y));
}
void PBody::revertForce(float dt)
{
    for (int i = 0; i < m_vectorArray->m_size; i++) {
        m_vectorArray->m_vectors[i]->m_x -= (m_movementVector->m_x * dt);
        m_vectorArray->m_vectors[i]->m_y -= (m_movementVector->m_y * dt);
    }
}
void PBody::applyForceWithMask(Vector2d* mask, float dt)
{
    for (int i = 0; i < m_vectorArray->m_size; i++) {
        m_vectorArray->m_vectors[i]->m_x += ((m_movementVector->m_x * mask->m_x) * dt);
        m_vectorArray->m_vectors[i]->m_y += ((m_movementVector->m_y * mask->m_y) * dt);
    }
}
void PBody::revertForceWithMask(Vector2d* mask, float dt)
{
    for (int i = 0; i < m_vectorArray->m_size; i++) {
        m_vectorArray->m_vectors[i]->m_x -= ((m_movementVector->m_x * mask->m_x) * dt);
        m_vectorArray->m_vectors[i]->m_y -= ((m_movementVector->m_y * mask->m_y) * dt);
    }
}
void PBody::addVector(Vector2d* vector)
{
    *m_movementVector += *vector;
}
void PBody::removeVector(Vector2d* vector)
{
    *m_movementVector -= vector;
}
void PBody::resetMovementVector()
{
    m_movementVector = new Vector2d(0.0,0.0);
}
void PBody::maskMovementVector(float x, float y)
{
    this->m_movementVector->m_x *= x;
    this->m_movementVector->m_y *= y;
}
void PBody::rotateAround(Vector2d* pivotPoint, float degrees)
{
    // Implement me plxzz
}
void PBody::translateBy(Vector2d* vector)
{
    for (int i = 0; i < this->m_vectorArray->m_size; i++) {
        *this->m_vectorArray->m_vectors[i] += *vector;
    }
}
Vector2dArray* PBody::getVectorArray()
{
    return m_vectorArray;
}
bool PBody::isAffectedByGravity()
{
    return m_affectedByGravity;
}
bool PBody::isStationary()
{
    return m_stationaryObject;
}
Vector2d* PBody::isCollidingWithBody(PBody* otherBody)
{

    Vector2d** axes1 = this->getAxes();
    Vector2d** axes2 = otherBody->getAxes();

    double overlap = -1;
    Vector2d* smallestAxis = 0;

    Vector2d* axis;
    Vector2d* proj1;
    Vector2d* proj2;

    double tmpOver;
    for (int a = 0; a < this->m_vectorArray->m_size; a++) {
        axis = axes1[a];

        proj1 = this->projectionOnVector(axis);
        proj2 = otherBody->projectionOnVector(axis);

        if ((proj1->m_x < proj2->m_x && proj1->m_y < proj2->m_x) || (
            proj2->m_x < proj1->m_x && proj2->m_y < proj1->m_x)) {

            delete proj1;
            delete proj2;

            for (int i = 0; i < this->m_vectorArray->m_size; i++)
                delete [] axes1[i];

            delete [] axes1;

            for (int i = 0; i < otherBody->m_vectorArray->m_size; i++)
                delete [] axes2[i];

            delete [] axes2;

            return 0;
        } else {
            if (proj1->m_y > proj2->m_x && proj2->m_y > proj1->m_y) {
                tmpOver = proj1->m_y - proj2->m_x;
            }
            else if (proj2->m_y > proj1->m_x && proj1->m_y > proj2->m_y) {
                tmpOver = proj2->m_y - proj1->m_x;
            }
            else if (proj1->m_x > proj2->m_x && proj1->m_y < proj2->m_y) {
                tmpOver = proj1->m_y-proj1->m_x;
            }
            else if (proj2->m_x > proj1->m_x && proj2->m_y < proj1->m_y) {
                tmpOver = proj2->m_y-proj2->m_x;
            }

            if (overlap == -1 || tmpOver < overlap) {
                overlap = tmpOver;
                smallestAxis = axis;
            }
        }

        delete proj1;
        delete proj2;

    }

    for (int a = 0; a < otherBody->m_vectorArray->m_size; a++) {
        axis = axes2[a];

        proj1 = this->projectionOnVector(axis);
        proj2 = otherBody->projectionOnVector(axis);

        if ((proj1->m_x < proj2->m_x && proj1->m_y < proj2->m_x) ||
            (proj2->m_x < proj1->m_x && proj2->m_y < proj1->m_x)) {
            delete proj1;
            delete proj2;

            for (int i = 0; i < this->m_vectorArray->m_size; i++)
                delete [] axes1[i];

            delete [] axes1;

            for (int i = 0; i < otherBody->m_vectorArray->m_size; i++)
                delete [] axes2[i];

            delete [] axes2;

            return 0;
        } else {
            if (proj1->m_y > proj2->m_x && proj2->m_y > proj1->m_y) {
                tmpOver = proj1->m_y - proj2->m_x;
            }
            else if (proj2->m_y > proj1->m_x && proj1->m_y > proj2->m_y) {
                tmpOver = proj2->m_y - proj1->m_x;
            }
            else if (proj1->m_x > proj2->m_x && proj1->m_y < proj2->m_y) {
                tmpOver = proj1->m_y-proj1->m_x;
            }
            else if (proj2->m_x > proj1->m_x && proj2->m_y < proj1->m_y) {
                tmpOver = proj2->m_y-proj2->m_x;
            }

            if (overlap == -1 || tmpOver < overlap) {
                overlap = tmpOver;
                smallestAxis = axis;
            }
        }

        delete proj1;
        delete proj2;
    }

    Vector2d* returnVector = new Vector2d(smallestAxis, overlap);

    for (int i = 0; i < this->m_vectorArray->m_size; i++)
        delete [] axes1[i];

    delete [] axes1;

    for (int i = 0; i < otherBody->m_vectorArray->m_size; i++)
        delete [] axes2[i];

    delete [] axes2;

    return returnVector;
}
PBodyType PBody::getTag()
{
    return m_tag;
}
Vector2d* PBody::getSize()
{
    double xmin = this->m_vectorArray->m_size > 0 ? this->m_vectorArray->m_vectors[0]->m_x : 0;
    double xmax = this->m_vectorArray->m_size > 0 ? this->m_vectorArray->m_vectors[0]->m_x : 0;
    double ymin = this->m_vectorArray->m_size > 0 ? this->m_vectorArray->m_vectors[0]->m_y : 0;
    double ymax = this->m_vectorArray->m_size > 0 ? this->m_vectorArray->m_vectors[0]->m_y : 0;

    for (int i = 0; i < this->m_vectorArray->m_size; i++) {
        xmin = this->m_vectorArray->m_vectors[i]->m_x < xmin ? this->m_vectorArray->m_vectors[i]->m_x : xmin;
        ymin = this->m_vectorArray->m_vectors[i]->m_y < ymin ? this->m_vectorArray->m_vectors[i]->m_y : ymin;

        xmax = this->m_vectorArray->m_vectors[i]->m_x > xmax ? this->m_vectorArray->m_vectors[i]->m_x : xmax;
        ymax = this->m_vectorArray->m_vectors[i]->m_y > ymax ? this->m_vectorArray->m_vectors[i]->m_y : ymax;
    }

    return new Vector2d(xmax - xmin, ymax - ymin);
}
Vector2d* PBody::getPosition()
{
    double x = this->m_vectorArray->m_size > 0 ? this->m_vectorArray->m_vectors[0]->m_x : 0;
    double y = this->m_vectorArray->m_size > 0 ? this->m_vectorArray->m_vectors[0]->m_y : 0;

    for (int i = 0; i < this->m_vectorArray->m_size; i++) {
        x = this->m_vectorArray->m_vectors[i]->m_x < x ? this->m_vectorArray->m_vectors[i]->m_x : x;
        y = this->m_vectorArray->m_vectors[i]->m_y < y ? this->m_vectorArray->m_vectors[i]->m_y : y;
    }

    return new Vector2d(x, y);
}

Vector2d** PBody::getAxes()
{
    Vector2d** edges = this->getEdges();
    Vector2d** axes = new Vector2d*[this->m_vectorArray->m_size];

    for (int i = 0; i < this->m_vectorArray->m_size; i++) {
        Vector2d* v = new Vector2d(edges[i]->m_y, -edges[i]->m_x);
        axes[i] = Math::generateUnitVectorOf(v);
        delete v;
        delete [] edges[i];
    }

    delete [] edges;

    return axes;
}

Vector2d** PBody::getEdges()
{
    Vector2d** edges = new Vector2d*[this->m_vectorArray->m_size];

    for (int a = 0; a < this->m_vectorArray->m_size; a++) {
        Vector2d* p1 = this->m_vectorArray->m_vectors[a];
        Vector2d* p2 = this->m_vectorArray->m_vectors[a + 1 == this->m_vectorArray->m_size ? 0 : a + 1];

        edges[a] = new Vector2d(p1->m_x - p2->m_x, p1->m_y - p2->m_y);
    }

    return edges;
}
Vector2d* PBody::projectionOnVector(Vector2d* axis)
{
    double min = this->m_vectorArray->m_vectors[0]->m_x*axis->m_x + this->m_vectorArray->m_vectors[0]->m_y*axis->m_y;
    double max = min;

    for (int i = 0; i < this->m_vectorArray->m_size; i++) {
        double dot = this->m_vectorArray->m_vectors[i]->m_x*axis->m_x + this->m_vectorArray->m_vectors[i]->m_y*axis->m_y;

        min = min < dot ? min : dot;
        max = max < dot ? dot : max;
    }
    return new Vector2d(min, max);
}
<|endoftext|>


<commit_before>#include "stdafx.h"
#include "WiimoteFactory.h"

WiimoteFactory::WiimoteFactory()
	:DeviceIndex(0), DeviceInfoSet(NULL), OpenDevice(INVALID_HANDLE_VALUE)
{
	HidD_GetHidGuid(&HidGuid);

	ZeroMemory(&DeviceInfoData, sizeof(SP_DEVINFO_DATA));
	DeviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA);

	DeviceInterfaceData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
}

WiimoteFactory::~WiimoteFactory()
{
	if (DeviceInfoSet)
	{
		SetupDiDestroyDeviceInfoList(DeviceInfoSet);
		DeviceInfoSet = NULL;
	}
}

WiimoteDeviceVector WiimoteFactory::GetWiimoteDevices()
{
	DeviceInfoSet = SetupDiGetClassDevs(&HidGuid, NULL, NULL, DIGCF_DEVICEINTERFACE | DIGCF_PRESENT);
	if (!DeviceInfoSet)
	{
		std::cout << "No HID Devices Found!" << std::endl;
		return WiimoteDevices;
	}

	while (SetupDiEnumDeviceInterfaces(DeviceInfoSet, NULL, &HidGuid, DeviceIndex, &DeviceInterfaceData))
	{
		std::cout << "New Device" << std::endl;
		CheckEnumeratedDeviceInterface();
		DeviceIndex++;
	}

	if (DeviceIndex == 0)
	{
		std::cout << "No Device Enumerated!" << std::endl;
	}

	return WiimoteDevices;
}

void WiimoteFactory::CheckEnumeratedDeviceInterface()
{
	BOOL Result;
	DWORD RequiredSize;

	Result = SetupDiGetDeviceInterfaceDetail(DeviceInfoSet, &DeviceInterfaceData, NULL, 0, &RequiredSize, NULL);

	PSP_DEVICE_INTERFACE_DETAIL_DATA DeviceInterfaceDetailData = (PSP_DEVICE_INTERFACE_DETAIL_DATA)malloc(RequiredSize);
	DeviceInterfaceDetailData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);

	Result = SetupDiGetDeviceInterfaceDetail(DeviceInfoSet, &DeviceInterfaceData, DeviceInterfaceDetailData, RequiredSize, NULL, NULL);

	BOOL IsWiimote = CheckDevice(DeviceInterfaceDetailData->DevicePath);

	if (IsWiimote)
	{
		WiimoteDevices.push_back(WiimoteDevice(OpenDevice));
	}
	else
	{
		CloseHandle(OpenDevice);
	}

	OpenDevice = INVALID_HANDLE_VALUE;
	free(DeviceInterfaceDetailData);
}

BOOL WiimoteFactory::CheckDevice(LPCTSTR DevicePath)
{
	OpenDevice = CreateFile(DevicePath, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);

	if (OpenDevice == INVALID_HANDLE_VALUE)
	{
		std::cout << "Failed to open Device." << std::endl;
		return FALSE;
	}

	std::cout << "0x" << std::hex << OpenDevice << std::endl;

	HIDD_ATTRIBUTES HidAttributes;
	HidAttributes.Size = sizeof(HidAttributes);

	BOOL Result = HidD_GetAttributes(OpenDevice, &HidAttributes);
	if (!Result)
	{
		std::cout << "Failed to get hid attributes" << std::endl;
		return FALSE;
	}

	std::cout << HidAttributes.VendorID << " - " << HidAttributes.ProductID << std::endl;

	TCHAR ProductName[255];

	if (HidD_GetProductString(OpenDevice, ProductName, 255))
	{
		std::wcout << ProductName << std::endl;
	}

	return (HidAttributes.VendorID == 0x057e) && ((HidAttributes.ProductID == 0x0306) || (HidAttributes.ProductID == 0x0330));
}<commit_msg>Adjust print outs<commit_after>#include "stdafx.h"
#include "WiimoteFactory.h"

WiimoteFactory::WiimoteFactory()
	:DeviceIndex(0), DeviceInfoSet(NULL), OpenDevice(INVALID_HANDLE_VALUE)
{
	HidD_GetHidGuid(&HidGuid);

	ZeroMemory(&DeviceInfoData, sizeof(SP_DEVINFO_DATA));
	DeviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA);

	DeviceInterfaceData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
}

WiimoteFactory::~WiimoteFactory()
{
	if (DeviceInfoSet)
	{
		SetupDiDestroyDeviceInfoList(DeviceInfoSet);
		DeviceInfoSet = NULL;
	}
}

WiimoteDeviceVector WiimoteFactory::GetWiimoteDevices()
{
	DeviceInfoSet = SetupDiGetClassDevs(&HidGuid, NULL, NULL, DIGCF_DEVICEINTERFACE | DIGCF_PRESENT);
	if (!DeviceInfoSet)
	{
		std::cout << "No HID Devices Found!" << std::endl;
		return WiimoteDevices;
	}

	while (SetupDiEnumDeviceInterfaces(DeviceInfoSet, NULL, &HidGuid, DeviceIndex, &DeviceInterfaceData))
	{
		std::cout << "--- New Device ---" << std::endl;
		CheckEnumeratedDeviceInterface();
		DeviceIndex++;
		std::cout << "------------------" << std::endl;
	}

	if (DeviceIndex == 0)
	{
		std::cout << "No Device Enumerated!" << std::endl;
	}

	return WiimoteDevices;
}

void WiimoteFactory::CheckEnumeratedDeviceInterface()
{
	BOOL Result;
	DWORD RequiredSize;

	Result = SetupDiGetDeviceInterfaceDetail(DeviceInfoSet, &DeviceInterfaceData, NULL, 0, &RequiredSize, NULL);

	PSP_DEVICE_INTERFACE_DETAIL_DATA DeviceInterfaceDetailData = (PSP_DEVICE_INTERFACE_DETAIL_DATA)malloc(RequiredSize);
	DeviceInterfaceDetailData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);

	Result = SetupDiGetDeviceInterfaceDetail(DeviceInfoSet, &DeviceInterfaceData, DeviceInterfaceDetailData, RequiredSize, NULL, NULL);

	BOOL IsWiimote = CheckDevice(DeviceInterfaceDetailData->DevicePath);

	if (IsWiimote)
	{
		WiimoteDevices.push_back(WiimoteDevice(OpenDevice));
	}
	else
	{
		CloseHandle(OpenDevice);
	}

	OpenDevice = INVALID_HANDLE_VALUE;
	free(DeviceInterfaceDetailData);
}

BOOL WiimoteFactory::CheckDevice(LPCTSTR DevicePath)
{
	OpenDevice = CreateFile(DevicePath, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);

	if (OpenDevice == INVALID_HANDLE_VALUE)
	{
		std::cout << "Failed to open Device." << std::endl;
		return FALSE;
	}

	std::cout << "DevicePath: \t0x" << std::hex << OpenDevice << std::endl;

	HIDD_ATTRIBUTES HidAttributes;
	HidAttributes.Size = sizeof(HidAttributes);

	BOOL Result = HidD_GetAttributes(OpenDevice, &HidAttributes);
	if (!Result)
	{
		std::cout << "Failed to get hid attributes" << std::endl;
		return FALSE;
	}

	std::cout << "VID&PID: \t" << HidAttributes.VendorID << " - " << HidAttributes.ProductID << std::endl;

	TCHAR ProductName[255];

	if (HidD_GetProductString(OpenDevice, ProductName, 255))
	{
		std::wcout << "HID Name: \t" << ProductName << std::endl;
	}

	return (HidAttributes.VendorID == 0x057e) && ((HidAttributes.ProductID == 0x0306) || (HidAttributes.ProductID == 0x0330));
}<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
#if !defined(VCPPDEFINITIONS_HEADER_GUARD_1357924680)
#define VCPPDEFINITIONS_HEADER_GUARD_1357924680

#pragma warning(disable: 4127 4251 4511 4512 4514 4702 4710 4711 4786 4097; error: 4150 4172 4238 4239 4715)

// ---------------------------------------------------------------------------
//  A define in the build for each project is also used to control whether
//  the export keyword is from the project's viewpoint or the client's.
//  These defines provide the platform specific keywords that they need
//  to do this.
// ---------------------------------------------------------------------------
#define XALAN_PLATFORM_EXPORT     __declspec(dllexport)
#define XALAN_PLATFORM_IMPORT     __declspec(dllimport)
#define XALAN_PLATFORM_EXPORT_FUNCTION(T) T XALAN_PLATFORM_EXPORT
#define XALAN_PLATFORM_IMPORT_FUNCTION(T) T XALAN_PLATFORM_IMPORT

#define XALAN_NO_COVARIANT_RETURN_TYPE
#define XALAN_LSTRSUPPORT
#define XALAN_FULL_WCHAR_SUPPORT
#define XALAN_USE_WCHAR_SUPPORT
#define XALAN_RTTI_AVAILABLE
#define XALAN_LITLE_ENDIAN
#define XALAN_NEWLINE_IS_CRLF

#endif	// VCPPDEFINITIONS_HEADER_GUARD_1357924680
<commit_msg>New #define to compensate for Microsoft's old std::string implementation.<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
#if !defined(VCPPDEFINITIONS_HEADER_GUARD_1357924680)
#define VCPPDEFINITIONS_HEADER_GUARD_1357924680

#pragma warning(disable: 4127 4251 4511 4512 4514 4702 4710 4711 4786 4097; error: 4150 4172 4238 4239 4715)

// ---------------------------------------------------------------------------
//  A define in the build for each project is also used to control whether
//  the export keyword is from the project's viewpoint or the client's.
//  These defines provide the platform specific keywords that they need
//  to do this.
// ---------------------------------------------------------------------------
#define XALAN_PLATFORM_EXPORT     __declspec(dllexport)
#define XALAN_PLATFORM_IMPORT     __declspec(dllimport)
#define XALAN_PLATFORM_EXPORT_FUNCTION(T) T XALAN_PLATFORM_EXPORT
#define XALAN_PLATFORM_IMPORT_FUNCTION(T) T XALAN_PLATFORM_IMPORT

#define XALAN_NO_COVARIANT_RETURN_TYPE
#define XALAN_LSTRSUPPORT
#define XALAN_FULL_WCHAR_SUPPORT
#define XALAN_USE_WCHAR_SUPPORT
#define XALAN_RTTI_AVAILABLE
#define XALAN_LITLE_ENDIAN
#define XALAN_NEWLINE_IS_CRLF

// This is defined because Microsoft's basic_string is old, and
// does not have some of the things that it ought, like push_back().
// Eventually, they will get with it.
#define XALAN_OLD_STD_STRING

#endif	// VCPPDEFINITIONS_HEADER_GUARD_1357924680
<|endoftext|>


<commit_before>#include "ArduinoInterface.h"
#include "ArduinoCmds.hpp"

#include "OSMC_driver.hpp"

class OSMC_4wd_driver
{
	public:

	OSMC_4wd_driver(const byte FORosmc, const byte FORcoder, const byte AFTosmc, const byte AFTcoder);
	//~OSMC_4wd_driver();

	//set motor
	bool setMotorPWM(const int FR, const int FL, const int BR, const int BL);//must be -255 <-> 255, larger input trucated to 255, sign is pos / rev, true on failure
	bool setMotorPWM(const byte FRdir, const byte FRmag, const byte FLdir, const byte FLmag, const byte BRdir, const byte BRmag, const byte BLdir, const byte BLmag);//must be 0 - 255, dir is pos / rev, true on failure
	void setMotorVel_pd(const double FR, const double FL, const double BR, const double BL);

	//update pd
	bool update_pd();

	//interog
	bool getEncoderVel(double& FL, double& FR, double& BL, double& BR);
	bool getLastPWMSent();

	private:

	volatile bool m_connected;

	OSMC_driver FOR;
	OSMC_driver AFT;
};
<commit_msg>spelling<commit_after>#include "ArduinoInterface.h"
#include "ArduinoCmds.hpp"

#include "OSMC_driver.hpp"

class OSMC_4wd_driver
{
	public:

	OSMC_4wd_driver(const byte FORosmc, const byte FORcoder, const byte AFTosmc, const byte AFTcoder);
	//~OSMC_4wd_driver();

	//set motor
	bool setMotorPWM(const int FR, const int FL, const int BR, const int BL);//must be -255 <-> 255, larger input mag truncated to 255, sign is pos / rev, true on failure
	bool setMotorPWM(const byte FRdir, const byte FRmag, const byte FLdir, const byte FLmag, const byte BRdir, const byte BRmag, const byte BLdir, const byte BLmag);//must be 0 - 255, dir is pos / rev, true on failure
	void setMotorVel_pd(const double FR, const double FL, const double BR, const double BL);

	//update pd
	bool update_pd();

	//interog
	bool getEncoderVel(double& FL, double& FR, double& BL, double& BR);
	bool getLastPWMSent();

	private:

	volatile bool m_connected;

	OSMC_driver FOR;
	OSMC_driver AFT;
};
<|endoftext|>


<commit_before>//===- lib/Driver/Driver.cpp - Linker Driver Emulator ---------------------===//
//
//                             The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "lld/Driver/Driver.h"

#include "lld/Core/LLVM.h"
#include "lld/Core/InputFiles.h"
#include "lld/Core/Instrumentation.h"
#include "lld/Core/PassManager.h"
#include "lld/Core/Parallel.h"
#include "lld/Core/Resolver.h"
#include "lld/ReaderWriter/Reader.h"
#include "lld/ReaderWriter/Writer.h"

#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Option/Arg.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"

namespace lld {

/// This is where the link is actually performed.
bool Driver::link(const LinkingContext &context, raw_ostream &diagnostics) {
  // Honor -mllvm
  if (!context.llvmOptions().empty()) {
    unsigned numArgs = context.llvmOptions().size();
    const char **args = new const char *[numArgs + 2];
    args[0] = "lld (LLVM option parsing)";
    for (unsigned i = 0; i != numArgs; ++i)
      args[i + 1] = context.llvmOptions()[i];
    args[numArgs + 1] = 0;
    llvm::cl::ParseCommandLineOptions(numArgs + 1, args);
  }
  InputGraph &inputGraph = context.inputGraph();
  if (!inputGraph.numFiles())
    return true;

  // Read inputs
  ScopedTask readTask(getDefaultDomain(), "Read Args");
  std::vector<std::vector<std::unique_ptr<File> > > files(
      inputGraph.numFiles());
  size_t index = 0;
  std::atomic<bool> fail(false);
  TaskGroup tg;
  std::vector<std::unique_ptr<LinkerInput> > linkerInputs;
  for (auto &ie : inputGraph.inputElements()) {
    if (ie->kind() == InputElement::Kind::File) {
      FileNode *fileNode = (llvm::dyn_cast<FileNode>)(ie.get());
      auto linkerInput = fileNode->createLinkerInput(context);
      if (!linkerInput) {
        llvm::outs() << fileNode->errStr(error_code(linkerInput)) << "\n";
        return true;
      }
      linkerInputs.push_back(std::move(*linkerInput));
    }
    else {
      llvm_unreachable("Not handling other types of InputElements");
      return true;
    }
  }
  for (const auto &input : linkerInputs) {
    if (context.logInputFiles())
      llvm::outs() << input->getPath() << "\n";

    tg.spawn([ &, index]{
      if (error_code ec = context.readFile(input->getPath(), files[index])) {
        diagnostics << "Failed to read file: " << input->getPath() << ": "
                    << ec.message() << "\n";
        fail = true;
        return;
      }
    });
    ++index;
  }
  tg.sync();
  readTask.end();

  if (fail)
    return true;

  InputFiles inputs;

  for (auto &f : inputGraph.internalFiles())
    inputs.appendFile(*f.get());

  for (auto &f : files)
    inputs.appendFiles(f);

  // Give target a chance to add files.
  context.addImplicitFiles(inputs);

  // assign an ordinal to each file so sort() can preserve command line order
  inputs.assignFileOrdinals();

  // Do core linking.
  ScopedTask resolveTask(getDefaultDomain(), "Resolve");
  Resolver resolver(context, inputs);
  if (resolver.resolve()) {
    if (!context.allowRemainingUndefines())
      return true;
  }
  MutableFile &merged = resolver.resultFile();
  resolveTask.end();

  // Run passes on linked atoms.
  ScopedTask passTask(getDefaultDomain(), "Passes");
  PassManager pm;
  context.addPasses(pm);
  pm.runOnFile(merged);
  passTask.end();

  // Give linked atoms to Writer to generate output file.
  ScopedTask writeTask(getDefaultDomain(), "Write");
  if (error_code ec = context.writeFile(merged)) {
    diagnostics << "Failed to write file '" << context.outputPath()
                << "': " << ec.message() << "\n";
    return true;
  }

  return false;
}

} // namespace
<commit_msg>[lld][Driver] remove return after llvm_unreachable<commit_after>//===- lib/Driver/Driver.cpp - Linker Driver Emulator ---------------------===//
//
//                             The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "lld/Driver/Driver.h"

#include "lld/Core/LLVM.h"
#include "lld/Core/InputFiles.h"
#include "lld/Core/Instrumentation.h"
#include "lld/Core/PassManager.h"
#include "lld/Core/Parallel.h"
#include "lld/Core/Resolver.h"
#include "lld/ReaderWriter/Reader.h"
#include "lld/ReaderWriter/Writer.h"

#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Option/Arg.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"

namespace lld {

/// This is where the link is actually performed.
bool Driver::link(const LinkingContext &context, raw_ostream &diagnostics) {
  // Honor -mllvm
  if (!context.llvmOptions().empty()) {
    unsigned numArgs = context.llvmOptions().size();
    const char **args = new const char *[numArgs + 2];
    args[0] = "lld (LLVM option parsing)";
    for (unsigned i = 0; i != numArgs; ++i)
      args[i + 1] = context.llvmOptions()[i];
    args[numArgs + 1] = 0;
    llvm::cl::ParseCommandLineOptions(numArgs + 1, args);
  }
  InputGraph &inputGraph = context.inputGraph();
  if (!inputGraph.numFiles())
    return true;

  // Read inputs
  ScopedTask readTask(getDefaultDomain(), "Read Args");
  std::vector<std::vector<std::unique_ptr<File> > > files(
      inputGraph.numFiles());
  size_t index = 0;
  std::atomic<bool> fail(false);
  TaskGroup tg;
  std::vector<std::unique_ptr<LinkerInput> > linkerInputs;
  for (auto &ie : inputGraph.inputElements()) {
    if (ie->kind() == InputElement::Kind::File) {
      FileNode *fileNode = (llvm::dyn_cast<FileNode>)(ie.get());
      auto linkerInput = fileNode->createLinkerInput(context);
      if (!linkerInput) {
        llvm::outs() << fileNode->errStr(error_code(linkerInput)) << "\n";
        return true;
      }
      linkerInputs.push_back(std::move(*linkerInput));
    }
    else {
      llvm_unreachable("Not handling other types of InputElements");
    }
  }
  for (const auto &input : linkerInputs) {
    if (context.logInputFiles())
      llvm::outs() << input->getPath() << "\n";

    tg.spawn([ &, index]{
      if (error_code ec = context.readFile(input->getPath(), files[index])) {
        diagnostics << "Failed to read file: " << input->getPath() << ": "
                    << ec.message() << "\n";
        fail = true;
        return;
      }
    });
    ++index;
  }
  tg.sync();
  readTask.end();

  if (fail)
    return true;

  InputFiles inputs;

  for (auto &f : inputGraph.internalFiles())
    inputs.appendFile(*f.get());

  for (auto &f : files)
    inputs.appendFiles(f);

  // Give target a chance to add files.
  context.addImplicitFiles(inputs);

  // assign an ordinal to each file so sort() can preserve command line order
  inputs.assignFileOrdinals();

  // Do core linking.
  ScopedTask resolveTask(getDefaultDomain(), "Resolve");
  Resolver resolver(context, inputs);
  if (resolver.resolve()) {
    if (!context.allowRemainingUndefines())
      return true;
  }
  MutableFile &merged = resolver.resultFile();
  resolveTask.end();

  // Run passes on linked atoms.
  ScopedTask passTask(getDefaultDomain(), "Passes");
  PassManager pm;
  context.addPasses(pm);
  pm.runOnFile(merged);
  passTask.end();

  // Give linked atoms to Writer to generate output file.
  ScopedTask writeTask(getDefaultDomain(), "Write");
  if (error_code ec = context.writeFile(merged)) {
    diagnostics << "Failed to write file '" << context.outputPath()
                << "': " << ec.message() << "\n";
    return true;
  }

  return false;
}

} // namespace
<|endoftext|>