<commit_before>//======================================================================
//-----------------------------------------------------------------------
/**
 * @file        unit_tests.cpp
 * @brief       iutest test
 *
 * @author      t.shirayanagi
 * @par         copyright
 * Copyright (C) 2013-2016, Takazumi Shirayanagi\n
 * The new BSD License is applied to this software.
 * see LICENSE
*/
//-----------------------------------------------------------------------
//======================================================================

//======================================================================
// include
#include "iutest.hpp"

class Base {};
class Derived : public Base {};
class Hoge {};
void Func(void) {}

typedef int inttype;

IUTEST(UnitTest, is_class)
{
    IUTEST_STATIC_ASSERT( !::iutest_type_traits::is_class<int>::value );
    IUTEST_STATIC_ASSERT(  ::iutest_type_traits::is_class<Base>::value );
    IUTEST_STATIC_ASSERT(  ::iutest_type_traits::is_class<Derived>::value );
    IUTEST_STATIC_ASSERT( !::iutest_type_traits::is_class<void (*)()>::value );
}

IUTEST(UnitTest, is_same)
{
    IUTEST_STATIC_ASSERT( !(::iutest_type_traits::is_same<int, char>::value) );
    IUTEST_STATIC_ASSERT(  (::iutest_type_traits::is_same<int, int>::value) );
    IUTEST_STATIC_ASSERT(  (::iutest_type_traits::is_same<int, inttype>::value) );
}

IUTEST(UnitTest, is_void)
{
    IUTEST_STATIC_ASSERT( !::iutest_type_traits::is_void<void*>::value );
    IUTEST_STATIC_ASSERT(  ::iutest_type_traits::is_void<void>::value );
    IUTEST_STATIC_ASSERT( !::iutest_type_traits::is_void<int>::value );
}

IUTEST(UnitTest, is_base_of)
{
    IUTEST_STATIC_ASSERT( !(::iutest_type_traits::is_base_of<int, Base>::value) );
    IUTEST_STATIC_ASSERT(  (::iutest_type_traits::is_base_of<Base, Derived>::value) );
    IUTEST_STATIC_ASSERT(  (::iutest_type_traits::is_base_of<Base, const Derived>::value) );
    IUTEST_STATIC_ASSERT(  (::iutest_type_traits::is_base_of<const volatile Base, Derived>::value) );
    IUTEST_STATIC_ASSERT(  (::iutest_type_traits::is_base_of<volatile Base, volatile Derived const>::value) );
    IUTEST_STATIC_ASSERT( !(::iutest_type_traits::is_base_of<Base, Hoge>::value) );
    IUTEST_STATIC_ASSERT(  (::iutest_type_traits::is_base_of<Derived, Derived>::value) );
}

#if !defined(IUTEST_NO_ARGUMENT_DEPENDENT_LOOKUP)

struct X
{
    int a,b,c;
};
struct Y
{
    int a,b,c;
    bool operator == (const Y&) { return true; }
};

struct Z
{
    int a,b,c;
};

bool operator == (const Z&, const Z&) { return true; }

IUTEST(UnitTest, has_equal_to)
{
    IUTEST_STATIC_ASSERT(  ::iutest_type_traits::has_equal_to<int>::value );
    IUTEST_STATIC_ASSERT(  ::iutest_type_traits::has_equal_to<float>::value );
    IUTEST_STATIC_ASSERT( !::iutest_type_traits::has_equal_to<X>::value );
    IUTEST_STATIC_ASSERT(  ::iutest_type_traits::has_equal_to<Y>::value );
    IUTEST_STATIC_ASSERT(  ::iutest_type_traits::has_equal_to<Z>::value );
    IUTEST_STATIC_ASSERT(  ::iutest_type_traits::has_equal_to< ::std::vector<int> >::value );
}

#if IUTEST_HAS_TUPLE
typedef ::iutest::tuples::tuple<bool, int, int> Tuple;

IUTEST(UnitTest, has_equal_to_tuple)
{
    IUTEST_STATIC_ASSERT(  ::iutest_type_traits::has_equal_to<Tuple>::value );
}
#endif

#endif

IUTEST(UnitTest, StringStrip)
{
    ::std::string str = "   a1 a2  ";
    IUTEST_EXPECT_STREQ("a1 a2  " , ::iutest::detail::StripLeadingSpace(str));
    IUTEST_EXPECT_STREQ("   a1 a2", ::iutest::detail::StripTrailingSpace(str));
    IUTEST_EXPECT_STREQ("a1 a2"   , ::iutest::detail::StripSpace(str));
}

IUTEST(UnitTest, StringReplace)
{
    ::std::string str = "a1a2a3a4b5";
    ::iutest::detail::StringReplace(str, 'a', "ii");
    IUTEST_EXPECT_STREQ("ii1ii2ii3ii4b5", str);
}

IUTEST(UnitTest, StringReplaceToLF)
{
    ::std::string str = "a\r\nb\r\rc\r\n\nd";
    ::iutest::detail::StringReplaceToLF(str);
    IUTEST_EXPECT_STREQ("a\nb\n\nc\n\nd", str);
}

IUTEST(UnitTest, AddDefaultPackageName)
{
    IUTEST_EXPECT_STREQ("Test.a1a2a3a4b5", ::iutest::TestEnv::AddDefaultPackageName("a1a2a3a4b5"));
    IUTEST_EXPECT_STREQ("Hoge.a1a2a3a4b5", ::iutest::TestEnv::AddDefaultPackageName("Hoge.a1a2a3a4b5"));
}

class HackXmlGeneratorListener : public ::iutest::DefaultXmlGeneratorListener
{
public:
    using DefaultXmlGeneratorListener::EscapeXmlAttribute;
    using DefaultXmlGeneratorListener::EscapeXmlText;
};

IUTEST(UnitTest, XmlEscape)
{
    IUTEST_EXPECT_STREQ("a<>	b& '"c
"
        , HackXmlGeneratorListener::EscapeXmlAttribute("a<> b& \'\"c\r\n"));
    IUTEST_EXPECT_STREQ("a<>  b& \'\"c\r\n"
        , HackXmlGeneratorListener::EscapeXmlText("a<>  b& \'\"c\r\n"));
}

IUTEST(UnitTest, FileLocqtion)
{
    ::iutest::IUTEST_FLAG(file_location_style_msvc) = false;
    IUTEST_EXPECT_STREQ("main.cpp:1"
        , ::iutest::detail::FormatFileLocation("main.cpp", 1) );
    IUTEST_EXPECT_STREQ("unknown file:1"
        , ::iutest::detail::FormatFileLocation(NULL, 1) );
    IUTEST_EXPECT_STREQ("main.cpp"
        , ::iutest::detail::FormatFileLocation("main.cpp", -1) );

    ::iutest::IUTEST_FLAG(file_location_style_msvc) = true;
    IUTEST_EXPECT_STREQ("main.cpp(1)"
        , ::iutest::detail::FormatFileLocation("main.cpp", 1) );
    IUTEST_EXPECT_STREQ("unknown file(1)"
        , ::iutest::detail::FormatFileLocation(NULL, 1) );
    IUTEST_EXPECT_STREQ("main.cpp"
        , ::iutest::detail::FormatFileLocation("main.cpp", -1) );
}

IUTEST(UnitTest, GetEnvironmentVariable)
{
    char buf[2];
    IUTEST_EXPECT_FALSE( ::iutest::detail::GetEnvironmentVariable("PATH", buf, sizeof(buf)) );
    IUTEST_EXPECT_FALSE( ::iutest::detail::GetEnvironmentVariable("PATH", NULL, 0) );
}

#ifdef UNICODE
int wmain(int argc, wchar_t* argv[])
#else
int main(int argc, char* argv[])
#endif
{
    IUTEST_INIT(&argc, argv);
    ::iutest::IUTEST_FLAG(default_package_name) = "Test";
    return IUTEST_RUN_ALL_TESTS();
}

<commit_msg>fix test update r1172<commit_after>//======================================================================
//-----------------------------------------------------------------------
/**
 * @file        unit_tests.cpp
 * @brief       iutest test
 *
 * @author      t.shirayanagi
 * @par         copyright
 * Copyright (C) 2013-2016, Takazumi Shirayanagi\n
 * The new BSD License is applied to this software.
 * see LICENSE
*/
//-----------------------------------------------------------------------
//======================================================================

//======================================================================
// include
#include "iutest.hpp"

class Base {};
class Derived : public Base {};
class Hoge {};
void Func(void) {}

typedef int inttype;

IUTEST(UnitTest, is_class)
{
    IUTEST_STATIC_ASSERT( !::iutest_type_traits::is_class<int>::value );
    IUTEST_STATIC_ASSERT(  ::iutest_type_traits::is_class<Base>::value );
    IUTEST_STATIC_ASSERT(  ::iutest_type_traits::is_class<Derived>::value );
    IUTEST_STATIC_ASSERT( !::iutest_type_traits::is_class<void (*)()>::value );
}

IUTEST(UnitTest, is_same)
{
    IUTEST_STATIC_ASSERT( !(::iutest_type_traits::is_same<int, char>::value) );
    IUTEST_STATIC_ASSERT(  (::iutest_type_traits::is_same<int, int>::value) );
    IUTEST_STATIC_ASSERT(  (::iutest_type_traits::is_same<int, inttype>::value) );
}

IUTEST(UnitTest, is_void)
{
    IUTEST_STATIC_ASSERT( !::iutest_type_traits::is_void<void*>::value );
    IUTEST_STATIC_ASSERT(  ::iutest_type_traits::is_void<void>::value );
    IUTEST_STATIC_ASSERT( !::iutest_type_traits::is_void<int>::value );
}

IUTEST(UnitTest, is_base_of)
{
    IUTEST_STATIC_ASSERT( !(::iutest_type_traits::is_base_of<int, Base>::value) );
    IUTEST_STATIC_ASSERT(  (::iutest_type_traits::is_base_of<Base, Derived>::value) );
    IUTEST_STATIC_ASSERT(  (::iutest_type_traits::is_base_of<Base, const Derived>::value) );
    IUTEST_STATIC_ASSERT(  (::iutest_type_traits::is_base_of<const volatile Base, Derived>::value) );
    IUTEST_STATIC_ASSERT(  (::iutest_type_traits::is_base_of<volatile Base, volatile Derived const>::value) );
    IUTEST_STATIC_ASSERT( !(::iutest_type_traits::is_base_of<Base, Hoge>::value) );
    IUTEST_STATIC_ASSERT(  (::iutest_type_traits::is_base_of<Derived, Derived>::value) );
}

#if !defined(IUTEST_NO_ARGUMENT_DEPENDENT_LOOKUP)

struct X
{
    int a,b,c;
};
struct Y
{
    int a,b,c;
    bool operator == (const Y&) { return true; }
};

struct Z
{
    int a,b,c;
};

bool operator == (const Z&, const Z&) { return true; }

IUTEST(UnitTest, has_equal_to)
{
    IUTEST_STATIC_ASSERT(  ::iutest_type_traits::has_equal_to<int>::value );
    IUTEST_STATIC_ASSERT(  ::iutest_type_traits::has_equal_to<float>::value );
    IUTEST_STATIC_ASSERT( !::iutest_type_traits::has_equal_to<X>::value );
    IUTEST_STATIC_ASSERT(  ::iutest_type_traits::has_equal_to<Y>::value );
    IUTEST_STATIC_ASSERT(  ::iutest_type_traits::has_equal_to<Z>::value );
    IUTEST_STATIC_ASSERT(  ::iutest_type_traits::has_equal_to< ::std::vector<int> >::value );
}

#if IUTEST_HAS_TUPLE
typedef ::iutest::tuples::tuple<bool, int, int> Tuple;

IUTEST(UnitTest, has_equal_to_tuple)
{
    IUTEST_STATIC_ASSERT(  ::iutest_type_traits::has_equal_to<Tuple>::value );
}
#endif

#endif

IUTEST(UnitTest, StringStrip)
{
    ::std::string str = "   a1 a2  ";
    IUTEST_EXPECT_STREQ("a1 a2  " , ::iutest::detail::StripLeadingSpace(str));
    IUTEST_EXPECT_STREQ("   a1 a2", ::iutest::detail::StripTrailingSpace(str));
    IUTEST_EXPECT_STREQ("a1 a2"   , ::iutest::detail::StripSpace(str));
}

IUTEST(UnitTest, StringReplace)
{
    ::std::string str = "a1a2a3a4b5";
    ::iutest::detail::StringReplace(str, 'a', "ii");
    IUTEST_EXPECT_STREQ("ii1ii2ii3ii4b5", str);
}

IUTEST(UnitTest, StringReplaceToLF)
{
    ::std::string str = "a\r\nb\r\rc\r\n\nd";
    ::iutest::detail::StringReplaceToLF(str);
    IUTEST_EXPECT_STREQ("a\nb\n\nc\n\nd", str);
}

IUTEST(UnitTest, AddDefaultPackageName)
{
    IUTEST_EXPECT_STREQ("Test.a1a2a3a4b5", ::iutest::TestEnv::AddDefaultPackageName("a1a2a3a4b5"));
    IUTEST_EXPECT_STREQ("Hoge.a1a2a3a4b5", ::iutest::TestEnv::AddDefaultPackageName("Hoge.a1a2a3a4b5"));
}

class HackXmlGeneratorListener : public ::iutest::DefaultXmlGeneratorListener
{
public:
    using DefaultXmlGeneratorListener::EscapeXmlAttribute;
    using DefaultXmlGeneratorListener::EscapeXmlText;
};

IUTEST(UnitTest, XmlEscape)
{
    IUTEST_EXPECT_STREQ("a<>	b& '"c
"
        , HackXmlGeneratorListener::EscapeXmlAttribute("a<>	b& \'\"c\r\n"));
    IUTEST_EXPECT_STREQ("a<>	b& \'\"c\r\n"
        , HackXmlGeneratorListener::EscapeXmlText("a<>	b& \'\"c\r\n"));
}

IUTEST(UnitTest, FileLocqtion)
{
    ::iutest::IUTEST_FLAG(file_location_style_msvc) = false;
    IUTEST_EXPECT_STREQ("main.cpp:1"
        , ::iutest::detail::FormatFileLocation("main.cpp", 1) );
    IUTEST_EXPECT_STREQ("unknown file:1"
        , ::iutest::detail::FormatFileLocation(NULL, 1) );
    IUTEST_EXPECT_STREQ("main.cpp"
        , ::iutest::detail::FormatFileLocation("main.cpp", -1) );

    ::iutest::IUTEST_FLAG(file_location_style_msvc) = true;
    IUTEST_EXPECT_STREQ("main.cpp(1)"
        , ::iutest::detail::FormatFileLocation("main.cpp", 1) );
    IUTEST_EXPECT_STREQ("unknown file(1)"
        , ::iutest::detail::FormatFileLocation(NULL, 1) );
    IUTEST_EXPECT_STREQ("main.cpp"
        , ::iutest::detail::FormatFileLocation("main.cpp", -1) );
}

IUTEST(UnitTest, GetEnvironmentVariable)
{
    char buf[2];
    IUTEST_EXPECT_FALSE( ::iutest::detail::GetEnvironmentVariable("PATH", buf, sizeof(buf)) );
    IUTEST_EXPECT_FALSE( ::iutest::detail::GetEnvironmentVariable("PATH", NULL, 0) );
}

#ifdef UNICODE
int wmain(int argc, wchar_t* argv[])
#else
int main(int argc, char* argv[])
#endif
{
    IUTEST_INIT(&argc, argv);
    ::iutest::IUTEST_FLAG(default_package_name) = "Test";
    return IUTEST_RUN_ALL_TESTS();
}

<|endoftext|>


<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2015 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

#include "runner.hpp"
#include "config.hpp"

#include <mapnik/datasource_cache.hpp>
#include <mapnik/font_engine_freetype.hpp>

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

#include "cleanup.hpp" // run_cleanup()

int main(int argc, char** argv)
{
    using namespace visual_tests;
    namespace po = boost::program_options;

    po::options_description desc("visual test runner");
    desc.add_options()
        ("help,h", "produce usage message")
        ("verbose,v", "verbose output")
        ("overwrite,o", "overwrite reference image")
        ("jobs,j", po::value<std::size_t>()->default_value(1), "number of parallel threads")
        ("styles-dir", po::value<std::string>()->default_value("test/data-visual/styles"), "directory with styles")
        ("images-dir", po::value<std::string>()->default_value("test/data-visual/images"), "directory with reference images")
        ("output-dir", po::value<std::string>()->default_value("/tmp/mapnik-visual-images"), "directory for output files")
        ("unique-subdir,u", "write output files to subdirectory with unique name")
        ("styles", po::value<std::vector<std::string>>(), "selected styles to test")
        ("fonts", po::value<std::string>()->default_value("fonts"), "font search path")
        ("plugins", po::value<std::string>()->default_value("plugins/input"), "input plugins search path")
        ;

    po::positional_options_description p;
    p.add("styles", -1);
    po::variables_map vm;
    po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm);
    po::notify(vm);

    if (vm.count("help"))
    {
        std::clog << desc << std::endl;
        return 1;
    }

    mapnik::freetype_engine::register_fonts(vm["fonts"].as<std::string>(), true);
    mapnik::datasource_cache::instance().register_datasources(vm["plugins"].as<std::string>());

    boost::filesystem::path output_dir(vm["output-dir"].as<std::string>());

    if (vm.count("unique-subdir"))
    {
        output_dir /= boost::filesystem::unique_path();
    }

    runner run(vm["styles-dir"].as<std::string>(),
               output_dir,
               vm["images-dir"].as<std::string>(),
               vm.count("overwrite"),
               vm["jobs"].as<std::size_t>());
    report_type report = vm.count("verbose") ? report_type((console_report())) : report_type((console_short_report()));
    result_list results;

    try
    {
        if (vm.count("styles"))
        {
            results = run.test(vm["styles"].as<std::vector<std::string>>(), report);
        }
        else
        {
            results = run.test_all(report);
        }
    }
    catch (std::exception & e)
    {
        std::cerr << "Error runnig tests: " << e.what() << std::endl;
        return 1;
    }

    unsigned failed_count = mapnik::util::apply_visitor(summary_visitor(results), report);

    if (failed_count)
    {
        html_summary(results, output_dir);
    }

    testing::run_cleanup();

    return failed_count;
}
<commit_msg>visual tests: add command line argument for controlling log level<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2015 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

#include "runner.hpp"
#include "config.hpp"

#include <mapnik/datasource_cache.hpp>
#include <mapnik/font_engine_freetype.hpp>

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

#include "cleanup.hpp" // run_cleanup()

#ifdef MAPNIK_LOG
using log_levels_map = std::map<std::string, mapnik::logger::severity_type>;

log_levels_map log_levels
{
    { "debug", mapnik::logger::severity_type::debug },
    { "warn",  mapnik::logger::severity_type::warn },
    { "error", mapnik::logger::severity_type::error },
    { "none",  mapnik::logger::severity_type::none }
};
#endif

int main(int argc, char** argv)
{
    using namespace visual_tests;
    namespace po = boost::program_options;

    po::options_description desc("visual test runner");
    desc.add_options()
        ("help,h", "produce usage message")
        ("verbose,v", "verbose output")
        ("overwrite,o", "overwrite reference image")
        ("jobs,j", po::value<std::size_t>()->default_value(1), "number of parallel threads")
        ("styles-dir", po::value<std::string>()->default_value("test/data-visual/styles"), "directory with styles")
        ("images-dir", po::value<std::string>()->default_value("test/data-visual/images"), "directory with reference images")
        ("output-dir", po::value<std::string>()->default_value("/tmp/mapnik-visual-images"), "directory for output files")
        ("unique-subdir,u", "write output files to subdirectory with unique name")
        ("styles", po::value<std::vector<std::string>>(), "selected styles to test")
        ("fonts", po::value<std::string>()->default_value("fonts"), "font search path")
        ("plugins", po::value<std::string>()->default_value("plugins/input"), "input plugins search path")
#ifdef MAPNIK_LOG
        ("log", po::value<std::string>()->default_value(std::find_if(log_levels.begin(), log_levels.end(),
             [](log_levels_map::value_type const & level) { return level.second == mapnik::logger::get_severity(); } )->first),
             "log level (debug, warn, error, none)")
#endif
        ;

    po::positional_options_description p;
    p.add("styles", -1);
    po::variables_map vm;
    po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm);
    po::notify(vm);

    if (vm.count("help"))
    {
        std::clog << desc << std::endl;
        return 1;
    }

#ifdef MAPNIK_LOG
    std::string log_level(vm["log"].as<std::string>());
    log_levels_map::const_iterator level_iter = log_levels.find(log_level);
    if (level_iter == log_levels.end())
    {
        std::cerr << "Error: Unknown log level: " << log_level << std::endl;
        return 1;
    }
    else
    {
        mapnik::logger::set_severity(level_iter->second);
    }
#endif

    mapnik::freetype_engine::register_fonts(vm["fonts"].as<std::string>(), true);
    mapnik::datasource_cache::instance().register_datasources(vm["plugins"].as<std::string>());

    boost::filesystem::path output_dir(vm["output-dir"].as<std::string>());

    if (vm.count("unique-subdir"))
    {
        output_dir /= boost::filesystem::unique_path();
    }

    runner run(vm["styles-dir"].as<std::string>(),
               output_dir,
               vm["images-dir"].as<std::string>(),
               vm.count("overwrite"),
               vm["jobs"].as<std::size_t>());
    report_type report = vm.count("verbose") ? report_type((console_report())) : report_type((console_short_report()));
    result_list results;

    try
    {
        if (vm.count("styles"))
        {
            results = run.test(vm["styles"].as<std::vector<std::string>>(), report);
        }
        else
        {
            results = run.test_all(report);
        }
    }
    catch (std::exception & e)
    {
        std::cerr << "Error runnig tests: " << e.what() << std::endl;
        return 1;
    }

    unsigned failed_count = mapnik::util::apply_visitor(summary_visitor(results), report);

    if (failed_count)
    {
        html_summary(results, output_dir);
    }

    testing::run_cleanup();

    return failed_count;
}
<|endoftext|>


<commit_before>//
// global.hpp
//
// Copyright (c) 2013 MacGeneration. 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.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS "AS IS" AND ANY EXPRESS 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 COPYRIGHT HOLDER OR
// 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.
//

#ifndef __MMGGLOBAL_H_
#define __MMGGLOBAL_H_

/* DEBUG FLAG */
//#define MMG_DEBUG
#undef MMG_DEBUG

#ifdef MMG_DEBUG
#define MMG_DLOG(...) fprintf(stdout, __VA_ARGS__)
#else
#define MMG_DLOG(...) ((void)0)
#define NDEBUG
#endif /* MMG_DEBUG */

/* Error log macro */
#define MMG_ERRLOG(...) fprintf(stderr, __VA_ARGS__)

/* APNS */
#define MMG_APNS_SERVER "gateway.push.apple.com"
#define MMG_APNS_SERVER_SANDBOX "gateway.sandbox.push.apple.com"
#define MMG_APNS_PORT 2195
/* APNS - FEEDBACK */
#define MMG_APNS_FEEDBACK_SERVER "feedback.push.apple.com"
#define MMG_APNS_FEEDBACK_SERVER_SANDBOX "feedback.sandbox.push.apple.com"
#define MMG_APNS_FEEDBACK_PORT 2196
/* Certificates paths */
#define MMG_APNS_CA_PATH "/path/to/certs/dir/"
#define MMG_APNS_CERT_PATH "/path/to/certs/dir/cert.pem"
#define MMG_APNS_PRIVATEKEY_PATH "/path/to/certs/dir/key.pem"

#endif /* __MMGGLOBAL_H_ */
<commit_msg>Typo in constant<commit_after>//
// global.hpp
//
// Copyright (c) 2013 MacGeneration. 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.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS "AS IS" AND ANY EXPRESS 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 COPYRIGHT HOLDER OR
// 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.
//

#ifndef __MMGGLOBAL_H__
#define __MMGGLOBAL_H__

/* DEBUG FLAG */
//#define MMG_DEBUG
#undef MMG_DEBUG

#ifdef MMG_DEBUG
#define MMG_DLOG(...) fprintf(stdout, __VA_ARGS__)
#else
#define MMG_DLOG(...) ((void)0)
#define NDEBUG
#endif /* MMG_DEBUG */

/* Error log macro */
#define MMG_ERRLOG(...) fprintf(stderr, __VA_ARGS__)

/* APNS */
#define MMG_APNS_SERVER "gateway.push.apple.com"
#define MMG_APNS_SERVER_SANDBOX "gateway.sandbox.push.apple.com"
#define MMG_APNS_PORT 2195
/* APNS - FEEDBACK */
#define MMG_APNS_FEEDBACK_SERVER "feedback.push.apple.com"
#define MMG_APNS_FEEDBACK_SERVER_SANDBOX "feedback.sandbox.push.apple.com"
#define MMG_APNS_FEEDBACK_PORT 2196
/* Certificates paths */
#define MMG_APNS_CA_PATH "/path/to/certs/dir/"
#define MMG_APNS_CERT_PATH "/path/to/certs/dir/cert.pem"
#define MMG_APNS_PRIVATEKEY_PATH "/path/to/certs/dir/key.pem"

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


<commit_before>#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <cstring>
#include <fcntl.h>

using namespace std;
/* Broken - Fix later to help clean up code
void tokenize(char* arr[], char* token, string delims){
    unsigned cnt = 0;
    while(token != NULL){
	cout << "arr[" << cnt << "]: " << arr[cnt] << endl;
	arr[cnt] = token;
	token = strtok(NULL, delims);
	cnt++;
    }
    strcat(arr[cnt - 1], "\0");
    arr[cnt] = token;
    return;
}*/

void redirect(char* argv[], int num, bool hasOp){//consider making a bool to check if any operators are found
    int x = 0;
    int y = 0;
    int last = -1;//char loc. of last symbol
    int flags = -1; //Holds val corresponding to type of sym

    while(x != num){//for each string
        y = 0;//Resets y to beginning of a string
	while(argv[x][y] != '\0'){// char in argv[]
	    if(argv[x][y] == '>'){//is Output
		if(argv[x][y+1] == '>'){//Append
		    //cout << "Append found!" << endl;
		    flags = 1;
		    hasOp = true;
		}else{
		    //cout << "Output found!" << endl;
		    last = x;
		    flags = 0;
		    hasOp = true;
		}
	    }else if(argv[x][y] == '<'){//is Input
		//cout << "Input found!" << endl;
		flags = 2;
		hasOp = true;
	    }else if(argv[x][y] == '|'){//is Pipe
		//cout << "Pipe found!" << endl;
		flags = 3;
		hasOp = true;
	    }
	    y++;//iterate through chars
	}//End of a string
	x++;//iterate through strings
    }
    //cout << "Flags before check: " << flags << endl;
    if(flags == 0){//Output
	if(last == (x - 1)){//Ends with >
	    cout << "error: expected argument for '>'" << endl;
	    //FIXME - Ensure exit goes back to prompt properly
	    exit(0);
	}else if(last == 0){//Symbol is first cmd
	    //FIXME - need to fdo open then cout will overwrite output file
	    cout << "";//Clears the output file
	}else{
	    //New char* [] goes here - FIXME FIXME FIXME
	    cerr << "argv[x-1]: " << argv[x-1] << endl;
	    cerr << "argv[x-2]: " << argv[x-2] << endl;
	    int fdo = open(argv[x - 1], O_WRONLY);
	    if(fdo == -1){
		perror("open output");
		exit(0);
		//Go back to prompt
	        //ensure execvp is NOT run on this
	    }
	    close(1);//close stdout
	    dup(fdo); //fdo is now in slot 1(stdout)
	    strcpy(argv[x-1], "\0");
	    strcpy(argv[x-2], "\0");
	}
    }
    if(flags != -1){//Recursive call
	redirect(argv, last, hasOp);
    }
    //cerr << "argv[x]: " << argv[x] << endl;
    return;

}

int main(int argc, char* argv[]){
    string usrInput; //Holds user input
    while(1){
	unsigned cnt = 0; //counter for slots in argv[]
        cout << "$ "; //Prints prompt
	getline(cin, usrInput);
	char* inputCpy = new char[usrInput.length() + 1]; //pointer for input str
	strcpy(inputCpy, usrInput.c_str()); //inputCpy holds c-str copy of input
	char* token = strtok(inputCpy, ";"); //removes semicolons
	char* a[usrInput.length() + 1]; //Creates array for cmds + args
	while(token != NULL){ //Tokenizes semicolons
	    a[cnt] = token;
	    token = strtok(NULL, ";");
	    cnt++;
	}
	strcat(a[cnt - 1], "\0");
	a[cnt] = token; //Null terminates a[]

	//Fork for each command (separated by semicolons)
	int curr = 0;
	for(int i = 0; i < cnt; i++){//Tokenizes a[] removing " "
	    token = strtok(a[i], " "); //Resets token
	    curr = 0;
	    while(token != NULL){ //Remove spaces
	        argv[curr] = token; //argv[] = a[] (without spaces)
		if(strcmp(argv[curr], "exit") == 0){//Exit check
		    cout << "Exiting..." << endl;
		    delete inputCpy;
		    exit(0);
		}

		strcat(argv[curr], "\0"); //Null terms
		token = strtok(NULL, " ");
		curr++;
	    }
	    argv[curr] = token; //Null terms array
	    int pid2 = fork(); //Forks before redirect()
	    if(pid2 == -1){
		perror("pid2 failed");
		exit(1);
	    }else if(pid2 == 0){//Child process
	        int num = 0;
		cerr << "-----------" << endl;
	    	while(argv[num] != NULL){//counts length of ars in argv
		    cerr << "argv[" << num << "]: " << argv[num] << endl;
		    num++;
	        }
		cerr << "-----------" << endl;
		bool hasOp = false;
	        redirect(argv, num, hasOp); //Calls check for i/o redirection

		//FIXME - do these next lines even get called?
		cerr << "-----------" << endl;
	    	while(argv[num] != NULL){//counts length of ars in argv
		    cerr << "argv[" << num << "]: " << argv[num] << endl;
		    num++;
	        }
		cerr << "-----------" << endl;

		/*if(hasOp == true){//Confirm that real cmds don't get called twice
		    //This should avoid children from running execvp multiple times
		    exit(0);
		}*/
		//Create new arr[] here?

	        int pid3 = fork();
	        if(pid3 == -1){
		    perror("pid fork  failed");
		    exit(1);
	        }
	  	if(pid3 == 0){ //Child process
	 	    if(execvp(argv[0], argv) == -1){//Runs on each argv[]
		    	perror("execvp() failed");
		        exit(1);
		    }
	    	}
	   	 //Parent function
	   	 if(-1 == wait(0)){ //waits on children - execs in order
		    perror("wait() failed");
		    exit(1);
	        }
	    //end pid2 process
	    }else{//pid2 parent
		if(-1 == wait(0)){
		    perror("wait() failed");
		    exit(1);
		}
	    }
	}
        delete inputCpy; //Deallocates memory - Fixme, might go elsewhere
    }//End while loop

    return 0;
}
<commit_msg>Output handling now fully works, now for the next one<commit_after>#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <cstring>
#include <fcntl.h>

using namespace std;
/* Broken - Fix later to help clean up code
void tokenize(char* arr[], char* token, string delims){
    unsigned cnt = 0;
    while(token != NULL){
	cout << "arr[" << cnt << "]: " << arr[cnt] << endl;
	arr[cnt] = token;
	token = strtok(NULL, delims);
	cnt++;
    }
    strcat(arr[cnt - 1], "\0");
    arr[cnt] = token;
    return;
}*/

void redirect(char* argv[], int num, bool hasOp){//consider making a bool to check if any operators are found
    int x = 0;
    int y = 0;
    int last = -1;//char loc. of last symbol
    int flags = -1; //Holds val corresponding to type of sym

    while(x != num){//for each string
        y = 0;//Resets y to beginning of a string
	while(argv[x][y] != '\0'){// char in argv[]
	    if(argv[x][y] == '>'){//is Output
		if(argv[x][y+1] == '>'){//Append
		    //cout << "Append found!" << endl;
		    flags = 1;
		    hasOp = true;
		}else{
		    //cout << "Output found!" << endl;
		    last = x;
		    flags = 0;
		    hasOp = true;
		}
	    }else if(argv[x][y] == '<'){//is Input
		//cout << "Input found!" << endl;
		flags = 2;
		hasOp = true;
	    }else if(argv[x][y] == '|'){//is Pipe
		//cout << "Pipe found!" << endl;
		flags = 3;
		hasOp = true;
	    }
	    y++;//iterate through chars
	}//End of a string
	x++;//iterate through strings
    }
    //cout << "Flags before check: " << flags << endl;
    if(flags == 0){//Output
	if(last == (x - 1)){//Ends with >
	    cout << "error: expected argument for '>'" << endl;
	    //FIXME - Ensure exit goes back to prompt properly
	    exit(0);
	}else if(last == 0){//Symbol is first cmd
	    //FIXME - need to fdo open then cout will overwrite output file
	    cout << "";//Clears the output file
	}else{
	    //New char* [] goes here - FIXME FIXME FIXME
	    cerr << "argv[x-1]: " << argv[x-1] << endl;
	    cerr << "argv[x-2]: " << argv[x-2] << endl;
	    int fdo = open(argv[x - 1], O_WRONLY);
	    if(fdo == -1){
		perror("open output");
		exit(0);
		//Go back to prompt
	        //ensure execvp is NOT run on this
	    }
	    close(1);//close stdout
	    dup(fdo); //fdo is now in slot 1(stdout)
	    strcpy(argv[x-1], "\0");
	    strcpy(argv[x-2], "\0");
	}
    }
    if(flags != -1){//Recursive call
	redirect(argv, last, hasOp);
    }
    //cerr << "argv[x]: " << argv[x] << endl;
    return;

}

int main(int argc, char* argv[]){
    string usrInput; //Holds user input
    while(1){
	unsigned cnt = 0; //counter for slots in argv[]
        cout << "$ "; //Prints prompt
	getline(cin, usrInput);
	char* inputCpy = new char[usrInput.length() + 1]; //pointer for input str
	strcpy(inputCpy, usrInput.c_str()); //inputCpy holds c-str copy of input
	char* token = strtok(inputCpy, ";"); //removes semicolons
	char* a[usrInput.length() + 1]; //Creates array for cmds + args
	while(token != NULL){ //Tokenizes semicolons
	    a[cnt] = token;
	    token = strtok(NULL, ";");
	    cnt++;
	}
	strcat(a[cnt - 1], "\0");
	a[cnt] = token; //Null terminates a[]

	//Fork for each command (separated by semicolons)
	int curr = 0;
	for(int i = 0; i < cnt; i++){//Tokenizes a[] removing " "
	    token = strtok(a[i], " "); //Resets token
	    curr = 0;
	    while(token != NULL){ //Remove spaces
	        argv[curr] = token; //argv[] = a[] (without spaces)
		if(strcmp(argv[curr], "exit") == 0){//Exit check
		    cout << "Exiting..." << endl;
		    delete inputCpy;
		    exit(0);
		}

		strcat(argv[curr], "\0"); //Null terms
		token = strtok(NULL, " ");
		curr++;
	    }
	    argv[curr] = token; //Null terms array
	    int pid2 = fork(); //Forks before redirect()
	    if(pid2 == -1){
		perror("pid2 failed");
		exit(1);
	    }else if(pid2 == 0){//Child process
	        int num = 0;
		cerr << "-----------" << endl;
	    	while(argv[num] != NULL){//counts length of ars in argv
		    cerr << "argv[" << num << "]: " << argv[num] << endl;
		    num++;
	        }
		cerr << "-----------" << endl;
		bool hasOp = false;
	        redirect(argv, num, hasOp); //Calls check for i/o redirection

		/*if(hasOp == true){//Confirm that real cmds don't get called twice
		    //This should avoid children from running execvp multiple times
		    exit(0);
		}*/

	        int pid3 = fork();
	        if(pid3 == -1){
		    perror("pid fork  failed");
		    exit(1);
	        }
	  	if(pid3 == 0){ //Child process
	 	    if(execvp(argv[0], argv) == -1){//Runs on each argv[]
		    	perror("execvp() failed");
		        exit(1);
		    }
	    	}
	   	 //Parent function
	   	 if(-1 == wait(0)){ //waits on children - execs in order
		    perror("wait() failed");
		    exit(1);
	        }
		exit(0);
	    //end pid2 process
	    }else{//pid2 parent
		if(-1 == wait(0)){
		    perror("wait() failed");
		    exit(1);
		}
	    }
	}
        delete inputCpy; //Deallocates memory - Fixme, might go elsewhere
    }//End while loop

    return 0;
}
<|endoftext|>


<commit_before>// ---------------------------------------------------------------------
// $Id$
//
// Copyright (C) 1998 - 2013 by the deal.II authors
//
// This file is part of the deal.II library.
//
// The deal.II library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE at
// the top level of the deal.II distribution.
//
// ---------------------------------------------------------------------

#include "../tests.h"
#include <deal.II/base/timer.h>
#include <deal.II/base/logstream.h>
#include <fstream>
#include <cmath>
#include <iomanip>

// compute the ratio of two measurements and compare to
// the expected value.

void compare (double t1, double t2, double ratio)
{
  double r = t2/t1;
  double d = std::fabs(r-ratio) / ratio;

  // relative error < 15%?
  if (d <= .15)
    {
      deallog << "OK" << std::endl;
    }
  else
    {
      deallog << "Ratio " << r << " should be " << ratio << std::endl;
    }
}

// burn computer time

double s = 0.;
void burn (unsigned int n)
{
  for (unsigned int i=0 ; i<n ; ++i)
    {
      for (unsigned int j=1 ; j<100000 ; ++j)
        {
          s += 1./j * i;
        }
    }
}

int main ()
{
  std::ofstream logfile("output");
  deallog.attach(logfile);
  deallog.depth_console(0);
  deallog.threshold_double(1.e-10);

  Timer t1,t2;
  burn (50);
  double s01 = t1.stop();
  double s02 = t2();
  burn (50);
  double s11 = t1.stop();
  double s12 = t2();
  t1.start();
  burn (50);
  double s21 = t1();
  double s22 = t2();
  burn (50);
  double s31 = t1();
  double s32 = t2();

  compare (s01,s02,1.);
  compare (s11,s12,2.);
  compare (s21,s22,3./2.);
  compare (s31,s32,4./3.);
}

<commit_msg>Testsuite: Be a bit more relaxed in base/timer<commit_after>// ---------------------------------------------------------------------
// $Id$
//
// Copyright (C) 1998 - 2013 by the deal.II authors
//
// This file is part of the deal.II library.
//
// The deal.II library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE at
// the top level of the deal.II distribution.
//
// ---------------------------------------------------------------------

#include "../tests.h"
#include <deal.II/base/timer.h>
#include <deal.II/base/logstream.h>
#include <fstream>
#include <cmath>
#include <iomanip>

// compute the ratio of two measurements and compare to
// the expected value.

void compare (double t1, double t2, double ratio)
{
  double r = t2/t1;
  double d = std::fabs(r-ratio) / ratio;

  // relative error < 25%?
  if (d <= .25)
    {
      deallog << "OK" << std::endl;
    }
  else
    {
      deallog << "Ratio " << r << " should be " << ratio << std::endl;
    }
}

// burn computer time

double s = 0.;
void burn (unsigned int n)
{
  for (unsigned int i=0 ; i<n ; ++i)
    {
      for (unsigned int j=1 ; j<100000 ; ++j)
        {
          s += 1./j * i;
        }
    }
}

int main ()
{
  std::ofstream logfile("output");
  deallog.attach(logfile);
  deallog.depth_console(0);
  deallog.threshold_double(1.e-10);

  Timer t1,t2;
  burn (50);
  double s01 = t1.stop();
  double s02 = t2();
  burn (50);
  double s11 = t1.stop();
  double s12 = t2();
  t1.start();
  burn (50);
  double s21 = t1();
  double s22 = t2();
  burn (50);
  double s31 = t1();
  double s32 = t2();

  compare (s01,s02,1.);
  compare (s11,s12,2.);
  compare (s21,s22,3./2.);
  compare (s31,s32,4./3.);
}

<|endoftext|>


<commit_before>/*

Copyright (c) 2003, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * 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.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS 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 COPYRIGHT OWNER OR 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.

*/

#include "libtorrent/pch.hpp"

#include <boost/scoped_ptr.hpp>
#ifdef _WIN32
// windows part
#include "libtorrent/utf8.hpp"

#include <io.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>

#ifndef _MODE_T_
typedef int mode_t;
#endif

#ifdef UNICODE
#include "libtorrent/storage.hpp"
#endif

#else
// unix part
#define _FILE_OFFSET_BITS 64
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>

#include <boost/static_assert.hpp>
// make sure the _FILE_OFFSET_BITS define worked
// on this platform
BOOST_STATIC_ASSERT(sizeof(lseek(0, 0, 0)) >= 8);

#endif

#include <boost/filesystem/operations.hpp>
#include "libtorrent/file.hpp"
#include <sstream>
#include <cstring>
#include <vector>

#ifndef O_BINARY
#define O_BINARY 0
#endif

#ifndef O_RANDOM
#define O_RANDOM 0
#endif

#ifdef UNICODE
#include "libtorrent/storage.hpp"
#endif

#include "libtorrent/assert.hpp"

namespace
{
	enum { mode_in = 1, mode_out = 2 };

	mode_t map_open_mode(int m)
	{
		if (m == (mode_in | mode_out)) return O_RDWR | O_CREAT | O_BINARY | O_RANDOM;
		if (m == mode_out) return O_WRONLY | O_CREAT | O_BINARY | O_RANDOM;
		if (m == mode_in) return O_RDONLY | O_BINARY | O_RANDOM;
		TORRENT_ASSERT(false);
		return 0;
	}

#ifdef WIN32
	std::string utf8_native(std::string const& s)
	{
		try
		{
			std::wstring ws;
			libtorrent::utf8_wchar(s, ws);
			std::size_t size = wcstombs(0, ws.c_str(), 0);
			if (size == std::size_t(-1)) return s;
			std::string ret;
			ret.resize(size);
			size = wcstombs(&ret[0], ws.c_str(), size + 1);
			if (size == wchar_t(-1)) return s;
			ret.resize(size);
			return ret;
		}
		catch(std::exception)
		{
			return s;
		}
	}
#else
	std::string const& utf8_native(std::string const& s)
	{
		return s;
	}
#endif

}

namespace libtorrent
{
	namespace fs = boost::filesystem;

	const file::open_mode file::in(mode_in);
	const file::open_mode file::out(mode_out);

	const file::seek_mode file::begin(1);
	const file::seek_mode file::end(2);

	struct file::impl
	{
		impl()
			: m_fd(-1)
			, m_open_mode(0)
		{}

		impl(fs::path const& path, int mode, error_code& ec)
			: m_fd(-1)
			, m_open_mode(0)
		{
			open(path, mode, ec);
		}

		~impl()
		{
			close();
		}

		bool open(fs::path const& path, int mode, error_code& ec)
		{
			close();
#ifdef TORRENT_WINDOWS

			const int permissions = _S_IREAD | _S_IWRITE;

#ifdef defined UNICODE
#define open _wopen
			std::wstring file_path(safe_convert(path.native_file_string()));
#else
#define open _open
			std::string const& file_path = path.native_file_string();
#endif
#else // if not windows
			const mode_t permissions = S_IRWXU | S_IRGRP | S_IROTH;
			std::string const& file_path = path.native_file_string();
#endif
			m_fd = ::open(file_path.c_str(), map_open_mode(mode), permissions);

#ifdef TORRENT_WINDOWS
#undef open
#endif

			if (m_fd == -1)
			{
				ec = error_code(errno, get_posix_category());
				return false;
			}
			m_open_mode = mode;
			return true;
		}

		void close()
		{
			if (m_fd == -1) return;

#ifdef _WIN32
			::_close(m_fd);
#else
			::close(m_fd);
#endif
			m_fd = -1;
			m_open_mode = 0;
		}

		size_type read(char* buf, size_type num_bytes, error_code& ec)
		{
			TORRENT_ASSERT(m_open_mode & mode_in);
			TORRENT_ASSERT(m_fd != -1);

#ifdef _WIN32
			size_type ret = ::_read(m_fd, buf, num_bytes);
#else
			size_type ret = ::read(m_fd, buf, num_bytes);
#endif
			if (ret == -1) ec = error_code(errno, get_posix_category());
			return ret;
		}

		size_type write(const char* buf, size_type num_bytes, error_code& ec)
		{
			TORRENT_ASSERT(m_open_mode & mode_out);
			TORRENT_ASSERT(m_fd != -1);

			// TODO: Test this a bit more, what happens with random failures in
			// the files?
//			if ((rand() % 100) > 80)
//				throw file_error("debug");

#ifdef _WIN32
			size_type ret = ::_write(m_fd, buf, num_bytes);
#else
			size_type ret = ::write(m_fd, buf, num_bytes);
#endif
			if (ret == -1) ec = error_code(errno, get_posix_category());
			return ret;
		}

		bool set_size(size_type s, error_code& ec)
		{
#ifdef _WIN32
#error file.cpp is for posix systems only. use file_win.cpp on windows
#else
			if (ftruncate(m_fd, s) < 0)
			{
				ec = error_code(errno, get_posix_category());
				return false;
			}
			return true;
#endif
		}

		size_type seek(size_type offset, int m, error_code& ec)
		{
			TORRENT_ASSERT(m_open_mode);
			TORRENT_ASSERT(m_fd != -1);

			int seekdir = (m == 1)?SEEK_SET:SEEK_END;
#ifdef _WIN32
			size_type ret = _lseeki64(m_fd, offset, seekdir);
#else
			size_type ret = lseek(m_fd, offset, seekdir);
#endif

			// For some strange reason this fails
			// on win32. Use windows specific file
			// wrapper instead.
			if (ret < 0) ec = error_code(errno, get_posix_category());
			return ret;
		}

		size_type tell(error_code& ec)
		{
			TORRENT_ASSERT(m_open_mode);
			TORRENT_ASSERT(m_fd != -1);

			size_type ret;
#ifdef _WIN32
			ret = _telli64(m_fd);
#else
			ret = lseek(m_fd, 0, SEEK_CUR);
#endif
			if (ret < 0) ec = error_code(errno, get_posix_category());
			return ret;
		}

		int m_fd;
		int m_open_mode;
	};

	// pimpl forwardings

	file::file() : m_impl(new impl()) {}

	file::file(fs::path const& p, file::open_mode m, error_code& ec)
		: m_impl(new impl(p, m.m_mask, ec))
	{}

	file::~file() {}

	bool file::open(fs::path const& p, file::open_mode m, error_code& ec)
	{
		return m_impl->open(p, m.m_mask, ec);
	}

	void file::close()
	{
		m_impl->close();
	}

	size_type file::write(const char* buf, size_type num_bytes, error_code& ec)
	{
		return m_impl->write(buf, num_bytes, ec);
	}

	size_type file::read(char* buf, size_type num_bytes, error_code& ec)
	{
		return m_impl->read(buf, num_bytes, ec);
	}

	bool file::set_size(size_type s, error_code& ec)
	{
		return m_impl->set_size(s, ec);
	}

	size_type file::seek(size_type pos, file::seek_mode m, error_code& ec)
	{
		return m_impl->seek(pos, m.m_val, ec);
	}

	size_type file::tell(error_code& ec)
	{
		return m_impl->tell(ec);
	}
}
<commit_msg>set all permission bits on files and let umask handle reducing permissions<commit_after>/*

Copyright (c) 2003, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * 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.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS 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 COPYRIGHT OWNER OR 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.

*/

#include "libtorrent/pch.hpp"

#include <boost/scoped_ptr.hpp>
#ifdef _WIN32
// windows part
#include "libtorrent/utf8.hpp"

#include <io.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>

#ifndef _MODE_T_
typedef int mode_t;
#endif

#ifdef UNICODE
#include "libtorrent/storage.hpp"
#endif

#else
// unix part
#define _FILE_OFFSET_BITS 64
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>

#include <boost/static_assert.hpp>
// make sure the _FILE_OFFSET_BITS define worked
// on this platform
BOOST_STATIC_ASSERT(sizeof(lseek(0, 0, 0)) >= 8);

#endif

#include <boost/filesystem/operations.hpp>
#include "libtorrent/file.hpp"
#include <sstream>
#include <cstring>
#include <vector>

#ifndef O_BINARY
#define O_BINARY 0
#endif

#ifndef O_RANDOM
#define O_RANDOM 0
#endif

#ifdef UNICODE
#include "libtorrent/storage.hpp"
#endif

#include "libtorrent/assert.hpp"

namespace
{
	enum { mode_in = 1, mode_out = 2 };

	mode_t map_open_mode(int m)
	{
		if (m == (mode_in | mode_out)) return O_RDWR | O_CREAT | O_BINARY | O_RANDOM;
		if (m == mode_out) return O_WRONLY | O_CREAT | O_BINARY | O_RANDOM;
		if (m == mode_in) return O_RDONLY | O_BINARY | O_RANDOM;
		TORRENT_ASSERT(false);
		return 0;
	}

#ifdef WIN32
	std::string utf8_native(std::string const& s)
	{
		try
		{
			std::wstring ws;
			libtorrent::utf8_wchar(s, ws);
			std::size_t size = wcstombs(0, ws.c_str(), 0);
			if (size == std::size_t(-1)) return s;
			std::string ret;
			ret.resize(size);
			size = wcstombs(&ret[0], ws.c_str(), size + 1);
			if (size == wchar_t(-1)) return s;
			ret.resize(size);
			return ret;
		}
		catch(std::exception)
		{
			return s;
		}
	}
#else
	std::string const& utf8_native(std::string const& s)
	{
		return s;
	}
#endif

}

namespace libtorrent
{
	namespace fs = boost::filesystem;

	const file::open_mode file::in(mode_in);
	const file::open_mode file::out(mode_out);

	const file::seek_mode file::begin(1);
	const file::seek_mode file::end(2);

	struct file::impl
	{
		impl()
			: m_fd(-1)
			, m_open_mode(0)
		{}

		impl(fs::path const& path, int mode, error_code& ec)
			: m_fd(-1)
			, m_open_mode(0)
		{
			open(path, mode, ec);
		}

		~impl()
		{
			close();
		}

		bool open(fs::path const& path, int mode, error_code& ec)
		{
			close();
#ifdef TORRENT_WINDOWS

			const int permissions = _S_IREAD | _S_IWRITE;

#ifdef defined UNICODE
#define open _wopen
			std::wstring file_path(safe_convert(path.native_file_string()));
#else
#define open _open
			std::string const& file_path = path.native_file_string();
#endif
#else // if not windows
			// rely on default umask to filter x and w permissions
			// for group and others
			const mode_t permissions = S_IRWXU | S_IRWXG | S_IRWXO;
			std::string const& file_path = path.native_file_string();
#endif
			m_fd = ::open(file_path.c_str(), map_open_mode(mode), permissions);

#ifdef TORRENT_WINDOWS
#undef open
#endif

			if (m_fd == -1)
			{
				ec = error_code(errno, get_posix_category());
				return false;
			}
			m_open_mode = mode;
			return true;
		}

		void close()
		{
			if (m_fd == -1) return;

#ifdef _WIN32
			::_close(m_fd);
#else
			::close(m_fd);
#endif
			m_fd = -1;
			m_open_mode = 0;
		}

		size_type read(char* buf, size_type num_bytes, error_code& ec)
		{
			TORRENT_ASSERT(m_open_mode & mode_in);
			TORRENT_ASSERT(m_fd != -1);

#ifdef _WIN32
			size_type ret = ::_read(m_fd, buf, num_bytes);
#else
			size_type ret = ::read(m_fd, buf, num_bytes);
#endif
			if (ret == -1) ec = error_code(errno, get_posix_category());
			return ret;
		}

		size_type write(const char* buf, size_type num_bytes, error_code& ec)
		{
			TORRENT_ASSERT(m_open_mode & mode_out);
			TORRENT_ASSERT(m_fd != -1);

			// TODO: Test this a bit more, what happens with random failures in
			// the files?
//			if ((rand() % 100) > 80)
//				throw file_error("debug");

#ifdef _WIN32
			size_type ret = ::_write(m_fd, buf, num_bytes);
#else
			size_type ret = ::write(m_fd, buf, num_bytes);
#endif
			if (ret == -1) ec = error_code(errno, get_posix_category());
			return ret;
		}

		bool set_size(size_type s, error_code& ec)
		{
#ifdef _WIN32
#error file.cpp is for posix systems only. use file_win.cpp on windows
#else
			if (ftruncate(m_fd, s) < 0)
			{
				ec = error_code(errno, get_posix_category());
				return false;
			}
			return true;
#endif
		}

		size_type seek(size_type offset, int m, error_code& ec)
		{
			TORRENT_ASSERT(m_open_mode);
			TORRENT_ASSERT(m_fd != -1);

			int seekdir = (m == 1)?SEEK_SET:SEEK_END;
#ifdef _WIN32
			size_type ret = _lseeki64(m_fd, offset, seekdir);
#else
			size_type ret = lseek(m_fd, offset, seekdir);
#endif

			// For some strange reason this fails
			// on win32. Use windows specific file
			// wrapper instead.
			if (ret < 0) ec = error_code(errno, get_posix_category());
			return ret;
		}

		size_type tell(error_code& ec)
		{
			TORRENT_ASSERT(m_open_mode);
			TORRENT_ASSERT(m_fd != -1);

			size_type ret;
#ifdef _WIN32
			ret = _telli64(m_fd);
#else
			ret = lseek(m_fd, 0, SEEK_CUR);
#endif
			if (ret < 0) ec = error_code(errno, get_posix_category());
			return ret;
		}

		int m_fd;
		int m_open_mode;
	};

	// pimpl forwardings

	file::file() : m_impl(new impl()) {}

	file::file(fs::path const& p, file::open_mode m, error_code& ec)
		: m_impl(new impl(p, m.m_mask, ec))
	{}

	file::~file() {}

	bool file::open(fs::path const& p, file::open_mode m, error_code& ec)
	{
		return m_impl->open(p, m.m_mask, ec);
	}

	void file::close()
	{
		m_impl->close();
	}

	size_type file::write(const char* buf, size_type num_bytes, error_code& ec)
	{
		return m_impl->write(buf, num_bytes, ec);
	}

	size_type file::read(char* buf, size_type num_bytes, error_code& ec)
	{
		return m_impl->read(buf, num_bytes, ec);
	}

	bool file::set_size(size_type s, error_code& ec)
	{
		return m_impl->set_size(s, ec);
	}

	size_type file::seek(size_type pos, file::seek_mode m, error_code& ec)
	{
		return m_impl->seek(pos, m.m_val, ec);
	}

	size_type file::tell(error_code& ec)
	{
		return m_impl->tell(ec);
	}
}
<|endoftext|>


<commit_before>#include "RMHD_converter.hpp"
#include <iostream>

int myrank, nprocs;

int main(int argc, char *argv[])
{
    MPI_Init(&argc, &argv);
    MPI_Comm_rank(MPI_COMM_WORLD, &myrank);
    MPI_Comm_size(MPI_COMM_WORLD, &nprocs);

    RMHD_converter *bla = new RMHD_converter(
            atoi(argv[1]), atoi(argv[2]), atoi(argv[3]),
            atoi(argv[4]), atoi(argv[5]), atoi(argv[6]),
            2);
//            (1364/2+1), 1364, 1364,
//            2048, 2048, 2048,
//            64);
    bla->convert("Kdata0", "Kdata1", "Rdata");

    //bla->convert("K138000QNP002",
    //             "K138000QNP003",
    //             "U138000");
    //bla->convert("K138000QNP005",
    //             "K138000QNP006",
    //             "B138000");
    delete bla;

    // clean up
    fftwf_mpi_cleanup();
    MPI_Finalize();
    return EXIT_SUCCESS;
}

<commit_msg>use generalized file names<commit_after>#include "RMHD_converter.hpp"
#include <iostream>

int myrank, nprocs;
const int iter0 = 138000;

int main(int argc, char *argv[])
{
    MPI_Init(&argc, &argv);
    MPI_Comm_rank(MPI_COMM_WORLD, &myrank);
    MPI_Comm_size(MPI_COMM_WORLD, &nprocs);

    char iname0[100], iname1[100], oname[100];
    RMHD_converter *bla = new RMHD_converter(
 //           atoi(argv[1]), atoi(argv[2]), atoi(argv[3]),
 //           atoi(argv[4]), atoi(argv[5]), atoi(argv[6]),
 //           2);
            (1364/2+1), 1364, 1364,
            2048, 2048, 2048,
            64);
 //   bla->convert("Kdata0", "Kdata1", "Rdata");
    proc_print_err_message("aloha");

    int iteration = 138000;
    sprintf(iname0, "K%.6dQNP002", iteration - iter0);
    sprintf(iname1, "K%.6dQNP003", iteration - iter0);
    sprintf(oname, "u_t%.3x", iteration - iter0);
    bla->convert(iname0, iname1, oname);
    sprintf(iname0, "K%.6dQNP005", iteration - iter0);
    sprintf(iname1, "K%.6dQNP006", iteration - iter0);
    sprintf(oname, "b_t%.3x", iteration - iter0);
    bla->convert(iname0, iname1, oname);
    delete bla;

    // clean up
    fftwf_mpi_cleanup();
    MPI_Finalize();
    return EXIT_SUCCESS;
}

<|endoftext|>


<commit_before>/* Copyright 2014-2015 Juhani Numminen
 *
 * 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 "game.hpp"

#ifdef _WIN32
#include <windows.h>
#endif

#include "config.hpp"
#include "i18n.hpp"
#include "random.hpp"

Game::Game()
: nBallsEnabled_{1},
  paddle1_{10.f, height / 2.f - 50.f, sf::Color::Blue},
  paddle2_{width - 30.f, height / 2.f - 50.f, sf::Color::Red},
  window_{{width, height}, "Pong v" PROJECT_VERSION},
  circle_{Ball::radius, 16},
  text_{{}, font_, 50},
  isRunning_{false}
{
  balls_[0].x = width / 2.f;
  balls_[0].y = height / 2.f;
  balls_[0].x_velocity = randomFloat();
  balls_[0].y_velocity = Ball::fromOtherComponent(balls_[0].x_velocity);

  window_.setFramerateLimit(60);

  circle_.setFillColor(sf::Color::Black);
  text_.setColor(sf::Color::Black);

  if (!font_.loadFromFile("font.ttf"))
    throw NoFontException();

  const auto startMessageMb = _("Press space to start");
  auto len = std::mbstowcs(nullptr, startMessageMb, 0) + 1;
  auto wstr = std::vector<wchar_t>(len);
  std::mbstowcs(wstr.data(), startMessageMb, wstr.size());
  startMessage_ = wstr.data();

#ifdef _WIN32
  auto hwnd = window_.getSystemHandle();
  auto icon = LoadImage(GetModuleHandle(nullptr), MAKEINTRESOURCE(IDI_ICON),
                        IMAGE_ICON, 0, 0, LR_DEFAULTCOLOR | LR_DEFAULTSIZE);
  SendMessage(hwnd, WM_SETICON, ICON_BIG, reinterpret_cast<LPARAM>(icon));
#endif
}

void Game::run1P()
{
  sf::Event event;

  while (window_.isOpen()) {

    while (window_.pollEvent(event)) {
      if (event.type == sf::Event::Closed) {
        window_.close();
      }
      else if (event.type == sf::Event::KeyPressed) {
        switch (event.key.code) {
        case sf::Keyboard::Escape:
          window_.close();
          break;
        case sf::Keyboard::Space:
          isRunning_ = !isRunning_;
          break;
        default:
          break;
        }
      }
    }

    update1P();
    render();
  }
}

void Game::update1P()
{
  // Control
  if (sf::Keyboard::isKeyPressed(sf::Keyboard::W) && paddle1_.y > 0.f) {
    paddle1_.y -= Paddle::speed;
  }
  else if (sf::Keyboard::isKeyPressed(sf::Keyboard::S) &&
           paddle1_.bottom() < height) {
    paddle1_.y += Paddle::speed;
  }

  if (!isRunning_) return;

  updatePaddleAuto(paddle2_);

  // Ball logic

  auto toEnableX = Ball::disabled;
  auto toEnableY = 0.f;
  auto toEnableXVel = 0.f;
  auto toEnableYVel = 0.f;
  auto toEnableIndex = indexDisabled;

  for (auto i = 0; i < nBalls; i++) {
    if (balls_[i].x == Ball::disabled) {
      if (toEnableIndex == indexDisabled) {
        toEnableIndex = i;
      }
      continue;
    }

    balls_[i].x += balls_[i].x_velocity;
    balls_[i].y += balls_[i].y_velocity;

    if (balls_[i].y < 0.f || balls_[i].bottom() > height) {
      balls_[i].y_velocity = -balls_[i].y_velocity;
    }

    if (intersects(paddle1_, balls_[i])) {
      balls_[i].x = paddle1_.right();
      balls_[i].x_velocity = -balls_[i].x_velocity;

      toEnableX = balls_[i].x;
      toEnableY = balls_[i].y;
      toEnableXVel = randomFloat();
      toEnableYVel = Ball::fromOtherComponent(toEnableXVel);
    }
    else if (intersects(paddle2_, balls_[i])) {
      balls_[i].x = paddle2_.x - Ball::radius*2;
      balls_[i].x_velocity = -balls_[i].x_velocity;

      toEnableX = balls_[i].x;
      toEnableY = balls_[i].y;
      toEnableXVel = -randomFloat();
      toEnableYVel = Ball::fromOtherComponent(toEnableXVel);
    }

    if (balls_[i].right() < 0.f) {
      paddle2_.points++;
      balls_[i].x = Ball::disabled;
      nBallsEnabled_--;
    }
    else if (balls_[i].x > width) {
      paddle1_.points++;
      balls_[i].x = Ball::disabled;
      nBallsEnabled_--;
    }
  }

  if (nBallsEnabled_ == 0) {
    toEnableX = width / 2.f - Ball::radius;
    toEnableY = height / 2.f - Ball::radius;
    toEnableXVel = randomFloat();
    toEnableYVel = Ball::fromOtherComponent(toEnableXVel);
    isRunning_ = false;
  }

  if (toEnableX != Ball::disabled && toEnableIndex != indexDisabled) {
    balls_[toEnableIndex].x = toEnableX;
    balls_[toEnableIndex].y = toEnableY;
    balls_[toEnableIndex].x_velocity = toEnableXVel;
    balls_[toEnableIndex].y_velocity = toEnableYVel;
    nBallsEnabled_++;
  }
}

//void Game::run2P()
//{
//}

//void Game::update2p()
//{
//}

/*
 * This is the CPU player logic.
 * The paddle will only move if it is a certain distance away from the ball.
 */
void Game::updatePaddleAuto(Paddle& paddle)
{
  for (const auto& ball : balls_) {
    if (ball.x == Ball::disabled) continue;

    if (std::abs(ball.x - paddle.x) < 200.f) {
      if (paddle.y > ball.y) {
        paddle.y -= Paddle::slowSpeed;
        return;
      }
      else if (paddle.bottom() < ball.bottom()) {
        paddle.y += Paddle::slowSpeed;
        return;
      }
    }
  }
}

void Game::render()
{
  window_.clear(sf::Color::White);

  window_.draw(paddle1_.getRectangleShape());
  window_.draw(paddle2_.getRectangleShape());

  for (const auto& ball : balls_) {
    if (ball.x == Ball::disabled) continue;

    circle_.setPosition(ball.x, ball.y);
    window_.draw(circle_);
  }

  text_.setString(std::to_string(paddle1_.points));
  text_.setPosition(width * 0.25f - text_.getGlobalBounds().width, 10.f);
  window_.draw(text_);

  text_.setString(std::to_string(paddle2_.points));
  text_.setPosition(width * 0.75f, 10.f);
  window_.draw(text_);

  if (!isRunning_) {
    text_.setString(startMessage_);
    text_.setCharacterSize(20);
    text_.setPosition(10.f, height - 30.f);
    window_.draw(text_);
    text_.setCharacterSize(50);
  }

  window_.display();
}
<commit_msg>sf:Text::setColor (deprecated) -> setFillColor, and changed the color while I'm at it<commit_after>/* Copyright 2014-2015 Juhani Numminen
 *
 * 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 "game.hpp"

#ifdef _WIN32
#include <windows.h>
#endif

#include "config.hpp"
#include "i18n.hpp"
#include "random.hpp"

Game::Game()
: nBallsEnabled_{1},
  paddle1_{10.f, height / 2.f - 50.f, sf::Color::Blue},
  paddle2_{width - 30.f, height / 2.f - 50.f, sf::Color::Red},
  window_{{width, height}, "Pong v" PROJECT_VERSION},
  circle_{Ball::radius, 16},
  text_{{}, font_, 50},
  isRunning_{false}
{
  balls_[0].x = width / 2.f;
  balls_[0].y = height / 2.f;
  balls_[0].x_velocity = randomFloat();
  balls_[0].y_velocity = Ball::fromOtherComponent(balls_[0].x_velocity);

  window_.setFramerateLimit(60);

  circle_.setFillColor(sf::Color::Black);
  text_.setFillColor(sf::Color::Green);

  if (!font_.loadFromFile("font.ttf"))
    throw NoFontException();

  const auto startMessageMb = _("Press space to start");
  auto len = std::mbstowcs(nullptr, startMessageMb, 0) + 1;
  auto wstr = std::vector<wchar_t>(len);
  std::mbstowcs(wstr.data(), startMessageMb, wstr.size());
  startMessage_ = wstr.data();

#ifdef _WIN32
  auto hwnd = window_.getSystemHandle();
  auto icon = LoadImage(GetModuleHandle(nullptr), MAKEINTRESOURCE(IDI_ICON),
                        IMAGE_ICON, 0, 0, LR_DEFAULTCOLOR | LR_DEFAULTSIZE);
  SendMessage(hwnd, WM_SETICON, ICON_BIG, reinterpret_cast<LPARAM>(icon));
#endif
}

void Game::run1P()
{
  sf::Event event;

  while (window_.isOpen()) {

    while (window_.pollEvent(event)) {
      if (event.type == sf::Event::Closed) {
        window_.close();
      }
      else if (event.type == sf::Event::KeyPressed) {
        switch (event.key.code) {
        case sf::Keyboard::Escape:
          window_.close();
          break;
        case sf::Keyboard::Space:
          isRunning_ = !isRunning_;
          break;
        default:
          break;
        }
      }
    }

    update1P();
    render();
  }
}

void Game::update1P()
{
  // Control
  if (sf::Keyboard::isKeyPressed(sf::Keyboard::W) && paddle1_.y > 0.f) {
    paddle1_.y -= Paddle::speed;
  }
  else if (sf::Keyboard::isKeyPressed(sf::Keyboard::S) &&
           paddle1_.bottom() < height) {
    paddle1_.y += Paddle::speed;
  }

  if (!isRunning_) return;

  updatePaddleAuto(paddle2_);

  // Ball logic

  auto toEnableX = Ball::disabled;
  auto toEnableY = 0.f;
  auto toEnableXVel = 0.f;
  auto toEnableYVel = 0.f;
  auto toEnableIndex = indexDisabled;

  for (auto i = 0; i < nBalls; i++) {
    if (balls_[i].x == Ball::disabled) {
      if (toEnableIndex == indexDisabled) {
        toEnableIndex = i;
      }
      continue;
    }

    balls_[i].x += balls_[i].x_velocity;
    balls_[i].y += balls_[i].y_velocity;

    if (balls_[i].y < 0.f || balls_[i].bottom() > height) {
      balls_[i].y_velocity = -balls_[i].y_velocity;
    }

    if (intersects(paddle1_, balls_[i])) {
      balls_[i].x = paddle1_.right();
      balls_[i].x_velocity = -balls_[i].x_velocity;

      toEnableX = balls_[i].x;
      toEnableY = balls_[i].y;
      toEnableXVel = randomFloat();
      toEnableYVel = Ball::fromOtherComponent(toEnableXVel);
    }
    else if (intersects(paddle2_, balls_[i])) {
      balls_[i].x = paddle2_.x - Ball::radius*2;
      balls_[i].x_velocity = -balls_[i].x_velocity;

      toEnableX = balls_[i].x;
      toEnableY = balls_[i].y;
      toEnableXVel = -randomFloat();
      toEnableYVel = Ball::fromOtherComponent(toEnableXVel);
    }

    if (balls_[i].right() < 0.f) {
      paddle2_.points++;
      balls_[i].x = Ball::disabled;
      nBallsEnabled_--;
    }
    else if (balls_[i].x > width) {
      paddle1_.points++;
      balls_[i].x = Ball::disabled;
      nBallsEnabled_--;
    }
  }

  if (nBallsEnabled_ == 0) {
    toEnableX = width / 2.f - Ball::radius;
    toEnableY = height / 2.f - Ball::radius;
    toEnableXVel = randomFloat();
    toEnableYVel = Ball::fromOtherComponent(toEnableXVel);
    isRunning_ = false;
  }

  if (toEnableX != Ball::disabled && toEnableIndex != indexDisabled) {
    balls_[toEnableIndex].x = toEnableX;
    balls_[toEnableIndex].y = toEnableY;
    balls_[toEnableIndex].x_velocity = toEnableXVel;
    balls_[toEnableIndex].y_velocity = toEnableYVel;
    nBallsEnabled_++;
  }
}

//void Game::run2P()
//{
//}

//void Game::update2p()
//{
//}

/*
 * This is the CPU player logic.
 * The paddle will only move if it is a certain distance away from the ball.
 */
void Game::updatePaddleAuto(Paddle& paddle)
{
  for (const auto& ball : balls_) {
    if (ball.x == Ball::disabled) continue;

    if (std::abs(ball.x - paddle.x) < 200.f) {
      if (paddle.y > ball.y) {
        paddle.y -= Paddle::slowSpeed;
        return;
      }
      else if (paddle.bottom() < ball.bottom()) {
        paddle.y += Paddle::slowSpeed;
        return;
      }
    }
  }
}

void Game::render()
{
  window_.clear(sf::Color::White);

  window_.draw(paddle1_.getRectangleShape());
  window_.draw(paddle2_.getRectangleShape());

  for (const auto& ball : balls_) {
    if (ball.x == Ball::disabled) continue;

    circle_.setPosition(ball.x, ball.y);
    window_.draw(circle_);
  }

  text_.setString(std::to_string(paddle1_.points));
  text_.setPosition(width * 0.25f - text_.getGlobalBounds().width, 10.f);
  window_.draw(text_);

  text_.setString(std::to_string(paddle2_.points));
  text_.setPosition(width * 0.75f, 10.f);
  window_.draw(text_);

  if (!isRunning_) {
    text_.setString(startMessage_);
    text_.setCharacterSize(20);
    text_.setPosition(10.f, height - 30.f);
    window_.draw(text_);
    text_.setCharacterSize(50);
  }

  window_.display();
}
<|endoftext|>


<commit_before>/*-------------------------------------------------------------------------
 * drawElements Quality Program OpenGL ES 3.1 Module
 * -------------------------------------------------
 *
 * Copyright 2016 The Android Open Source Project
 *
 * 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.
 *
 *//*!
 * \file
 * \brief Negative Precise Tests
 *//*--------------------------------------------------------------------*/

#include "es31fNegativePreciseTests.hpp"

#include "gluShaderProgram.hpp"
#include "glwEnums.hpp"

namespace deqp
{
namespace gles31
{
namespace Functional
{
namespace NegativeTestShared
{
namespace
{

enum TestPrecise
{
	TEST_PRECISE_AS_VARIABLE_NAME = 0,
	TEST_PRECISE_AS_FUNCTION_NAME,
	TEST_PRECISE_AS_ARGUMENT_NAME,
	TEST_PRECISE_AS_MACRO_NAME,
	TEST_PRECISE_MACRO_AND_VARIABLE,
	TEST_PRECISE_MACRO_AND_FUNCTION,
	TEST_PRECISE_MACRO_AND_ARGUMENT,

	TEST_PRECISE_LAST
};

static const glu::ShaderType s_shaderTypes[] =
{
	glu::SHADERTYPE_VERTEX,
	glu::SHADERTYPE_FRAGMENT,
	glu::SHADERTYPE_GEOMETRY,
	glu::SHADERTYPE_COMPUTE,
	glu::SHADERTYPE_TESSELLATION_CONTROL,
	glu::SHADERTYPE_TESSELLATION_EVALUATION
};

std::string generateShaderSource (NegativeTestContext& ctx, glu::ShaderType shaderType, TestPrecise test)
{
	const bool				isES32	= contextSupports(ctx.getRenderContext().getType(), glu::ApiType::es(3, 2));
	const glu::GLSLVersion	version	= isES32 ? glu::GLSL_VERSION_320_ES : glu::GLSL_VERSION_310_ES;
	std::ostringstream		source;

	source	<< glu::getGLSLVersionDeclaration(version) << "\n"
			<< (isES32 ? "" : "#extension GL_EXT_gpu_shader5 : enable\n");

	switch (test)
	{
		case TEST_PRECISE_AS_MACRO_NAME:		source << "#define precise 0\n";		break;

		case TEST_PRECISE_MACRO_AND_VARIABLE:
		case TEST_PRECISE_MACRO_AND_FUNCTION:
		case TEST_PRECISE_MACRO_AND_ARGUMENT:	source << "#define precise aName\n";	break;
		default:
			break;
	}

    switch (shaderType)
    {
        case glu::SHADERTYPE_GEOMETRY:
            source  << (isES32 ? "" : "#extension GL_EXT_geometry_shader : enable\n")
                    << "layout(max_vertices = 5) out;\n";
            break;

        case glu::SHADERTYPE_TESSELLATION_CONTROL:
            source  << (isES32 ? "" : "#extension GL_EXT_tessellation_shader : enable\n")
                    << "layout(vertices = 3) out;\n";
            break;

        case glu::SHADERTYPE_TESSELLATION_EVALUATION:
            source  << (isES32 ? "" : "#extension GL_EXT_tessellation_shader : enable\n")
                    << "layout(triangles, equal_spacing, cw) in;\n";
            break;

        default:
            break;
    }

	switch (test)
	{
		case TEST_PRECISE_AS_FUNCTION_NAME:
		case TEST_PRECISE_MACRO_AND_FUNCTION:
			source	<< "\n"
					<< "void precise()\n"
					<< "{\n"
					<< "}\n";
			break;

		case TEST_PRECISE_AS_ARGUMENT_NAME:
		case TEST_PRECISE_MACRO_AND_ARGUMENT:
			source	<< "\n"
					<< "void example(int precise)\n"
					<< "{\n"
					<< "}\n";
			break;

		default:
			break;
	}

    source  << "void main()\n"
			<< "{\n";

	switch (test)
	{
		case TEST_PRECISE_AS_VARIABLE_NAME:
		case TEST_PRECISE_MACRO_AND_VARIABLE:	source << "	int precise = 1;\n";		break;
		case TEST_PRECISE_AS_MACRO_NAME:		source << "	int number = precise;\n";	break;
		default:
			break;
	}

	source << "}\n";

	return source.str();
}

void generateAndVerifyShader (NegativeTestContext& ctx, glu::ShaderType shaderType, TestPrecise test)
{
	glu::Shader 		shader			(ctx.getRenderContext(), shaderType);
	std::string 		shaderSource	= generateShaderSource(ctx, shaderType, test);
	const char* const	source			= shaderSource.c_str();
	const int 			length			= (int) shaderSource.size();

	shader.setSources(1, &source, &length);
	shader.compile();

	ctx.getLog() << shader;

	if (shader.getCompileStatus())
		ctx.fail("Shader was not expected to compile.");
}

void precise_as_variable_name (NegativeTestContext& ctx)
{
	TCU_CHECK_AND_THROW(NotSupportedError,
		ctx.isExtensionSupported("GL_EXT_gpu_shader5") || contextSupports(ctx.getRenderContext().getType(), glu::ApiType::es(3, 2)),
		"This test requires support for the extension GL_EXT_gpu_shader5 or context version 3.2 or higher.");

	ctx.beginSection("Test that precise cannot be used as a variable name.");
	for (int ndx = 0; ndx < DE_LENGTH_OF_ARRAY(s_shaderTypes); ++ndx)
		generateAndVerifyShader(ctx, s_shaderTypes[ndx], TEST_PRECISE_AS_VARIABLE_NAME);
	ctx.endSection();
}

void precise_as_function_name (NegativeTestContext& ctx)
{
	TCU_CHECK_AND_THROW(NotSupportedError,
		ctx.isExtensionSupported("GL_EXT_gpu_shader5") || contextSupports(ctx.getRenderContext().getType(), glu::ApiType::es(3, 2)),
		"This test requires support for the extension GL_EXT_gpu_shader5 or context version 3.2 or higher.");

	ctx.beginSection("Test that precise cannot be used as a function name.");
	for (int ndx = 0; ndx < DE_LENGTH_OF_ARRAY(s_shaderTypes); ++ndx)
		generateAndVerifyShader(ctx, s_shaderTypes[ndx], TEST_PRECISE_AS_FUNCTION_NAME);
	ctx.endSection();
}

void precise_as_function_argument (NegativeTestContext& ctx)
{
	TCU_CHECK_AND_THROW(NotSupportedError,
		ctx.isExtensionSupported("GL_EXT_gpu_shader5") || contextSupports(ctx.getRenderContext().getType(), glu::ApiType::es(3, 2)),
		"This test requires support for the extension GL_EXT_gpu_shader5 or context version 3.2 or higher.");

	ctx.beginSection("Test that precise cannot be used as a argument name.");
	for (int ndx = 0; ndx < DE_LENGTH_OF_ARRAY(s_shaderTypes); ++ndx)
		generateAndVerifyShader(ctx, s_shaderTypes[ndx], TEST_PRECISE_AS_ARGUMENT_NAME);
	ctx.endSection();
}

} // anonymous

std::vector<FunctionContainer> getNegativePreciseTestFunctions (void)
{
	const FunctionContainer funcs[] =
	{
        {precise_as_variable_name,			"precise_as_variable_name",			"Test precise keyword as variable name."			},
        {precise_as_function_name,			"precise_as_function_name",			"Test precise keyword as function name."			},
        {precise_as_function_argument,		"precise_as_function_argument",		"Test precise keyword as argument name."			},
	};

	return std::vector<FunctionContainer>(DE_ARRAY_BEGIN(funcs), DE_ARRAY_END(funcs));
}

} // NegativeTestShared
} // Functional
} // gles31
} // deqp
<commit_msg>Check for shader type support in negative precise tests am: 4a3a2d79a0 am: dd142e90db<commit_after>/*-------------------------------------------------------------------------
 * drawElements Quality Program OpenGL ES 3.1 Module
 * -------------------------------------------------
 *
 * Copyright 2016 The Android Open Source Project
 *
 * 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.
 *
 *//*!
 * \file
 * \brief Negative Precise Tests
 *//*--------------------------------------------------------------------*/

#include "es31fNegativePreciseTests.hpp"

#include "gluShaderProgram.hpp"
#include "glwEnums.hpp"

namespace deqp
{
namespace gles31
{
namespace Functional
{
namespace NegativeTestShared
{
namespace
{

enum TestPrecise
{
	TEST_PRECISE_AS_VARIABLE_NAME = 0,
	TEST_PRECISE_AS_FUNCTION_NAME,
	TEST_PRECISE_AS_ARGUMENT_NAME,
	TEST_PRECISE_AS_MACRO_NAME,
	TEST_PRECISE_MACRO_AND_VARIABLE,
	TEST_PRECISE_MACRO_AND_FUNCTION,
	TEST_PRECISE_MACRO_AND_ARGUMENT,

	TEST_PRECISE_LAST
};

static const glu::ShaderType s_shaderTypes[] =
{
	glu::SHADERTYPE_VERTEX,
	glu::SHADERTYPE_FRAGMENT,
	glu::SHADERTYPE_GEOMETRY,
	glu::SHADERTYPE_COMPUTE,
	glu::SHADERTYPE_TESSELLATION_CONTROL,
	glu::SHADERTYPE_TESSELLATION_EVALUATION
};

std::string generateShaderSource (NegativeTestContext& ctx, glu::ShaderType shaderType, TestPrecise test)
{
	const bool				isES32	= contextSupports(ctx.getRenderContext().getType(), glu::ApiType::es(3, 2));
	const glu::GLSLVersion	version	= isES32 ? glu::GLSL_VERSION_320_ES : glu::GLSL_VERSION_310_ES;
	std::ostringstream		source;

	source	<< glu::getGLSLVersionDeclaration(version) << "\n"
			<< (isES32 ? "" : "#extension GL_EXT_gpu_shader5 : enable\n");

	switch (test)
	{
		case TEST_PRECISE_AS_MACRO_NAME:		source << "#define precise 0\n";		break;

		case TEST_PRECISE_MACRO_AND_VARIABLE:
		case TEST_PRECISE_MACRO_AND_FUNCTION:
		case TEST_PRECISE_MACRO_AND_ARGUMENT:	source << "#define precise aName\n";	break;
		default:
			break;
	}

    switch (shaderType)
    {
        case glu::SHADERTYPE_GEOMETRY:
            source  << (isES32 ? "" : "#extension GL_EXT_geometry_shader : enable\n")
                    << "layout(max_vertices = 5) out;\n";
            break;

        case glu::SHADERTYPE_TESSELLATION_CONTROL:
            source  << (isES32 ? "" : "#extension GL_EXT_tessellation_shader : enable\n")
                    << "layout(vertices = 3) out;\n";
            break;

        case glu::SHADERTYPE_TESSELLATION_EVALUATION:
            source  << (isES32 ? "" : "#extension GL_EXT_tessellation_shader : enable\n")
                    << "layout(triangles, equal_spacing, cw) in;\n";
            break;

        default:
            break;
    }

	switch (test)
	{
		case TEST_PRECISE_AS_FUNCTION_NAME:
		case TEST_PRECISE_MACRO_AND_FUNCTION:
			source	<< "\n"
					<< "void precise()\n"
					<< "{\n"
					<< "}\n";
			break;

		case TEST_PRECISE_AS_ARGUMENT_NAME:
		case TEST_PRECISE_MACRO_AND_ARGUMENT:
			source	<< "\n"
					<< "void example(int precise)\n"
					<< "{\n"
					<< "}\n";
			break;

		default:
			break;
	}

    source  << "void main()\n"
			<< "{\n";

	switch (test)
	{
		case TEST_PRECISE_AS_VARIABLE_NAME:
		case TEST_PRECISE_MACRO_AND_VARIABLE:	source << "	int precise = 1;\n";		break;
		case TEST_PRECISE_AS_MACRO_NAME:		source << "	int number = precise;\n";	break;
		default:
			break;
	}

	source << "}\n";

	return source.str();
}

void generateAndVerifyShader (NegativeTestContext& ctx, glu::ShaderType shaderType, TestPrecise test)
{
	glu::Shader 		shader			(ctx.getRenderContext(), shaderType);
	std::string 		shaderSource	= generateShaderSource(ctx, shaderType, test);
	const char* const	source			= shaderSource.c_str();
	const int 			length			= (int) shaderSource.size();

	shader.setSources(1, &source, &length);
	shader.compile();

	ctx.getLog() << shader;

	if (shader.getCompileStatus())
		ctx.fail("Shader was not expected to compile.");
}

void precise_as_variable_name (NegativeTestContext& ctx)
{
	TCU_CHECK_AND_THROW(NotSupportedError,
		ctx.isExtensionSupported("GL_EXT_gpu_shader5") || contextSupports(ctx.getRenderContext().getType(), glu::ApiType::es(3, 2)),
		"This test requires support for the extension GL_EXT_gpu_shader5 or context version 3.2 or higher.");

	ctx.beginSection("Test that precise cannot be used as a variable name.");
	for (int ndx = 0; ndx < DE_LENGTH_OF_ARRAY(s_shaderTypes); ++ndx)
	{
		if (ctx.isShaderSupported(s_shaderTypes[ndx]))
			generateAndVerifyShader(ctx, s_shaderTypes[ndx], TEST_PRECISE_AS_VARIABLE_NAME);
	}
	ctx.endSection();
}

void precise_as_function_name (NegativeTestContext& ctx)
{
	TCU_CHECK_AND_THROW(NotSupportedError,
		ctx.isExtensionSupported("GL_EXT_gpu_shader5") || contextSupports(ctx.getRenderContext().getType(), glu::ApiType::es(3, 2)),
		"This test requires support for the extension GL_EXT_gpu_shader5 or context version 3.2 or higher.");

	ctx.beginSection("Test that precise cannot be used as a function name.");
	for (int ndx = 0; ndx < DE_LENGTH_OF_ARRAY(s_shaderTypes); ++ndx)
	{
		if (ctx.isShaderSupported(s_shaderTypes[ndx]))
			generateAndVerifyShader(ctx, s_shaderTypes[ndx], TEST_PRECISE_AS_FUNCTION_NAME);
	}
	ctx.endSection();
}

void precise_as_function_argument (NegativeTestContext& ctx)
{
	TCU_CHECK_AND_THROW(NotSupportedError,
		ctx.isExtensionSupported("GL_EXT_gpu_shader5") || contextSupports(ctx.getRenderContext().getType(), glu::ApiType::es(3, 2)),
		"This test requires support for the extension GL_EXT_gpu_shader5 or context version 3.2 or higher.");

	ctx.beginSection("Test that precise cannot be used as a argument name.");
	for (int ndx = 0; ndx < DE_LENGTH_OF_ARRAY(s_shaderTypes); ++ndx)
	{
		if (ctx.isShaderSupported(s_shaderTypes[ndx]))
			generateAndVerifyShader(ctx, s_shaderTypes[ndx], TEST_PRECISE_AS_ARGUMENT_NAME);
	}
	ctx.endSection();
}

} // anonymous

std::vector<FunctionContainer> getNegativePreciseTestFunctions (void)
{
	const FunctionContainer funcs[] =
	{
        {precise_as_variable_name,			"precise_as_variable_name",			"Test precise keyword as variable name."			},
        {precise_as_function_name,			"precise_as_function_name",			"Test precise keyword as function name."			},
        {precise_as_function_argument,		"precise_as_function_argument",		"Test precise keyword as argument name."			},
	};

	return std::vector<FunctionContainer>(DE_ARRAY_BEGIN(funcs), DE_ARRAY_END(funcs));
}

} // NegativeTestShared
} // Functional
} // gles31
} // deqp
<|endoftext|>


<commit_before>#include "game.h"

#include <iostream>
using std::cout;
using std::endl;

// in binding.cpp
void register_all_classes( lua_State* L );

void Game::initialiseAllegro()
{
    al_init();
    al_install_mouse();
    al_install_keyboard();
    al_init_image_addon();
    al_init_font_addon();
}

bool Game::createDisplay()
{
    al_set_new_display_flags( ALLEGRO_RESIZABLE );
    display = al_create_display( SCREEN_W, SCREEN_H );
    if( display == nullptr )
        return false;
    al_set_window_title( display, "My Game" );

    resize();

    return true;
}

void Game::resize()
{
    width = al_get_display_width( display );
    height = al_get_display_height( display );

    float sx = width / (float)SCREEN_W;
    float sy = height / (float)SCREEN_H;

    ALLEGRO_TRANSFORM trans;
    al_identity_transform(&trans);
    al_scale_transform(&trans, sx, sy);
    al_use_transform(&trans);
}

void Game::registerEventSources()
{
    frameTimer = al_create_timer( 1.0 / 60.0 );  // 60 FPS
    scriptTimer = al_create_timer( 1.0 / 100.0 ); // Update script called 100x per second
    eventQueue = al_create_event_queue();

    al_register_event_source( eventQueue, al_get_keyboard_event_source() );
    al_register_event_source( eventQueue, al_get_mouse_event_source() );
    al_register_event_source( eventQueue, al_get_display_event_source(display) );
    al_register_event_source( eventQueue, al_get_timer_event_source(frameTimer) );
    al_register_event_source( eventQueue, al_get_timer_event_source(scriptTimer) );

    al_start_timer( frameTimer );
    al_start_timer( scriptTimer );
}

void Game::initialiseLua()
{
    L = luaL_newstate();
    luaL_openlibs( L );

    register_all_classes( L );

    FontBinding::push( L, font );
    lua_setglobal( L, "fixed_font" );

    RenderListBinding::push( L, renderlist );
    lua_setglobal( L, "renderlist" );
}

bool Game::boot()
{
    renderlist = std::make_shared<RenderList>();

    initialiseAllegro();

    if( ! createDisplay() )
        return false;

    registerEventSources();

    font = al_load_font( "data/fixed_font.tga", 0, 0 );
    icon = al_load_bitmap( "data/icon.tga" );

    if( !font || !icon )
        return false;

    al_set_display_icon( display, icon );

    initialiseLua();

    redraw = true;

    return true;
}

void Game::setScene()
{
    using std::make_shared;

    RenderListPtr rl = make_shared<RenderList>();

    rl->add( make_shared<Rectangle>( 4, 4,  100, 30, 8, 8, al_map_rgba(58,68,115,200)));
    rl->add( make_shared<Rectangle>( 4, 34, 100, 60, 8, 8, al_map_rgba(58,68,15,200)));
    rl->add( make_shared<Rectangle>( 4, 64, 120, 90, 8, 8, al_map_rgba(58,28,75,200)));

    fpsText = make_shared<Text>( font, al_map_rgb( 255, 255, 255 ), 54, 8 );
    rl->add( fpsText );

    spsText = make_shared<Text>( font, al_map_rgb( 255, 255, 255 ), 54, 38 );
    rl->add( spsText );

    mouseText = make_shared<Text>( font, al_map_rgb( 255, 255, 255 ), 61, 68 );
    rl->add( mouseText );

    rl->setOrder( 255 );

    renderlist->add( std::move(rl) );

    updateMouseText();
}

void Game::updateMouseText()
{
    char mouseStr[MAX_BUTTONS+1];

    for( int i=1; i < MAX_BUTTONS; i++ )
        mouseStr[i-1] = mouse.buttons[i] ? '^' : '_';

    mouseStr[MAX_BUTTONS-1] = 0;

    mouseText->clearText();
    mouseText << "Mouse: [" << mouseStr << "]";
}

void Game::run()
{
    if( luaL_dofile( L, "scripts/main.lua" ) )
    {
        std::cerr << lua_tostring( L, -1 ) << std::endl;
        return;
    }

    LuaRef updateScripts = LuaRef::getGlobal( L, "update" );

    int fps_accum = 0, fps = 0;
    double fps_time = 0;

    int sps_accum = 0, sps = 0;
    double sps_time = 0;

    while( true )
    {
        ALLEGRO_EVENT event;
        al_wait_for_event( eventQueue, &event );

        if( event.type == ALLEGRO_EVENT_DISPLAY_CLOSE )
            break;

        if( event.type == ALLEGRO_EVENT_KEY_DOWN )
        {
            if( event.keyboard.keycode == ALLEGRO_KEY_ESCAPE )
                break;

            if( event.keyboard.keycode == ALLEGRO_KEY_Z )
            {
                renderlist->remove( mouseText );
            }

            if( event.keyboard.keycode == ALLEGRO_KEY_X )
            {
                renderlist->add( mouseText );
            }
        }

        if( event.type == ALLEGRO_EVENT_TIMER && event.timer.source == frameTimer )
        {
            double t = al_get_time();
            fps_accum++;

            if( t - fps_time >= 1 )
            {
                fps = fps_accum;
                fps_accum = 0;
                fps_time = t;
                fpsText->clearText();
                fpsText << "FPS:  " << fps;
            }

            redraw = true;
        }

        if( event.type == ALLEGRO_EVENT_TIMER && event.timer.source == scriptTimer )
        {
            double t = al_get_time();
            sps_accum++;
            if( t - sps_time >= 1 )
            {
                sps = sps_accum;
                sps_accum = 0;
                sps_time = t;
                spsText->clearText();
                spsText << "SPS: " << sps;
            }

            try {
                updateScripts( t );
            }
            catch( LuaException &e )
            {
                std::cerr << e.what() << std::endl;
            }
        }

        if( event.type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN ) {
            if( event.mouse.button < MAX_BUTTONS )
                mouse.buttons[event.mouse.button] = true;
            updateMouseText();
        }

        if( event.type == ALLEGRO_EVENT_MOUSE_BUTTON_UP ) {
            if( event.mouse.button < MAX_BUTTONS )
                mouse.buttons[event.mouse.button] = false;
            updateMouseText();
        }

        if( event.type == ALLEGRO_EVENT_DISPLAY_RESIZE )
        {
            al_acknowledge_resize( display );

            resize();

            redraw = true;
        }

        if( redraw && al_is_event_queue_empty( eventQueue ) )
        {
            redraw = false;

            al_clear_to_color( al_map_rgb( 83, 24, 24 ) );

            renderlist->render();

            al_flip_display();

        }
    }
}

void Game::deregisterEventSources()
{
    if( eventQueue )
    {
        al_destroy_event_queue( eventQueue );
        eventQueue = nullptr;
    }
}

void Game::destroyDisplay()
{
    if( display )
    {
        al_destroy_display( display );
        display = nullptr;
    }
}

Game::~Game()
{
    if( L ) {
        lua_close( L );
    }
    deregisterEventSources();
    destroyDisplay();
}
<commit_msg>Linear filtering<commit_after>#include "game.h"

#include <iostream>
using std::cout;
using std::endl;

// in binding.cpp
void register_all_classes( lua_State* L );

void Game::initialiseAllegro()
{
    al_init();
    al_install_mouse();
    al_install_keyboard();
    al_init_image_addon();
    al_init_font_addon();
}

bool Game::createDisplay()
{
    al_set_new_display_flags( ALLEGRO_RESIZABLE );
    display = al_create_display( SCREEN_W, SCREEN_H );
    if( display == nullptr )
        return false;
    al_set_window_title( display, "My Game" );
    al_set_new_bitmap_flags(ALLEGRO_MIN_LINEAR | ALLEGRO_MAG_LINEAR);

    resize();

    return true;
}

void Game::resize()
{
    width = al_get_display_width( display );
    height = al_get_display_height( display );

    float sx = width / (float)SCREEN_W;
    float sy = height / (float)SCREEN_H;

    ALLEGRO_TRANSFORM trans;
    al_identity_transform(&trans);
    al_scale_transform(&trans, sx, sy);
    al_use_transform(&trans);
}

void Game::registerEventSources()
{
    frameTimer = al_create_timer( 1.0 / 60.0 );  // 60 FPS
    scriptTimer = al_create_timer( 1.0 / 100.0 ); // Update script called 100x per second
    eventQueue = al_create_event_queue();

    al_register_event_source( eventQueue, al_get_keyboard_event_source() );
    al_register_event_source( eventQueue, al_get_mouse_event_source() );
    al_register_event_source( eventQueue, al_get_display_event_source(display) );
    al_register_event_source( eventQueue, al_get_timer_event_source(frameTimer) );
    al_register_event_source( eventQueue, al_get_timer_event_source(scriptTimer) );

    al_start_timer( frameTimer );
    al_start_timer( scriptTimer );
}

void Game::initialiseLua()
{
    L = luaL_newstate();
    luaL_openlibs( L );

    register_all_classes( L );

    FontBinding::push( L, font );
    lua_setglobal( L, "fixed_font" );

    RenderListBinding::push( L, renderlist );
    lua_setglobal( L, "renderlist" );
}

bool Game::boot()
{
    renderlist = std::make_shared<RenderList>();

    initialiseAllegro();

    if( ! createDisplay() )
        return false;

    registerEventSources();

    font = al_load_font( "data/fixed_font.tga", 0, 0 );
    icon = al_load_bitmap( "data/icon.tga" );

    if( !font || !icon )
        return false;

    al_set_display_icon( display, icon );

    initialiseLua();

    redraw = true;

    return true;
}

void Game::setScene()
{
    using std::make_shared;

    RenderListPtr rl = make_shared<RenderList>();

    rl->add( make_shared<Rectangle>( 4, 4,  100, 30, 8, 8, al_map_rgba(58,68,115,200)));
    rl->add( make_shared<Rectangle>( 4, 34, 100, 60, 8, 8, al_map_rgba(58,68,15,200)));
    rl->add( make_shared<Rectangle>( 4, 64, 120, 90, 8, 8, al_map_rgba(58,28,75,200)));

    fpsText = make_shared<Text>( font, al_map_rgb( 255, 255, 255 ), 54, 8 );
    rl->add( fpsText );

    spsText = make_shared<Text>( font, al_map_rgb( 255, 255, 255 ), 54, 38 );
    rl->add( spsText );

    mouseText = make_shared<Text>( font, al_map_rgb( 255, 255, 255 ), 61, 68 );
    rl->add( mouseText );

    rl->setOrder( 255 );

    renderlist->add( std::move(rl) );

    updateMouseText();
}

void Game::updateMouseText()
{
    char mouseStr[MAX_BUTTONS+1];

    for( int i=1; i < MAX_BUTTONS; i++ )
        mouseStr[i-1] = mouse.buttons[i] ? '^' : '_';

    mouseStr[MAX_BUTTONS-1] = 0;

    mouseText->clearText();
    mouseText << "Mouse: [" << mouseStr << "]";
}

void Game::run()
{
    if( luaL_dofile( L, "scripts/main.lua" ) )
    {
        std::cerr << lua_tostring( L, -1 ) << std::endl;
        return;
    }

    LuaRef updateScripts = LuaRef::getGlobal( L, "update" );

    int fps_accum = 0, fps = 0;
    double fps_time = 0;

    int sps_accum = 0, sps = 0;
    double sps_time = 0;

    while( true )
    {
        ALLEGRO_EVENT event;
        al_wait_for_event( eventQueue, &event );

        if( event.type == ALLEGRO_EVENT_DISPLAY_CLOSE )
            break;

        if( event.type == ALLEGRO_EVENT_KEY_DOWN )
        {
            if( event.keyboard.keycode == ALLEGRO_KEY_ESCAPE )
                break;

            if( event.keyboard.keycode == ALLEGRO_KEY_Z )
            {
                renderlist->remove( mouseText );
            }

            if( event.keyboard.keycode == ALLEGRO_KEY_X )
            {
                renderlist->add( mouseText );
            }
        }

        if( event.type == ALLEGRO_EVENT_TIMER && event.timer.source == frameTimer )
        {
            double t = al_get_time();
            fps_accum++;

            if( t - fps_time >= 1 )
            {
                fps = fps_accum;
                fps_accum = 0;
                fps_time = t;
                fpsText->clearText();
                fpsText << "FPS:  " << fps;
            }

            redraw = true;
        }

        if( event.type == ALLEGRO_EVENT_TIMER && event.timer.source == scriptTimer )
        {
            double t = al_get_time();
            sps_accum++;
            if( t - sps_time >= 1 )
            {
                sps = sps_accum;
                sps_accum = 0;
                sps_time = t;
                spsText->clearText();
                spsText << "SPS: " << sps;
            }

            try {
                updateScripts( t );
            }
            catch( LuaException &e )
            {
                std::cerr << e.what() << std::endl;
            }
        }

        if( event.type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN ) {
            if( event.mouse.button < MAX_BUTTONS )
                mouse.buttons[event.mouse.button] = true;
            updateMouseText();
        }

        if( event.type == ALLEGRO_EVENT_MOUSE_BUTTON_UP ) {
            if( event.mouse.button < MAX_BUTTONS )
                mouse.buttons[event.mouse.button] = false;
            updateMouseText();
        }

        if( event.type == ALLEGRO_EVENT_DISPLAY_RESIZE )
        {
            al_acknowledge_resize( display );

            resize();

            redraw = true;
        }

        if( redraw && al_is_event_queue_empty( eventQueue ) )
        {
            redraw = false;

            al_clear_to_color( al_map_rgb( 83, 24, 24 ) );

            renderlist->render();

            al_flip_display();

        }
    }
}

void Game::deregisterEventSources()
{
    if( eventQueue )
    {
        al_destroy_event_queue( eventQueue );
        eventQueue = nullptr;
    }
}

void Game::destroyDisplay()
{
    if( display )
    {
        al_destroy_display( display );
        display = nullptr;
    }
}

Game::~Game()
{
    if( L ) {
        lua_close( L );
    }
    deregisterEventSources();
    destroyDisplay();
}
<|endoftext|>