<commit_before>// Copyright (c) 2013 - 2015, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.

#include <iostream>
#include <nix/file/Directory.hpp>

using namespace std;

using namespace boost::filesystem;

namespace nix {
namespace file {

Directory::Directory(const path &location, FileMode mode)
    : loc(location), mode(mode) {
    open_or_create();
}

Directory::Directory(const string &location, FileMode mode): Directory(path(location.c_str()), mode) {}

void Directory::open_or_create() {
    if (!exists(loc)) {
        if (mode > FileMode::ReadOnly) {
            create_directories(loc);
        } else {
            throw std::logic_error("Trying to create new directory in ReadOnly mode!");
        }
    }
}

string Directory::location() const {
    return loc.string();
}

FileMode Directory::fileMode() const {
    return mode;
}

ndsize_t Directory::subdirCount() const {
    ndsize_t count = 0;
    directory_iterator end;
    directory_iterator di(location().c_str());
    while (di != end) {
        if (is_directory(*di))
            count ++;
        ++di;
    }
    return count;
}

void Directory::removeAll() {
    path p(location());
    for (directory_iterator end_it, it(p); it!=end_it; ++it) {
        remove_all(it->path());
    }
}

boost::filesystem::path Directory::sub_dir_by_index(ndsize_t index) const {
    path p;
    vector<path> paths;
    copy(directory_iterator(loc), directory_iterator(), back_inserter(paths));
    sort(paths.begin(), paths.end());
    if (index < paths.size())
        p = paths[index];
    return p;
}

boost::optional<path> Directory::findByNameOrAttribute(const std::string &attribute, const std::string &value) const {
    boost::optional<path> p;
    if (hasObject(value)) {
        p = location() / path(value.c_str());
        return p;
    }
    if (util::looksLikeUUID(value)) {
        path attr_path("attributes");
        directory_iterator end;
        directory_iterator di(location().c_str());
        while (di != end) {
            path temp = *di;
            if (is_directory(temp) && exists(temp / attr_path)){
                AttributesFS attr(temp);
                string s;
                if (attr.has(attribute)) {
                    attr.get(attribute, s);
                    if (s == value) {
                        p = temp;
                        return p;
                    }
                }
            }
            ++di;
        }
    }
    return p;
}

bool Directory::hasObject(const std::string &name) const {
    directory_iterator end;
    directory_iterator di(location().c_str());
    while (di != end) {
        path temp = *di;
        if (is_directory(temp) && temp.filename().string() == name)
            return true;
        ++di;
    }
    return false;
}

bool Directory::removeObjectByNameOrAttribute(const std::string &attribute, const std::string &name_or_id) const {
    boost::optional<path> p = findByNameOrAttribute(attribute, name_or_id);
    if (p && mode > FileMode::ReadOnly) {
        path attr_path = "attributes";
        if (exists(*p / attr_path)) {
            AttributesFS attr(*p, mode);
            if (attr.has("links")) {
                vector<string> links;
                attr.get("links", links);
                for (auto &l :links) {
                    remove_all(path(l));
                }
            }
        }
        uintmax_t ret = remove_all(*p);
        return ret > 0;
    }
    return false;
}

void Directory::createDirectoryLink(const std::string &target, const std::string &name) {
    if (boost::filesystem::exists({target})) {
        boost::filesystem::create_directory_symlink(boost::filesystem::path(target), loc / boost::filesystem::path(name));
    } else {
        throw runtime_error("Directory::createLink: target does not exist");
    }

}

void Directory::renameSubdir(const std::string &old_name, const std::string &new_name) {
    path o(path(location()) / path(old_name)), n(path(location()) / path(new_name));
    if (hasObject(old_name) && ! hasObject(new_name)) {
        rename(o, n);
    }
}

} // nix::file
} // nix<commit_msg>[file_backend/Directory] findByNameOrAttrib remove check for uuid<commit_after>// Copyright (c) 2013 - 2015, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.

#include <iostream>
#include <nix/file/Directory.hpp>

using namespace std;

using namespace boost::filesystem;

namespace nix {
namespace file {

Directory::Directory(const path &location, FileMode mode)
    : loc(location), mode(mode) {
    open_or_create();
}

Directory::Directory(const string &location, FileMode mode): Directory(path(location.c_str()), mode) {}

void Directory::open_or_create() {
    if (!exists(loc)) {
        if (mode > FileMode::ReadOnly) {
            create_directories(loc);
        } else {
            throw std::logic_error("Trying to create new directory in ReadOnly mode!");
        }
    }
}

string Directory::location() const {
    return loc.string();
}

FileMode Directory::fileMode() const {
    return mode;
}

ndsize_t Directory::subdirCount() const {
    ndsize_t count = 0;
    directory_iterator end;
    directory_iterator di(location().c_str());
    while (di != end) {
        if (is_directory(*di))
            count ++;
        ++di;
    }
    return count;
}

void Directory::removeAll() {
    path p(location());
    for (directory_iterator end_it, it(p); it!=end_it; ++it) {
        remove_all(it->path());
    }
}

boost::filesystem::path Directory::sub_dir_by_index(ndsize_t index) const {
    path p;
    vector<path> paths;
    copy(directory_iterator(loc), directory_iterator(), back_inserter(paths));
    sort(paths.begin(), paths.end());
    if (index < paths.size())
        p = paths[index];
    return p;
}

boost::optional<path> Directory::findByNameOrAttribute(const std::string &attribute, const std::string &value) const {
    boost::optional<path> p;
    if (hasObject(value)) {
        p = location() / path(value.c_str());
        return p;
    }
    path attr_path("attributes");
    directory_iterator end;
    directory_iterator di(location().c_str());
    while (di != end) {
        path temp = *di;
        if (is_directory(temp) && exists(temp / attr_path)){
            AttributesFS attr(temp);
            string s;
            if (attr.has(attribute)) {
                attr.get(attribute, s);
                if (s == value) {
                    p = temp;
                    return p;
                }
            }
        }
        ++di;
    }
    return p;
}

bool Directory::hasObject(const std::string &name) const {
    directory_iterator end;
    directory_iterator di(location().c_str());
    while (di != end) {
        path temp = *di;
        if (is_directory(temp) && temp.filename().string() == name)
            return true;
        ++di;
    }
    return false;
}

bool Directory::removeObjectByNameOrAttribute(const std::string &attribute, const std::string &name_or_id) const {
    boost::optional<path> p = findByNameOrAttribute(attribute, name_or_id);
    if (p && mode > FileMode::ReadOnly) {
        path attr_path = "attributes";
        if (exists(*p / attr_path)) {
            AttributesFS attr(*p, mode);
            if (attr.has("links")) {
                vector<string> links;
                attr.get("links", links);
                for (auto &l :links) {
                    remove_all(path(l));
                }
            }
        }
        uintmax_t ret = remove_all(*p);
        return ret > 0;
    }
    return false;
}

void Directory::createDirectoryLink(const std::string &target, const std::string &name) {
    if (boost::filesystem::exists({target})) {
        boost::filesystem::create_directory_symlink(boost::filesystem::path(target), loc / boost::filesystem::path(name));
    } else {
        throw runtime_error("Directory::createLink: target does not exist");
    }

}

void Directory::renameSubdir(const std::string &old_name, const std::string &new_name) {
    path o(path(location()) / path(old_name)), n(path(location()) / path(new_name));
    if (hasObject(old_name) && ! hasObject(new_name)) {
        rename(o, n);
    }
}

} // nix::file
} // nix<|endoftext|>


<commit_before>// Copyright (c) 2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "version.h"

#include <string>

// Name of client reported in the 'version' message. Report the same name
// for both kryptohashd and kryptohash-qt, to make it harder for attackers to
// target servers or GUI users specifically.
const std::string CLIENT_NAME("Kryptohatoshi");

// Client version number
#define CLIENT_VERSION_SUFFIX   "-beta"

// The following part of the code determines the CLIENT_BUILD variable.
// Several mechanisms are used for this:
// * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
//   generated by the build environment, possibly containing the output
//   of git-describe in a macro called BUILD_DESC
// * secondly, if this is an exported version of the code, GIT_ARCHIVE will
//   be defined (automatically using the export-subst git attribute), and
//   GIT_COMMIT will contain the commit id.
// * then, three options exist for determining CLIENT_BUILD:
//   * if BUILD_DESC is defined, use that literally (output of git-describe)
//   * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
//   * otherwise, use v[maj].[min].[rev].[build]-unk
// finally CLIENT_VERSION_SUFFIX is added

// First, include build.h if requested
#ifdef HAVE_BUILD_INFO
#    include "build.h"
#endif

// git will put "#define GIT_ARCHIVE 1" on the next line inside archives.
#define GIT_ARCHIVE 1
#ifdef GIT_ARCHIVE
#    define GIT_COMMIT_ID "0"
#    define GIT_COMMIT_DATE "Wed, 10 Jun 2015 12:59:59 +0000"
#endif

#define BUILD_DESC_WITH_SUFFIX(maj,min,rev,build,suffix) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-" DO_STRINGIZE(suffix)

#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit

#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk"

#ifndef BUILD_DESC
#    ifdef BUILD_SUFFIX
#        define BUILD_DESC BUILD_DESC_WITH_SUFFIX(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, BUILD_SUFFIX)
#    elif defined(GIT_COMMIT_ID)
#        define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID)
#    else
#        define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD)
#    endif
#endif

#ifndef BUILD_DATE
#    ifdef GIT_COMMIT_DATE
#        define BUILD_DATE GIT_COMMIT_DATE
#    else
#        define BUILD_DATE __DATE__ ", " __TIME__
#    endif
#endif

const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
<commit_msg>Updated version date<commit_after>// Copyright (c) 2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "version.h"

#include <string>

// Name of client reported in the 'version' message. Report the same name
// for both kryptohashd and kryptohash-qt, to make it harder for attackers to
// target servers or GUI users specifically.
const std::string CLIENT_NAME("Kryptohatoshi");

// Client version number
#define CLIENT_VERSION_SUFFIX   "-beta"

// The following part of the code determines the CLIENT_BUILD variable.
// Several mechanisms are used for this:
// * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
//   generated by the build environment, possibly containing the output
//   of git-describe in a macro called BUILD_DESC
// * secondly, if this is an exported version of the code, GIT_ARCHIVE will
//   be defined (automatically using the export-subst git attribute), and
//   GIT_COMMIT will contain the commit id.
// * then, three options exist for determining CLIENT_BUILD:
//   * if BUILD_DESC is defined, use that literally (output of git-describe)
//   * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
//   * otherwise, use v[maj].[min].[rev].[build]-unk
// finally CLIENT_VERSION_SUFFIX is added

// First, include build.h if requested
#ifdef HAVE_BUILD_INFO
#    include "build.h"
#endif

// git will put "#define GIT_ARCHIVE 1" on the next line inside archives.
#define GIT_ARCHIVE 1
#ifdef GIT_ARCHIVE
#    define GIT_COMMIT_ID "0"
#    define GIT_COMMIT_DATE "Fri, 12 Jun 2015 12:59:59 +0000"
#endif

#define BUILD_DESC_WITH_SUFFIX(maj,min,rev,build,suffix) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-" DO_STRINGIZE(suffix)

#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit

#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk"

#ifndef BUILD_DESC
#    ifdef BUILD_SUFFIX
#        define BUILD_DESC BUILD_DESC_WITH_SUFFIX(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, BUILD_SUFFIX)
#    elif defined(GIT_COMMIT_ID)
#        define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID)
#    else
#        define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD)
#    endif
#endif

#ifndef BUILD_DATE
#    ifdef GIT_COMMIT_DATE
#        define BUILD_DATE GIT_COMMIT_DATE
#    else
#        define BUILD_DATE __DATE__ ", " __TIME__
#    endif
#endif

const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
<|endoftext|>


<commit_before>// Copyright (c) 2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <string>

#include "version.h"

// Name of client reported in the 'version' message. Report the same name
// for both bitcoind and bitcoin-qt, to make it harder for attackers to
// target servers or GUI users specifically.
const std::string CLIENT_NAME("Lithium");

// Client version number
#define CLIENT_VERSION_SUFFIX   "-beta"

// The following part of the code determines the CLIENT_BUILD variable.
// Several mechanisms are used for this:
// * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
//   generated by the build environment, possibly containing the output
//   of git-describe in a macro called BUILD_DESC
// * secondly, if this is an exported version of the code, GIT_ARCHIVE will
//   be defined (automatically using the export-subst git attribute), and
//   GIT_COMMIT will contain the commit id.
// * then, three options exist for determining CLIENT_BUILD:
//   * if BUILD_DESC is defined, use that literally (output of git-describe)
//   * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
//   * otherwise, use v[maj].[min].[rev].[build]-unk
// finally CLIENT_VERSION_SUFFIX is added

// First, include build.h if requested
#ifdef HAVE_BUILD_INFO
#    include "build.h"
#endif

// git will put "#define GIT_ARCHIVE 1" on the next line inside archives.
#define GIT_ARCHIVE 1
#ifdef GIT_ARCHIVE
#    define GIT_COMMIT_ID "1"
#    define GIT_COMMIT_DATE "$Format:%cD"
#endif

#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit

#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk"

#ifndef BUILD_DESC
#    ifdef GIT_COMMIT_ID
#        define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID)
#    else
#        define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD)
#    endif
#endif

#ifndef BUILD_DATE
#    ifdef GIT_COMMIT_DATE
#        define BUILD_DATE GIT_COMMIT_DATE
#    else
#        define BUILD_DATE __DATE__ ", " __TIME__
#    endif
#endif

const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
<commit_msg>date-time<commit_after>// Copyright (c) 2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <string>

#include "version.h"

// Name of client reported in the 'version' message. Report the same name
// for both bitcoind and bitcoin-qt, to make it harder for attackers to
// target servers or GUI users specifically.
const std::string CLIENT_NAME("Lithium");

// Client version number
#define CLIENT_VERSION_SUFFIX   "-beta"

// The following part of the code determines the CLIENT_BUILD variable.
// Several mechanisms are used for this:
// * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
//   generated by the build environment, possibly containing the output
//   of git-describe in a macro called BUILD_DESC
// * secondly, if this is an exported version of the code, GIT_ARCHIVE will
//   be defined (automatically using the export-subst git attribute), and
//   GIT_COMMIT will contain the commit id.
// * then, three options exist for determining CLIENT_BUILD:
//   * if BUILD_DESC is defined, use that literally (output of git-describe)
//   * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
//   * otherwise, use v[maj].[min].[rev].[build]-unk
// finally CLIENT_VERSION_SUFFIX is added

// First, include build.h if requested
#ifdef HAVE_BUILD_INFO
#    include "build.h"
#endif

// git will put "#define GIT_ARCHIVE 1" on the next line inside archives.
#define GIT_ARCHIVE 1
#ifdef GIT_ARCHIVE
#    define GIT_COMMIT_ID "1"
#    define GIT_COMMIT_DATE "2015-08-12 20:22:33 +0100"
#endif

#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit

#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk"

#ifndef BUILD_DESC
#    ifdef GIT_COMMIT_ID
#        define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID)
#    else
#        define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD)
#    endif
#endif

#ifndef BUILD_DATE
#    ifdef GIT_COMMIT_DATE
#        define BUILD_DATE GIT_COMMIT_DATE
#    else
#        define BUILD_DATE __DATE__ ", " __TIME__
#    endif
#endif

const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
<|endoftext|>


<commit_before>/* This file is in the public domain.
 *
 * File:   XercesString.cpp
 * Author: tjoppen
 *
 * Created on February 12, 2010, 5:43 PM
 */

#include "XercesString.h"
#include <xercesc/util/XMLString.hpp>
#include <boost/shared_ptr.hpp>

using namespace xercesc;
using namespace boost;
using namespace std;
using namespace james;

class XMLChDeleter {
public:
    void operator() (XMLCh *str) {
        XMLString::release(&str);
    }
};

XercesString::XercesString(const string& str) {
    shared_ptr<XMLCh> xstr(XMLString::transcode(str.c_str()), XMLChDeleter());

    *this = xstr.get();
}

XercesString::XercesString(const XMLCh *str) : basic_string<XMLCh>(str) {
}

XercesString::operator string () const {
    char *str = XMLString::transcode(c_str());

    string ret = str;

    XMLString::release(&str);

    return ret;
}

XercesString::operator const XMLCh* () const {
    return c_str();
}

bool XercesString::operator== (const string& str) const {
    return (string)*this == str;
}

bool XercesString::operator!= (const string& str) const {
    return !(*this == str);
}

ostream& operator<< (ostream& os, const XercesString& str) {
    return os << (string)str;
}

ostream& operator<< (ostream& os, const XMLCh* str) {
    if(!str)
        return os << "(null)";

    return os << XercesString(str);
}
<commit_msg>XercesString: Remove use of boost::shared_ptr<commit_after>/* This file is in the public domain.
 *
 * File:   XercesString.cpp
 * Author: tjoppen
 *
 * Created on February 12, 2010, 5:43 PM
 */

#include "XercesString.h"
#include <xercesc/util/XMLString.hpp>

using namespace xercesc;
using namespace std;
using namespace james;

XercesString::XercesString(const string& str) {
    XMLCh *xstr = XMLString::transcode(str.c_str());

    *this = xstr;

    XMLString::release(&xstr);
}

XercesString::XercesString(const XMLCh *str) : basic_string<XMLCh>(str) {
}

XercesString::operator string () const {
    char *str = XMLString::transcode(c_str());

    string ret = str;

    XMLString::release(&str);

    return ret;
}

XercesString::operator const XMLCh* () const {
    return c_str();
}

bool XercesString::operator== (const string& str) const {
    return (string)*this == str;
}

bool XercesString::operator!= (const string& str) const {
    return !(*this == str);
}

ostream& operator<< (ostream& os, const XercesString& str) {
    return os << (string)str;
}

ostream& operator<< (ostream& os, const XMLCh* str) {
    if(!str)
        return os << "(null)";

    return os << XercesString(str);
}
<|endoftext|>


<commit_before>///
/// @file   main.cpp
/// @brief  primecount console application.
///
/// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#include "cmdoptions.hpp"

#include <primecount.hpp>
#include <primecount-internal.hpp>
#include <ptypes.hpp>
#include <utils.hpp>

#include <stdexcept>
#include <iostream>
#include <limits>
#include <stdint.h>

using namespace std;
using namespace primecount;

namespace {

int64_t int64_cast(maxint_t x)
{
  if (x > numeric_limits<int64_t>::max())
    throw primecount_error("this is a 63-bit function, x must be < 2^63");
  return (int64_t) x;
}

} // namespace

int main (int argc, char* argv[])
{
  PrimeCountOptions pco = parseOptions(argc, argv);
  maxint_t res = 0;
  double time = get_wtime();

  try
  {
    switch (pco.option)
    {
      case OPTION_DELEGLISE_RIVAT:
        res = pi_deleglise_rivat(pco.x, pco.threads); break;
      case OPTION_DELEGLISE_RIVAT1:
        res = pi_deleglise_rivat1(int64_cast(pco.x)); break;
      case OPTION_DELEGLISE_RIVAT2:
        res = pi_deleglise_rivat2(int64_cast(pco.x)); break;
      case OPTION_DELEGLISE_RIVAT3:
        res = pi_deleglise_rivat3(int64_cast(pco.x)); break;
      case OPTION_DELEGLISE_RIVAT_PARALLEL1:
        res = pi_deleglise_rivat_parallel1(int64_cast(pco.x), pco.threads); break;
      case OPTION_DELEGLISE_RIVAT_PARALLEL2:
        res = pi_deleglise_rivat_parallel2(int64_cast(pco.x), pco.threads); break;
      case OPTION_DELEGLISE_RIVAT_PARALLEL3:
        res = pi_deleglise_rivat_parallel3(int64_cast(pco.x), pco.threads); break;
      case OPTION_LEGENDRE:
        res = pi_legendre(int64_cast(pco.x), pco.threads); break;
      case OPTION_LEHMER:
        res = pi_lehmer(int64_cast(pco.x), pco.threads); break;
      case OPTION_LEHMER2:
        res = pi_lehmer2(int64_cast(pco.x), pco.threads); break;
      case OPTION_LMO:
        res = pi_lmo(int64_cast(pco.x), pco.threads); break;
      case OPTION_LMO1:
        res = pi_lmo1(int64_cast(pco.x)); break;
      case OPTION_LMO2:
        res = pi_lmo2(int64_cast(pco.x)); break;
      case OPTION_LMO3:
        res = pi_lmo3(int64_cast(pco.x)); break;
      case OPTION_LMO4:
        res = pi_lmo4(int64_cast(pco.x)); break;
      case OPTION_LMO5:
        res = pi_lmo5(int64_cast(pco.x)); break;
      case OPTION_LMO_PARALLEL1:
        res = pi_lmo_parallel1(int64_cast(pco.x), pco.threads); break;
      case OPTION_LMO_PARALLEL2:
        res = pi_lmo_parallel2(int64_cast(pco.x), pco.threads); break;
      case OPTION_LMO_PARALLEL3:
        res = pi_lmo_parallel3(int64_cast(pco.x), pco.threads); break;
      case OPTION_MEISSEL:
        res = pi_meissel(int64_cast(pco.x), pco.threads); break;
      case OPTION_PRIMESIEVE:
        res = pi_primesieve(int64_cast(pco.x), pco.threads); break;
      case OPTION_PHI:
        res = phi(int64_cast(pco.x), int64_cast(pco.a)); break;
      case OPTION_PI:
        res = pi(pco.x, pco.threads); break;
      case OPTION_LI:
        res = Li(int64_cast(pco.x)); break;
      case OPTION_LIINV:
        res = Li_inverse(int64_cast(pco.x)); break;
      case OPTION_NTHPRIME:
        res = nth_prime(int64_cast(pco.x), pco.threads); break;

#ifdef HAVE_INT128_T
      case OPTION_DELEGLISE_RIVAT4:
        res = pi_deleglise_rivat4(pco.x); break;
      case OPTION_DELEGLISE_RIVAT_PARALLEL4:
        res = pi_deleglise_rivat_parallel4(pco.x, pco.threads); break;
#endif
    }
  }
  catch (exception& e)
  {
    cerr << "Error: " << e.what() << endl;
    return 1;
  }

  cout << res << endl;
  if (pco.time)
    cout << "Seconds: " << get_wtime() - time << endl;

  return 0;
}
<commit_msg>Refactoring<commit_after>///
/// @file   main.cpp
/// @brief  primecount console application.
///
/// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#include "cmdoptions.hpp"

#include <primecount.hpp>
#include <primecount-internal.hpp>
#include <ptypes.hpp>
#include <utils.hpp>

#include <stdexcept>
#include <iostream>
#include <limits>
#include <stdint.h>

using namespace std;
using namespace primecount;

namespace {

int64_t int64_cast(maxint_t x)
{
  if (x > numeric_limits<int64_t>::max())
    throw primecount_error("this is a 63-bit function, x must be < 2^63");
  return (int64_t) x;
}

} // namespace

int main (int argc, char* argv[])
{
  PrimeCountOptions pco = parseOptions(argc, argv);
  double time = get_wtime();

  maxint_t x = pco.x;
  maxint_t a = pco.a;
  maxint_t res = 0;
  int threads = pco.threads;

  try
  {
    switch (pco.option)
    {
      case OPTION_DELEGLISE_RIVAT:
        res = pi_deleglise_rivat(x, threads); break;
      case OPTION_DELEGLISE_RIVAT1:
        res = pi_deleglise_rivat1(int64_cast(x)); break;
      case OPTION_DELEGLISE_RIVAT2:
        res = pi_deleglise_rivat2(int64_cast(x)); break;
      case OPTION_DELEGLISE_RIVAT3:
        res = pi_deleglise_rivat3(int64_cast(x)); break;
      case OPTION_DELEGLISE_RIVAT_PARALLEL1:
        res = pi_deleglise_rivat_parallel1(int64_cast(x), threads); break;
      case OPTION_DELEGLISE_RIVAT_PARALLEL2:
        res = pi_deleglise_rivat_parallel2(int64_cast(x), threads); break;
      case OPTION_DELEGLISE_RIVAT_PARALLEL3:
        res = pi_deleglise_rivat_parallel3(int64_cast(x), threads); break;
      case OPTION_LEGENDRE:
        res = pi_legendre(int64_cast(x), threads); break;
      case OPTION_LEHMER:
        res = pi_lehmer(int64_cast(x), threads); break;
      case OPTION_LEHMER2:
        res = pi_lehmer2(int64_cast(x), threads); break;
      case OPTION_LMO:
        res = pi_lmo(int64_cast(x), threads); break;
      case OPTION_LMO1:
        res = pi_lmo1(int64_cast(x)); break;
      case OPTION_LMO2:
        res = pi_lmo2(int64_cast(x)); break;
      case OPTION_LMO3:
        res = pi_lmo3(int64_cast(x)); break;
      case OPTION_LMO4:
        res = pi_lmo4(int64_cast(x)); break;
      case OPTION_LMO5:
        res = pi_lmo5(int64_cast(x)); break;
      case OPTION_LMO_PARALLEL1:
        res = pi_lmo_parallel1(int64_cast(x), threads); break;
      case OPTION_LMO_PARALLEL2:
        res = pi_lmo_parallel2(int64_cast(x), threads); break;
      case OPTION_LMO_PARALLEL3:
        res = pi_lmo_parallel3(int64_cast(x), threads); break;
      case OPTION_MEISSEL:
        res = pi_meissel(int64_cast(x), threads); break;
      case OPTION_PRIMESIEVE:
        res = pi_primesieve(int64_cast(x), threads); break;
      case OPTION_PHI:
        res = phi(int64_cast(x), int64_cast(a)); break;
      case OPTION_PI:
        res = pi(x, threads); break;
      case OPTION_LI:
        res = Li(int64_cast(x)); break;
      case OPTION_LIINV:
        res = Li_inverse(int64_cast(x)); break;
      case OPTION_NTHPRIME:
        res = nth_prime(int64_cast(x), threads); break;

#ifdef HAVE_INT128_T
      case OPTION_DELEGLISE_RIVAT4:
        res = pi_deleglise_rivat4(x); break;
      case OPTION_DELEGLISE_RIVAT_PARALLEL4:
        res = pi_deleglise_rivat_parallel4(x, threads); break;
#endif
    }
  }
  catch (exception& e)
  {
    cerr << "Error: " << e.what() << endl;
    return 1;
  }

  cout << res << endl;
  if (pco.time)
    cout << "Seconds: " << get_wtime() - time << endl;

  return 0;
}
<|endoftext|>


<commit_before>//  Copyright (C) 2001  MandrakeSoft S.A.
//
//    MandrakeSoft S.A.
//    43, rue d'Aboukir
//    75002 Paris - France
//    http://www.linux-mandrake.com/
//    http://www.mandrakesoft.com/
//
//  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 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA

// eth.cc  - helper code to find and create pktmover classes

// Peter Grehan (grehan@iprg.nokia.com) coded all of this
// NE2000/ether stuff.

#include "bochs.h"
#define LOG_THIS /* not needed */

eth_locator_c *eth_locator_c::all;

//
// Each pktmover module has a static locator class that registers
// here
//
eth_locator_c::eth_locator_c(const char *type)
{
  next = all;
  all  = this;
  this->type = type;
}

#ifdef ETH_NULL
extern class bx_null_locator_c bx_null_match;
#endif
#ifdef ETH_FBSD
extern class bx_fbsd_locator_c bx_fbsd_match;
#endif
#ifdef ETH_LINUX
extern class bx_linux_locator_c bx_linux_match;
#endif
#ifdef ETH_TEST
extern bx_test_match;
#endif
#ifdef ETH_ARPBACK
extern class bx_arpback_locator_c bx_arpback_match;
#endif

//
// Called by ethernet chip emulations to locate and create a pktmover
// object
//
eth_pktmover_c *
eth_locator_c::create(const char *type, const char *netif,
		      const char *macaddr,
		      eth_rx_handler_t rxh, void *rxarg)
{
#ifdef eth_static_constructors
  for (eth_locator_c *p = all; p != NULL; p = p->next) {
    if (strcmp(type, p->type) == 0)
      return (p->allocate(netif, macaddr, rxh, rxarg));
  }
#else
  eth_locator_c *ptr = 0;

#ifdef ETH_ARPBACK
  {
    if (!strcmp(type, "arpback"))
      ptr = (eth_locator_c *) &bx_arpback_match;
  }
#endif
#ifdef ETH_NULL
  {
    if (!strcmp(type, "null"))
      ptr = (eth_locator_c *) &bx_null_match;
  }
#endif
#ifdef ETH_FBSD
  {
    if (!strcmp(type, "fbsd"))
      ptr = (eth_locator_c *) &bx_fbsd_match;
  }
#endif
#ifdef ETH_LINUX
  {
    if (!strcmp(type, "linux"))
      ptr = (eth_locator_c *) &bx_linux_match;
  }
#endif
#ifdef ETH_TEST
  {
    if (!strcmp(type, "test"))
      ptr = (eth_locator_c *) &bx_test_match;
  }
#endif
  if (ptr)
    return (ptr->allocate(netif, macaddr, rxh, rxarg));
#endif

  return (NULL);
}
<commit_msg>- add win32.  Code from Don Becker.<commit_after>//  Copyright (C) 2001  MandrakeSoft S.A.
//
//    MandrakeSoft S.A.
//    43, rue d'Aboukir
//    75002 Paris - France
//    http://www.linux-mandrake.com/
//    http://www.mandrakesoft.com/
//
//  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 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA

// eth.cc  - helper code to find and create pktmover classes

// Peter Grehan (grehan@iprg.nokia.com) coded all of this
// NE2000/ether stuff.

#include "bochs.h"
#define LOG_THIS /* not needed */

eth_locator_c *eth_locator_c::all;

//
// Each pktmover module has a static locator class that registers
// here
//
eth_locator_c::eth_locator_c(const char *type)
{
  next = all;
  all  = this;
  this->type = type;
}

#ifdef ETH_NULL
extern class bx_null_locator_c bx_null_match;
#endif
#ifdef ETH_FBSD
extern class bx_fbsd_locator_c bx_fbsd_match;
#endif
#ifdef ETH_LINUX
extern class bx_linux_locator_c bx_linux_match;
#endif
#ifdef ETH_WIN32
extern class bx_win32_locator_c bx_win32_match;
#endif
#ifdef ETH_TEST
extern bx_test_match;
#endif
#ifdef ETH_ARPBACK
extern class bx_arpback_locator_c bx_arpback_match;
#endif

//
// Called by ethernet chip emulations to locate and create a pktmover
// object
//
eth_pktmover_c *
eth_locator_c::create(const char *type, const char *netif,
		      const char *macaddr,
		      eth_rx_handler_t rxh, void *rxarg)
{
#ifdef eth_static_constructors
  for (eth_locator_c *p = all; p != NULL; p = p->next) {
    if (strcmp(type, p->type) == 0)
      return (p->allocate(netif, macaddr, rxh, rxarg));
  }
#else
  eth_locator_c *ptr = 0;

#ifdef ETH_ARPBACK
  {
    if (!strcmp(type, "arpback"))
      ptr = (eth_locator_c *) &bx_arpback_match;
  }
#endif
#ifdef ETH_NULL
  {
    if (!strcmp(type, "null"))
      ptr = (eth_locator_c *) &bx_null_match;
  }
#endif
#ifdef ETH_FBSD
  {
    if (!strcmp(type, "fbsd"))
      ptr = (eth_locator_c *) &bx_fbsd_match;
  }
#endif
#ifdef ETH_LINUX
  {
    if (!strcmp(type, "linux"))
      ptr = (eth_locator_c *) &bx_linux_match;
  }
#endif
#ifdef ETH_WIN32
  {
    if(!strcmp(type, "win32"))
      ptr = (eth_locator_c *) &bx_win32_match;
  }
#endif
#ifdef ETH_TEST
  {
    if (!strcmp(type, "test"))
      ptr = (eth_locator_c *) &bx_test_match;
  }
#endif
  if (ptr)
    return (ptr->allocate(netif, macaddr, rxh, rxarg));
#endif

  return (NULL);
}
<|endoftext|>


<commit_before>#include "./assemble.h"

#include <png.h>

#include <fstream>
#include <tbb/mutex.h>

uint8_t* global_image;
int32_t* global_image_depth;
int32_t g_width;
int32_t g_height;
int32_t g_x_min = 0;
int32_t g_y_min = 0;
int32_t g_x_max = 0;
int32_t g_y_max = 0;
uint16_t g_header_size = 0;
std::string g_filename = "";

std::pair<int, int> projectCoords(std::pair<int, int> p, int phi) {
  if (phi == 0) return p;
  int cos_phi = phi % 2 - 1;
  if (!phi) cos_phi = 1;
  int sin_phi = phi % 2;
  if (phi == 3) sin_phi = -1;
  return std::make_pair(p.first * cos_phi - p.second * sin_phi,
                        p.first * sin_phi + p.second * cos_phi);
}

int render_tile(Image<uint8_t>& image,
                std::pair<int, int> projected) {
  uint16_t width = image.cols;
  uint16_t height = image.rows;

  static tbb::mutex render_mutex;

  for (size_t i = 0; i < 1u * width * height; ++i) {
    size_t index = i * 4;
    std::swap(image.data[index], image.data[index + 2]);
  }
  int64_t pos = (projected.second * g_width
               + projected.first) * 4l;
  render_mutex.lock();
  if (g_filename.size()) {
    std::fstream pam(g_filename.c_str());
    pam.seekp(g_header_size + pos, std::ios_base::cur);
    for (size_t i = 0; i < height; ++i) {
      for (size_t j = 0; j < width; ++j) {
        if (image.data[i * width * 4 + j * 4 + 3] != 0 &&
            global_image_depth[pos >> 2] <= projected.second) {
          pam.write(reinterpret_cast<const char*>
                    (&(image.data[i * width * 4 + j * 4])), 4);
        } else {
          pam.seekp(4, std::ios_base::cur);
        }
      }
      pam.seekp((g_width - width) * 4, std::ios_base::cur);
    }
  } else {
    for (size_t i = 0; i < height; ++i) {
      for (size_t j = 0; j < width; ++j) {
        if (image.data[i * width * 4 + j * 4 + 3] != 0 &&
            global_image_depth[pos >> 2] <= projected.second) {
          memcpy(global_image + pos, &image.data[i * width * 4 + j * 4], 4);
          global_image_depth[pos >> 2] = projected.second;
        }
        pos += 4;
      }
      pos += (g_width - width) * 4;
    }
  }
  render_mutex.unlock();
  return 0;
}

uint16_t writeHeader(std::string filename,
                   std::pair<int, int> min_norm,
                   std::pair<int, int> max_norm,
                   const nbt& bf) {
  if (bf.set().isometric) {
    g_width =  g_x_max - g_x_min + 64;
    g_height = g_y_max - g_y_min + 288;
  } else {
    g_width =  (max_norm.first - min_norm.first + 1) * 16;
    g_height = (max_norm.second - min_norm.second + 1) * 16;
    if (bf.set().oblique) g_height += 128;
  }
  uint16_t header_size = 0;
  if (filename.size()) {
    g_filename = filename;
    std::stringstream ss;
    ss << "P7\n"
       << "WIDTH "     << g_width << "\n"
       << "HEIGHT "    << g_height << "\n"
       << "DEPTH "     << 4 << "\n"
       << "MAXVAL "    << 255 << "\n"
       << "TUPLTYPE "  << "RGB_ALPHA" << "\n"
       << "ENDHDR"     << "\n";
    g_header_size = header_size = static_cast<uint16_t>(ss.str().size());
    std::ofstream pam(filename.c_str());
    pam << ss.str();

    pam.seekp(g_width * g_height * 4 - 1, std::ios_base::cur);
    pam.put('\0');
    global_image_depth = reinterpret_cast<int32_t*>
                         (calloc(static_cast<size_t>(g_width * g_height), sizeof(int32_t)));
  } else {
    global_image = reinterpret_cast<uint8_t*>
                   (calloc(static_cast<size_t>(g_width * g_height), 4));
    if (!global_image) {
      throw std::runtime_error("Memory allocation error");
    }
    global_image_depth = reinterpret_cast<int32_t*>
                         (calloc(static_cast<size_t>(g_width * g_height), sizeof(int32_t)));
  }
  return header_size;
}

void ApplyFoo::operator() (const tbb::blocked_range<std::vector<int>
                                                         ::iterator>& r) const {
  for (std::vector<int>::iterator j = r.begin(); j != r.end(); ++j) {
    bool result = false;
    std::pair<int, int> bp = projectCoords(std::make_pair(*j, i_),
                                      (4 - bf_->set().rotate) % 4);
    Image<uint8_t> image = bf_->getImage(bp.first, bp.second, &result);
    if (!result) {
      continue;
    }
    *index_ += 1;
    bp = projectCoords(bp, bf_->set().rotate);
    int offset_x = (bp.first - min_norm_.first) * 16;
    int offset_y = (bp.second - min_norm_.second) * 16;
    if (bf_->set().isometric) {
      bp = std::make_pair(2 * bp.first - 2 * bp.second, bp.first + bp.second);
      offset_x = bp.first * 16 - g_x_min;
      offset_y = bp.second * 16 - g_y_min;
    }
    render_tile(image, std::make_pair(offset_x, offset_y));
  }
}
ApplyFoo::ApplyFoo(nbt* bf, int i, tbb::atomic<size_t>* index,
                   std::pair<int, int> min_norm)
        : bf_(bf), i_(i), index_(index), min_norm_(min_norm) {}

Settings getSettings() {
  Settings set;
  set.topview = false;
  set.oblique = false;
  set.isometric = true;
  set.heightmap = false;
  set.color = false;
  set.shadow_strength = 60;
  set.shadow_quality = true;
  set.shadow_quality_ultra = true;
  set.relief_strength = 10;
  set.sun_direction = 2;
  set.rotate = 1;
  set.nightmode = 0;
  set.sun_direction = (set.sun_direction + ((set.rotate + 3) % 4) * 2) % 8;
  set.shadow = set.shadow_strength;
  set.relief = set.relief_strength;
  return set;
}

void calculateMinMaxPoint(std::pair<int, int>& min_norm,
                          std::pair<int, int>& max_norm,
                          const nbt& bf) {
  std::pair<int, int> min(bf.xPos_min(), bf.zPos_min());
  std::pair<int, int> max(bf.xPos_max(), bf.zPos_max());
  min = projectCoords(min, bf.set().rotate);
  max = projectCoords(max, bf.set().rotate);
  min_norm = std::make_pair(std::min(min.first, max.first),
                            std::min(min.second, max.second));
  max_norm = std::make_pair(std::max(min.first, max.first),
                            std::max(min.second, max.second));
}

void pamToPng(std::string png_name) {
  FILE* pam = NULL;
  if (g_filename.size()) {
    pam = fopen(g_filename.c_str(), "rb");
    fseek(pam, g_header_size, SEEK_CUR);
  }
  FILE* out = fopen(png_name.c_str(), "wb");
  png_struct* pngP;
  png_info* infoP;
  fprintf(stderr, "Set up PNG structs\n");
  pngP = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
  infoP = png_create_info_struct(pngP);
  fprintf(stderr, "Set up PNG IHDR\n");
  png_set_IHDR(pngP, infoP, static_cast<png_uint_32>(g_width),
                            static_cast<png_uint_32>(g_height), 8,
               PNG_COLOR_TYPE_RGB_ALPHA,
               PNG_INTERLACE_NONE,
               PNG_COMPRESSION_TYPE_DEFAULT,
               PNG_FILTER_TYPE_DEFAULT);
  fprintf(stderr, "Init IO\n");
  png_init_io(pngP, out);
  fprintf(stderr, "Write Info\n");
  png_write_info(pngP, infoP);

  fprintf(stderr, "Write rows\n");
  png_byte* pngRow = new png_byte[g_width * 4];
  for (int32_t i = 0; i < g_height; ++i) {
    if (pam) {
      fread(pngRow, 4, static_cast<size_t>(g_width), pam);
    } else {
      memcpy(pngRow, global_image + i * g_width * 4, static_cast<size_t>(g_width) * 4);
    }
    png_write_row(pngP, pngRow);
  }
  delete[] pngRow;

  fprintf(stderr, "Write end\n");
  png_write_end(pngP, infoP);
  png_destroy_write_struct(&pngP, &infoP);
  fclose(out);
  if (pam) {
    fclose(pam);
    free(global_image_depth);
  } else {
    free(global_image);
    free(global_image_depth);
  }
}

size_t fillTiles(std::list<std::vector<int> >& tiles, const nbt& bf,
                 const std::pair<int, int>& min_norm,
                 const std::pair<int, int>& max_norm,
                 boost::progress_display& show_progress) {
  size_t tiles_nr = 0;
  std::list<std::vector<int> >::iterator it = tiles.begin();
  for (int i = min_norm.second; i <= max_norm.second; ++i) {
    for (int j = min_norm.first; j <= max_norm.first; ++j) {
      std::pair<int, int> p = projectCoords(std::make_pair(j, i),
                                            (4 - bf.set().rotate) % 4);
      boost::filesystem::path path;
      if (bf.exists(p.first, p.second, path)) {
        p = projectCoords(p, bf.set().rotate);
        it->push_back(p.first);
        if (bf.set().isometric) {
          p = std::make_pair(32 * p.first - 32 * p.second,
                             16 * (p.first + p.second));
        }
        if (p.first < g_x_min) {
          g_x_min = p.first;
        }
        if (p.second < g_y_min) {
          g_y_min = p.second;
        }
        if (p.first > g_x_max) {
          g_x_max = p.first;
        }
        if (p.second > g_y_max) {
          g_y_max = p.second;
        }
      }
    }
    tiles_nr += it->size();
    ++it;
    ++show_progress;
  }
  return tiles_nr;
}

<commit_msg>also check global_image_depth<commit_after>#include "./assemble.h"

#include <png.h>

#include <fstream>
#include <tbb/mutex.h>

uint8_t* global_image;
int32_t* global_image_depth;
int32_t g_width;
int32_t g_height;
int32_t g_x_min = 0;
int32_t g_y_min = 0;
int32_t g_x_max = 0;
int32_t g_y_max = 0;
uint16_t g_header_size = 0;
std::string g_filename = "";

std::pair<int, int> projectCoords(std::pair<int, int> p, int phi) {
  if (phi == 0) return p;
  int cos_phi = phi % 2 - 1;
  if (!phi) cos_phi = 1;
  int sin_phi = phi % 2;
  if (phi == 3) sin_phi = -1;
  return std::make_pair(p.first * cos_phi - p.second * sin_phi,
                        p.first * sin_phi + p.second * cos_phi);
}

int render_tile(Image<uint8_t>& image,
                std::pair<int, int> projected) {
  uint16_t width = image.cols;
  uint16_t height = image.rows;

  static tbb::mutex render_mutex;

  for (size_t i = 0; i < 1u * width * height; ++i) {
    size_t index = i * 4;
    std::swap(image.data[index], image.data[index + 2]);
  }
  int64_t pos = (projected.second * g_width
               + projected.first) * 4l;
  render_mutex.lock();
  if (g_filename.size()) {
    std::fstream pam(g_filename.c_str());
    pam.seekp(g_header_size + pos, std::ios_base::cur);
    for (size_t i = 0; i < height; ++i) {
      for (size_t j = 0; j < width; ++j) {
        if (image.data[i * width * 4 + j * 4 + 3] != 0 &&
            global_image_depth[pos >> 2] <= projected.second) {
          pam.write(reinterpret_cast<const char*>
                    (&(image.data[i * width * 4 + j * 4])), 4);
        } else {
          pam.seekp(4, std::ios_base::cur);
        }
      }
      pam.seekp((g_width - width) * 4, std::ios_base::cur);
    }
  } else {
    for (size_t i = 0; i < height; ++i) {
      for (size_t j = 0; j < width; ++j) {
        if (image.data[i * width * 4 + j * 4 + 3] != 0 &&
            global_image_depth[pos >> 2] <= projected.second) {
          memcpy(global_image + pos, &image.data[i * width * 4 + j * 4], 4);
          global_image_depth[pos >> 2] = projected.second;
        }
        pos += 4;
      }
      pos += (g_width - width) * 4;
    }
  }
  render_mutex.unlock();
  return 0;
}

uint16_t writeHeader(std::string filename,
                   std::pair<int, int> min_norm,
                   std::pair<int, int> max_norm,
                   const nbt& bf) {
  if (bf.set().isometric) {
    g_width =  g_x_max - g_x_min + 64;
    g_height = g_y_max - g_y_min + 288;
  } else {
    g_width =  (max_norm.first - min_norm.first + 1) * 16;
    g_height = (max_norm.second - min_norm.second + 1) * 16;
    if (bf.set().oblique) g_height += 128;
  }
  uint16_t header_size = 0;
  if (filename.size()) {
    g_filename = filename;
    std::stringstream ss;
    ss << "P7\n"
       << "WIDTH "     << g_width << "\n"
       << "HEIGHT "    << g_height << "\n"
       << "DEPTH "     << 4 << "\n"
       << "MAXVAL "    << 255 << "\n"
       << "TUPLTYPE "  << "RGB_ALPHA" << "\n"
       << "ENDHDR"     << "\n";
    g_header_size = header_size = static_cast<uint16_t>(ss.str().size());
    std::ofstream pam(filename.c_str());
    pam << ss.str();

    pam.seekp(g_width * g_height * 4 - 1, std::ios_base::cur);
    pam.put('\0');
    global_image_depth = reinterpret_cast<int32_t*>
                         (calloc(static_cast<size_t>(g_width * g_height), sizeof(int32_t)));
  } else {
    global_image = reinterpret_cast<uint8_t*>
                   (calloc(static_cast<size_t>(g_width * g_height), 4));
    global_image_depth = reinterpret_cast<int32_t*>
                         (calloc(static_cast<size_t>(g_width * g_height), sizeof(int32_t)));
    if (!global_image || !global_image_depth) {
      throw std::runtime_error("Memory allocation error");
    }
  }
  return header_size;
}

void ApplyFoo::operator() (const tbb::blocked_range<std::vector<int>
                                                         ::iterator>& r) const {
  for (std::vector<int>::iterator j = r.begin(); j != r.end(); ++j) {
    bool result = false;
    std::pair<int, int> bp = projectCoords(std::make_pair(*j, i_),
                                      (4 - bf_->set().rotate) % 4);
    Image<uint8_t> image = bf_->getImage(bp.first, bp.second, &result);
    if (!result) {
      continue;
    }
    *index_ += 1;
    bp = projectCoords(bp, bf_->set().rotate);
    int offset_x = (bp.first - min_norm_.first) * 16;
    int offset_y = (bp.second - min_norm_.second) * 16;
    if (bf_->set().isometric) {
      bp = std::make_pair(2 * bp.first - 2 * bp.second, bp.first + bp.second);
      offset_x = bp.first * 16 - g_x_min;
      offset_y = bp.second * 16 - g_y_min;
    }
    render_tile(image, std::make_pair(offset_x, offset_y));
  }
}
ApplyFoo::ApplyFoo(nbt* bf, int i, tbb::atomic<size_t>* index,
                   std::pair<int, int> min_norm)
        : bf_(bf), i_(i), index_(index), min_norm_(min_norm) {}

Settings getSettings() {
  Settings set;
  set.topview = false;
  set.oblique = false;
  set.isometric = true;
  set.heightmap = false;
  set.color = false;
  set.shadow_strength = 60;
  set.shadow_quality = true;
  set.shadow_quality_ultra = true;
  set.relief_strength = 10;
  set.sun_direction = 2;
  set.rotate = 1;
  set.nightmode = 0;
  set.sun_direction = (set.sun_direction + ((set.rotate + 3) % 4) * 2) % 8;
  set.shadow = set.shadow_strength;
  set.relief = set.relief_strength;
  return set;
}

void calculateMinMaxPoint(std::pair<int, int>& min_norm,
                          std::pair<int, int>& max_norm,
                          const nbt& bf) {
  std::pair<int, int> min(bf.xPos_min(), bf.zPos_min());
  std::pair<int, int> max(bf.xPos_max(), bf.zPos_max());
  min = projectCoords(min, bf.set().rotate);
  max = projectCoords(max, bf.set().rotate);
  min_norm = std::make_pair(std::min(min.first, max.first),
                            std::min(min.second, max.second));
  max_norm = std::make_pair(std::max(min.first, max.first),
                            std::max(min.second, max.second));
}

void pamToPng(std::string png_name) {
  FILE* pam = NULL;
  if (g_filename.size()) {
    pam = fopen(g_filename.c_str(), "rb");
    fseek(pam, g_header_size, SEEK_CUR);
  }
  FILE* out = fopen(png_name.c_str(), "wb");
  png_struct* pngP;
  png_info* infoP;
  fprintf(stderr, "Set up PNG structs\n");
  pngP = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
  infoP = png_create_info_struct(pngP);
  fprintf(stderr, "Set up PNG IHDR\n");
  png_set_IHDR(pngP, infoP, static_cast<png_uint_32>(g_width),
                            static_cast<png_uint_32>(g_height), 8,
               PNG_COLOR_TYPE_RGB_ALPHA,
               PNG_INTERLACE_NONE,
               PNG_COMPRESSION_TYPE_DEFAULT,
               PNG_FILTER_TYPE_DEFAULT);
  fprintf(stderr, "Init IO\n");
  png_init_io(pngP, out);
  fprintf(stderr, "Write Info\n");
  png_write_info(pngP, infoP);

  fprintf(stderr, "Write rows\n");
  png_byte* pngRow = new png_byte[g_width * 4];
  for (int32_t i = 0; i < g_height; ++i) {
    if (pam) {
      fread(pngRow, 4, static_cast<size_t>(g_width), pam);
    } else {
      memcpy(pngRow, global_image + i * g_width * 4, static_cast<size_t>(g_width) * 4);
    }
    png_write_row(pngP, pngRow);
  }
  delete[] pngRow;

  fprintf(stderr, "Write end\n");
  png_write_end(pngP, infoP);
  png_destroy_write_struct(&pngP, &infoP);
  fclose(out);
  if (pam) {
    fclose(pam);
    free(global_image_depth);
  } else {
    free(global_image);
    free(global_image_depth);
  }
}

size_t fillTiles(std::list<std::vector<int> >& tiles, const nbt& bf,
                 const std::pair<int, int>& min_norm,
                 const std::pair<int, int>& max_norm,
                 boost::progress_display& show_progress) {
  size_t tiles_nr = 0;
  std::list<std::vector<int> >::iterator it = tiles.begin();
  for (int i = min_norm.second; i <= max_norm.second; ++i) {
    for (int j = min_norm.first; j <= max_norm.first; ++j) {
      std::pair<int, int> p = projectCoords(std::make_pair(j, i),
                                            (4 - bf.set().rotate) % 4);
      boost::filesystem::path path;
      if (bf.exists(p.first, p.second, path)) {
        p = projectCoords(p, bf.set().rotate);
        it->push_back(p.first);
        if (bf.set().isometric) {
          p = std::make_pair(32 * p.first - 32 * p.second,
                             16 * (p.first + p.second));
        }
        if (p.first < g_x_min) {
          g_x_min = p.first;
        }
        if (p.second < g_y_min) {
          g_y_min = p.second;
        }
        if (p.first > g_x_max) {
          g_x_max = p.first;
        }
        if (p.second > g_y_max) {
          g_y_max = p.second;
        }
      }
    }
    tiles_nr += it->size();
    ++it;
    ++show_progress;
  }
  return tiles_nr;
}

<|endoftext|>


<commit_before>/*
 * Copyright (C) 2019 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.
 */

#include "perfetto/ext/base/uuid.h"

#include <random>

#include "perfetto/ext/base/time.h"

namespace perfetto {
namespace base {

// See https://www.ietf.org/rfc/rfc4122.txt
std::array<uint8_t, 16> Uuidv4() {
  static std::minstd_rand rng(static_cast<size_t>(GetBootTimeNs().count()));
  std::array<uint8_t, 16> uuid;
  for (size_t i = 0; i < 16; ++i)
    uuid[i] = static_cast<uint8_t>(rng());

  // version:
  uuid[6] = (uuid[6] & 0x0f) | 0x40;
  // clock_seq_hi_and_reserved:
  uuid[8] = (uuid[8] & 0x3f) | 0x80;

  return uuid;
}

}  // namespace base
}  // namespace perfetto
<commit_msg>base: fix build of UUID on mac am: c17e81c243 am: 914626f1e6<commit_after>/*
 * Copyright (C) 2019 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.
 */

#include "perfetto/ext/base/uuid.h"

#include <random>

#include "perfetto/ext/base/time.h"

namespace perfetto {
namespace base {

// See https://www.ietf.org/rfc/rfc4122.txt
std::array<uint8_t, 16> Uuidv4() {
  static std::minstd_rand rng(static_cast<uint32_t>(GetBootTimeNs().count()));
  std::array<uint8_t, 16> uuid;
  for (size_t i = 0; i < 16; ++i)
    uuid[i] = static_cast<uint8_t>(rng());

  // version:
  uuid[6] = (uuid[6] & 0x0f) | 0x40;
  // clock_seq_hi_and_reserved:
  uuid[8] = (uuid[8] & 0x3f) | 0x80;

  return uuid;
}

}  // namespace base
}  // namespace perfetto
<|endoftext|>


<commit_before>/*
    Dynamics/Kinematics modeling and simulation library.
    Copyright (C) 1999 by Michael Alexander Ewert

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

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public
    License along with this library; if not, write to the Free
    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

*/

#include "csphyzik/articula.h"
#include "csphyzik/world.h"
#include "csphyzik/rigidbod.h"
#include "csphyzik/debug.h"

static ctWorld *gcurrent_world = NULL;

void dydt(real t, const real y[], real dy[] )
{
//	assert_goto( gcurrent_world != NULL, "current world NULL in dydt\n", ASSERTFAIL );

	gcurrent_world->calc_delta_state( t, y, dy );

//ASSERTFAIL:

}

ctWorld::ctWorld()
{
	ctPhysicalEntity::ctPhysicalEntity();
	ctArticulatedBody::set_joint_friction( DEFAULT_JOINT_FRICTION );

	// default
	ode_to_math = new OdeRungaKutta4();
}

//!me delete _lists and ode
ctWorld::~ctWorld()
{
	if( ode_to_math ) delete ode_to_math;
	//!me lists delete here
}

void ctWorld::calc_delta_state( real t, const real y[], real dy[] )
{
	// move data from y array into all entities in this world
	reintegrate_state( y );

	// zero out force accumulator and what-not
	init_state();

	// solve forces and torques of bodies in this world
	solve( t );

	// load all delta step data from bodies into ydot
	load_delta_state( dy );

}

// zero out force accumulator and other transient variables
void ctWorld::init_state()
{
ctPhysicalEntity *pe;

	pe = body_list.get_first();
	while( pe ){
		pe->init_state();
		pe = body_list.get_next();
	}

}

// calculate new positions of world objects after time dt
errorcode ctWorld::evolve( real t0, real t1 )
{
long arr_size = 0;
ctPhysicalEntity *pe = body_list.get_first();

	while( pe ){
//		if( pe->uses_ODE() ){
			arr_size +=	pe->get_state_size();
//		}
		pe = body_list.get_next();
	}

	//!me slow.  change to having y0 and y1 as members of world that get resized as needed.
	gcurrent_world = this;
	real *y0 = new real[arr_size];
	real *y1 = new real[arr_size];

	load_state( y0 );

	if( ode_to_math ){
		ode_to_math->calc_step( y0, y1, arr_size, t0, t1, dydt );
	}else{
		//!me boom!  no ode, so get out.
		return WORLD_ERR_NOODE;
	}

	reintegrate_state( y1 );

	//!me auch langsam.  kuch mal uber.
	delete [] y0;
	delete [] y1;
	gcurrent_world = NULL;

	return WORLD_NOERR;

}

// find and resolve collisions
void ctWorld::collide()
{

}

// resolve forces on all bodies
void ctWorld::solve( real t )
{
ctPhysicalEntity *pe;
ctForce *frc;

	// solve for forces affecting contents of world.  the order matters

	// first apply all environmental forces of this world to bodies
	frc = enviro_force_list.get_first();
	while( frc ){
		pe = body_list.get_first();
		while( pe ){
			pe->apply_given_F( *frc );
			pe = body_list.get_next();
		}

		frc = enviro_force_list.get_next();
	}

	pe = body_list.get_first();
	while( pe ){
		pe->solve(t);
		pe = body_list.get_next();
	}

}

// state to array
void ctWorld::load_state( real *state_array )
{
ctPhysicalEntity *pe;
long state_size;
	pe = body_list.get_first();
	while( pe ){
		//if( pe->uses_ODE() ){
			state_size = pe->set_state( state_array );
			state_array += state_size;
		//}
		pe = body_list.get_next();
	}

}

// array to state
void ctWorld::reintegrate_state( const real *state_array )
{
ctPhysicalEntity *pe;
long state_size;
	pe = body_list.get_first();
	while( pe ){
		//if( pe->uses_ODE() ){
			state_size = pe->get_state( state_array );
			state_array += state_size;
		//}
		pe = body_list.get_next();
	}

}

void ctWorld::load_delta_state( real *state_array )
{
ctPhysicalEntity *pe;
long state_size;
	pe = body_list.get_first();
	while( pe ){
		//if( pe->uses_ODE() ){
			state_size = pe->set_delta_state( state_array );
			state_array += state_size;
		//}
		pe = body_list.get_next();
	}

}

// add a rigidbody to this world
errorcode ctWorld::add_rigidbody( ctRigidBody *rb )
{
	if( rb ){
		body_list.add_link( rb );
		return WORLD_NOERR;
	}else{
		return WORLD_ERR_NULLPARAMETER;
	}
}

// add an articulated body to this world.
errorcode ctWorld::add_articulatedbodybase( ctArticulatedBody *ab )
{
	if( ab ){
		body_list.add_link( ab );
		return WORLD_NOERR;
	}else{
		return WORLD_ERR_NULLPARAMETER;
	}
}

errorcode ctWorld::add_enviro_force( ctForce *f )
{
	if( f ){
		enviro_force_list.add_link( f );
		return WORLD_NOERR;
	}else{
		return WORLD_ERR_NULLPARAMETER;
	}
}

errorcode ctWorld::delete_articulatedbody( ctArticulatedBody *pbase )
{
	if( pbase ){
		body_list.delete_link( pbase );
		return WORLD_NOERR;
	}else{
		return WORLD_ERR_NULLPARAMETER;
	}
}
<commit_msg>Fixed a transmogrification bug 8-)  The problem was that ctWorld was incorrectly calling the constructor for ctPhysicalEntity manually within its own constructor.  In other words:   ctWorld::ctWorld() { ctPhysicalEntity::ctPhysicalEntity(); ... } For non-conforming compilers (such as with NextStep) this had the unfortunate side-effect of transmogrifying the ctWorld into a ctPhysicalEntity, such that all virtual method dispatches went to ctPhysicalEntity rather than ctWorld as expected.  The correct way to construct ctWorld is:   ctWorld::ctWorld() : ctPhysicalEntity() { ... } Or alternatively:   ctWorld::ctWorld() { ... }<commit_after>/*
    Dynamics/Kinematics modeling and simulation library.
    Copyright (C) 1999 by Michael Alexander Ewert

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

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public
    License along with this library; if not, write to the Free
    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

*/

#include "csphyzik/articula.h"
#include "csphyzik/world.h"
#include "csphyzik/rigidbod.h"
#include "csphyzik/debug.h"

static ctWorld *gcurrent_world = NULL;

void dydt(real t, const real y[], real dy[] )
{
//	assert_goto( gcurrent_world != NULL, "current world NULL in dydt\n", ASSERTFAIL );

	gcurrent_world->calc_delta_state( t, y, dy );

//ASSERTFAIL:

}

ctWorld::ctWorld()
{
	ctArticulatedBody::set_joint_friction( DEFAULT_JOINT_FRICTION );

	// default
	ode_to_math = new OdeRungaKutta4();
}

//!me delete _lists and ode
ctWorld::~ctWorld()
{
	if( ode_to_math ) delete ode_to_math;
	//!me lists delete here
}

void ctWorld::calc_delta_state( real t, const real y[], real dy[] )
{
	// move data from y array into all entities in this world
	reintegrate_state( y );

	// zero out force accumulator and what-not
	init_state();

	// solve forces and torques of bodies in this world
	solve( t );

	// load all delta step data from bodies into ydot
	load_delta_state( dy );

}

// zero out force accumulator and other transient variables
void ctWorld::init_state()
{
ctPhysicalEntity *pe;

	pe = body_list.get_first();
	while( pe ){
		pe->init_state();
		pe = body_list.get_next();
	}

}

// calculate new positions of world objects after time dt
errorcode ctWorld::evolve( real t0, real t1 )
{
long arr_size = 0;
ctPhysicalEntity *pe = body_list.get_first();

	while( pe ){
//		if( pe->uses_ODE() ){
			arr_size +=	pe->get_state_size();
//		}
		pe = body_list.get_next();
	}

	//!me slow.  change to having y0 and y1 as members of world that get resized as needed.
	gcurrent_world = this;
	real *y0 = new real[arr_size];
	real *y1 = new real[arr_size];

	load_state( y0 );

	if( ode_to_math ){
		ode_to_math->calc_step( y0, y1, arr_size, t0, t1, dydt );
	}else{
		//!me boom!  no ode, so get out.
		return WORLD_ERR_NOODE;
	}

	reintegrate_state( y1 );

	//!me auch langsam.  kuch mal uber.
	delete [] y0;
	delete [] y1;
	gcurrent_world = NULL;

	return WORLD_NOERR;

}

// find and resolve collisions
void ctWorld::collide()
{

}

// resolve forces on all bodies
void ctWorld::solve( real t )
{
ctPhysicalEntity *pe;
ctForce *frc;

	// solve for forces affecting contents of world.  the order matters

	// first apply all environmental forces of this world to bodies
	frc = enviro_force_list.get_first();
	while( frc ){
		pe = body_list.get_first();
		while( pe ){
			pe->apply_given_F( *frc );
			pe = body_list.get_next();
		}

		frc = enviro_force_list.get_next();
	}

	pe = body_list.get_first();
	while( pe ){
		pe->solve(t);
		pe = body_list.get_next();
	}

}

// state to array
void ctWorld::load_state( real *state_array )
{
ctPhysicalEntity *pe;
long state_size;
	pe = body_list.get_first();
	while( pe ){
		//if( pe->uses_ODE() ){
			state_size = pe->set_state( state_array );
			state_array += state_size;
		//}
		pe = body_list.get_next();
	}

}

// array to state
void ctWorld::reintegrate_state( const real *state_array )
{
ctPhysicalEntity *pe;
long state_size;
	pe = body_list.get_first();
	while( pe ){
		//if( pe->uses_ODE() ){
			state_size = pe->get_state( state_array );
			state_array += state_size;
		//}
		pe = body_list.get_next();
	}

}

void ctWorld::load_delta_state( real *state_array )
{
ctPhysicalEntity *pe;
long state_size;
	pe = body_list.get_first();
	while( pe ){
		//if( pe->uses_ODE() ){
			state_size = pe->set_delta_state( state_array );
			state_array += state_size;
		//}
		pe = body_list.get_next();
	}

}

// add a rigidbody to this world
errorcode ctWorld::add_rigidbody( ctRigidBody *rb )
{
	if( rb ){
		body_list.add_link( rb );
		return WORLD_NOERR;
	}else{
		return WORLD_ERR_NULLPARAMETER;
	}
}

// add an articulated body to this world.
errorcode ctWorld::add_articulatedbodybase( ctArticulatedBody *ab )
{
	if( ab ){
		body_list.add_link( ab );
		return WORLD_NOERR;
	}else{
		return WORLD_ERR_NULLPARAMETER;
	}
}

errorcode ctWorld::add_enviro_force( ctForce *f )
{
	if( f ){
		enviro_force_list.add_link( f );
		return WORLD_NOERR;
	}else{
		return WORLD_ERR_NULLPARAMETER;
	}
}

errorcode ctWorld::delete_articulatedbody( ctArticulatedBody *pbase )
{
	if( pbase ){
		body_list.delete_link( pbase );
		return WORLD_NOERR;
	}else{
		return WORLD_ERR_NULLPARAMETER;
	}
}
<|endoftext|>


<commit_before>//---------------------------------------------------------------------------
//    $Id$
//    Version: $Name$
//
//    Copyright (C) 2001, 2002, 2003, 2004, 2005 by the deal.II authors
//
//    This file is subject to QPL and may not be  distributed
//    without copyright and license information. Please refer
//    to the file deal.II/doc/license.html for the  text  and
//    further information on this license.
//
//---------------------------------------------------------------------------

#include <fe/mapping_q1_eulerian.h>
#include <lac/vector.h>
#include <lac/petsc_vector.h>
#include <grid/tria_iterator.h>
#include <dofs/dof_handler.h>
#include <dofs/dof_accessor.h>
#include <fe/fe.h>

template <int dim, class EulerVectorType>
MappingQ1Eulerian<dim, EulerVectorType>::
MappingQ1Eulerian (const EulerVectorType  &euler_transform_vectors,
		   const DoFHandler<dim> &shiftmap_dof_handler)
                     :
		     euler_transform_vectors(euler_transform_vectors),
		     shiftmap_dof_handler(&shiftmap_dof_handler)
{}

template <int dim, class EulerVectorType>
void
MappingQ1Eulerian<dim, EulerVectorType>::
compute_mapping_support_points(const typename Triangulation<dim>::cell_iterator &cell,
			       std::vector<Point<dim> > &a) const
{

				   // The assertions can not be in the
				   // constructor, since this would
				   // require to call
				   // dof_handler.distribute_dofs(fe)
				   // *before* the mapping object is
				   // constructed, which is not
				   // necessarily what we want.
  Assert (dim == shiftmap_dof_handler->get_fe().n_dofs_per_vertex(),
          ExcWrongNoOfComponents());
  Assert (shiftmap_dof_handler->get_fe().n_components() == dim,
	  ExcWrongNoOfComponents());

  Assert (shiftmap_dof_handler->n_dofs() == euler_transform_vectors.size(),
          ExcWrongVectorSize(euler_transform_vectors.size(),
			     shiftmap_dof_handler->n_dofs()));

				   // cast the
				   // Triangulation<dim>::cell_iterator
				   // into a
				   // DoFHandler<dim>::cell_iterator
				   // which is necessary for access to
				   // DoFCellAccessor::get_dof_values()
  typename DoFHandler<dim>::cell_iterator
    dof_cell (const_cast<Triangulation<dim> *> (&(cell->get_triangulation())),
	      cell->level(),
	      cell->index(),
	      shiftmap_dof_handler);

				   // We require the cell to be active
				   // since we can only then get nodal
				   // values for the shifts
  Assert (dof_cell->active() == true, ExcInactiveCell());

				   // for Q1 elements, the number of
				   // support points should equal the
				   // number of vertices
  a.resize(GeometryInfo<dim>::vertices_per_cell);

				   // now get the values of the shift
				   // vectors at the vertices
  Vector<double> mapping_values (shiftmap_dof_handler->get_fe().dofs_per_cell);
  dof_cell->get_dof_values (euler_transform_vectors, mapping_values);

  for (unsigned int i=0; i<GeometryInfo<dim>::vertices_per_cell; ++i)
    {
      Point<dim> shift_vector;

				       // pick out the value of the
				       // shift vector at the present
				       // vertex. since vertex dofs
				       // are always numbered first,
				       // we can access them easily
      for (unsigned int j=0; j<dim; ++j)
	shift_vector[j] = mapping_values(this->vertex_mapping[i]*dim+j);

				       // compute new support point by
				       // old (reference) value and
				       // added shift
      a[i] = cell->vertex(this->vertex_mapping[i]) + shift_vector;
    }
}

// explicit instantiation
template class MappingQ1Eulerian<deal_II_dimension, Vector<double> >;
template class MappingQ1Eulerian<deal_II_dimension, PETScWrappers::Vector>;
<commit_msg>Guard instantiation.<commit_after>//---------------------------------------------------------------------------
//    $Id$
//    Version: $Name$
//
//    Copyright (C) 2001, 2002, 2003, 2004, 2005 by the deal.II authors
//
//    This file is subject to QPL and may not be  distributed
//    without copyright and license information. Please refer
//    to the file deal.II/doc/license.html for the  text  and
//    further information on this license.
//
//---------------------------------------------------------------------------

#include <fe/mapping_q1_eulerian.h>
#include <lac/vector.h>
#include <lac/petsc_vector.h>
#include <grid/tria_iterator.h>
#include <dofs/dof_handler.h>
#include <dofs/dof_accessor.h>
#include <fe/fe.h>

template <int dim, class EulerVectorType>
MappingQ1Eulerian<dim, EulerVectorType>::
MappingQ1Eulerian (const EulerVectorType  &euler_transform_vectors,
		   const DoFHandler<dim> &shiftmap_dof_handler)
                     :
		     euler_transform_vectors(euler_transform_vectors),
		     shiftmap_dof_handler(&shiftmap_dof_handler)
{}

template <int dim, class EulerVectorType>
void
MappingQ1Eulerian<dim, EulerVectorType>::
compute_mapping_support_points(const typename Triangulation<dim>::cell_iterator &cell,
			       std::vector<Point<dim> > &a) const
{

				   // The assertions can not be in the
				   // constructor, since this would
				   // require to call
				   // dof_handler.distribute_dofs(fe)
				   // *before* the mapping object is
				   // constructed, which is not
				   // necessarily what we want.
  Assert (dim == shiftmap_dof_handler->get_fe().n_dofs_per_vertex(),
          ExcWrongNoOfComponents());
  Assert (shiftmap_dof_handler->get_fe().n_components() == dim,
	  ExcWrongNoOfComponents());

  Assert (shiftmap_dof_handler->n_dofs() == euler_transform_vectors.size(),
          ExcWrongVectorSize(euler_transform_vectors.size(),
			     shiftmap_dof_handler->n_dofs()));

				   // cast the
				   // Triangulation<dim>::cell_iterator
				   // into a
				   // DoFHandler<dim>::cell_iterator
				   // which is necessary for access to
				   // DoFCellAccessor::get_dof_values()
  typename DoFHandler<dim>::cell_iterator
    dof_cell (const_cast<Triangulation<dim> *> (&(cell->get_triangulation())),
	      cell->level(),
	      cell->index(),
	      shiftmap_dof_handler);

				   // We require the cell to be active
				   // since we can only then get nodal
				   // values for the shifts
  Assert (dof_cell->active() == true, ExcInactiveCell());

				   // for Q1 elements, the number of
				   // support points should equal the
				   // number of vertices
  a.resize(GeometryInfo<dim>::vertices_per_cell);

				   // now get the values of the shift
				   // vectors at the vertices
  Vector<double> mapping_values (shiftmap_dof_handler->get_fe().dofs_per_cell);
  dof_cell->get_dof_values (euler_transform_vectors, mapping_values);

  for (unsigned int i=0; i<GeometryInfo<dim>::vertices_per_cell; ++i)
    {
      Point<dim> shift_vector;

				       // pick out the value of the
				       // shift vector at the present
				       // vertex. since vertex dofs
				       // are always numbered first,
				       // we can access them easily
      for (unsigned int j=0; j<dim; ++j)
	shift_vector[j] = mapping_values(this->vertex_mapping[i]*dim+j);

				       // compute new support point by
				       // old (reference) value and
				       // added shift
      a[i] = cell->vertex(this->vertex_mapping[i]) + shift_vector;
    }
}

// explicit instantiation
template class MappingQ1Eulerian<deal_II_dimension, Vector<double> >;
#ifdef DEAL_II_USE_PETSC
template class MappingQ1Eulerian<deal_II_dimension, PETScWrappers::Vector>;
#endif
<|endoftext|>


<commit_before>
#include <libclientserver.h>

/**
 * Str2Hex
 * @param[in] str the string value to be encoded
 * @return The encoded value
 *
 * HexEncode encodes a string and returns the same string encoded in hex.
 * An example would be " " will be returned as "20"
 */
std::string Encoder::Str2Hex(const std::string &str) {
	std::string tmp;
	const char *c = str.c_str();
	char buf[3];

	while(*c != 0) {
		sprintf(buf, "%02X", (unsigned char) *c);
		tmp += buf;
		c++;
	}

	return tmp;
}

std::string Encoder::Buf2Hex(const char *c, size_t buflen)
{
	std::string tmp;
	char buf[3];

	for(size_t i = 0;i<buflen;i++)
	{
		sprintf(buf, "%02X", (unsigned char) c[i]);
		tmp += buf;
	}

	return tmp;
}

std::string Encoder::Char2Str(char value)
{
	char buf[2];
	sprintf(buf, "%c", value);
	return std::string(buf);
}

std::string Encoder::UChar2Str(unsigned char value)
{
	char buf[32];
	sprintf(buf, "%d", value);
	return std::string(buf);
}

std::string Encoder::Short2Str(short value)
{
	char buf[32];
	sprintf(buf, "%d", value);
	return std::string(buf);
}

std::string Encoder::UShort2Str(unsigned short value)
{
	char buf[32];
	sprintf(buf, "%d", value);
	return std::string(buf);
}

std::string Encoder::Int2Str(int value)
{
	char buf[32];
	sprintf(buf, "%d", value);
	return std::string(buf);
}

std::string Encoder::UInt2Str(unsigned int value)
{
	char buf[32];
	sprintf(buf, "%d", value);
	return std::string(buf);
}

std::string Encoder::Long2Str(long value)
{
	char buf[32];
	sprintf(buf, "%ld", value);
	return std::string(buf);
}

std::string Encoder::ULong2Str(unsigned long value)
{
	char buf[32];
	sprintf(buf, "%lu", value);
	return std::string(buf);
}

std::string Encoder::Float2Str(float value)
{
	char buf[32];
	sprintf(buf, "%f", value);
	return std::string(buf);
}

std::string Encoder::Double2Str(double value)
{
	char buf[32];
	sprintf(buf, "%f", value);
	return std::string(buf);
}

<commit_msg>Implemented functions for converting to strings<commit_after>
#include <libclientserver.h>

/**
 * Str2Hex
 * @param[in] str the string value to be encoded
 * @return The encoded value
 *
 * HexEncode encodes a string and returns the same string encoded in hex.
 * An example would be " " will be returned as "20"
 */
std::string Encoder::Str2Hex(const std::string &str) {
	std::string tmp;
	const char *c = str.c_str();
	char buf[3];

	while(*c != 0) {
		sprintf(buf, "%02X", (unsigned char) *c);
		tmp += buf;
		c++;
	}

	return tmp;
}

std::string Encoder::Buf2Hex(const char *c, size_t buflen)
{
	std::string tmp;
	char buf[3];

	for(size_t i = 0;i<buflen;i++)
	{
		sprintf(buf, "%02X", (unsigned char) c[i]);
		tmp += buf;
	}

	return tmp;
}

std::string Encoder::Char2Str(char value)
{
	char buf[2];
	sprintf(buf, "%c", value);
	return std::string(buf);
}

std::string Encoder::UChar2Str(unsigned char value)
{
	char buf[32];
	sprintf(buf, "%d", value);
	return std::string(buf);
}

std::string Encoder::Short2Str(short value)
{
	char buf[32];
	sprintf(buf, "%d", value);
	return std::string(buf);
}

std::string Encoder::UShort2Str(unsigned short value)
{
	char buf[32];
	sprintf(buf, "%d", value);
	return std::string(buf);
}

std::string Encoder::Int2Str(int value)
{
	char buf[32];
	sprintf(buf, "%d", value);
	return std::string(buf);
}

std::string Encoder::UInt2Str(unsigned int value)
{
	char buf[32];
	sprintf(buf, "%d", value);
	return std::string(buf);
}

std::string Encoder::Long2Str(long value)
{
	char buf[32];
	sprintf(buf, "%ld", value);
	return std::string(buf);
}

std::string Encoder::ULong2Str(unsigned long value)
{
	char buf[32];
	sprintf(buf, "%lu", value);
	return std::string(buf);
}

std::string Encoder::Float2Str(float value)
{
	char buf[32];
	sprintf(buf, "%f", value);
	return std::string(buf);
}

std::string Encoder::Double2Str(double value)
{
	char buf[32];
	sprintf(buf, "%f", value);
	return std::string(buf);
}

<|endoftext|>


<commit_before>#ifndef GUI_HPP
#define GUI_HPP
#include "MainFrame.hpp"
#include "Notifier.hpp"
#include <string>

namespace Slic3r { namespace GUI {

// Friendly indices for the preset lists.
enum class PresetID {
    PRINT = 0,
    FILAMENT = 1,
    PRINTER = 2
};
using preset_list = std::vector<std::string>;

class App: public wxApp
{
public:
    virtual bool OnInit();
    App(std::shared_ptr<Settings> config) : wxApp(), gui_config(config) {}

    void check_version(bool manual) { /* stub */}

private:
    std::shared_ptr<Settings> gui_config; // GUI-specific configuration options
    Notifier* notifier;
    std::vector<preset_list> presets { preset_list(), preset_list(), preset_list() };
};

}} // namespace Slic3r::GUI
#endif // GUI_HPP
<commit_msg>Update GUI.hpp<commit_after>#ifndef GUI_HPP
#define GUI_HPP
#include "MainFrame.hpp"
#include "Notifier.hpp"
#include <string>
#include  <vector>

namespace Slic3r { namespace GUI {

// Friendly indices for the preset lists.
enum class PresetID {
    PRINT = 0,
    FILAMENT = 1,
    PRINTER = 2
};
using preset_list = std::vector<std::string>;

class App: public wxApp
{
public:
    virtual bool OnInit();
    App(std::shared_ptr<Settings> config) : wxApp(), gui_config(config) {}

    void check_version(bool manual) { /* stub */}

private:
    std::shared_ptr<Settings> gui_config; // GUI-specific configuration options
    Notifier* notifier;
    std::vector<preset_list> presets { preset_list(), preset_list(), preset_list() };
};

}} // namespace Slic3r::GUI
#endif // GUI_HPP
<|endoftext|>