<commit_before>// For conditions of distribution and use, see copyright notice in license.txt

#include "StableHeaders.h"
#include "Foundation.h"
#include "Renderer.h"
#include "OgreRenderingModule.h"

#include "Ogre.h"

using namespace Foundation;

namespace OgreRenderer
{
    class EventListener : public Ogre::WindowEventListener
    {
    public:
        EventListener(Renderer* renderer) :
            renderer_(renderer)
        {
        }

        ~EventListener()
        {
        }

        void windowResized(Ogre::RenderWindow* rw)
        {
            if ((renderer_->camera_) && (rw == renderer_->renderwindow_))
                renderer_->camera_->setAspectRatio(Ogre::Real(rw->getWidth() / Ogre::Real(rw->getHeight())));
        }

        void windowClosed(Ogre::RenderWindow* rw)
        {
            if (rw == renderer_->renderwindow_)
                renderer_->framework_->Exit();
        }

    private:
        Renderer* renderer_;
    };

    Renderer::Renderer(Framework* framework) :
        initialized_(false),
        framework_(framework),
        scenemanager_(0),
        camera_(0),
        renderwindow_(0),
        listener_(EventListenerPtr(new EventListener(this)))
    {
        event_category_ = framework_->GetEventManager()->RegisterEventCategory("Renderer");
    }

    Renderer::~Renderer()
    {
        if (initialized_)
            Ogre::WindowEventUtilities::removeWindowEventListener(renderwindow_, listener_.get());

        root_.reset();
    }

    void Renderer::Initialize()
    {
        if (initialized_)
            return;

#ifdef _DEBUG
        std::string plugins_filename = "pluginsd.cfg";
#else
        std::string plugins_filename = "plugins.cfg";
#endif

        std::string logfilepath = framework_->GetPlatform()->GetUserDocumentsDirectory();
        logfilepath += "/Ogre.log";

        root_ = OgreRootPtr(new Ogre::Root("", "ogre.cfg", logfilepath));
        LoadPlugins(plugins_filename);

#ifdef _WINDOWS
        std::string rendersystem_name = framework_->GetDefaultConfig().DeclareSetting("OgreRenderer", "RenderSystem", "Direct3D9 Rendering Subsystem");
#else
        std::string rendersystem_name = "OpenGL Rendering Subsystem";
        framework_->GetDefaultConfig().DeclareSetting("OgreRenderer", "RenderSystem", rendersystem_name);
#endif
        int width = framework_->GetDefaultConfig().DeclareSetting("OgreRenderer", "WindowWidth", 800);
        int height = framework_->GetDefaultConfig().DeclareSetting("OgreRenderer", "WindowHeight", 600);
        bool fullscreen = framework_->GetDefaultConfig().DeclareSetting("OgreRenderer", "Fullscreen", false);

        Ogre::RenderSystem* rendersystem = root_->getRenderSystemByName(rendersystem_name);

        if (!rendersystem)
        {
            throw Core::Exception("Could not find Ogre rendersystem.");
        }

        // GTK's pango/cairo/whatever's font rendering doesn't work if the floating point mode is not set to strict.
        // This however creates undefined behavior for D3D (refrast + D3DX), but we aren't using those anyway.
        rendersystem->setConfigOption("Floating-point mode", "Consistent");

        root_->setRenderSystem(rendersystem);
        root_->initialise(false);

        Ogre::NameValuePairList params;
        std::string application_name = framework_->GetDefaultConfig().GetString(Foundation::Framework::ConfigurationGroup(), "application_name");

        try
        {
            renderwindow_ = root_->createRenderWindow(application_name, width, height, fullscreen, &params);
        }
        catch (Ogre::Exception e) {}

        if (!renderwindow_)
        {
            throw Core::Exception("Could not create Ogre rendering window");
        }

        SetupResources();
        SetupScene();

        Ogre::WindowEventUtilities::addWindowEventListener(renderwindow_, listener_.get());

        initialized_ = true;
    }

    void Renderer::LoadPlugins(const std::string& plugin_filename)
    {
        Ogre::ConfigFile file;
        try
        {
            file.load(plugin_filename);
        }
        catch (Ogre::Exception e)
        {
            OgreRenderingModule::LogError("Could not load Ogre plugins configuration file");
            return;
        }

        Ogre::String plugin_dir = file.getSetting("PluginFolder");
        Ogre::StringVector plugins = file.getMultiSetting("Plugin");

        if (plugin_dir.length())
        {
            if ((plugin_dir[plugin_dir.length() - 1] != '\\') && (plugin_dir[plugin_dir.length() - 1] != '/'))
            {
#ifdef _WINDOWS
                plugin_dir += "\\";
#else
                plugin_dir += "/";
#endif
            }
        }

        for (unsigned i = 0; i < plugins.size(); ++i)
        {
            try
            {
                root_->loadPlugin(plugin_dir + plugins[i]);
            }
            catch (Ogre::Exception e)
            {
                OgreRenderingModule::LogError("Plugin " + plugins[i] + " failed to load");
            }
        }
    }

    void Renderer::SetupResources()
    {
        Ogre::ConfigFile cf;
        cf.load("resources.cfg");

        Ogre::ConfigFile::SectionIterator seci = cf.getSectionIterator();
        Ogre::String sec_name, type_name, arch_name;

        while(seci.hasMoreElements())
        {
            sec_name = seci.peekNextKey();
            Ogre::ConfigFile::SettingsMultiMap* settings = seci.getNext();
            Ogre::ConfigFile::SettingsMultiMap::iterator i;
            for(i = settings->begin(); i != settings->end(); ++i)
            {
                type_name = i->first;
                arch_name = i->second;
                Ogre::ResourceGroupManager::getSingleton().addResourceLocation(arch_name, type_name, sec_name);
            }
        }

        Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
    }

    void Renderer::SetupScene()
    {
        scenemanager_ = root_->createSceneManager(Ogre::ST_GENERIC, "SceneManager");
        camera_ = scenemanager_->createCamera("Camera");
        Ogre::Viewport* viewport = renderwindow_->addViewport(camera_);
        camera_->setAspectRatio(Ogre::Real(viewport->getActualWidth()) / Ogre::Real(viewport->getActualHeight()));
    }

    void Renderer::Update()
    {
        if (!initialized_) return;

        Ogre::WindowEventUtilities::messagePump();

        root_->_fireFrameStarted();

        // Render without swapping buffers first
        Ogre::RenderSystem* renderer = root_->getRenderSystem();
        renderer->_updateAllRenderTargets(false);
        // Send postrender event, so that custom rendering may be added
        framework_->GetEventManager()->SendEvent(event_category_, event_postrender, NULL);
        // Swap buffers now
        renderer->_swapAllRenderTargetBuffers(renderer->getWaitForVerticalBlank());

        root_->_fireFrameEnded();
    }
}

<commit_msg>Floating-point mode config option only set if it exists.<commit_after>// For conditions of distribution and use, see copyright notice in license.txt

#include "StableHeaders.h"
#include "Foundation.h"
#include "Renderer.h"
#include "OgreRenderingModule.h"

#include "Ogre.h"

using namespace Foundation;

namespace OgreRenderer
{
    class EventListener : public Ogre::WindowEventListener
    {
    public:
        EventListener(Renderer* renderer) :
            renderer_(renderer)
        {
        }

        ~EventListener()
        {
        }

        void windowResized(Ogre::RenderWindow* rw)
        {
            if ((renderer_->camera_) && (rw == renderer_->renderwindow_))
                renderer_->camera_->setAspectRatio(Ogre::Real(rw->getWidth() / Ogre::Real(rw->getHeight())));
        }

        void windowClosed(Ogre::RenderWindow* rw)
        {
            if (rw == renderer_->renderwindow_)
                renderer_->framework_->Exit();
        }

    private:
        Renderer* renderer_;
    };

    Renderer::Renderer(Framework* framework) :
        initialized_(false),
        framework_(framework),
        scenemanager_(0),
        camera_(0),
        renderwindow_(0),
        listener_(EventListenerPtr(new EventListener(this)))
    {
        event_category_ = framework_->GetEventManager()->RegisterEventCategory("Renderer");
    }

    Renderer::~Renderer()
    {
        if (initialized_)
            Ogre::WindowEventUtilities::removeWindowEventListener(renderwindow_, listener_.get());

        root_.reset();
    }

    void Renderer::Initialize()
    {
        if (initialized_)
            return;

#ifdef _DEBUG
        std::string plugins_filename = "pluginsd.cfg";
#else
        std::string plugins_filename = "plugins.cfg";
#endif

        std::string logfilepath = framework_->GetPlatform()->GetUserDocumentsDirectory();
        logfilepath += "/Ogre.log";

        root_ = OgreRootPtr(new Ogre::Root("", "ogre.cfg", logfilepath));
        LoadPlugins(plugins_filename);

#ifdef _WINDOWS
        std::string rendersystem_name = framework_->GetDefaultConfig().DeclareSetting("OgreRenderer", "RenderSystem", "Direct3D9 Rendering Subsystem");
#else
        std::string rendersystem_name = "OpenGL Rendering Subsystem";
        framework_->GetDefaultConfig().DeclareSetting("OgreRenderer", "RenderSystem", rendersystem_name);
#endif
        int width = framework_->GetDefaultConfig().DeclareSetting("OgreRenderer", "WindowWidth", 800);
        int height = framework_->GetDefaultConfig().DeclareSetting("OgreRenderer", "WindowHeight", 600);
        bool fullscreen = framework_->GetDefaultConfig().DeclareSetting("OgreRenderer", "Fullscreen", false);

        Ogre::RenderSystem* rendersystem = root_->getRenderSystemByName(rendersystem_name);

        if (!rendersystem)
        {
            throw Core::Exception("Could not find Ogre rendersystem.");
        }

        // GTK's pango/cairo/whatever's font rendering doesn't work if the floating point mode is not set to strict.
        // This however creates undefined behavior for D3D (refrast + D3DX), but we aren't using those anyway.
        Ogre::ConfigOptionMap& map = rendersystem->getConfigOptions();
        if (map.find("Floating-point mode") != map.end())
            rendersystem->setConfigOption("Floating-point mode", "Consistent");

        root_->setRenderSystem(rendersystem);
        root_->initialise(false);

        Ogre::NameValuePairList params;
        std::string application_name = framework_->GetDefaultConfig().GetString(Foundation::Framework::ConfigurationGroup(), "application_name");

        try
        {
            renderwindow_ = root_->createRenderWindow(application_name, width, height, fullscreen, &params);
        }
        catch (Ogre::Exception e) {}

        if (!renderwindow_)
        {
            throw Core::Exception("Could not create Ogre rendering window");
        }

        SetupResources();
        SetupScene();

        Ogre::WindowEventUtilities::addWindowEventListener(renderwindow_, listener_.get());

        initialized_ = true;
    }

    void Renderer::LoadPlugins(const std::string& plugin_filename)
    {
        Ogre::ConfigFile file;
        try
        {
            file.load(plugin_filename);
        }
        catch (Ogre::Exception e)
        {
            OgreRenderingModule::LogError("Could not load Ogre plugins configuration file");
            return;
        }

        Ogre::String plugin_dir = file.getSetting("PluginFolder");
        Ogre::StringVector plugins = file.getMultiSetting("Plugin");

        if (plugin_dir.length())
        {
            if ((plugin_dir[plugin_dir.length() - 1] != '\\') && (plugin_dir[plugin_dir.length() - 1] != '/'))
            {
#ifdef _WINDOWS
                plugin_dir += "\\";
#else
                plugin_dir += "/";
#endif
            }
        }

        for (unsigned i = 0; i < plugins.size(); ++i)
        {
            try
            {
                root_->loadPlugin(plugin_dir + plugins[i]);
            }
            catch (Ogre::Exception e)
            {
                OgreRenderingModule::LogError("Plugin " + plugins[i] + " failed to load");
            }
        }
    }

    void Renderer::SetupResources()
    {
        Ogre::ConfigFile cf;
        cf.load("resources.cfg");

        Ogre::ConfigFile::SectionIterator seci = cf.getSectionIterator();
        Ogre::String sec_name, type_name, arch_name;

        while(seci.hasMoreElements())
        {
            sec_name = seci.peekNextKey();
            Ogre::ConfigFile::SettingsMultiMap* settings = seci.getNext();
            Ogre::ConfigFile::SettingsMultiMap::iterator i;
            for(i = settings->begin(); i != settings->end(); ++i)
            {
                type_name = i->first;
                arch_name = i->second;
                Ogre::ResourceGroupManager::getSingleton().addResourceLocation(arch_name, type_name, sec_name);
            }
        }

        Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
    }

    void Renderer::SetupScene()
    {
        scenemanager_ = root_->createSceneManager(Ogre::ST_GENERIC, "SceneManager");
        camera_ = scenemanager_->createCamera("Camera");
        Ogre::Viewport* viewport = renderwindow_->addViewport(camera_);
        camera_->setAspectRatio(Ogre::Real(viewport->getActualWidth()) / Ogre::Real(viewport->getActualHeight()));
    }

    void Renderer::Update()
    {
        if (!initialized_) return;

        Ogre::WindowEventUtilities::messagePump();

        root_->_fireFrameStarted();

        // Render without swapping buffers first
        Ogre::RenderSystem* renderer = root_->getRenderSystem();
        renderer->_updateAllRenderTargets(false);
        // Send postrender event, so that custom rendering may be added
        framework_->GetEventManager()->SendEvent(event_category_, event_postrender, NULL);
        // Swap buffers now
        renderer->_swapAllRenderTargetBuffers(renderer->getWaitForVerticalBlank());

        root_->_fireFrameEnded();
    }
}

<|endoftext|>


<commit_before>/* ------------------------------------------------------------------------- *
*                        OpenSim:  testPath.cpp                              *
* -------------------------------------------------------------------------- *
* The OpenSim API is a toolkit for musculoskeletal modeling and simulation.  *
* See http://opensim.stanford.edu and the NOTICE file for more information.  *
* OpenSim is developed at Stanford University and supported by the US        *
* National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA    *
* through the Warrior Web program.                                           *
*                                                                            *
* Copyright (c) 2005-2017 Stanford University and the Authors                *
* Author(s): Carmichael Ong                                                  *
*                                                                            *
* 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.         *
*                                                                            *
* 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 <OpenSim/Common/ComponentPath.h>
#include <OpenSim/Auxiliary/auxiliaryTestFunctions.h>

/* The purpose of this test is strictly to check that classes derived from
 * the Path class work outside of the objects/components they are meant to
 * service (i.e. check that the path logic works).
 */

using namespace OpenSim;
using namespace std;

void testComponentPath() {
    /* Test that creating ComponentPath with paths that should not be cleaned up */

    using CP = ComponentPath;
    using std::string;

    // Absolute paths
    ASSERT(CP{"/a/b/c/d"}.toString() == "/a/b/c/d");
    ASSERT(CP{"/a/b/e/f/g/h"}.toString() == "/a/b/e/f/g/h");
    ASSERT(CP{"/a/b"}.toString() == "/a/b");

    // Relative paths
    //     note: relative path can start with ".."
    ASSERT(CP{"c/d"}.toString() == "c/d");
    ASSERT(CP{"e/f/g/h"}.toString() == "e/f/g/h");
    ASSERT(CP{"../../../../c/d"}.toString() == "../../../../c/d");

    // Empty paths
    ASSERT(CP{""}.toString() == "");
    ASSERT(CP{"/"}.toString() == "/");

    /* Test the equality operator */
    ASSERT(CP{"/a/b"} == CP{"/a/b"});
    ASSERT(CP{"/a/b"} != CP{"/a/b/c/d"});
    ASSERT(CP{"/c/d"} != CP{"c/d"});

    // test vector ctor
    ASSERT_THROW(Exception, CP(std::vector<std::string>{"in+valid"}, true));
    ASSERT_THROW(Exception, CP(std::vector<std::string>{"in+valid"}, false));
    ASSERT_THROW(Exception, CP(std::vector<std::string>{"a", "in+valid"}, true));
    ASSERT_THROW(Exception, CP(std::vector<std::string>{"b", "in+valid"}, false));

    /* Test formAbsolutePath(). Test a variety of paths. The argument
     * in formAbsolutePath() must be an absolute path itself. */
    // Test without any ".."
    ASSERT(CP{"c/d"}.formAbsolutePath(CP{"/a/b"}).toString() == "/a/b/c/d");
    ASSERT(CP{"e/f/g/h"}.formAbsolutePath(CP{"/a/b"}).toString() == "/a/b/e/f/g/h");
    // Any absolute path should return itself
    ASSERT(CP{"/a/b/c/d"}.formAbsolutePath(CP{"/a/b/e/f/g/h"}) == CP{"/a/b/c/d"});
    // Test if this works from root.
    ASSERT(CP{"c/d"}.formAbsolutePath(CP{"/"}).toString() == "/c/d");
    // Test with lots of ".."
    ASSERT(CP{"../../../../c/d"}.formAbsolutePath(CP{"/a/b/e/f/g/h"}) == CP{"/a/b/c/d"});
    // argument can't be a relative path
    ASSERT_THROW(Exception, CP{"c/d"}.formAbsolutePath(CP{"e/f/g/h"}));

    /* Test formRelativePath(). Both paths must be absolute */
    // Test path that go up and back down the tree
    ASSERT(CP{"/a/b/c/d"}.formRelativePath(CP{"/a/b/e/f/g/h"}).toString() == "../../../../c/d");
    ASSERT(CP{"/a/b/e/f/g/h"}.formRelativePath(CP{"/a/b/c/d"}).toString() == "../../e/f/g/h");
    // Test path that just goes down a tree
    ASSERT(CP{"/a/b/c/d"}.formRelativePath(CP{"/a/b"}).toString() == "c/d");
    // Test path that only goes up the tree
    ASSERT(CP{"/a/b"}.formRelativePath(CP{"/a/b/e/f/g/h"}).toString() == "../../../..");
    // Throw exceptions if either or both paths are not absolute
    ASSERT_THROW(Exception, CP{"c/d"}.formRelativePath(CP{"/a/b/e/f/g/h"}));
    ASSERT_THROW(Exception, CP{"/a/b/e/f/g/h"}.formRelativePath(CP{"e/f/g/h"}));
    ASSERT_THROW(Exception, CP{"e/f/g/h"}.formRelativePath(CP{"c/d"}));

    /* Test paths with "." and ".." */
    // Remove all ".", clean up ".." and ignore "/" at the end
    ASSERT(CP{"/a/././b/c/..//d/.././"}.toString() == CP{"/a/b"}.toString());
    // Test ".." at the end of a path
    ASSERT(CP{"/a/b/c/d/../.."} == CP{"/a/b"});
    // Test ".." at the beginning of an absolute path (should throw exception)
    ASSERT_THROW(Exception, CP{"/../b/c/d"});
    // Test if there are so many ".." that it will end up at the front of
    // an absolute path, and thus should fail like the one above
    ASSERT_THROW(Exception, CP{"/a/../../c/d"});

    /* Test that invalid characters will throw an exception. This should throw
     * exceptions when "\\", "+", or "*" appear in the string that initializes
     * the ComponentPath. Although "/" is also an invalid character, it should
     * NOT throw an exception here since it is read in as a separator. */
    ASSERT_THROW(Exception, CP{"/a/b\\/c/"});
    ASSERT_THROW(Exception, CP{"/a+b+c/"});
    ASSERT_THROW(Exception, CP{"/abc*/def/g/"});

    /* Test the pushBack() function */
    {
        ComponentPath path1{"/a/b"};
        // can't add multiple levels at once
        ASSERT_THROW(Exception, path1.pushBack("c/d"));

        // add the levels separately
        path1.pushBack("c");
        path1.pushBack("d");
        ASSERT(path1 == CP{"/a/b/c/d"});

        /* Test invalid characters in pushBack(). Unlike the invalid
         * character test above, "/" should be considered invalid since
         * pushBack() cannot add multiple levels at once. It is also
         * invalid to attempt to add an empty pathElement.
         */
        ASSERT_THROW(Exception, path1.pushBack("a\\b"));
        ASSERT_THROW(Exception, path1.pushBack("a+b*"));
        ASSERT_THROW(Exception, path1.pushBack("test/this"));
        ASSERT_THROW(Exception, path1.pushBack(""));

        CP cp2{""};
        cp2.pushBack("a");
        ASSERT(cp2.toString() == "a");

        CP cp3{"/"};
        cp3.pushBack("a");
        ASSERT(cp3.toString() == "/a");
    }

    /* Test functions for getting certain parts of ComponentPath. */
    // Create a path "/zero/one/two/three/four"
    std::vector<std::string> levels = {"zero", "one", "two", "three", "four"};
    ComponentPath numberedAbsPath(levels, true);
    // Parent path is "/zero/one/two/three"
    std::string numberedAbsPathParentStr = "/zero/one/two/three";
    ComponentPath numberedAbsPathParent(numberedAbsPathParentStr);
    // Test if getParentPath() returns correct ComponentPath object
    ASSERT(numberedAbsPath.getParentPath() == numberedAbsPathParent);
    // Test if getParentPathStr() returns correct string
    ASSERT(numberedAbsPath.getParentPathString() == numberedAbsPathParentStr);

    // test number of path levels behaves sanely
    {
        static const std::pair<std::string, int> expectedNumPathLevels[] = {
                {"", 0},
                {"/", 0},
                {"a", 1},
                {"/a", 1},
                {"/a/", 1},
                {"a/b", 2},
                {"/a/b", 2},
                {"/a/b/", 2},
                {"/a/b/c", 3},
                {"../", 1},
                {"a/..", 0},
                {"/a/..", 0},
        };

        for (auto p : expectedNumPathLevels) {
            ASSERT(CP{p.first}.getNumPathLevels() == p.second);
        }
    }

    // Loop through all levels of the subtree and see if names match
    for (size_t ind = 0; ind < levels.size(); ++ind) {
        ASSERT(numberedAbsPath.getSubcomponentNameAtLevel(ind) == levels[ind]);
    }
    // Test getComponentName()
    ASSERT(numberedAbsPath.getComponentName() == levels[levels.size()-1]);
    ASSERT(CP{""}.getComponentName() == ""); // empty ComponentPath should return empty string

    // Do the same as above but with a relative path instead
    ComponentPath numberedRelPath(levels, false);
    std::string numberedRelPathParentStr = "zero/one/two/three";
    ComponentPath numberedRelPathParent(numberedRelPathParentStr);
    ASSERT(numberedRelPath.getParentPath() == numberedRelPathParent);
    ASSERT(numberedRelPath.getParentPathString() == numberedRelPathParentStr);
    for (size_t ind = 0; ind < levels.size(); ++ind) {
        ASSERT(numberedRelPath.getSubcomponentNameAtLevel(ind) == levels[ind]);
    }

    // ensure isAbsolute is sane for vector inputs
    ASSERT(CP{std::vector<std::string>{}, true}.isAbsolute());
    ASSERT(CP{std::vector<std::string>{""}, true}.isAbsolute());
    ASSERT(CP{std::vector<std::string>{"a", "b"}, true}.isAbsolute());

    // general tests to ensure it normalizes a variety of paths correctly
    {
        static const std::pair<std::string, std::string> shouldPass[] = {
            { "",                "" },
            { "/",               "/" },
            { "a/b/c",           "a/b/c" },
            { "a/..",            "" },
            { "a/../",           "" },
            { "a/../c",          "c" },
            { "a/../c/",         "c" },
            { "/a/../c",         "/c" },
            { "/a/b/../../c",    "/c" },
            { "a/b/../../c",     "c" },
            { "/./././c",        "/c" },
            { "./././c",         "c" },
            { "./",              "" },
            { ".",               "" },
            { "./.",             "" },
            { "./a/.",           "a" },
            { "./a/./",          "a" },
            { "a//b/.///",       "a/b" },
            { "///",             "/" },
            { ".///",            "" },
            { "a///b",           "a/b" },
            { "a/b/c/",          "a/b/c" },
            { "a/b/c//",         "a/b/c" },
            { "../a/b",          "../a/b" },
            { "../a/b/",         "../a/b" },
            { "./../a/../",      ".." },
            { "/a/b/c/d",        "/a/b/c/d" },
            { "/a/b/e/f/g/h",    "/a/b/e/f/g/h" },
            { "/a/b",            "/a/b" },
            { "c/d",             "c/d" },
            { "e/f/g/h",         "e/f/g/h" },
            { "/a/././b/c/..//d/.././", "/a/b" },
            { "../../../../c/d", "../../../../c/d" },
            { "/a/b/c/d/../..", "/a/b" },
        };

        for (const auto& tc : shouldPass) {
            std::cerr << "input = " << tc.first << std::endl;
            std::string output = ComponentPath{tc.first}.toString();
            if (output != tc.second) {
                std::stringstream msg;
                msg << "ComponentPath::resolveRelativeElements: invalid output:" << std::endl;
                msg << "              input = " << tc.first << std::endl;
                msg << "             output = " << output << std::endl;
                msg << "    expected output = " << tc.second << std::endl;
                throw std::runtime_error{msg.str()};
            }
        }

        static const std::string shouldThrow[] = {
            "a/../..",
            "./a/../..",
            "/..",
            "/./..",
            "/a/../..",
            "/./../",
            "/a/./.././..",
            "/../b/c/d",
            "/a/../../c/d",

            // contain invalid chars
            "foo\\bar",
            "a/foo\\bar/c",
            "foo*bar",
            "a/foo*bar*/c",
            "foo+bar",
            "a/foo+bar",
            "foo\tbar",
            "a/b/c/foo\tbar/d",
            "foo\nbar",
            "/a/foo\nbar",
        };

        for (const std::string& tc : shouldThrow) {
            std::string maybeError;
            try {
                std::string p = ComponentPath{tc}.toString();
                std::stringstream msg;
                msg << tc << ": did not throw an exception: instead, it output: " << p;
                maybeError = msg.str();
            } catch (...) {
                // good
            }
            if (!maybeError.empty()) {
                throw std::runtime_error{maybeError};
            }
        }
    }
}

int main()
{
    SimTK_START_TEST("testPath");
        SimTK_SUBTEST(testComponentPath);
    SimTK_END_TEST();

    return 0;
}
<commit_msg>Fixed unsigned vs. signed comparison in testPath.cpp<commit_after>/* ------------------------------------------------------------------------- *
*                        OpenSim:  testPath.cpp                              *
* -------------------------------------------------------------------------- *
* The OpenSim API is a toolkit for musculoskeletal modeling and simulation.  *
* See http://opensim.stanford.edu and the NOTICE file for more information.  *
* OpenSim is developed at Stanford University and supported by the US        *
* National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA    *
* through the Warrior Web program.                                           *
*                                                                            *
* Copyright (c) 2005-2017 Stanford University and the Authors                *
* Author(s): Carmichael Ong                                                  *
*                                                                            *
* 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.         *
*                                                                            *
* 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 <OpenSim/Common/ComponentPath.h>
#include <OpenSim/Auxiliary/auxiliaryTestFunctions.h>

/* The purpose of this test is strictly to check that classes derived from
 * the Path class work outside of the objects/components they are meant to
 * service (i.e. check that the path logic works).
 */

using namespace OpenSim;
using namespace std;

void testComponentPath() {
    /* Test that creating ComponentPath with paths that should not be cleaned up */

    using CP = ComponentPath;
    using std::string;

    // Absolute paths
    ASSERT(CP{"/a/b/c/d"}.toString() == "/a/b/c/d");
    ASSERT(CP{"/a/b/e/f/g/h"}.toString() == "/a/b/e/f/g/h");
    ASSERT(CP{"/a/b"}.toString() == "/a/b");

    // Relative paths
    //     note: relative path can start with ".."
    ASSERT(CP{"c/d"}.toString() == "c/d");
    ASSERT(CP{"e/f/g/h"}.toString() == "e/f/g/h");
    ASSERT(CP{"../../../../c/d"}.toString() == "../../../../c/d");

    // Empty paths
    ASSERT(CP{""}.toString() == "");
    ASSERT(CP{"/"}.toString() == "/");

    /* Test the equality operator */
    ASSERT(CP{"/a/b"} == CP{"/a/b"});
    ASSERT(CP{"/a/b"} != CP{"/a/b/c/d"});
    ASSERT(CP{"/c/d"} != CP{"c/d"});

    // test vector ctor
    ASSERT_THROW(Exception, CP(std::vector<std::string>{"in+valid"}, true));
    ASSERT_THROW(Exception, CP(std::vector<std::string>{"in+valid"}, false));
    ASSERT_THROW(Exception, CP(std::vector<std::string>{"a", "in+valid"}, true));
    ASSERT_THROW(Exception, CP(std::vector<std::string>{"b", "in+valid"}, false));

    /* Test formAbsolutePath(). Test a variety of paths. The argument
     * in formAbsolutePath() must be an absolute path itself. */
    // Test without any ".."
    ASSERT(CP{"c/d"}.formAbsolutePath(CP{"/a/b"}).toString() == "/a/b/c/d");
    ASSERT(CP{"e/f/g/h"}.formAbsolutePath(CP{"/a/b"}).toString() == "/a/b/e/f/g/h");
    // Any absolute path should return itself
    ASSERT(CP{"/a/b/c/d"}.formAbsolutePath(CP{"/a/b/e/f/g/h"}) == CP{"/a/b/c/d"});
    // Test if this works from root.
    ASSERT(CP{"c/d"}.formAbsolutePath(CP{"/"}).toString() == "/c/d");
    // Test with lots of ".."
    ASSERT(CP{"../../../../c/d"}.formAbsolutePath(CP{"/a/b/e/f/g/h"}) == CP{"/a/b/c/d"});
    // argument can't be a relative path
    ASSERT_THROW(Exception, CP{"c/d"}.formAbsolutePath(CP{"e/f/g/h"}));

    /* Test formRelativePath(). Both paths must be absolute */
    // Test path that go up and back down the tree
    ASSERT(CP{"/a/b/c/d"}.formRelativePath(CP{"/a/b/e/f/g/h"}).toString() == "../../../../c/d");
    ASSERT(CP{"/a/b/e/f/g/h"}.formRelativePath(CP{"/a/b/c/d"}).toString() == "../../e/f/g/h");
    // Test path that just goes down a tree
    ASSERT(CP{"/a/b/c/d"}.formRelativePath(CP{"/a/b"}).toString() == "c/d");
    // Test path that only goes up the tree
    ASSERT(CP{"/a/b"}.formRelativePath(CP{"/a/b/e/f/g/h"}).toString() == "../../../..");
    // Throw exceptions if either or both paths are not absolute
    ASSERT_THROW(Exception, CP{"c/d"}.formRelativePath(CP{"/a/b/e/f/g/h"}));
    ASSERT_THROW(Exception, CP{"/a/b/e/f/g/h"}.formRelativePath(CP{"e/f/g/h"}));
    ASSERT_THROW(Exception, CP{"e/f/g/h"}.formRelativePath(CP{"c/d"}));

    /* Test paths with "." and ".." */
    // Remove all ".", clean up ".." and ignore "/" at the end
    ASSERT(CP{"/a/././b/c/..//d/.././"}.toString() == CP{"/a/b"}.toString());
    // Test ".." at the end of a path
    ASSERT(CP{"/a/b/c/d/../.."} == CP{"/a/b"});
    // Test ".." at the beginning of an absolute path (should throw exception)
    ASSERT_THROW(Exception, CP{"/../b/c/d"});
    // Test if there are so many ".." that it will end up at the front of
    // an absolute path, and thus should fail like the one above
    ASSERT_THROW(Exception, CP{"/a/../../c/d"});

    /* Test that invalid characters will throw an exception. This should throw
     * exceptions when "\\", "+", or "*" appear in the string that initializes
     * the ComponentPath. Although "/" is also an invalid character, it should
     * NOT throw an exception here since it is read in as a separator. */
    ASSERT_THROW(Exception, CP{"/a/b\\/c/"});
    ASSERT_THROW(Exception, CP{"/a+b+c/"});
    ASSERT_THROW(Exception, CP{"/abc*/def/g/"});

    /* Test the pushBack() function */
    {
        ComponentPath path1{"/a/b"};
        // can't add multiple levels at once
        ASSERT_THROW(Exception, path1.pushBack("c/d"));

        // add the levels separately
        path1.pushBack("c");
        path1.pushBack("d");
        ASSERT(path1 == CP{"/a/b/c/d"});

        /* Test invalid characters in pushBack(). Unlike the invalid
         * character test above, "/" should be considered invalid since
         * pushBack() cannot add multiple levels at once. It is also
         * invalid to attempt to add an empty pathElement.
         */
        ASSERT_THROW(Exception, path1.pushBack("a\\b"));
        ASSERT_THROW(Exception, path1.pushBack("a+b*"));
        ASSERT_THROW(Exception, path1.pushBack("test/this"));
        ASSERT_THROW(Exception, path1.pushBack(""));

        CP cp2{""};
        cp2.pushBack("a");
        ASSERT(cp2.toString() == "a");

        CP cp3{"/"};
        cp3.pushBack("a");
        ASSERT(cp3.toString() == "/a");
    }

    /* Test functions for getting certain parts of ComponentPath. */
    // Create a path "/zero/one/two/three/four"
    std::vector<std::string> levels = {"zero", "one", "two", "three", "four"};
    ComponentPath numberedAbsPath(levels, true);
    // Parent path is "/zero/one/two/three"
    std::string numberedAbsPathParentStr = "/zero/one/two/three";
    ComponentPath numberedAbsPathParent(numberedAbsPathParentStr);
    // Test if getParentPath() returns correct ComponentPath object
    ASSERT(numberedAbsPath.getParentPath() == numberedAbsPathParent);
    // Test if getParentPathStr() returns correct string
    ASSERT(numberedAbsPath.getParentPathString() == numberedAbsPathParentStr);

    // test number of path levels behaves sanely
    {
        static const std::pair<std::string, size_t> expectedNumPathLevels[] = {
                {"", 0},
                {"/", 0},
                {"a", 1},
                {"/a", 1},
                {"/a/", 1},
                {"a/b", 2},
                {"/a/b", 2},
                {"/a/b/", 2},
                {"/a/b/c", 3},
                {"../", 1},
                {"a/..", 0},
                {"/a/..", 0},
        };

        for (auto p : expectedNumPathLevels) {
            ASSERT(CP{p.first}.getNumPathLevels() == p.second);
        }
    }

    // Loop through all levels of the subtree and see if names match
    for (size_t ind = 0; ind < levels.size(); ++ind) {
        ASSERT(numberedAbsPath.getSubcomponentNameAtLevel(ind) == levels[ind]);
    }
    // Test getComponentName()
    ASSERT(numberedAbsPath.getComponentName() == levels[levels.size()-1]);
    ASSERT(CP{""}.getComponentName() == ""); // empty ComponentPath should return empty string

    // Do the same as above but with a relative path instead
    ComponentPath numberedRelPath(levels, false);
    std::string numberedRelPathParentStr = "zero/one/two/three";
    ComponentPath numberedRelPathParent(numberedRelPathParentStr);
    ASSERT(numberedRelPath.getParentPath() == numberedRelPathParent);
    ASSERT(numberedRelPath.getParentPathString() == numberedRelPathParentStr);
    for (size_t ind = 0; ind < levels.size(); ++ind) {
        ASSERT(numberedRelPath.getSubcomponentNameAtLevel(ind) == levels[ind]);
    }

    // ensure isAbsolute is sane for vector inputs
    ASSERT(CP{std::vector<std::string>{}, true}.isAbsolute());
    ASSERT(CP{std::vector<std::string>{""}, true}.isAbsolute());
    ASSERT(CP{std::vector<std::string>{"a", "b"}, true}.isAbsolute());

    // general tests to ensure it normalizes a variety of paths correctly
    {
        static const std::pair<std::string, std::string> shouldPass[] = {
            { "",                "" },
            { "/",               "/" },
            { "a/b/c",           "a/b/c" },
            { "a/..",            "" },
            { "a/../",           "" },
            { "a/../c",          "c" },
            { "a/../c/",         "c" },
            { "/a/../c",         "/c" },
            { "/a/b/../../c",    "/c" },
            { "a/b/../../c",     "c" },
            { "/./././c",        "/c" },
            { "./././c",         "c" },
            { "./",              "" },
            { ".",               "" },
            { "./.",             "" },
            { "./a/.",           "a" },
            { "./a/./",          "a" },
            { "a//b/.///",       "a/b" },
            { "///",             "/" },
            { ".///",            "" },
            { "a///b",           "a/b" },
            { "a/b/c/",          "a/b/c" },
            { "a/b/c//",         "a/b/c" },
            { "../a/b",          "../a/b" },
            { "../a/b/",         "../a/b" },
            { "./../a/../",      ".." },
            { "/a/b/c/d",        "/a/b/c/d" },
            { "/a/b/e/f/g/h",    "/a/b/e/f/g/h" },
            { "/a/b",            "/a/b" },
            { "c/d",             "c/d" },
            { "e/f/g/h",         "e/f/g/h" },
            { "/a/././b/c/..//d/.././", "/a/b" },
            { "../../../../c/d", "../../../../c/d" },
            { "/a/b/c/d/../..", "/a/b" },
        };

        for (const auto& tc : shouldPass) {
            std::cerr << "input = " << tc.first << std::endl;
            std::string output = ComponentPath{tc.first}.toString();
            if (output != tc.second) {
                std::stringstream msg;
                msg << "ComponentPath::resolveRelativeElements: invalid output:" << std::endl;
                msg << "              input = " << tc.first << std::endl;
                msg << "             output = " << output << std::endl;
                msg << "    expected output = " << tc.second << std::endl;
                throw std::runtime_error{msg.str()};
            }
        }

        static const std::string shouldThrow[] = {
            "a/../..",
            "./a/../..",
            "/..",
            "/./..",
            "/a/../..",
            "/./../",
            "/a/./.././..",
            "/../b/c/d",
            "/a/../../c/d",

            // contain invalid chars
            "foo\\bar",
            "a/foo\\bar/c",
            "foo*bar",
            "a/foo*bar*/c",
            "foo+bar",
            "a/foo+bar",
            "foo\tbar",
            "a/b/c/foo\tbar/d",
            "foo\nbar",
            "/a/foo\nbar",
        };

        for (const std::string& tc : shouldThrow) {
            std::string maybeError;
            try {
                std::string p = ComponentPath{tc}.toString();
                std::stringstream msg;
                msg << tc << ": did not throw an exception: instead, it output: " << p;
                maybeError = msg.str();
            } catch (...) {
                // good
            }
            if (!maybeError.empty()) {
                throw std::runtime_error{maybeError};
            }
        }
    }
}

int main()
{
    SimTK_START_TEST("testPath");
        SimTK_SUBTEST(testComponentPath);
    SimTK_END_TEST();

    return 0;
}
<|endoftext|>


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

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "otbImage.h"
#include "otbImageToEnvelopeVectorDataFilter.h"
#include "otbVectorData.h"
#include "otbImageFileReader.h"
#include "otbVectorDataFileWriter.h"

#include "otbCommandLineArgumentParser.h"

typedef unsigned short                            PixelType;
typedef otb::Image<PixelType,2>                   ImageType;
typedef otb::ImageFileReader<ImageType>           ReaderType;
typedef otb::VectorData<>                         VectorDataType;
typedef otb::VectorDataFileWriter<VectorDataType> WriterType;
typedef otb::ImageToEnvelopeVectorDataFilter
    <ImageType,VectorDataType>                    FilterType;

int main(int argc,char* argv[])
{

  // Parse command line parameters
  typedef otb::CommandLineArgumentParser ParserType;
  ParserType::Pointer parser = ParserType::New();

  parser->SetProgramDescription("Write a vector file containing a polygon corresponding to the imate envelope.");
  parser->AddInputImage();
  parser->AddOption("--OutputVectorData","Vector Data file containg the envelope.","-out",1,true);

  typedef otb::CommandLineArgumentParseResult ParserResultType;
  ParserResultType::Pointer  parseResult = ParserResultType::New();

  try
  {
    parser->ParseCommandLine(argc,argv,parseResult);
  }
  catch ( itk::ExceptionObject & err )
  {
    std::string descriptionException = err.GetDescription();
    if (descriptionException.find("ParseCommandLine(): Help Parser") != std::string::npos)
      {
      return EXIT_SUCCESS;
      }
    if (descriptionException.find("ParseCommandLine(): Version Parser") != std::string::npos)
      {
      return EXIT_SUCCESS;
      }
    return EXIT_FAILURE;
  }

  ReaderType::Pointer reader = ReaderType::New();
  reader->SetFileName(parseResult->GetInputImage());
  FilterType::Pointer filter = FilterType::New();
  filter->SetInput(reader->GetOutput());
  WriterType::Pointer writer = WriterType::New();
  writer->SetInput(filter->GetOutput());
  writer->SetFileName(parseResult->GetParameterString("--OutputVectorData"));
  writer->Update();

  return EXIT_SUCCESS;
}
<commit_msg>STYLE<commit_after>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "otbImage.h"
#include "otbImageToEnvelopeVectorDataFilter.h"
#include "otbVectorData.h"
#include "otbImageFileReader.h"
#include "otbVectorDataFileWriter.h"

#include "otbCommandLineArgumentParser.h"

typedef unsigned short                            PixelType;
typedef otb::Image<PixelType, 2>                   ImageType;
typedef otb::ImageFileReader<ImageType>           ReaderType;
typedef otb::VectorData<>                         VectorDataType;
typedef otb::VectorDataFileWriter<VectorDataType> WriterType;
typedef otb::ImageToEnvelopeVectorDataFilter
    <ImageType, VectorDataType>                    FilterType;

int main(int argc, char* argv[])
{

  // Parse command line parameters
  typedef otb::CommandLineArgumentParser ParserType;
  ParserType::Pointer parser = ParserType::New();

  parser->SetProgramDescription("Write a vector file containing a polygon corresponding to the imate envelope.");
  parser->AddInputImage();
  parser->AddOption("--OutputVectorData","Vector Data file containg the envelope.","-out", 1, true);

  typedef otb::CommandLineArgumentParseResult ParserResultType;
  ParserResultType::Pointer  parseResult = ParserResultType::New();

  try
  {
    parser->ParseCommandLine(argc, argv, parseResult);
  }
  catch ( itk::ExceptionObject & err )
  {
    std::string descriptionException = err.GetDescription();
    if (descriptionException.find("ParseCommandLine(): Help Parser") != std::string::npos)
      {
      return EXIT_SUCCESS;
      }
    if (descriptionException.find("ParseCommandLine(): Version Parser") != std::string::npos)
      {
      return EXIT_SUCCESS;
      }
    return EXIT_FAILURE;
  }

  ReaderType::Pointer reader = ReaderType::New();
  reader->SetFileName(parseResult->GetInputImage());
  FilterType::Pointer filter = FilterType::New();
  filter->SetInput(reader->GetOutput());
  WriterType::Pointer writer = WriterType::New();
  writer->SetInput(filter->GetOutput());
  writer->SetFileName(parseResult->GetParameterString("--OutputVectorData"));
  writer->Update();

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>/* This file is part of Strigi Desktop Search
 *
 * Copyright (C) 2006 Jos van den Oever <jos@vandenoever.info>
 *
 * 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; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

#include "../archivereader.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <unistd.h>

using namespace jstreams;
using namespace std;

int errors;

void
test1(const char* path) {
    FileStreamOpener opener;
    ArchiveReader r;
    r.addStreamOpener(&opener);
    StreamBase<char>* s = r.openStream(path);
    r.closeStream(s);
}
void
test2(const char* path) {
    FileStreamOpener opener;
    ArchiveReader r;
    r.addStreamOpener(&opener);
    DirLister dl = r.getDirEntries(path);
    EntryInfo e;
    while (dl.nextEntry(e)) {
        printf("%s\n", e.filename.c_str());
    }
}

void
walkdirectories(const char* path, void (*callback)(const char*)) {
    DIR* dir = opendir(path);
    if (dir == 0) return;
    string p(path);
    struct dirent* subdir = readdir(dir);
    struct stat dirstat;
    while (subdir) {
        if (subdir->d_name[0] == '.') {
            subdir = readdir(dir);
            continue;
        }
        string name = subdir->d_name;
        string filepath = p + name;
        if (lstat(filepath.c_str(), &dirstat) == 0) {
            if (S_ISREG(dirstat.st_mode)) {
                callback(filepath.c_str());
            } else if (S_ISDIR(dirstat.st_mode)) {
                filepath += "/";
                walkdirectories(filepath.c_str(), callback);
            }
        }
        subdir = readdir(dir);
    }
    closedir(dir);
}

/**
 * Test the class ArchiveReader by analyzing all files in the given
 * directory.
 **/
int
ArchiveReaderTest(int argc, char** argv) {
    if (argc < 2) return 1;
    errors = 0;
    printf("%s\n", argv[1]);
    walkdirectories(argv[1], test1);
    walkdirectories(argv[1], test2);
    return errors;
}
<commit_msg>More thorough test for ArchiveReader<commit_after>/* This file is part of Strigi Desktop Search
 *
 * Copyright (C) 2006 Jos van den Oever <jos@vandenoever.info>
 *
 * 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; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

#include "../archivereader.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <unistd.h>

using namespace jstreams;
using namespace std;

int errors;

void
test1(const char* path) {
    FileStreamOpener opener;
    ArchiveReader r;
    r.addStreamOpener(&opener);
    StreamBase<char>* s = r.openStream(path);
    if (s == 0) {
        fprintf(stderr, "cannot open stream to %s\n", path);
        errors++;
    }
    r.closeStream(s);
}
void
test2(const char* path) {
    FileStreamOpener opener;
    ArchiveReader r;
    r.addStreamOpener(&opener);
    DirLister dl = r.getDirEntries(path);
    EntryInfo e;
    while (dl.nextEntry(e)) {
        string filepath(path);
        filepath += "/";
        filepath += e.filename;
        if (e.type == EntryInfo::File) {
            test1(filepath.c_str());
        }
        test2(filepath.c_str());
    }
}

void
walkdirectories(const char* path, void (*callback)(const char*)) {
    DIR* dir = opendir(path);
    if (dir == 0) return;
    string p(path);
    struct dirent* subdir = readdir(dir);
    struct stat dirstat;
    while (subdir) {
        if (subdir->d_name[0] == '.') {
            subdir = readdir(dir);
            continue;
        }
        string name = subdir->d_name;
        string filepath = p + name;
        if (lstat(filepath.c_str(), &dirstat) == 0) {
            if (S_ISREG(dirstat.st_mode)) {
                callback(filepath.c_str());
            } else if (S_ISDIR(dirstat.st_mode)) {
                filepath += "/";
                walkdirectories(filepath.c_str(), callback);
            }
        }
        subdir = readdir(dir);
    }
    closedir(dir);
}

/**
 * Test the class ArchiveReader by analyzing all files in the given
 * directory.
 **/
int
ArchiveReaderTest(int argc, char** argv) {
    if (argc < 2) return 1;
    errors = 0;
    walkdirectories(argv[1], test1);
    walkdirectories(argv[1], test2);
    if (errors) {
        fprintf(stderr, "%i errors\n", errors);
    }
    return errors;
}
<|endoftext|>


<commit_before>#pragma once

#include <supermarx/util/cached_downloader.hpp>
#include <supermarx/util/stubborn.hpp>

#include <functional>
#include <deque>

namespace supermarx
{

class download_manager
{
public:
	typedef std::function<void(downloader::response)> f_t;
	typedef std::function<void()> error_f_t;

	struct job_t
	{
		std::string uri;
		f_t f;

		job_t(job_t const&) = delete;
		job_t(job_t&&) = default;
	};

private:
	cached_downloader& dl;
	std::deque<job_t> queue;
	error_f_t error_f;

	static void nil() {}

public:
	download_manager(cached_downloader& _dl, error_f_t const& _error_f = nil)
		: dl(_dl)
		, queue()
		, error_f(_error_f)
	{}

	void schedule(std::string const& _uri, f_t&& _f)
	{
		job_t j = {_uri, std::move(_f)};
		queue.emplace_back(std::move(j));
	}

	void process_all()
	{
		while(!queue.empty())
		{
			job_t j = std::move(queue.front());
			queue.pop_front();

			try
			{
				j.f(stubborn::attempt<downloader::response, downloader::error>([&]() {
					return dl.fetch(j.uri);
				}));
			} catch(std::runtime_error e)
			{
				std::cerr << "Failed " << j.uri << std::endl
					<< '\t' << e.what() << std::endl;
				error_f();
				continue;
			}
		}
	}
};

}
<commit_msg>Added missing iostream dependency<commit_after>#pragma once

#include <supermarx/util/cached_downloader.hpp>
#include <supermarx/util/stubborn.hpp>

#include <iostream>
#include <functional>
#include <deque>

namespace supermarx
{

class download_manager
{
public:
	typedef std::function<void(downloader::response)> f_t;
	typedef std::function<void()> error_f_t;

	struct job_t
	{
		std::string uri;
		f_t f;

		job_t(job_t const&) = delete;
		job_t(job_t&&) = default;
	};

private:
	cached_downloader& dl;
	std::deque<job_t> queue;
	error_f_t error_f;

	static void nil() {}

public:
	download_manager(cached_downloader& _dl, error_f_t const& _error_f = nil)
		: dl(_dl)
		, queue()
		, error_f(_error_f)
	{}

	void schedule(std::string const& _uri, f_t&& _f)
	{
		job_t j = {_uri, std::move(_f)};
		queue.emplace_back(std::move(j));
	}

	void process_all()
	{
		while(!queue.empty())
		{
			job_t j = std::move(queue.front());
			queue.pop_front();

			try
			{
				j.f(stubborn::attempt<downloader::response, downloader::error>([&]() {
					return dl.fetch(j.uri);
				}));
			} catch(std::runtime_error e)
			{
				std::cerr << "Failed " << j.uri << std::endl
					<< '\t' << e.what() << std::endl;
				error_f();
				continue;
			}
		}
	}
};

}
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QObject>
#include <QTimer>

#include <wlanmgmtclient.h>
#include <wlanmgmtinterface.h>
#include <wlanmgmtcommon.h>
#include "wlaninfo_s60.h"

const int KWlanInfoSignalStrengthMax = 60;
const int KWlanInfoSignalStrengthMin = 100;

CWlanInfo::CWlanInfo(QObject *parent) : QObject(parent)
    , m_wlanStatus(false)
    , m_wlanSsid()
    , m_wlanSignalStrength(-1)
{
#ifndef __WINSCW__
    TRAP_IGNORE(
        m_wlanMgmtClient = CWlanMgmtClient::NewL();
        m_wlanMgmtClient->ActivateNotificationsL(*this);
    )

    m_timer = new QTimer(this);
    connect(m_timer, SIGNAL(timeout()), this, SLOT(checkWlanInfo()));
    m_timer->setInterval(1000);
    m_timer->start();
#endif
}

CWlanInfo::~CWlanInfo()
{
    m_wlanMgmtClient->CancelNotifications();
    delete m_wlanMgmtClient;
}

QString CWlanInfo::wlanNetworkName() const
{
    return m_wlanSsid;
}

int CWlanInfo::wlanNetworkSignalStrength() const
{
    return m_wlanSignalStrength;
}

bool CWlanInfo::wlanNetworkConnectionStatus() const
{
    return m_wlanStatus;
}

void CWlanInfo::checkWlanInfo()
{
#ifndef __WINSCW__
    TWlanConnectionMode connectionMode;
    TInt err = m_wlanMgmtClient->GetConnectionMode(connectionMode);
    if (err == KErrNone && connectionMode != EWlanConnectionModeNotConnected) {
        m_wlanStatus = true;
        emit wlanNetworkStatusChanged();
    } else {
        stopPolling();
        return;
    }

    TWlanSsid ssid;
    err = m_wlanMgmtClient->GetConnectionSsid(ssid);
    ssid.ZeroTerminate();
    if (err == KErrNone && m_wlanSsid != (char*)ssid.Ptr()) {
        m_wlanSsid = (char*)ssid.Ptr();
        emit wlanNetworkNameChanged();
    }

    TInt32 signalQuality;
    err = m_wlanMgmtClient->GetConnectionSignalQuality(signalQuality);

    if (err == KErrNone && m_wlanSignalStrength != signalQuality) {
        if (signalQuality <= KWlanInfoSignalStrengthMax && signalQuality >= 0)
            m_wlanSignalStrength = 100;
        else if (signalQuality >= KWlanInfoSignalStrengthMin)
            m_wlanSignalStrength = 0;
        else {
            m_wlanSignalStrength = (KWlanInfoSignalStrengthMin - signalQuality) * 100 /
            (KWlanInfoSignalStrengthMin - KWlanInfoSignalStrengthMax);
        }
        emit wlanNetworkSignalStrengthChanged();
    }
#endif
}

void CWlanInfo::ConnectionStateChanged(TWlanConnectionMode aNewState)
{
    if (aNewState == EWlanConnectionModeNotConnected)
        stopPolling();
    else {
        m_timer->start();
        checkWlanInfo();
    }
}

void CWlanInfo::stopPolling()
{
    m_timer->stop();
    m_wlanStatus = false;
    m_wlanSsid = "";
    m_wlanSignalStrength = 0;

    emit wlanNetworkStatusChanged();
    emit wlanNetworkNameChanged();
    emit wlanNetworkSignalStrengthChanged();
}
<commit_msg>MOBILITY-1499 : Fix for CWlanInfo crash ( added handle checks)<commit_after>/****************************************************************************
**
** Copyright (C) 2009-2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QObject>
#include <QTimer>

#include <wlanmgmtclient.h>
#include <wlanmgmtinterface.h>
#include <wlanmgmtcommon.h>
#include "wlaninfo_s60.h"

const int KWlanInfoSignalStrengthMax = 60;
const int KWlanInfoSignalStrengthMin = 100;

CWlanInfo::CWlanInfo(QObject *parent) : QObject(parent)
    , m_wlanMgmtClient(NULL)
    , m_wlanStatus(false)
    , m_wlanSsid()
    , m_wlanSignalStrength(-1)
{
#ifndef __WINSCW__
    TRAP_IGNORE( m_wlanMgmtClient = CWlanMgmtClient::NewL();)

		if (m_wlanMgmtClient){
			m_wlanMgmtClient->ActivateNotificationsL(*this);
	    m_timer = new QTimer(this);
	    connect(m_timer, SIGNAL(timeout()), this, SLOT(checkWlanInfo()));
	    m_timer->setInterval(1000);
	    m_timer->start();
	  	}
#endif
}

CWlanInfo::~CWlanInfo()
{
    if (m_wlanMgmtClient)
    	m_wlanMgmtClient->CancelNotifications();
    delete m_wlanMgmtClient;
}

QString CWlanInfo::wlanNetworkName() const
{
    return m_wlanSsid;
}

int CWlanInfo::wlanNetworkSignalStrength() const
{
    return m_wlanSignalStrength;
}

bool CWlanInfo::wlanNetworkConnectionStatus() const
{
    return m_wlanStatus;
}

void CWlanInfo::checkWlanInfo()
{
#ifndef __WINSCW__
		if(!m_wlanMgmtClient)
			return;
    TWlanConnectionMode connectionMode;
    TInt err = m_wlanMgmtClient->GetConnectionMode(connectionMode);
    if (err == KErrNone && connectionMode != EWlanConnectionModeNotConnected) {
        m_wlanStatus = true;
        emit wlanNetworkStatusChanged();
    } else {
        stopPolling();
        return;
    }

    TWlanSsid ssid;
    err = m_wlanMgmtClient->GetConnectionSsid(ssid);
    ssid.ZeroTerminate();
    if (err == KErrNone && m_wlanSsid != (char*)ssid.Ptr()) {
        m_wlanSsid = (char*)ssid.Ptr();
        emit wlanNetworkNameChanged();
    }

    TInt32 signalQuality;
    err = m_wlanMgmtClient->GetConnectionSignalQuality(signalQuality);

    if (err == KErrNone && m_wlanSignalStrength != signalQuality) {
        if (signalQuality <= KWlanInfoSignalStrengthMax && signalQuality >= 0)
            m_wlanSignalStrength = 100;
        else if (signalQuality >= KWlanInfoSignalStrengthMin)
            m_wlanSignalStrength = 0;
        else {
            m_wlanSignalStrength = (KWlanInfoSignalStrengthMin - signalQuality) * 100 /
            (KWlanInfoSignalStrengthMin - KWlanInfoSignalStrengthMax);
        }
        emit wlanNetworkSignalStrengthChanged();
    }
#endif
}

void CWlanInfo::ConnectionStateChanged(TWlanConnectionMode aNewState)
{
    if (aNewState == EWlanConnectionModeNotConnected)
        stopPolling();
    else {
        m_timer->start();
        checkWlanInfo();
    }
}

void CWlanInfo::stopPolling()
{
    m_timer->stop();
    m_wlanStatus = false;
    m_wlanSsid = "";
    m_wlanSignalStrength = 0;

    emit wlanNetworkStatusChanged();
    emit wlanNetworkNameChanged();
    emit wlanNetworkSignalStrengthChanged();
}
<|endoftext|>


<commit_before>#include "stdafx.h"

#include <string>
#include <map>
#include <vector>
#include "../Application.h"
#include "../ModuleScripting.h"
#include "../ModuleInput.h"
#include "../ModuleWindow.h"
#include "../ComponentTransform.h"
#include "../ModuleGOManager.h"
#include "../GameObject.h"
#include "../Component.h"
#include "../ComponentScript.h"
#include "../ComponentRectTransform.h"
#include "../SDL/include/SDL_scancode.h"
#include "../Globals.h"
#include "../ComponentUiButton.h"
#include "../ComponentCanvas.h"
#include "../ModuleResourceManager.h"
#include "../Random.h"
#include "../Time.h"

#include "../ComponentAudioSource.h"

namespace MapSelectUI
{

	GameObject* map_fields = nullptr;
	GameObject* map_umi = nullptr;
	GameObject* map_ricing = nullptr;

	GameObject* players_vote[4];
	GameObject* right_arrow = nullptr;
	GameObject* left_arrow = nullptr;

	ComponentUiButton* c_players_vote[4];
	// 0 - P1 Red, 1 - P2 Red, 2 - P1 Blue, 2 - P2 Blue,
	ComponentUiButton* c_right_arrow = nullptr;
	ComponentUiButton* c_left_arrow = nullptr;

	string path_map1 = "";
	string path_map2 = "";
	string path_map3 = "";

	bool players_ready[4] = { false, false, false, false };

	bool a_pressed = false;
	bool b_pressed = false;
	bool dpad_left_pressed = false;
	bool dpad_right_pressed = false;
	int current_level = 0;
	int current_map = 0; // 1 -   , 2 -   , 3 -   ,
	int votes[4] = { 0, 0, 0, 0 };

	int arrow_counter_left = 30;
	int arrow_counter_right = 30;
	int time = 30;
	int player_order[4];
	void MapSelectUI_GetPublics(map<const char*, string>* public_chars, map<const char*, int>* public_ints, map<const char*, float>* public_float, map<const char*, bool>* public_bools, map<const char*, GameObject*>* public_gos)
	{
		public_gos->insert(std::pair<const char*, GameObject*>("Map Fields", map_fields));
		public_gos->insert(std::pair<const char*, GameObject*>("Map Umi", map_umi));
		public_gos->insert(std::pair<const char*, GameObject*>("Map Ricing", map_ricing));
		public_gos->insert(std::pair<const char*, GameObject*>("P1-Red Vote", players_vote[2]));
		public_gos->insert(std::pair<const char*, GameObject*>("P2-Red Vote", players_vote[3]));
		public_gos->insert(std::pair<const char*, GameObject*>("P1-Blue Vote", players_vote[0]));
		public_gos->insert(std::pair<const char*, GameObject*>("P2-Blue Vote", players_vote[1]));
		public_gos->insert(std::pair<const char*, GameObject*>("R-Arrow", right_arrow));
		public_gos->insert(std::pair<const char*, GameObject*>("L-Arrow", left_arrow));

		public_ints->insert(std::pair<const char*, int>("Button Cooldown", time));
	}

	void MapSelectUI_UpdatePublics(GameObject* game_object)
	{
		ComponentScript* test_script = (ComponentScript*)game_object->GetComponent(ComponentType::C_SCRIPT);

		map_fields = test_script->public_gos.at("Map Fields");
		map_umi = test_script->public_gos.at("Map Umi");
		map_ricing = test_script->public_gos.at("Map Ricing");
		players_vote[0] = test_script->public_gos.at("P1-Blue Vote");
		players_vote[1] = test_script->public_gos.at("P2-Blue Vote");
		players_vote[2] = test_script->public_gos.at("P1-Red Vote");
		players_vote[3] = test_script->public_gos.at("P2-Red Vote");

		right_arrow = test_script->public_gos.at("R-Arrow");
		left_arrow = test_script->public_gos.at("L-Arrow");
		time = test_script->public_ints.at("Button Cooldown");

		c_players_vote[0] = (ComponentUiButton*)players_vote[0]->GetComponent(C_UI_BUTTON);
		c_players_vote[1] = (ComponentUiButton*)players_vote[1]->GetComponent(C_UI_BUTTON);
		c_players_vote[2] = (ComponentUiButton*)players_vote[2]->GetComponent(C_UI_BUTTON);
		c_players_vote[3] = (ComponentUiButton*)players_vote[3]->GetComponent(C_UI_BUTTON);
		c_right_arrow = (ComponentUiButton*)right_arrow->GetComponent(C_UI_BUTTON);
		c_left_arrow = (ComponentUiButton*)left_arrow->GetComponent(C_UI_BUTTON);
	}

	void MapSelectUI_ActualizePublics(GameObject* game_object)
	{
		ComponentScript* this_script = (ComponentScript*)game_object->GetComponent(ComponentType::C_SCRIPT);

		this_script->public_gos.at("Map Fields") = map_fields;
		this_script->public_gos.at("Map Umi") = map_umi;
		this_script->public_gos.at("Map Ricing") = map_ricing;
		this_script->public_gos.at("P1-Blue Vote") = players_vote[0];
		this_script->public_gos.at("P2-Blue Vote") = players_vote[1];
		this_script->public_gos.at("P1-Red Vote") = players_vote[2];
		this_script->public_gos.at("P2-Red Vote") = players_vote[3];

		this_script->public_gos.at("R-Arrow") = right_arrow;
		this_script->public_gos.at("L-Arrow") = left_arrow;
		this_script->public_ints.at("Button Cooldown") = time;
		c_players_vote[0] = (ComponentUiButton*)players_vote[0]->GetComponent(C_UI_BUTTON);
		c_players_vote[1] = (ComponentUiButton*)players_vote[1]->GetComponent(C_UI_BUTTON);
		c_players_vote[2] = (ComponentUiButton*)players_vote[2]->GetComponent(C_UI_BUTTON);
		c_players_vote[3] = (ComponentUiButton*)players_vote[3]->GetComponent(C_UI_BUTTON);
		c_right_arrow = (ComponentUiButton*)right_arrow->GetComponent(C_UI_BUTTON);
		c_left_arrow = (ComponentUiButton*)left_arrow->GetComponent(C_UI_BUTTON);
	}

	void MapSelectUI_UpdatePublics(GameObject* game_object);

	void MapSelectUI_Start(GameObject* game_object)
	{
		// Play Move Selection
		ComponentAudioSource *a_comp = (ComponentAudioSource*)game_object->GetComponent(ComponentType::C_AUDIO_SOURCE);
		if (a_comp) a_comp->PlayAudio(0);

		arrow_counter_left = time;
		arrow_counter_right = time;
		current_map = 0;
		current_level = 0;
		player_order[0] = App->go_manager->team1_front;
		player_order[1] = App->go_manager->team1_back;
		player_order[2] = App->go_manager->team2_front;
		player_order[3] = App->go_manager->team2_back;
	}

	void MapSelectUI_Update(GameObject* game_object)
	{
		for (int playerID = 0; playerID < 4; playerID++)
		{
			int id = 0;
			for (int j = 0; j < 4; j++)
			{
				if (player_order[j] == playerID)
				{
					id = j;
				}
			}
			if (App->input->GetJoystickButton(playerID, JOY_BUTTON::A) == KEY_DOWN || App->input->GetKey(SDL_SCANCODE_A) == KEY_DOWN)
			{
				c_players_vote[id]->OnPressId(current_level); // TO BE TESTED

				votes[id] = current_level;
				players_ready[id] = true;
			}

			if (App->input->GetJoystickButton(playerID, JOY_BUTTON::B) == KEY_DOWN || App->input->GetKey(SDL_SCANCODE_B) == KEY_DOWN)
			{
				if (players_ready[id])
				{
					c_players_vote[id]->OnPressId(votes[id]); // TO BE TESTED

					players_ready[id] = false;
				}
			}

			if (App->input->GetJoystickButton(playerID, JOY_BUTTON::DPAD_LEFT) == KEY_DOWN || App->input->GetKey(SDL_SCANCODE_LEFT) == KEY_DOWN)
			{
				// Play Move Selection
				ComponentAudioSource *a_comp = (ComponentAudioSource*)game_object->GetComponent(ComponentType::C_AUDIO_SOURCE);
				if (a_comp) a_comp->PlayAudio(1);

				current_level--;
				if (current_level < 0)
					current_level = 2;

				switch (current_level)
				{
				case 0:
					map_fields->SetActive(true);
					map_umi->SetActive(false);
					map_ricing->SetActive(false);
					break;
				case 1:
					map_fields->SetActive(false);
					map_umi->SetActive(true);
					map_ricing->SetActive(false);
					break;
				case 2:
					map_fields->SetActive(false);
					map_umi->SetActive(false);
					map_ricing->SetActive(true);
					break;
				}

				if (arrow_counter_left >= time)
				{
					c_left_arrow->OnPress();
				}
				arrow_counter_left = 0;
			}

			if (App->input->GetJoystickButton(playerID, JOY_BUTTON::DPAD_RIGHT) == KEY_DOWN || App->input->GetKey(SDL_SCANCODE_RIGHT) == KEY_DOWN)
			{
				// Play Move Selection
				ComponentAudioSource *a_comp = (ComponentAudioSource*)game_object->GetComponent(ComponentType::C_AUDIO_SOURCE);
				if (a_comp) a_comp->PlayAudio(1);

				current_level++;
				if (current_level > 2)
					current_level = 0;
				switch (current_level)
				{
				case 0:
					map_fields->SetActive(true);
					map_umi->SetActive(false);
					map_ricing->SetActive(false);
					break;
				case 1:
					map_fields->SetActive(false);
					map_umi->SetActive(true);
					map_ricing->SetActive(false);
					break;
				case 2:
					map_fields->SetActive(false);
					map_umi->SetActive(false);
					map_ricing->SetActive(true);
					break;
				}

				if (arrow_counter_right >= time)
				{
					c_right_arrow->OnPress();
				}
				arrow_counter_right = 0;
			}
		}

		if (arrow_counter_left < time)
		{
			arrow_counter_left++;

			if (arrow_counter_left == time)
				c_left_arrow->OnPress();
		}

		if (arrow_counter_right < time)
		{
			arrow_counter_right++;

			if (arrow_counter_right == time)
				c_right_arrow->OnPress();
		}

		int total = 0;
		for (int j = 0; j < 4; j++)
		{
			if (players_ready[j])
				total++;

			if (total == 4)
			{
				unsigned int k = App->rnd->RandomInt(1, 4);

				switch (votes[k])
				{
				case 1:
					App->resource_manager->LoadSceneFromAssets(path_map1.data());
					break;
				case 2:
					App->resource_manager->LoadSceneFromAssets(path_map2.data());
					break;
				case 3:
					App->resource_manager->LoadSceneFromAssets(path_map3.data());
					break;
				default:
					// Error Reset, but loads map 1 instead (because we need to cover bugs lol lmao pls don't kill me)
					App->resource_manager->LoadSceneFromAssets(path_map1.data());
					break;

				}
			}
			else
				total = 0; // Redundancy
		}
	}

	void MapSelectUI_OnFocus()
	{

	}
}
<commit_msg>Fixed Issue in map selection<commit_after>#include "stdafx.h"

#include <string>
#include <map>
#include <vector>
#include "../Application.h"
#include "../ModuleScripting.h"
#include "../ModuleInput.h"
#include "../ModuleWindow.h"
#include "../ComponentTransform.h"
#include "../ModuleGOManager.h"
#include "../GameObject.h"
#include "../Component.h"
#include "../ComponentScript.h"
#include "../ComponentRectTransform.h"
#include "../SDL/include/SDL_scancode.h"
#include "../Globals.h"
#include "../ComponentUiButton.h"
#include "../ComponentCanvas.h"
#include "../ModuleResourceManager.h"
#include "../Random.h"
#include "../Time.h"

#include "../ComponentAudioSource.h"

namespace MapSelectUI
{

	GameObject* map_fields = nullptr;
	GameObject* map_umi = nullptr;
	GameObject* map_ricing = nullptr;

	GameObject* players_vote[4];
	GameObject* right_arrow = nullptr;
	GameObject* left_arrow = nullptr;

	ComponentUiButton* c_players_vote[4];
	// 0 - P1 Red, 1 - P2 Red, 2 - P1 Blue, 2 - P2 Blue,
	ComponentUiButton* c_right_arrow = nullptr;
	ComponentUiButton* c_left_arrow = nullptr;

	string path_map1 = "";
	string path_map2 = "";
	string path_map3 = "";

	bool players_ready[4] = { false, false, false, false };

	bool a_pressed = false;
	bool b_pressed = false;
	bool dpad_left_pressed = false;
	bool dpad_right_pressed = false;
	int current_level = 0;
	int current_map = 0; // 1 -   , 2 -   , 3 -   ,
	int votes[4] = { 0, 0, 0, 0 };

	int arrow_counter_left = 30;
	int arrow_counter_right = 30;
	int time = 30;
	int player_order[4];
	void MapSelectUI_GetPublics(map<const char*, string>* public_chars, map<const char*, int>* public_ints, map<const char*, float>* public_float, map<const char*, bool>* public_bools, map<const char*, GameObject*>* public_gos)
	{
		public_gos->insert(std::pair<const char*, GameObject*>("Map Fields", map_fields));
		public_gos->insert(std::pair<const char*, GameObject*>("Map Umi", map_umi));
		public_gos->insert(std::pair<const char*, GameObject*>("Map Ricing", map_ricing));
		public_gos->insert(std::pair<const char*, GameObject*>("P1-Red Vote", players_vote[2]));
		public_gos->insert(std::pair<const char*, GameObject*>("P2-Red Vote", players_vote[3]));
		public_gos->insert(std::pair<const char*, GameObject*>("P1-Blue Vote", players_vote[0]));
		public_gos->insert(std::pair<const char*, GameObject*>("P2-Blue Vote", players_vote[1]));
		public_gos->insert(std::pair<const char*, GameObject*>("R-Arrow", right_arrow));
		public_gos->insert(std::pair<const char*, GameObject*>("L-Arrow", left_arrow));

		public_ints->insert(std::pair<const char*, int>("Button Cooldown", time));
	}

	void MapSelectUI_UpdatePublics(GameObject* game_object)
	{
		ComponentScript* test_script = (ComponentScript*)game_object->GetComponent(ComponentType::C_SCRIPT);

		map_fields = test_script->public_gos.at("Map Fields");
		map_umi = test_script->public_gos.at("Map Umi");
		map_ricing = test_script->public_gos.at("Map Ricing");
		players_vote[0] = test_script->public_gos.at("P1-Blue Vote");
		players_vote[1] = test_script->public_gos.at("P2-Blue Vote");
		players_vote[2] = test_script->public_gos.at("P1-Red Vote");
		players_vote[3] = test_script->public_gos.at("P2-Red Vote");

		right_arrow = test_script->public_gos.at("R-Arrow");
		left_arrow = test_script->public_gos.at("L-Arrow");
		time = test_script->public_ints.at("Button Cooldown");

		c_players_vote[0] = (ComponentUiButton*)players_vote[0]->GetComponent(C_UI_BUTTON);
		c_players_vote[1] = (ComponentUiButton*)players_vote[1]->GetComponent(C_UI_BUTTON);
		c_players_vote[2] = (ComponentUiButton*)players_vote[2]->GetComponent(C_UI_BUTTON);
		c_players_vote[3] = (ComponentUiButton*)players_vote[3]->GetComponent(C_UI_BUTTON);
		c_right_arrow = (ComponentUiButton*)right_arrow->GetComponent(C_UI_BUTTON);
		c_left_arrow = (ComponentUiButton*)left_arrow->GetComponent(C_UI_BUTTON);
	}

	void MapSelectUI_ActualizePublics(GameObject* game_object)
	{
		ComponentScript* this_script = (ComponentScript*)game_object->GetComponent(ComponentType::C_SCRIPT);

		this_script->public_gos.at("Map Fields") = map_fields;
		this_script->public_gos.at("Map Umi") = map_umi;
		this_script->public_gos.at("Map Ricing") = map_ricing;
		this_script->public_gos.at("P1-Blue Vote") = players_vote[0];
		this_script->public_gos.at("P2-Blue Vote") = players_vote[1];
		this_script->public_gos.at("P1-Red Vote") = players_vote[2];
		this_script->public_gos.at("P2-Red Vote") = players_vote[3];

		this_script->public_gos.at("R-Arrow") = right_arrow;
		this_script->public_gos.at("L-Arrow") = left_arrow;
		this_script->public_ints.at("Button Cooldown") = time;
		c_players_vote[0] = (ComponentUiButton*)players_vote[0]->GetComponent(C_UI_BUTTON);
		c_players_vote[1] = (ComponentUiButton*)players_vote[1]->GetComponent(C_UI_BUTTON);
		c_players_vote[2] = (ComponentUiButton*)players_vote[2]->GetComponent(C_UI_BUTTON);
		c_players_vote[3] = (ComponentUiButton*)players_vote[3]->GetComponent(C_UI_BUTTON);
		c_right_arrow = (ComponentUiButton*)right_arrow->GetComponent(C_UI_BUTTON);
		c_left_arrow = (ComponentUiButton*)left_arrow->GetComponent(C_UI_BUTTON);
	}

	void MapSelectUI_UpdatePublics(GameObject* game_object);

	void MapSelectUI_Start(GameObject* game_object)
	{
		// Play Move Selection
		ComponentAudioSource *a_comp = (ComponentAudioSource*)game_object->GetComponent(ComponentType::C_AUDIO_SOURCE);
		if (a_comp) a_comp->PlayAudio(0);

		arrow_counter_left = time;
		arrow_counter_right = time;
		current_map = 0;
		current_level = 0;
		player_order[0] = App->go_manager->team1_front;
		player_order[1] = App->go_manager->team1_back;
		player_order[2] = App->go_manager->team2_front;
		player_order[3] = App->go_manager->team2_back;
	}

	void MapSelectUI_Update(GameObject* game_object)
	{
		for (int playerID = 0; playerID < 4; playerID++)
		{
			int id = 0;
			for (int j = 0; j < 4; j++)
			{
				if (player_order[j] == playerID)
				{
					id = j;
				}
			}
			if (App->input->GetJoystickButton(playerID, JOY_BUTTON::A) == KEY_DOWN || App->input->GetKey(SDL_SCANCODE_A) == KEY_DOWN)
			{
				if (!players_ready[id])
				{
					c_players_vote[id]->OnPressId(current_level); // TO BE TESTED

					votes[id] = current_level;
					players_ready[id] = true;
				}

			}

			if (App->input->GetJoystickButton(playerID, JOY_BUTTON::B) == KEY_DOWN || App->input->GetKey(SDL_SCANCODE_B) == KEY_DOWN)
			{
				if (players_ready[id])
				{
					c_players_vote[id]->OnPressId(votes[id]); // TO BE TESTED

					players_ready[id] = false;
				}
			}

			if (App->input->GetJoystickButton(playerID, JOY_BUTTON::DPAD_LEFT) == KEY_DOWN || App->input->GetKey(SDL_SCANCODE_LEFT) == KEY_DOWN)
			{
				// Play Move Selection
				ComponentAudioSource *a_comp = (ComponentAudioSource*)game_object->GetComponent(ComponentType::C_AUDIO_SOURCE);
				if (a_comp) a_comp->PlayAudio(1);

				current_level--;
				if (current_level < 0)
					current_level = 2;

				switch (current_level)
				{
				case 0:
					map_fields->SetActive(true);
					map_umi->SetActive(false);
					map_ricing->SetActive(false);
					break;
				case 1:
					map_fields->SetActive(false);
					map_umi->SetActive(true);
					map_ricing->SetActive(false);
					break;
				case 2:
					map_fields->SetActive(false);
					map_umi->SetActive(false);
					map_ricing->SetActive(true);
					break;
				}

				if (arrow_counter_left >= time)
				{
					c_left_arrow->OnPress();
				}
				arrow_counter_left = 0;
			}

			if (App->input->GetJoystickButton(playerID, JOY_BUTTON::DPAD_RIGHT) == KEY_DOWN || App->input->GetKey(SDL_SCANCODE_RIGHT) == KEY_DOWN)
			{
				// Play Move Selection
				ComponentAudioSource *a_comp = (ComponentAudioSource*)game_object->GetComponent(ComponentType::C_AUDIO_SOURCE);
				if (a_comp) a_comp->PlayAudio(1);

				current_level++;
				if (current_level > 2)
					current_level = 0;
				switch (current_level)
				{
				case 0:
					map_fields->SetActive(true);
					map_umi->SetActive(false);
					map_ricing->SetActive(false);
					break;
				case 1:
					map_fields->SetActive(false);
					map_umi->SetActive(true);
					map_ricing->SetActive(false);
					break;
				case 2:
					map_fields->SetActive(false);
					map_umi->SetActive(false);
					map_ricing->SetActive(true);
					break;
				}

				if (arrow_counter_right >= time)
				{
					c_right_arrow->OnPress();
				}
				arrow_counter_right = 0;
			}
		}

		if (arrow_counter_left < time)
		{
			arrow_counter_left++;

			if (arrow_counter_left == time)
				c_left_arrow->OnPress();
		}

		if (arrow_counter_right < time)
		{
			arrow_counter_right++;

			if (arrow_counter_right == time)
				c_right_arrow->OnPress();
		}

		int total = 0;
		for (int j = 0; j < 4; j++)
		{
			if (players_ready[j])
				total++;

			if (total == 4)
			{
				unsigned int k = App->rnd->RandomInt(1, 4);

				switch (votes[k])
				{
				case 1:
					App->resource_manager->LoadSceneFromAssets(path_map1.data());
					break;
				case 2:
					App->resource_manager->LoadSceneFromAssets(path_map2.data());
					break;
				case 3:
					App->resource_manager->LoadSceneFromAssets(path_map3.data());
					break;
				default:
					// Error Reset, but loads map 1 instead (because we need to cover bugs lol lmao pls don't kill me)
					App->resource_manager->LoadSceneFromAssets(path_map1.data());
					break;

				}
			}
			else
				total = 0; // Redundancy
		}
	}

	void MapSelectUI_OnFocus()
	{

	}
}
<|endoftext|>


<commit_before>#include "stdafx.h"
#include "Unit.h"
#include "Scheduler.h"
#include "GameManager.h"
#include "Player.h"
#include "ClientSession.h"

Unit::Unit()
{
    static int makeId = 0;
    m_UnitID = ++makeId;

    m_Owner = nullptr;
    m_Hp = m_MaxHp = -1;
    m_Damage = 0;
    m_Speed = -1;
    m_Contacting = false;
    m_TargetPos = { -1, -1 };
    m_Body = nullptr;

    m_State = m_StandbyState = new StandbyState;
    m_MovingState = new MovingState;
    m_CrashedState = new CrashedState;
}

Unit::~Unit()
{
    delete m_StandbyState;
    delete m_MovingState;
    delete m_CrashedState;
}

void Unit::Moving()
{
    auto curPos = m_Body->GetPosition();
    auto distance = m_TargetPos - curPos;
    if (distance.Length() < 0.5f)
    {
        EndMove();
        printf(" - Reach: UnitID:  %d, \t\t\t x : %.f \t y : %.f\n", INIT_TYPE(m_UnitID),
            EXTEND(curPos.x), EXTEND(curPos.y));
    }
}

void Unit::Crashing(bool isCrashing)
{
    switch (GET_MAIN_TYPE(m_UnitID))
    {
    case UNIT_HERO:
        if (m_Hp <= 0) IamDead();
        break;
    case UNIT_MISSILE:
        isCrashing = false;
        Extinction();
        break;
    case UNIT_OBSTRUCT:
        break;

    };

    auto client = m_Owner->GetClient();
    if (client == nullptr)
    {
		EndCrash();
		printf(" - Crashing Failed ! : client is invalid \n");
        return;
    }

    auto curPos = m_Body->GetPosition();
    auto expectPos = curPos;

    if (isCrashing)
    {
        auto velocity = m_Body->GetLinearVelocity();
        velocity *= 1.0f / DAMPING;
        expectPos += velocity;
        printf(" - Crashing:    UnitID: %d,  \t   expectPos:   x : %.f \t y : %.f\n", INIT_TYPE(m_UnitID),
            EXTEND(expectPos.x), EXTEND(expectPos.y));
    }
    else
    {
        EndCrash();
    }

    client->CrashedBroadCast(m_UnitID, curPos, expectPos, isCrashing);
}

void Unit::TryMove(b2Vec2 currentPos, b2Vec2 targetPos)
{
    auto client = m_Owner->GetClient();
    if (client == nullptr)
    {
        printf(" - TryMove Failed ! : client is invalid \n");
        return;
    }

    auto displacement = targetPos - m_Body->GetPosition();
    if (displacement.Normalize() < 0.5f)
    {
        m_Body->SetLinearVelocity(b2Vec2(0, 0));
        return;
    }
    displacement *= m_Speed;
    m_Body->SetLinearVelocity(displacement);

    m_TargetPos = targetPos;
    m_State->TryMove(this);

    client->SendHeroInfo(m_UnitID, currentPos, m_TargetPos);
}

void Unit::Damaged(int damage)
{
    m_Hp -= damage;
    m_Owner->GetClient()->HpBroadCast(m_Owner->GetPlayerID(), m_UnitID, m_Hp);

    switch (GET_MAIN_TYPE(m_UnitID))
    {
    case UNIT_HERO:
        if (m_Hp <= 0)
        {
            CallFuncAfter(MANAGER_UPDATE_INTERVAL, GGameManager, &GameManager::GameOver, m_Owner);
        }
        break;
    case UNIT_OBSTRUCT:
        if (m_Hp <= 0)
        {

        }
        break;
    default:
        break;
    }
}

void Unit::IamDead()
{

}
<commit_msg>[S]공백 커밋<commit_after>#include "stdafx.h"
#include "Unit.h"
#include "Scheduler.h"
#include "GameManager.h"
#include "Player.h"
#include "ClientSession.h"

Unit::Unit()
{
    static int makeId = 0;
    m_UnitID = ++makeId;

    m_Owner = nullptr;
    m_Hp = m_MaxHp = -1;
    m_Damage = 0;
    m_Speed = -1;
    m_Contacting = false;
    m_TargetPos = { -1, -1 };
    m_Body = nullptr;

    m_State = m_StandbyState = new StandbyState;
    m_MovingState = new MovingState;
    m_CrashedState = new CrashedState;
}

Unit::~Unit()
{
    delete m_StandbyState;
    delete m_MovingState;
    delete m_CrashedState;
}

void Unit::Moving()
{
    auto curPos = m_Body->GetPosition();
    auto distance = m_TargetPos - curPos;
    if (distance.Length() < 0.5f)
    {
        EndMove();
        printf(" - Reach: UnitID:  %d, \t\t\t x : %.f \t y : %.f\n", INIT_TYPE(m_UnitID),
            EXTEND(curPos.x), EXTEND(curPos.y));
    }
}

void Unit::Crashing(bool isCrashing)
{
    switch (GET_MAIN_TYPE(m_UnitID))
    {
    case UNIT_HERO:
        if (m_Hp <= 0) IamDead();
        break;
    case UNIT_MISSILE:
        isCrashing = false;
        Extinction();
        break;
    case UNIT_OBSTRUCT:
        break;

    };

    auto client = m_Owner->GetClient();
    if (client == nullptr)
    {
		EndCrash();
		printf(" - Crashing Failed ! : client is invalid \n");
        return;
    }

    auto curPos = m_Body->GetPosition();
    auto expectPos = curPos;

    if (isCrashing)
    {
        auto velocity = m_Body->GetLinearVelocity();
        velocity *= 1.0f / DAMPING;
        expectPos += velocity;
        printf(" - Crashing:    UnitID: %d,  \t   expectPos:   x : %.f \t y : %.f\n", INIT_TYPE(m_UnitID),
            EXTEND(expectPos.x), EXTEND(expectPos.y));
    }
    else
    {
        EndCrash();
    }

    client->CrashedBroadCast(m_UnitID, curPos, expectPos, isCrashing);
}

void Unit::TryMove(b2Vec2 currentPos, b2Vec2 targetPos)
{
    auto client = m_Owner->GetClient();
    if (client == nullptr)
    {
        printf(" - TryMove Failed ! : client is invalid \n");
        return;
    }

    auto displacement = targetPos - m_Body->GetPosition();
    if (displacement.Normalize() < 0.5f)
    {
        m_Body->SetLinearVelocity(b2Vec2(0, 0));
        return;
    }
    displacement *= m_Speed;
    m_Body->SetLinearVelocity(displacement);

    m_TargetPos = targetPos;
    m_State->TryMove(this);

    client->SendHeroInfo(m_UnitID, currentPos, m_TargetPos);
}

void Unit::Damaged(int damage)
{
    m_Hp -= damage;
    m_Owner->GetClient()->HpBroadCast(m_Owner->GetPlayerID(), m_UnitID, m_Hp);

    switch (GET_MAIN_TYPE(m_UnitID))
    {
    case UNIT_HERO:
        if (m_Hp <= 0)
        {
            CallFuncAfter(MANAGER_UPDATE_INTERVAL, GGameManager, &GameManager::GameOver, m_Owner);
        }
        break;
    case UNIT_OBSTRUCT:
        if (m_Hp <= 0)
        {

        }
        break;
    default:
        break;
    }
}

void Unit::IamDead()
{

}
<|endoftext|>