<commit_before>//======================================================================
//-----------------------------------------------------------------------
/**
 * @file        japanese_tests.cpp
 * @brief       IUTEST_JAPANESE_NAME 対応テスト
 *
 * @author      t.shirayanagi
 * @par         copyright
 * Copyright (C) 2013-2016, Takazumi Shirayanagi\n
 * This software is released under the new BSD License,
 * see LICENSE
*/
//-----------------------------------------------------------------------
//======================================================================

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

#if IUTEST_HAS_TESTNAME_ALIAS_JP

IUTEST_PACKAGE(japanese_test)
{
IUTEST(JapaneseTest, IUTEST_JAPANESE_NAME(あいうえお))
{
//  IUTEST_SUCCEED() << "あいうえお";
    IUTEST_SUCCEED() << ::iutest::UnitTest::GetInstance()->current_test_info()->name();
    IUTEST_ASSERT_STREQ("あいうえお", ::iutest::UnitTest::GetInstance()->current_test_info()->name());
}

IUTEST(JapaneseTest, IUTEST_JAPANESE_NAME(かきくけこ))
{
    IUTEST_ASSERT_STREQ("かきくけこ", ::iutest::UnitTest::GetInstance()->current_test_info()->name());
}

IUTEST(IUTEST_JAPANESE_NAME(あいうえお), IUTEST_JAPANESE_NAME(かきくけこ))
{
#if IUTEST_HAS_PACKAGE
    IUTEST_ASSERT_STREQ("japanese_test.あいうえお", ::iutest::UnitTest::GetInstance()->current_test_info()->test_case_name());
#else
    IUTEST_ASSERT_STREQ("あいうえお", ::iutest::UnitTest::GetInstance()->current_test_info()->test_case_name());
#endif
    IUTEST_ASSERT_STREQ("かきくけこ", ::iutest::UnitTest::GetInstance()->current_test_info()->name());
}

class FixedTest : public ::iutest::Test {};

IUTEST_F(IUTEST_JAPANESE_NAME_F(あいうえお, FixedTest), IUTEST_JAPANESE_NAME(かきくけこ))
{
#if IUTEST_HAS_PACKAGE
    IUTEST_ASSERT_STREQ("japanese_test.あいうえお", ::iutest::UnitTest::GetInstance()->current_test_info()->test_case_name());
#else
    IUTEST_ASSERT_STREQ("あいうえお", ::iutest::UnitTest::GetInstance()->current_test_info()->test_case_name());
#endif
    IUTEST_ASSERT_STREQ("かきくけこ", ::iutest::UnitTest::GetInstance()->current_test_info()->name());
}

#if IUTEST_HAS_PARAM_TEST
class ParamTest : public ::iutest::TestWithParam<int> {};

IUTEST_P(IUTEST_JAPANESE_NAME_F(あいうえお, ParamTest), IUTEST_JAPANESE_NAME(あいうえお))
{
#if IUTEST_HAS_PACKAGE
    IUTEST_ASSERT_STREQ("japanese_test.My1/あいうえお", ::iutest::UnitTest::GetInstance()->current_test_info()->test_case_name());
#else
    IUTEST_ASSERT_STREQ("My1/あいうえお", ::iutest::UnitTest::GetInstance()->current_test_info()->test_case_name());
#endif
    IUTEST_ASSERT_STREQ("あいうえお/0", ::iutest::UnitTest::GetInstance()->current_test_info()->name());
}

IUTEST_P(IUTEST_JAPANESE_NAME_F(あいうえお, ParamTest), Japanese)
{
#if IUTEST_HAS_PACKAGE
    IUTEST_ASSERT_STREQ("japanese_test.My1/あいうえお", ::iutest::UnitTest::GetInstance()->current_test_info()->test_case_name());
#else
    IUTEST_ASSERT_STREQ("My1/あいうえお", ::iutest::UnitTest::GetInstance()->current_test_info()->test_case_name());
#endif
    IUTEST_ASSERT_STREQ("Japanese/0", ::iutest::UnitTest::GetInstance()->current_test_info()->name());
}

IUTEST_INSTANTIATE_TEST_CASE_P(My1, IUTEST_JAPANESE_NAME_F(あいうえお, ParamTest), ::iutest::Values(0));

#endif

#if IUTEST_HAS_TYPED_TEST

template<typename T>
class TypedTest : public ::iutest::Test {};

IUTEST_TYPED_TEST_CASE(TypedTest, int);

IUTEST_TYPED_TEST(IUTEST_JAPANESE_NAME_F(あいうえお, TypedTest), IUTEST_JAPANESE_NAME(あいうえお))
{
#if IUTEST_HAS_PACKAGE
    IUTEST_ASSERT_STREQ("japanese_test.あいうえお/0", ::iutest::UnitTest::GetInstance()->current_test_info()->test_case_name());
#else
    IUTEST_ASSERT_STREQ("あいうえお/0", ::iutest::UnitTest::GetInstance()->current_test_info()->test_case_name());
#endif
    IUTEST_ASSERT_STREQ("あいうえお", ::iutest::UnitTest::GetInstance()->current_test_info()->name());
}

#endif

#if 0   // 未サポート
#if IUTEST_HAS_TYPED_TEST_P

template<typename T>
class TypeParamTest : public ::iutest::Test {};

IUTEST_TYPED_TEST_CASE_P(TypeParamTest);

IUTEST_TYPED_TEST_P(TypeParamTest, IUTEST_JAPANESE_NAME_F(あいうえお, aiueo))
{
    IUTEST_ASSERT_STREQ("あいうえお", ::iutest::UnitTest::GetInstance()->current_test_info()->name());
}

IUTEST_REGISTER_TYPED_TEST_CASE_P(TypeParamTest, aiueo);

IUTEST_INSTANTIATE_TYPED_TEST_CASE_P(My1, TypeParamTest, int);

#endif

#endif

#if IUTEST_HAS_PARAM_METHOD_TEST

void TestFunction(int x, int y)
{
    IUTEST_ASSERT_EQ(x, y);
#if IUTEST_HAS_PACKAGE
    IUTEST_ASSERT_STREQ("japanese_test.あいうえお", ::iutest::UnitTest::GetInstance()->current_test_info()->test_case_name());
#else
    IUTEST_ASSERT_STREQ("あいうえお", ::iutest::UnitTest::GetInstance()->current_test_info()->test_case_name());
#endif
    IUTEST_ASSERT_STREQ("イコール/0", ::iutest::UnitTest::GetInstance()->current_test_info()->name());
}
IUTEST_PMZ(IUTEST_JAPANESE_NAME(あいうえお), IUTEST_JAPANESE_NAME(イコール), TestFunction, 0, 0);

#endif

#if IUTEST_HAS_IGNORE_TEST

namespace ignore_test
{

IUTEST_IGNORE(IUTEST_JAPANESE_NAME(あいうえお), IUTEST_JAPANESE_NAME(あいうえお))
{
}

IUTEST_F_IGNORE(IUTEST_JAPANESE_NAME_F(あいうえお, FixedTest), IUTEST_JAPANESE_NAME(かきくけこ))
{
}

#if IUTEST_HAS_PARAM_TEST

IUTEST_P_IGNORE(IUTEST_JAPANESE_NAME_F(あいうえお, ParamTest), IUTEST_JAPANESE_NAME(かきくけこ))
{
}

#endif

#if IUTEST_HAS_TYPED_TEST

IUTEST_TYPED_TEST_IGNORE(IUTEST_JAPANESE_NAME_F(あいうえお, TypedTest), IUTEST_JAPANESE_NAME(あいうえお))
{
}

#endif

}   // end of namespace ignore_test

#endif
}

#endif

#ifdef UNICODE
int wmain(int argc, wchar_t* argv[])
#else
int main(int argc, char* argv[])
#endif
{
    IUTEST_INIT(&argc, argv);

    int ret = IUTEST_RUN_ALL_TESTS();
    if( ret != 0 ) return 1;

#if IUTEST_HAS_TESTNAME_ALIAS_JP

    int testcase_count = 3;
    int test_count = 4;
#if IUTEST_HAS_PARAM_TEST
    testcase_count+=1;
    test_count += 2;
#endif
#if IUTEST_HAS_TYPED_TEST
    testcase_count+=1;
    test_count += 1;
#endif
#if IUTEST_HAS_PARAM_METHOD_TEST
    test_count += 1;
#endif

#if IUTEST_HAS_IGNORE_TEST
    test_count += 2;
#if IUTEST_HAS_PARAM_TEST
    test_count += 1;
#endif
#if IUTEST_HAS_TYPED_TEST
    test_count += 1;
#endif
#endif

#if IUTEST_HAS_ASSERTION_RETURN
    IUTEST_ASSERT_EQ( testcase_count, ::iutest::UnitTest::GetInstance()->total_test_case_count()) << ::iutest::AssertionReturn(1);
    IUTEST_ASSERT_EQ( test_count, ::iutest::UnitTest::GetInstance()->total_test_count() ) << ::iutest::AssertionReturn(1);
#else
    IUTEST_ASSERT_EXIT( ::iutest::UnitTest::GetInstance()->total_test_case_count() == testcase_count );
    IUTEST_ASSERT_EXIT( ::iutest::UnitTest::GetInstance()->total_test_count() == test_count );
#endif

#endif
    printf("*** Successful ***\n");
    return 0;
}
<commit_msg>disable warning C4566<commit_after>//======================================================================
//-----------------------------------------------------------------------
/**
 * @file        japanese_tests.cpp
 * @brief       IUTEST_JAPANESE_NAME 対応テスト
 *
 * @author      t.shirayanagi
 * @par         copyright
 * Copyright (C) 2013-2016, Takazumi Shirayanagi\n
 * This software is released under the new BSD License,
 * see LICENSE
*/
//-----------------------------------------------------------------------
//======================================================================

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

#if IUTEST_HAS_TESTNAME_ALIAS_JP

IUTEST_PRAGMA_MSC_WARN_DISABLE(4566)

IUTEST_PACKAGE(japanese_test)
{
IUTEST(JapaneseTest, IUTEST_JAPANESE_NAME(あいうえお))
{
//  IUTEST_SUCCEED() << "あいうえお";
    IUTEST_SUCCEED() << ::iutest::UnitTest::GetInstance()->current_test_info()->name();
    IUTEST_ASSERT_STREQ("あいうえお", ::iutest::UnitTest::GetInstance()->current_test_info()->name());
}

IUTEST(JapaneseTest, IUTEST_JAPANESE_NAME(かきくけこ))
{
    IUTEST_ASSERT_STREQ("かきくけこ", ::iutest::UnitTest::GetInstance()->current_test_info()->name());
}

IUTEST(IUTEST_JAPANESE_NAME(あいうえお), IUTEST_JAPANESE_NAME(かきくけこ))
{
#if IUTEST_HAS_PACKAGE
    IUTEST_ASSERT_STREQ("japanese_test.あいうえお", ::iutest::UnitTest::GetInstance()->current_test_info()->test_case_name());
#else
    IUTEST_ASSERT_STREQ("あいうえお", ::iutest::UnitTest::GetInstance()->current_test_info()->test_case_name());
#endif
    IUTEST_ASSERT_STREQ("かきくけこ", ::iutest::UnitTest::GetInstance()->current_test_info()->name());
}

class FixedTest : public ::iutest::Test {};

IUTEST_F(IUTEST_JAPANESE_NAME_F(あいうえお, FixedTest), IUTEST_JAPANESE_NAME(かきくけこ))
{
#if IUTEST_HAS_PACKAGE
    IUTEST_ASSERT_STREQ("japanese_test.あいうえお", ::iutest::UnitTest::GetInstance()->current_test_info()->test_case_name());
#else
    IUTEST_ASSERT_STREQ("あいうえお", ::iutest::UnitTest::GetInstance()->current_test_info()->test_case_name());
#endif
    IUTEST_ASSERT_STREQ("かきくけこ", ::iutest::UnitTest::GetInstance()->current_test_info()->name());
}

#if IUTEST_HAS_PARAM_TEST
class ParamTest : public ::iutest::TestWithParam<int> {};

IUTEST_P(IUTEST_JAPANESE_NAME_F(あいうえお, ParamTest), IUTEST_JAPANESE_NAME(あいうえお))
{
#if IUTEST_HAS_PACKAGE
    IUTEST_ASSERT_STREQ("japanese_test.My1/あいうえお", ::iutest::UnitTest::GetInstance()->current_test_info()->test_case_name());
#else
    IUTEST_ASSERT_STREQ("My1/あいうえお", ::iutest::UnitTest::GetInstance()->current_test_info()->test_case_name());
#endif
    IUTEST_ASSERT_STREQ("あいうえお/0", ::iutest::UnitTest::GetInstance()->current_test_info()->name());
}

IUTEST_P(IUTEST_JAPANESE_NAME_F(あいうえお, ParamTest), Japanese)
{
#if IUTEST_HAS_PACKAGE
    IUTEST_ASSERT_STREQ("japanese_test.My1/あいうえお", ::iutest::UnitTest::GetInstance()->current_test_info()->test_case_name());
#else
    IUTEST_ASSERT_STREQ("My1/あいうえお", ::iutest::UnitTest::GetInstance()->current_test_info()->test_case_name());
#endif
    IUTEST_ASSERT_STREQ("Japanese/0", ::iutest::UnitTest::GetInstance()->current_test_info()->name());
}

IUTEST_INSTANTIATE_TEST_CASE_P(My1, IUTEST_JAPANESE_NAME_F(あいうえお, ParamTest), ::iutest::Values(0));

#endif

#if IUTEST_HAS_TYPED_TEST

template<typename T>
class TypedTest : public ::iutest::Test {};

IUTEST_TYPED_TEST_CASE(TypedTest, int);

IUTEST_TYPED_TEST(IUTEST_JAPANESE_NAME_F(あいうえお, TypedTest), IUTEST_JAPANESE_NAME(あいうえお))
{
#if IUTEST_HAS_PACKAGE
    IUTEST_ASSERT_STREQ("japanese_test.あいうえお/0", ::iutest::UnitTest::GetInstance()->current_test_info()->test_case_name());
#else
    IUTEST_ASSERT_STREQ("あいうえお/0", ::iutest::UnitTest::GetInstance()->current_test_info()->test_case_name());
#endif
    IUTEST_ASSERT_STREQ("あいうえお", ::iutest::UnitTest::GetInstance()->current_test_info()->name());
}

#endif

#if 0   // 未サポート
#if IUTEST_HAS_TYPED_TEST_P

template<typename T>
class TypeParamTest : public ::iutest::Test {};

IUTEST_TYPED_TEST_CASE_P(TypeParamTest);

IUTEST_TYPED_TEST_P(TypeParamTest, IUTEST_JAPANESE_NAME_F(あいうえお, aiueo))
{
    IUTEST_ASSERT_STREQ("あいうえお", ::iutest::UnitTest::GetInstance()->current_test_info()->name());
}

IUTEST_REGISTER_TYPED_TEST_CASE_P(TypeParamTest, aiueo);

IUTEST_INSTANTIATE_TYPED_TEST_CASE_P(My1, TypeParamTest, int);

#endif

#endif

#if IUTEST_HAS_PARAM_METHOD_TEST

void TestFunction(int x, int y)
{
    IUTEST_ASSERT_EQ(x, y);
#if IUTEST_HAS_PACKAGE
    IUTEST_ASSERT_STREQ("japanese_test.あいうえお", ::iutest::UnitTest::GetInstance()->current_test_info()->test_case_name());
#else
    IUTEST_ASSERT_STREQ("あいうえお", ::iutest::UnitTest::GetInstance()->current_test_info()->test_case_name());
#endif
    IUTEST_ASSERT_STREQ("イコール/0", ::iutest::UnitTest::GetInstance()->current_test_info()->name());
}
IUTEST_PMZ(IUTEST_JAPANESE_NAME(あいうえお), IUTEST_JAPANESE_NAME(イコール), TestFunction, 0, 0);

#endif

#if IUTEST_HAS_IGNORE_TEST

namespace ignore_test
{

IUTEST_IGNORE(IUTEST_JAPANESE_NAME(あいうえお), IUTEST_JAPANESE_NAME(あいうえお))
{
}

IUTEST_F_IGNORE(IUTEST_JAPANESE_NAME_F(あいうえお, FixedTest), IUTEST_JAPANESE_NAME(かきくけこ))
{
}

#if IUTEST_HAS_PARAM_TEST

IUTEST_P_IGNORE(IUTEST_JAPANESE_NAME_F(あいうえお, ParamTest), IUTEST_JAPANESE_NAME(かきくけこ))
{
}

#endif

#if IUTEST_HAS_TYPED_TEST

IUTEST_TYPED_TEST_IGNORE(IUTEST_JAPANESE_NAME_F(あいうえお, TypedTest), IUTEST_JAPANESE_NAME(あいうえお))
{
}

#endif

}   // end of namespace ignore_test

#endif
}

#endif

#ifdef UNICODE
int wmain(int argc, wchar_t* argv[])
#else
int main(int argc, char* argv[])
#endif
{
    IUTEST_INIT(&argc, argv);

    int ret = IUTEST_RUN_ALL_TESTS();
    if( ret != 0 ) return 1;

#if IUTEST_HAS_TESTNAME_ALIAS_JP

    int testcase_count = 3;
    int test_count = 4;
#if IUTEST_HAS_PARAM_TEST
    testcase_count+=1;
    test_count += 2;
#endif
#if IUTEST_HAS_TYPED_TEST
    testcase_count+=1;
    test_count += 1;
#endif
#if IUTEST_HAS_PARAM_METHOD_TEST
    test_count += 1;
#endif

#if IUTEST_HAS_IGNORE_TEST
    test_count += 2;
#if IUTEST_HAS_PARAM_TEST
    test_count += 1;
#endif
#if IUTEST_HAS_TYPED_TEST
    test_count += 1;
#endif
#endif

#if IUTEST_HAS_ASSERTION_RETURN
    IUTEST_ASSERT_EQ( testcase_count, ::iutest::UnitTest::GetInstance()->total_test_case_count()) << ::iutest::AssertionReturn(1);
    IUTEST_ASSERT_EQ( test_count, ::iutest::UnitTest::GetInstance()->total_test_count() ) << ::iutest::AssertionReturn(1);
#else
    IUTEST_ASSERT_EXIT( ::iutest::UnitTest::GetInstance()->total_test_case_count() == testcase_count );
    IUTEST_ASSERT_EXIT( ::iutest::UnitTest::GetInstance()->total_test_count() == test_count );
#endif

#endif
    printf("*** Successful ***\n");
    return 0;
}
<|endoftext|>


<commit_before>#pragma once
#include "allocator.hpp"
#include <cstddef>
#include <iterator>
#include <limits>
#include <utility>
namespace mcpputil
{
  template <typename T>
  class vector_extrensic_allocator_t
  {
  public:
    using value_type = T;
    using index_type = ptrdiff_t;
    using difference_type = ptrdiff_t;
    using reference = T &;
    using const_reference = const T &;
    using pointer = T *;
    using const_pointer = const T *;
    using iterator = pointer;
    using const_iterator = const_pointer;
    using reverse_iterator = ::std::reverse_iterator<iterator>;
    using const_reverse_iterator = ::std::reverse_iterator<const_iterator>;

    vector_extrensic_allocator_t();
    explicit vector_extrensic_allocator_t(index_type count);
    template <class InputIt, typename Allocator>
    vector_extrensic_allocator_t(InputIt first, InputIt last, Allocator &allocator);
    template <typename Allocator>
    vector_extrensic_allocator_t(const vector_extrensic_allocator_t &other, Allocator &alloc);
    vector_extrensic_allocator_t(vector_extrensic_allocator_t &&other);
    template <typename Allocator>
    vector_extrensic_allocator_t(std::initializer_list<T> init, Allocator &alloc);

    template <typename Allocator>
    void assign(index_type count, const T &value, Allocator &allocator);
    template <class InputIt, typename Allocator>
    void assign(InputIt first, InputIt last, Allocator &allocator);
    template <typename Allocator>
    void assign(std::initializer_list<T> ilist, Allocator &allocator);
    reference at(index_type pos);
    const_reference at(index_type pos) const;
    reference operator[](index_type pos);
    const_reference operator[](index_type pos) const;
    reference front();
    const_reference front() const;
    reference back();
    const_reference back() const;
    T *data();
    const T *data() const;

    iterator begin();
    const_iterator begin() const;
    const_iterator cbegin() const;
    iterator end();
    const_iterator end() const;
    const_iterator cend() const;
    reverse_iterator rbegin();
    const_reverse_iterator rbegin() const;
    const_reverse_iterator crbegin() const;
    reverse_iterator rend();
    const_reverse_iterator rend() const;
    const_reverse_iterator crend() const;

    bool empty() const;
    index_type size() const;
    index_type max_size() const;
    template <typename Allocator>
    void reserve(index_type new_cap, Allocator &allocator);
    index_type capacity() const;
    template <typename Allocator>
    void shrink_to_fit(Allocator &allocator);

    template <typename Allocator>
    void clear(Allocator &allocator);
    template <typename Allocator>
    iterator insert(const_iterator pos, const T &value, Allocator &allocator);
    template <typename Allocator>
    iterator insert(const_iterator pos, T &&value, Allocator &allocator);
    template <typename Allocator>
    iterator insert(const_iterator pos, index_type count, const T &value, Allocator &allocator);
    template <class InputIt, typename Allocator>
    iterator insert(const_iterator pos, InputIt first, InputIt last, Allocator &allocator);
    template <typename Allocator>
    iterator insert(const_iterator pos, std::initializer_list<T> ilist, Allocator &allocator);
    template <typename Allocator, class... Args>
    iterator emplace(const_iterator pos, Args &&... args, Allocator &allocator);
    iterator erase(const_iterator pos);
    iterator erase(const_iterator first, const_iterator last);
    template <typename Allocator>
    void push_back(const T &value, Allocator &allocator);
    template <typename Allocator>
    void push_back(T &&value, Allocator &allocator);
    template <typename Allocator, class... Args>
    reference emplace_back(Allocator &allocator, Args &&... args);
    void pop_back();
    template <typename Allocator>
    void resize(index_type count, Allocator &allocator);
    template <typename Allocator>
    void resize(index_type count, const value_type &value, Allocator &allocator);
    void swap(vector_extrensic_allocator_t &other);

  private:
    pointer m_data;
    difference_type m_size;
    difference_type m_capacity;
  };
  template <typename T>
  vector_extrensic_allocator_t<T>::vector_extrensic_allocator_t() : m_data(nullptr), m_size(0), m_capacity(0)
  {
  }
  template <typename T>
  vector_extrensic_allocator_t<T>::vector_extrensic_allocator_t(index_type count) : vector_extrensic_allocator_t()
  {
    resize(count);
  }
  template <typename T>
  template <class InputIt, typename Allocator>
  vector_extrensic_allocator_t<T>::vector_extrensic_allocator_t(InputIt first, InputIt last, Allocator &allocator)
      : vector_extrensic_allocator_t()
  {
    assign(first, last, allocator);
  }
  template <typename T>
  template <typename Allocator>
  vector_extrensic_allocator_t<T>::vector_extrensic_allocator_t(const vector_extrensic_allocator_t &other, Allocator &allocator)
      : vector_extrensic_allocator_t()
  {
    assign(other.begin(), other.end(), allocator);
  }
  template <typename T>
  vector_extrensic_allocator_t<T>::vector_extrensic_allocator_t(vector_extrensic_allocator_t &&other)
      : m_data(other.m_data), m_size(other.m_size), m_capacity(other.m_capacity)
  {
    other.m_data = nullptr;
    other.m_size = 0;
    other.m_capacity = 0;
  }
  template <typename T>
  template <typename Allocator>
  vector_extrensic_allocator_t<T>::vector_extrensic_allocator_t(std::initializer_list<T> init, Allocator &allocator)
      : vector_extrensic_allocator_t()
  {
    assign(init.begin(), init.end(), allocator);
  }
  template <typename T>
  template <typename Allocator>
  void vector_extrensic_allocator_t<T>::assign(index_type count, const T &value, Allocator &allocator)
  {
    clear(allocator);
    resize(count);
    m_size = count;
    ::std::uninitialized_fill_n(m_data, count, value);
  }
  template <typename T>
  template <class InputIt, typename Allocator>
  void vector_extrensic_allocator_t<T>::assign(InputIt first, InputIt last, Allocator &allocator)
  {
    clear(allocator);
    auto it = first;
    while (it != last) {
      push_back(*it);
    }
  }
  template <typename T>
  template <typename Allocator>
  void vector_extrensic_allocator_t<T>::assign(std::initializer_list<T> ilist, Allocator &allocator)
  {
    assign(ilist.begin(), ilist.end(), allocator);
  }
  template <typename T>
  auto vector_extrensic_allocator_t<T>::at(index_type pos) -> reference
  {
    if (pos >= size())
      throw ::std::out_of_range("");
    return m_data[pos];
  }
  template <typename T>
  auto vector_extrensic_allocator_t<T>::at(index_type pos) const -> const_reference
  {
    if (pos >= size())
      throw ::std::out_of_range("");
    return m_data[pos];
  }
  template <typename T>
  auto vector_extrensic_allocator_t<T>::operator[](index_type pos) -> reference
  {
    return m_data[pos];
  }
  template <typename T>
  auto vector_extrensic_allocator_t<T>::operator[](index_type pos) const -> const_reference
  {
    return m_data[pos];
  }
  template <typename T>
  auto vector_extrensic_allocator_t<T>::front() -> reference
  {
    return m_data[0];
  }
  template <typename T>
  auto vector_extrensic_allocator_t<T>::front() const -> const_reference
  {
    return m_data[0];
  }
  template <typename T>
  auto vector_extrensic_allocator_t<T>::back() -> reference
  {
    return m_data[m_size - 1];
  }
  template <typename T>
  auto vector_extrensic_allocator_t<T>::back() const -> const_reference
  {
    return m_data[m_size - 1];
  }
  template <typename T>
  T *vector_extrensic_allocator_t<T>::data()
  {
    return m_data;
  }
  template <typename T>
  const T *vector_extrensic_allocator_t<T>::data() const
  {
    return m_data;
  }

  template <typename T>
  auto vector_extrensic_allocator_t<T>::begin() -> iterator
  {
    return m_data;
  }
  template <typename T>
  auto vector_extrensic_allocator_t<T>::begin() const -> const_iterator
  {
    return m_data;
  }
  template <typename T>
  auto vector_extrensic_allocator_t<T>::cbegin() const -> const_iterator
  {
    return m_data;
  }
  template <typename T>
  auto vector_extrensic_allocator_t<T>::end() -> iterator
  {
    return m_data + m_size;
  }
  template <typename T>
  auto vector_extrensic_allocator_t<T>::end() const -> const_iterator
  {
    return m_data + m_size;
  }
  template <typename T>
  auto vector_extrensic_allocator_t<T>::cend() const -> const_iterator
  {
    return m_data + m_size;
  }
  template <typename T>
  auto vector_extrensic_allocator_t<T>::rbegin() -> reverse_iterator
  {
    return ::std::make_reverse_iterator(end());
  }
  template <typename T>
  auto vector_extrensic_allocator_t<T>::rbegin() const -> const_reverse_iterator
  {
    return ::std::make_reverse_iterator(end());
  }
  template <typename T>
  auto vector_extrensic_allocator_t<T>::crbegin() const -> const_reverse_iterator
  {
    return ::std::make_reverse_iterator(end());
  }
  template <typename T>
  auto vector_extrensic_allocator_t<T>::rend() -> reverse_iterator
  {
    return ::std::make_reverse_iterator(begin());
  }
  template <typename T>
  auto vector_extrensic_allocator_t<T>::rend() const -> const_reverse_iterator
  {
    return ::std::make_reverse_iterator(begin());
  }
  template <typename T>
  auto vector_extrensic_allocator_t<T>::crend() const -> const_reverse_iterator
  {
    return ::std::make_reverse_iterator(begin());
  }
  template <typename T>
  bool vector_extrensic_allocator_t<T>::empty() const
  {
    return m_size == 0;
  }
  template <typename T>
  auto vector_extrensic_allocator_t<T>::size() const -> index_type
  {
    return m_size;
  }
  template <typename T>
  auto vector_extrensic_allocator_t<T>::max_size() const -> index_type
  {
    return ::std::numeric_limits<index_type>::max();
  }
  template <typename T>
  template <typename Allocator>
  void vector_extrensic_allocator_t<T>::reserve(index_type new_cap, Allocator &allocator)
  {
    if (new_cap <= m_capacity) {
      return;
    }
    auto new_pointer = ::std::allocator_traits<Allocator>::allocate(allocator, new_cap);
    move_uninitialized(begin(), end(), new_pointer);
    ::std::allocator_traits<Allocator>::deallocate(allocator, m_data, m_capacity);
    m_capacity = new_cap;
    m_data = new_pointer;
  }
  template <typename T>
  auto vector_extrensic_allocator_t<T>::capacity() const -> index_type
  {
    return m_capacity;
  }
  template <typename T>
  template <typename Allocator>
  void vector_extrensic_allocator_t<T>::shrink_to_fit(Allocator &allocator)
  {
    auto new_cap = size();
    auto new_pointer = ::std::allocator_traits<Allocator>::allocate(allocator, new_cap);
    move_uninitialized(begin(), end(), new_pointer);
    ::std::allocator_traits<Allocator>::deallocate(allocator, m_data, m_capacity);
    m_capacity = new_cap;
    m_data = new_pointer;
  }
  template <typename T>
  template <typename Allocator>
  void vector_extrensic_allocator_t<T>::clear(Allocator &allocator)
  {
    destroy(begin(), end(), allocator);
    m_size = 0;
  }
}
<commit_msg>Work on allocators and vector_extrensic_allocator(unfinished)<commit_after>#pragma once
#include "allocator.hpp"
#include <cstddef>
#include <iterator>
#include <limits>
#include <utility>
namespace mcpputil
{
  template <typename T>
  class vector_extrensic_allocator_t
  {
  public:
    using value_type = T;
    using index_type = ptrdiff_t;
    using difference_type = ptrdiff_t;
    using reference = T &;
    using const_reference = const T &;
    using pointer = T *;
    using const_pointer = const T *;
    using iterator = pointer;
    using const_iterator = const_pointer;
    using reverse_iterator = ::std::reverse_iterator<iterator>;
    using const_reverse_iterator = ::std::reverse_iterator<const_iterator>;

    vector_extrensic_allocator_t();
    explicit vector_extrensic_allocator_t(index_type count);
    template <class InputIt, typename Allocator>
    vector_extrensic_allocator_t(InputIt first, InputIt last, Allocator &allocator);
    template <typename Allocator>
    vector_extrensic_allocator_t(const vector_extrensic_allocator_t &other, Allocator &alloc);
    vector_extrensic_allocator_t(vector_extrensic_allocator_t &&other);
    template <typename Allocator>
    vector_extrensic_allocator_t(std::initializer_list<T> init, Allocator &alloc);

    template <typename Allocator>
    void assign(index_type count, const T &value, Allocator &allocator);
    template <class InputIt, typename Allocator>
    void assign(InputIt first, InputIt last, Allocator &allocator);
    template <typename Allocator>
    void assign(std::initializer_list<T> ilist, Allocator &allocator);
    reference at(index_type pos);
    const_reference at(index_type pos) const;
    reference operator[](index_type pos);
    const_reference operator[](index_type pos) const;
    reference front();
    const_reference front() const;
    reference back();
    const_reference back() const;
    T *data();
    const T *data() const;

    iterator begin();
    const_iterator begin() const;
    const_iterator cbegin() const;
    iterator end();
    const_iterator end() const;
    const_iterator cend() const;
    reverse_iterator rbegin();
    const_reverse_iterator rbegin() const;
    const_reverse_iterator crbegin() const;
    reverse_iterator rend();
    const_reverse_iterator rend() const;
    const_reverse_iterator crend() const;

    bool empty() const;
    index_type size() const;
    index_type max_size() const;
    template <typename Allocator>
    void reserve(index_type new_cap, Allocator &allocator);
    index_type capacity() const;
    template <typename Allocator>
    void shrink_to_fit(Allocator &allocator);

    template <typename Allocator>
    void clear(Allocator &allocator);
    template <typename Allocator>
    iterator insert(const_iterator pos, const T &value, Allocator &allocator);
    template <typename Allocator>
    iterator insert(const_iterator pos, T &&value, Allocator &allocator);
    template <typename Allocator>
    iterator insert(const_iterator pos, index_type count, const T &value, Allocator &allocator);
    template <class InputIt, typename Allocator>
    iterator insert(const_iterator pos, InputIt first, InputIt last, Allocator &allocator);
    template <typename Allocator>
    iterator insert(const_iterator pos, std::initializer_list<T> ilist, Allocator &allocator);
    template <typename Allocator, class... Args>
    iterator emplace(const_iterator pos, Args &&... args, Allocator &allocator);
    iterator erase(const_iterator pos);
    iterator erase(const_iterator first, const_iterator last);
    template <typename Allocator>
    void push_back(const T &value, Allocator &allocator);
    template <typename Allocator>
    void push_back(T &&value, Allocator &allocator);
    template <typename Allocator, class... Args>
    reference emplace_back(Allocator &allocator, Args &&... args);
    void pop_back();
    template <typename Allocator>
    void resize(index_type count, Allocator &allocator);
    template <typename Allocator>
    void resize(index_type count, const value_type &value, Allocator &allocator);
    void swap(vector_extrensic_allocator_t &other);

  private:
    pointer m_data;
    difference_type m_size;
    difference_type m_capacity;
  };
  template <typename T>
  vector_extrensic_allocator_t<T>::vector_extrensic_allocator_t() : m_data(nullptr), m_size(0), m_capacity(0)
  {
  }
  template <typename T>
  vector_extrensic_allocator_t<T>::vector_extrensic_allocator_t(index_type count) : vector_extrensic_allocator_t()
  {
    resize(count);
  }
  template <typename T>
  template <class InputIt, typename Allocator>
  vector_extrensic_allocator_t<T>::vector_extrensic_allocator_t(InputIt first, InputIt last, Allocator &allocator)
      : vector_extrensic_allocator_t()
  {
    assign(first, last, allocator);
  }
  template <typename T>
  template <typename Allocator>
  vector_extrensic_allocator_t<T>::vector_extrensic_allocator_t(const vector_extrensic_allocator_t &other, Allocator &allocator)
      : vector_extrensic_allocator_t()
  {
    assign(other.begin(), other.end(), allocator);
  }
  template <typename T>
  vector_extrensic_allocator_t<T>::vector_extrensic_allocator_t(vector_extrensic_allocator_t &&other)
      : m_data(other.m_data), m_size(other.m_size), m_capacity(other.m_capacity)
  {
    other.m_data = nullptr;
    other.m_size = 0;
    other.m_capacity = 0;
  }
  template <typename T>
  template <typename Allocator>
  vector_extrensic_allocator_t<T>::vector_extrensic_allocator_t(std::initializer_list<T> init, Allocator &allocator)
      : vector_extrensic_allocator_t()
  {
    assign(init.begin(), init.end(), allocator);
  }
  template <typename T>
  template <typename Allocator>
  void vector_extrensic_allocator_t<T>::assign(index_type count, const T &value, Allocator &allocator)
  {
    clear(allocator);
    resize(count);
    m_size = count;
    ::std::uninitialized_fill_n(m_data, count, value);
  }
  template <typename T>
  template <class InputIt, typename Allocator>
  void vector_extrensic_allocator_t<T>::assign(InputIt first, InputIt last, Allocator &allocator)
  {
    clear(allocator);
    auto it = first;
    while (it != last) {
      push_back(*it);
    }
  }
  template <typename T>
  template <typename Allocator>
  void vector_extrensic_allocator_t<T>::assign(std::initializer_list<T> ilist, Allocator &allocator)
  {
    assign(ilist.begin(), ilist.end(), allocator);
  }
  template <typename T>
  auto vector_extrensic_allocator_t<T>::at(index_type pos) -> reference
  {
    if (pos >= size())
      throw ::std::out_of_range("");
    return m_data[pos];
  }
  template <typename T>
  auto vector_extrensic_allocator_t<T>::at(index_type pos) const -> const_reference
  {
    if (pos >= size())
      throw ::std::out_of_range("");
    return m_data[pos];
  }
  template <typename T>
  auto vector_extrensic_allocator_t<T>::operator[](index_type pos) -> reference
  {
    return m_data[pos];
  }
  template <typename T>
  auto vector_extrensic_allocator_t<T>::operator[](index_type pos) const -> const_reference
  {
    return m_data[pos];
  }
  template <typename T>
  auto vector_extrensic_allocator_t<T>::front() -> reference
  {
    return m_data[0];
  }
  template <typename T>
  auto vector_extrensic_allocator_t<T>::front() const -> const_reference
  {
    return m_data[0];
  }
  template <typename T>
  auto vector_extrensic_allocator_t<T>::back() -> reference
  {
    return m_data[m_size - 1];
  }
  template <typename T>
  auto vector_extrensic_allocator_t<T>::back() const -> const_reference
  {
    return m_data[m_size - 1];
  }
  template <typename T>
  T *vector_extrensic_allocator_t<T>::data()
  {
    return m_data;
  }
  template <typename T>
  const T *vector_extrensic_allocator_t<T>::data() const
  {
    return m_data;
  }

  template <typename T>
  auto vector_extrensic_allocator_t<T>::begin() -> iterator
  {
    return m_data;
  }
  template <typename T>
  auto vector_extrensic_allocator_t<T>::begin() const -> const_iterator
  {
    return m_data;
  }
  template <typename T>
  auto vector_extrensic_allocator_t<T>::cbegin() const -> const_iterator
  {
    return m_data;
  }
  template <typename T>
  auto vector_extrensic_allocator_t<T>::end() -> iterator
  {
    return m_data + m_size;
  }
  template <typename T>
  auto vector_extrensic_allocator_t<T>::end() const -> const_iterator
  {
    return m_data + m_size;
  }
  template <typename T>
  auto vector_extrensic_allocator_t<T>::cend() const -> const_iterator
  {
    return m_data + m_size;
  }
  template <typename T>
  auto vector_extrensic_allocator_t<T>::rbegin() -> reverse_iterator
  {
    return ::std::make_reverse_iterator(end());
  }
  template <typename T>
  auto vector_extrensic_allocator_t<T>::rbegin() const -> const_reverse_iterator
  {
    return ::std::make_reverse_iterator(end());
  }
  template <typename T>
  auto vector_extrensic_allocator_t<T>::crbegin() const -> const_reverse_iterator
  {
    return ::std::make_reverse_iterator(end());
  }
  template <typename T>
  auto vector_extrensic_allocator_t<T>::rend() -> reverse_iterator
  {
    return ::std::make_reverse_iterator(begin());
  }
  template <typename T>
  auto vector_extrensic_allocator_t<T>::rend() const -> const_reverse_iterator
  {
    return ::std::make_reverse_iterator(begin());
  }
  template <typename T>
  auto vector_extrensic_allocator_t<T>::crend() const -> const_reverse_iterator
  {
    return ::std::make_reverse_iterator(begin());
  }
  template <typename T>
  bool vector_extrensic_allocator_t<T>::empty() const
  {
    return m_size == 0;
  }
  template <typename T>
  auto vector_extrensic_allocator_t<T>::size() const -> index_type
  {
    return m_size;
  }
  template <typename T>
  auto vector_extrensic_allocator_t<T>::max_size() const -> index_type
  {
    return ::std::numeric_limits<index_type>::max();
  }
  template <typename T>
  template <typename Allocator>
  void vector_extrensic_allocator_t<T>::reserve(index_type new_cap, Allocator &allocator)
  {
    if (new_cap <= m_capacity) {
      return;
    }
    auto new_pointer = ::std::allocator_traits<Allocator>::allocate(allocator, new_cap);
    move_uninitialized(begin(), end(), new_pointer);
    ::std::allocator_traits<Allocator>::deallocate(allocator, m_data, m_capacity);
    m_capacity = new_cap;
    m_data = new_pointer;
  }
  template <typename T>
  auto vector_extrensic_allocator_t<T>::capacity() const -> index_type
  {
    return m_capacity;
  }
  template <typename T>
  template <typename Allocator>
  void vector_extrensic_allocator_t<T>::shrink_to_fit(Allocator &allocator)
  {
    auto new_cap = size();
    auto new_pointer = ::std::allocator_traits<Allocator>::allocate(allocator, new_cap);
    move_uninitialized(begin(), end(), new_pointer);
    ::std::allocator_traits<Allocator>::deallocate(allocator, m_data, m_capacity);
    m_capacity = new_cap;
    m_data = new_pointer;
  }
  template <typename T>
  template <typename Allocator>
  void vector_extrensic_allocator_t<T>::clear(Allocator &allocator)
  {
    destroy(begin(), end(), allocator);
    m_size = 0;
  }
  template <typename T>
  template <typename Allocator>
  auto vector_extrensic_allocator_t<T>::insert(const_iterator pos, const T &value, Allocator &allocator) -> iterator
  {
  }
  template <typename T>
  template <typename Allocator>
  auto vector_extrensic_allocator_t<T>::insert(const_iterator pos, T &&value, Allocator &allocator) -> iterator
  {
  }
  template <typename T>
  template <typename Allocator>
  auto vector_extrensic_allocator_t<T>::insert(const_iterator pos, index_type count, const T &value, Allocator &allocator)
      -> iterator
  {
  }
  template <typename T>
  template <class InputIt, typename Allocator>
  auto vector_extrensic_allocator_t<T>::insert(const_iterator pos, InputIt first, InputIt last, Allocator &allocator) -> iterator
  {
  }
  template <typename T>
  template <typename Allocator>
  auto vector_extrensic_allocator_t<T>::insert(const_iterator pos, std::initializer_list<T> ilist, Allocator &allocator)
      -> iterator
  {
  }
  template <typename T>
  template <typename Allocator, class... Args>
  auto vector_extrensic_allocator_t<T>::emplace(const_iterator pos, Args &&... args, Allocator &allocator) -> iterator
  {
  }
  template <typename T>
  auto vector_extrensic_allocator_t<T>::erase(const_iterator pos) -> iterator
  {
  }
  template <typename T>
  auto vector_extrensic_allocator_t<T>::erase(const_iterator first, const_iterator last) -> iterator
  {
  }
  template <typename T>
  template <typename Allocator>
  void vector_extrensic_allocator_t<T>::push_back(const T &value, Allocator &allocator)
  {
  }
  template <typename T>
  template <typename Allocator>
  void vector_extrensic_allocator_t<T>::push_back(T &&value, Allocator &allocator)
  {
  }
  template <typename T>
  template <typename Allocator, class... Args>
  auto vector_extrensic_allocator_t<T>::emplace_back(Allocator &allocator, Args &&... args) -> reference
  {
  }
  template <typename T>
  void vector_extrensic_allocator_t<T>::pop_back()
  {
    --m_size;
  }
  template <typename T>
  template <typename Allocator>
  void vector_extrensic_allocator_t<T>::resize(index_type count, Allocator &allocator)
  {
  }
  template <typename T>
  template <typename Allocator>
  void vector_extrensic_allocator_t<T>::resize(index_type count, const value_type &value, Allocator &allocator)
  {
  }
  template <typename T>
  void vector_extrensic_allocator_t<T>::swap(vector_extrensic_allocator_t &other)
  {
    using ::std::swap;
    swap(m_data, other.m_data);
    swap(m_size, other.m_size);
    swap(m_capacity, other.m_capacity);
  }
}
<|endoftext|>


<commit_before>#include <CoinCore/secp256k1.h>
#include <stdutils/uchar_vector.h>

#include <iostream>

#include <string>

using namespace CoinCrypto;
using namespace std;

int main(int argc, char* argv[])
{
    if (argc < 2)
    {
        cerr << "# usage: " << argv[0] << " <hex data to sign>" << endl;
        return -1;
    }

    try
    {
        uchar_vector data(argv[1]);
        cout << "Using data " << data.getHex() << endl;

        cout << "Creating new key..." << flush;
        secp256k1_key key;
        key.newKey();
        cout << "done." << endl;
    }
    catch (const exception& e)
    {
        cerr << "Error: " << e.what() << endl;
        return -2;
    }

    return 0;
}
<commit_msg>Added verification test to secp256k1_test.<commit_after>#include <CoinCore/secp256k1.h>
#include <stdutils/uchar_vector.h>

#include <iostream>

#include <string>

using namespace CoinCrypto;
using namespace std;

int main(int argc, char* argv[])
{
    if (argc < 2)
    {
        cerr << "# usage: " << argv[0] << " <hex data to sign>" << endl;
        return -1;
    }

    try
    {
        uchar_vector data(argv[1]);
        cout << "Using data " << data.getHex() << endl;

        cout << endl << "Creating new key..." << flush;
        secp256k1_key key;
        key.newKey();
        cout << "done." << endl;

        uchar_vector privkey = key.getPrivKey();
        cout << "Private key: " << privkey.getHex() << endl;

        uchar_vector pubkey = key.getPubKey();
        cout << "Public key: " << pubkey.getHex() << endl;

        cout << endl << "Signing data..." << flush;
        uchar_vector sig = secp256k1_sign(key, data);
        cout << "done." << endl;
        cout << "Signature: " << sig.getHex() << endl;

        cout << endl << "Verifying signature (should be valid)..." << flush;
        if (secp256k1_verify(key, data, sig))  { cout << "valid." << endl; }
        else                                    { cout << "invalid." << endl; }

        cout << endl << "Creating public key object..." << flush;
        secp256k1_key key2;
        key2.setPubKey(pubkey);
        cout << "done." << endl;

        try
        {
            cout << "Trying to get private key (should fail)..." << flush;
            privkey = key2.getPrivKey();
            cout << "done." << endl;
            cout << "Private key: " << privkey.getHex() << endl;
        }
        catch (const exception& e)
        {
            cout << "failed - " << e.what() << endl;
        }

        pubkey = key2.getPubKey();
        cout << "Public key: " << pubkey.getHex() << endl;

        cout << endl << "Verifying signature (should be valid)..." << flush;
        if (secp256k1_verify(key2, data, sig))  { cout << "valid." << endl; }
        else                                    { cout << "invalid." << endl; }

        cout << endl << "Creating new key..." << flush;
        key.newKey();
        cout << "done." << endl;

        privkey = key.getPrivKey();
        cout << "Private key: " << privkey.getHex() << endl;

        pubkey = key.getPubKey();
        cout << "Public key: " << pubkey.getHex() << endl;

        cout << endl << "Verifying old signature with new key (should be invalid)..." << flush;
        if (secp256k1_verify(key, data, sig))   { cout << "valid." << endl; }
        else                                    { cout << "invalid." << endl; }
    }
    catch (const exception& e)
    {
        cerr << "Error: " << e.what() << endl;
        return -2;
    }

    return 0;
}
<|endoftext|>


<commit_before>#include "../include/obj.hpp"

bool AIplayer::tankCollision_(int side, int id) {
	FloatRect	tempRect	= Tank::getRect();

	switch (side) {
		case LEFT_SIDE:		tempRect.left--;	break;
		case RIGHT_SIDE:	tempRect.left++;	break;
		case UP_SIDE:		tempRect.top--;		break;
		case DOWN_SIDE:		tempRect.top++;		break;
	}

	Tank::setSide(side);

	for (int	i	= 0; i < nAIPlayers_; i++)	// Столкновение с другом
		if ((AIplayers_tanks_[i].getLife() > 0) && (id != AIplayers_tanks_[i].getID()) && (tempRect.intersects(AIplayers_tanks_[i].getRect())))
			return true;

	for (int	i	= 0; i < nPlayers_; i++)	// Столкновение с врагом
		if ((players_tanks_[i].getLife() > 0) && (tempRect.intersects(players_tanks_[i].getRect())))
			return true;

	return false;
}

void AIplayer::bulletCollision_() {
	for (int	i	= 0; i < nAIPlayers_; i++)	// Обработка столкновений пули с другом
		if ((AIplayers_tanks_[i].getLife() > 0) && ((i + 1) != Tank::getID()) && (Tank::bulletComparsion(AIplayers_tanks_[i].getRect())))
			Tank::bulletDestroy();

	for (int	i	= 0; i < nPlayers_; i++)	// Обработка столкновений пули с пулей противника
		if ((players_tanks_[i].getLife() > 0) && (players_tanks_[i].bulletStatus()) && (Tank::bulletComparsion(players_tanks_[i].getBulletRect())))
		{
			players_tanks_[i].bulletDestroy();
			Tank::bulletDestroy();
		}

	for (int	i	= 0; i < nPlayers_; i++)	// Обработка столкновений пули с врагом
		if ((players_tanks_[i].getLife() > 0) && (Tank::bulletComparsion(players_tanks_[i].getRect())))
		{
			Tank::bulletDestroy();
			players_tanks_[i].bax_bax();

			if ((i + 1) == 1)
				Tank::r_b->setP1Life(Tank::r_b->getP1Life() - 1);
			else
				Tank::r_b->setP2Life(Tank::r_b->getP2Life() - 1);
		}
}

void AIplayer::init(Texture &image, Player *players, int intNPlayer, AIplayer *l_frends, int intNAIplayer, GameMap *l_main_map, RightBar *l_r_b, int l_life, int l_type, int l_id) {
	Tank::init(image, l_main_map, l_r_b);
	Tank::setLife(0);
	Tank::setID(l_id);

	main_map_		= l_main_map;
	type_			= l_type;
	AIplayers_tanks_	= l_frends;
	nAIPlayers_		= intNAIplayer;
	players_tanks_	= players;
	nPlayers_		= intNPlayer;
	currentSide_		= 8;
}

int abs(int x){
	if (x<0)
		return x*(-1);
	else
		return x;
}

bool AIplayer::checkWallX_(int x, int x2, int y) {
	bool	noWall			= true;
	int 	temp;
	if (x2<x)
	{
		temp = x2;
		x2 = x;
		x = temp;
	}
	for (int k = 0; k < x2-x; ++k)
	{
		temp = main_map_->getElement(x+k, y);
		if ((temp != 's') && (temp != 'v') && (temp != 'i'))
		{
			noWall = false;
			break;
		}
	}
	return noWall;

}
bool AIplayer::checkWallY_(int y, int y2, int x) {
	bool	noWall			= true;
	int 	temp;
	if (y2<y)
	{
		temp = y2;
		y2 = x;
		y = temp;
	}
	for (int k = 0; k < y2-y; ++k)
	{
		temp = main_map_->getElement(x, y+k);
		if ((temp != 's') && (temp != 'v') && (temp != 'i'))
		{
			noWall = false;
			break;
		}
	}
	return noWall;

}

void AIplayer::update(float time) {
	bool 	canMove			= false;

	char	temp;
	int 	tankTop			= Tank::getRect().top;
	int 	tankLeft		= Tank::getRect().left;
	if (Tank::getLife()>0)
	{
		if (currentSide_ == 8)
		{
			currentSide_ = (rand()%4)*2;
		}

		for (int	i	= 0; i < nPlayers_; i++)	{
			if(abs(tankLeft - players_tanks_[i].getRect().left) < 16 and players_tanks_[i].getLife()>0)	// танк на вертикальной линии с игроком
			{
				if(AIplayer::checkWallY_(tankTop/16, players_tanks_[i].getRect().top/16, (tankLeft)/16))
				{
					if(tankTop < players_tanks_[i].getRect().top)
					{
						if (currentSide_ == UP_SIDE){ //сверху игрок, танк едет туда же, между ними нет стен
							Tank::piu_piu();
						}
						else if (currentSide_ == RIGHT_SIDE or currentSide_ == LEFT_SIDE)
						{
							currentSide_ = UP_SIDE;
						}
					}

					if(tankTop < players_tanks_[i].getRect().top)	//снизу игрок, танк едет туда же, между ними нет стен
					{
						if (currentSide_ == DOWN_SIDE)
						{
							Tank::piu_piu();
						}
						else if (currentSide_ == RIGHT_SIDE or currentSide_ == LEFT_SIDE)
						{
							currentSide_ = DOWN_SIDE;
						}
					}
				}
			}

			if(abs(tankTop - players_tanks_[i].getRect().top)<16 and players_tanks_[i].getLife()>0)	// танк на горизонтальной линии с игроком
			{
				if(AIplayer::checkWallY_(tankLeft/16, players_tanks_[i].getRect().left/16, (tankTop)/16))
				{
					if(tankLeft > players_tanks_[i].getRect().left)
					{
						if (currentSide_ == LEFT_SIDE)	//слева игрок, танк едет туда же, между ними нет стен
						{
							Tank::piu_piu();
						}
						else if (currentSide_ == UP_SIDE or currentSide_ == DOWN_SIDE)
						{
							currentSide_ = LEFT_SIDE;
						}
					}

					if(tankLeft < players_tanks_[i].getRect().left)
					{
						if (currentSide_ == RIGHT_SIDE)	//справа игрок, танк едет туда же, между ними нет стен
						{
							Tank::piu_piu();
						}
						else if (currentSide_ == UP_SIDE or currentSide_ == DOWN_SIDE)
						{
							currentSide_ = RIGHT_SIDE;
						}
					}
				}
			}
		}

		if (not Tank::move(currentSide_)) //если в сторону, в которую хотим ехать, нельзя проехать
		{
			for (int i = 0; i < 4; ++i)
			{
				if (!AIplayer::tankCollision_(i*2, Tank::getID()))
				{
					canMove = Tank::move(i*2) || canMove;
				}
			}

			if (!canMove)
			{
				currentSide_ = (rand()%4)*2;
				Tank::move(currentSide_);
				Tank::piu_piu();
			}
			else
			{
				currentSide_ = (rand()%4)*2;
			}
		}
		if ((rand()%500) == 0) // с шансом ~3% стреляет просто так
		{
			Tank::piu_piu();
		}

		if (!AIplayer::tankCollision_(currentSide_, Tank::getID()))
		{
		Tank::move(currentSide_);
		}
		Tank::update(time);
	}

	if (Tank::bulletStatus())
		bulletCollision_();
}

void AIplayer::activation(unsigned int x, unsigned int y) {
	if (Tank::r_b->getEminems() > 0)
	{
		Tank::setLife(3);
		nAIPlayers_--;
		startPosition_.left = x;
		startPosition_.top = y;
		Tank::setPosition(x, y, DOWN_SIDE);
	}
}

void AIplayer::bax_bax() {
	if (Tank::getLife() > 0) {
		Tank::setLife(Tank::getLife() - 1);
		if (Tank::getLife() == 0) {
			Tank::r_b->setEminems(Tank::r_b->getEminems() - 1);
			AIplayer::activation(startPosition_.left, startPosition_.top);
		}
	}
}

void AIplayer::draw(RenderWindow &window) {
	if (Tank::getLife()!=0)
	{
		Tank::draw(window);
	}
}
<commit_msg>Fix sex with tank<commit_after>#include "../include/obj.hpp"

bool AIplayer::tankCollision_(int side, int id) {
	FloatRect	tempRect	= Tank::getRect();

	switch (side) {
		case LEFT_SIDE:		tempRect.left--;	break;
		case RIGHT_SIDE:	tempRect.left++;	break;
		case UP_SIDE:		tempRect.top--;		break;
		case DOWN_SIDE:		tempRect.top++;		break;
	}

	for (int	i	= 0; i < nAIPlayers_; i++)	// Столкновение с другом
		if ((AIplayers_tanks_[i].getLife() > 0) && (id != AIplayers_tanks_[i].getID()) && (tempRect.intersects(AIplayers_tanks_[i].getRect())))
			return true;

	for (int	i	= 0; i < nPlayers_; i++)	// Столкновение с врагом
		if ((players_tanks_[i].getLife() > 0) && (tempRect.intersects(players_tanks_[i].getRect())))
			return true;

	return false;
}

void AIplayer::bulletCollision_() {
	for (int	i	= 0; i < nAIPlayers_; i++)	// Обработка столкновений пули с другом
		if ((AIplayers_tanks_[i].getLife() > 0) && ((i + 1) != Tank::getID()) && (Tank::bulletComparsion(AIplayers_tanks_[i].getRect())))
			Tank::bulletDestroy();

	for (int	i	= 0; i < nPlayers_; i++)	// Обработка столкновений пули с пулей противника
		if ((players_tanks_[i].getLife() > 0) && (players_tanks_[i].bulletStatus()) && (Tank::bulletComparsion(players_tanks_[i].getBulletRect())))
		{
			players_tanks_[i].bulletDestroy();
			Tank::bulletDestroy();
		}

	for (int	i	= 0; i < nPlayers_; i++)	// Обработка столкновений пули с врагом
		if ((players_tanks_[i].getLife() > 0) && (Tank::bulletComparsion(players_tanks_[i].getRect())))
		{
			Tank::bulletDestroy();
			players_tanks_[i].bax_bax();

			if ((i + 1) == 1)
				Tank::r_b->setP1Life(Tank::r_b->getP1Life() - 1);
			else
				Tank::r_b->setP2Life(Tank::r_b->getP2Life() - 1);
		}
}

void AIplayer::init(Texture &image, Player *players, int intNPlayer, AIplayer *l_frends, int intNAIplayer, GameMap *l_main_map, RightBar *l_r_b, int l_life, int l_type, int l_id) {
	Tank::init(image, l_main_map, l_r_b);
	Tank::setLife(0);
	Tank::setID(l_id);

	main_map_		= l_main_map;
	type_			= l_type;
	AIplayers_tanks_	= l_frends;
	nAIPlayers_		= intNAIplayer;
	players_tanks_	= players;
	nPlayers_		= intNPlayer;
	currentSide_		= 8;
}

int abs(int x){
	if (x<0)
		return x*(-1);
	else
		return x;
}

bool AIplayer::checkWallX_(int x, int x2, int y) {
	bool	noWall			= true;
	int 	temp;
	if (x2<x)
	{
		temp = x2;
		x2 = x;
		x = temp;
	}
	for (int k = 0; k < x2-x; ++k)
	{
		temp = main_map_->getElement(x+k, y);
		if ((temp != 's') && (temp != 'v') && (temp != 'i'))
		{
			noWall = false;
			break;
		}
	}
	return noWall;

}
bool AIplayer::checkWallY_(int y, int y2, int x) {
	bool	noWall			= true;
	int 	temp;
	if (y2<y)
	{
		temp = y2;
		y2 = x;
		y = temp;
	}
	for (int k = 0; k < y2-y; ++k)
	{
		temp = main_map_->getElement(x, y+k);
		if ((temp != 's') && (temp != 'v') && (temp != 'i'))
		{
			noWall = false;
			break;
		}
	}
	return noWall;

}

void AIplayer::update(float time) {
	bool 	canMove		= false;

	char	temp;

	int 	tankTop		= Tank::getRect().top,
			tankLeft	= Tank::getRect().left;

	if (Tank::getLife() > 0)
	{
		if (currentSide_ == 8)
		{
			currentSide_ = (rand()%4)*2;
		}

		for (int	i	= 0; i < nPlayers_; i++)	{
			if(abs(tankLeft - players_tanks_[i].getRect().left) < 16 and players_tanks_[i].getLife()>0)	// танк на вертикальной линии с игроком
			{
				if(AIplayer::checkWallY_(tankTop/16, players_tanks_[i].getRect().top/16, (tankLeft)/16))
				{
					if(tankTop < players_tanks_[i].getRect().top)
					{
						if (currentSide_ == UP_SIDE){ //сверху игрок, танк едет туда же, между ними нет стен
							Tank::piu_piu();
						}
						else if (currentSide_ == RIGHT_SIDE or currentSide_ == LEFT_SIDE)
						{
							currentSide_ = UP_SIDE;
						}
					}

					if(tankTop < players_tanks_[i].getRect().top)	//снизу игрок, танк едет туда же, между ними нет стен
					{
						if (currentSide_ == DOWN_SIDE)
						{
							Tank::piu_piu();
						}
						else if (currentSide_ == RIGHT_SIDE or currentSide_ == LEFT_SIDE)
						{
							currentSide_ = DOWN_SIDE;
						}
					}
				}
			}

			if(abs(tankTop - players_tanks_[i].getRect().top)<16 and players_tanks_[i].getLife()>0)	// танк на горизонтальной линии с игроком
			{
				if(AIplayer::checkWallY_(tankLeft/16, players_tanks_[i].getRect().left/16, (tankTop)/16))
				{
					if(tankLeft > players_tanks_[i].getRect().left)
					{
						if (currentSide_ == LEFT_SIDE)	//слева игрок, танк едет туда же, между ними нет стен
						{
							Tank::piu_piu();
						}
						else if (currentSide_ == UP_SIDE or currentSide_ == DOWN_SIDE)
						{
							currentSide_ = LEFT_SIDE;
						}
					}

					if(tankLeft < players_tanks_[i].getRect().left)
					{
						if (currentSide_ == RIGHT_SIDE)	//справа игрок, танк едет туда же, между ними нет стен
						{
							Tank::piu_piu();
						}
						else if (currentSide_ == UP_SIDE or currentSide_ == DOWN_SIDE)
						{
							currentSide_ = RIGHT_SIDE;
						}
					}
				}
			}
		}

		if ((!Tank::move(currentSide_)) || (AIplayer::tankCollision_(currentSide_, Tank::getID()))) //если в сторону, в которую хотим ехать, нельзя проехать
		{
			for (int i = 0; i < 4; ++i)
			{
				if (!AIplayer::tankCollision_(i*2, Tank::getID()))
				{
					canMove = Tank::move(i*2) || canMove;
				}
			}

			if (!canMove)
			{
				currentSide_ = (rand()%4)*2;
				Tank::move(currentSide_);
				Tank::piu_piu();
			}
			else
			{
				currentSide_ = (rand()%4)*2;
			}
		}

		if ((rand()%500) == 0) // с шансом ~3% стреляет просто так
		{
			Tank::piu_piu();
		}

		if (!AIplayer::tankCollision_(currentSide_, Tank::getID()))
		{
			Tank::move(currentSide_);
		}

		Tank::update(time);
	}

	if (Tank::bulletStatus())
		bulletCollision_();
}

void AIplayer::activation(unsigned int x, unsigned int y) {
	if (Tank::r_b->getEminems() > 0)
	{
		Tank::setLife(3);
		nAIPlayers_--;
		startPosition_.left = x;
		startPosition_.top = y;
		Tank::setPosition(x, y, DOWN_SIDE);
	}
}

void AIplayer::bax_bax() {
	if (Tank::getLife() > 0) {
		Tank::setLife(Tank::getLife() - 1);
		if (Tank::getLife() == 0) {
			Tank::r_b->setEminems(Tank::r_b->getEminems() - 1);
			AIplayer::activation(startPosition_.left, startPosition_.top);
		}
	}
}

void AIplayer::draw(RenderWindow &window) {
	if (Tank::getLife()!=0)
	{
		Tank::draw(window);
	}
}
<|endoftext|>


<commit_before>// Copyright (c) 2021 by Apex.AI Inc. All rights reserved.
//
// 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.
//
// SPDX-License-Identifier: Apache-2.0

#include "iceoryx_posh/popo/listener.hpp"
#include "iceoryx_posh/popo/publisher.hpp"
#include "iceoryx_posh/popo/subscriber.hpp"
#include "iceoryx_posh/popo/untyped_subscriber.hpp"
#include "iceoryx_posh/testing/roudi_gtest.hpp"

#include "test.hpp"

using namespace ::testing;
using ::testing::Return;

using namespace iox::popo;
using namespace iox::capro;
using namespace iox::runtime;

namespace
{
void onSampleReceivedCallback(Subscriber<int>* subscriber IOX_MAYBE_UNUSED)
{
}

void onSampleReceivedCallbackForUntypedSub(UntypedSubscriber* subscriber IOX_MAYBE_UNUSED)
{
}

class PubSubListener_IntegrationTest : public RouDi_GTest
{
  public:
    void SetUp() override
    {
        PoshRuntime::initRuntime("PubSubListener_IntegrationTest");
        m_listener = std::make_unique<Listener>();
        m_subscriber = std::make_unique<Subscriber<int>>(m_serviceDescr);
        m_untypedSubscriber = std::make_unique<UntypedSubscriber>(m_serviceDescr);
    }
    void TearDown() override
    {
    }

    ServiceDescription m_serviceDescr{"Radar", "FrontLeft", "Counter"};
    std::unique_ptr<Listener> m_listener;
    std::unique_ptr<Subscriber<int>> m_subscriber;
    std::unique_ptr<UntypedSubscriber> m_untypedSubscriber;
};
} // namespace

/// @note Here we test that the trigger reset methods are called correctly in the d'tor of SubscriberImpl. They must not
/// be called in the BaseSubscriber d'tor since the SubscriberImpl was attached to the Listener. When it goes out of
/// scope, the trigger tries to access it but SubscriberImpl does not longer exist. This is caught by the
/// UndefinedBehaviorSanitizer.
TEST_F(PubSubListener_IntegrationTest, SubscriberGoesOutOfScopeAndDetachingWorks)
{
    m_listener
        ->attachEvent(*m_subscriber,
                      iox::popo::SubscriberEvent::DATA_RECEIVED,
                      iox::popo::createEventCallback(onSampleReceivedCallback))
        .or_else([](auto) { ASSERT_TRUE(false); });

    m_subscriber.reset();
}

/// @note Here we test that the trigger reset methods are called correctly in the d'tor of UntypedSubscriberImpl. They
/// must not be called in the BaseSubscriber d'tor since the UntypedSubscriberImpl was attached to the Listener. When it
/// goes out of scope, the trigger tries to access it but UntypedSubscriberImpl does not longer exist. This is caught
/// by the UndefinedBehaviorSanitizer.
TEST_F(PubSubListener_IntegrationTest, UntypedSubscriberGoesOutOfScopeAndDetachingWorks)
{
    m_listener
        ->attachEvent(*m_untypedSubscriber,
                      iox::popo::SubscriberEvent::DATA_RECEIVED,
                      iox::popo::createEventCallback(onSampleReceivedCallbackForUntypedSub))
        .or_else([](auto) { ASSERT_TRUE(false); });

    m_untypedSubscriber.reset();
}

<commit_msg>iox-#350 renamed createEventCallback into createNotificationCallback for pub sub integration test<commit_after>// Copyright (c) 2021 by Apex.AI Inc. All rights reserved.
//
// 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.
//
// SPDX-License-Identifier: Apache-2.0

#include "iceoryx_posh/popo/listener.hpp"
#include "iceoryx_posh/popo/publisher.hpp"
#include "iceoryx_posh/popo/subscriber.hpp"
#include "iceoryx_posh/popo/untyped_subscriber.hpp"
#include "iceoryx_posh/testing/roudi_gtest.hpp"

#include "test.hpp"

using namespace ::testing;
using ::testing::Return;

using namespace iox::popo;
using namespace iox::capro;
using namespace iox::runtime;

namespace
{
void onSampleReceivedCallback(Subscriber<int>* subscriber IOX_MAYBE_UNUSED)
{
}

void onSampleReceivedCallbackForUntypedSub(UntypedSubscriber* subscriber IOX_MAYBE_UNUSED)
{
}

class PubSubListener_IntegrationTest : public RouDi_GTest
{
  public:
    void SetUp() override
    {
        PoshRuntime::initRuntime("PubSubListener_IntegrationTest");
        m_listener = std::make_unique<Listener>();
        m_subscriber = std::make_unique<Subscriber<int>>(m_serviceDescr);
        m_untypedSubscriber = std::make_unique<UntypedSubscriber>(m_serviceDescr);
    }
    void TearDown() override
    {
    }

    ServiceDescription m_serviceDescr{"Radar", "FrontLeft", "Counter"};
    std::unique_ptr<Listener> m_listener;
    std::unique_ptr<Subscriber<int>> m_subscriber;
    std::unique_ptr<UntypedSubscriber> m_untypedSubscriber;
};
} // namespace

/// @note Here we test that the trigger reset methods are called correctly in the d'tor of SubscriberImpl. They must not
/// be called in the BaseSubscriber d'tor since the SubscriberImpl was attached to the Listener. When it goes out of
/// scope, the trigger tries to access it but SubscriberImpl does not longer exist. This is caught by the
/// UndefinedBehaviorSanitizer.
TEST_F(PubSubListener_IntegrationTest, SubscriberGoesOutOfScopeAndDetachingWorks)
{
    m_listener
        ->attachEvent(*m_subscriber,
                      iox::popo::SubscriberEvent::DATA_RECEIVED,
                      iox::popo::createNotificationCallback(onSampleReceivedCallback))
        .or_else([](auto) { ASSERT_TRUE(false); });

    m_subscriber.reset();
}

/// @note Here we test that the trigger reset methods are called correctly in the d'tor of UntypedSubscriberImpl. They
/// must not be called in the BaseSubscriber d'tor since the UntypedSubscriberImpl was attached to the Listener. When it
/// goes out of scope, the trigger tries to access it but UntypedSubscriberImpl does not longer exist. This is caught
/// by the UndefinedBehaviorSanitizer.
TEST_F(PubSubListener_IntegrationTest, UntypedSubscriberGoesOutOfScopeAndDetachingWorks)
{
    m_listener
        ->attachEvent(*m_untypedSubscriber,
                      iox::popo::SubscriberEvent::DATA_RECEIVED,
                      iox::popo::createNotificationCallback(onSampleReceivedCallbackForUntypedSub))
        .or_else([](auto) { ASSERT_TRUE(false); });

    m_untypedSubscriber.reset();
}

<|endoftext|>


<commit_before>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Justin Madsen
// =============================================================================
//
// model a single track chain system, as part of a tracked vehicle.
// Static variable values are based on a M113 model in the report by Shabana
//
// =============================================================================

#include <cstdio>

#include "subsys/suspension/TorsionArmSuspension.h"

#include "assets/ChCylinderShape.h"
#include "assets/ChTriangleMeshShape.h"
#include "assets/ChTexture.h"
#include "assets/ChColorAsset.h"

namespace chrono {

// static variables
const double TorsionArmSuspension::m_armMass = 75.26; // [kg]
const ChVector<> TorsionArmSuspension::m_armInertia(0.77, 0.37, 0.77);  // [kg-m2]
const double TorsionArmSuspension::m_armRadius = 0.1; // [m]

const double TorsionArmSuspension::m_wheelMass = 561.1; // [kg]
const ChVector<> TorsionArmSuspension::m_wheelInertia(19.82, 19.82, 26.06); // [kg-m2]
const double TorsionArmSuspension::m_wheelWidth = 0.16;  // [m]
const double TorsionArmSuspension::m_wheelWidthGap = 0.03;  // inner gap between outer cylinders .038?
const double TorsionArmSuspension::m_wheelRadius = 0.305; // [m]
const ChVector<> TorsionArmSuspension::m_wheel_Pos(-0.2034, -0.2271, 0.24475); // loc of right wheel COG in the local c-sys
const double TorsionArmSuspension::m_springK = 10000;	// torsional spring constant [N-m/rad]
const double TorsionArmSuspension::m_springC = 100;	// torsional damping constant [N-m-s/rad]
const double TorsionArmSuspension::m_TorquePreload = 10.0;  // torque preload [N-m]

TorsionArmSuspension::TorsionArmSuspension(const std::string& name,
                                           VisualizationType vis,
                                           CollisionType collide,
                                           bool use_custom_spring)
: m_vis(vis), m_collide(collide), m_use_custom_spring(use_custom_spring)
{
  // FILE* fp = fopen(filename.c_str(), "r");
  // char readBuffer[65536];
  // fclose(fp);

  Create(name);
}

// 1) load data from file, 2) create bodies using data
void TorsionArmSuspension::Create(const std::string& name)
{
/*
  // load data for the arm
  m_armMass = d["Arm"]["Mass"].GetDouble();
  m_armInertia = loadVector(d["Arm"]["Inertia"]);
  m_armRadius = d["Arm"]["Radius"].GetDouble();

  // load data for the wheel
  m_wheelMass = d["Wheel"]["Mass"].GetDouble();
  m_wheelInertia = loadVector(d["Wheel"]["Inertia"]);
  m_wheelRadius = d["Wheel"]["Radius"].GetDouble();
  m_wheelWidth = d["Wheel"]["Width"].GetDouble();
  m_wheelRelLoc = loadVector(d["Wheel"]["Location"]);

  // load data for the torsion bar
  m_springK = d["Torsion Bar"]["Stiffness"].GetDouble();
  m_springC = d["Torsion Bar"]["Damping"].GetDouble();

  */

  // create the suspension arm body
  m_arm = ChSharedPtr<ChBody>(new ChBody);
  m_arm->SetNameString(name + "_arm");
  m_arm->SetMass(m_armMass);
  m_arm->SetInertiaXX(m_armInertia);  // link distance along y-axis
  // create the roadwheel body
  m_wheel = ChSharedPtr<ChBody>(new ChBody);
  m_wheel->SetNameString(name + "_roadWheel");
  m_wheel->SetMass(m_wheelMass);
  m_wheel->SetInertiaXX(m_wheelInertia);  // wheel width along z-axis

  // relative distance from chassis/arm pin to wheel center
  // NOTE: correct for which side its on Initialize()
  m_wheel_PosRel = m_wheel_Pos;

  // create the constraints
  m_armChassis_rev = ChSharedPtr<ChLinkLockRevolute>(new ChLinkLockRevolute);
  m_armChassis_rev->SetName("_arm-chassis_revolute");
  m_armWheel_rev = ChSharedPtr<ChLinkLockRevolute>(new ChLinkLockRevolute);
  m_armWheel_rev->SetName("_arm-wheel-revolute");

  // create the torsional spring damper assembly
  m_rot_spring = new ChLinkForce;
  m_rot_spring->Set_active(1);
  m_rot_spring->Set_K(m_springK);
  m_rot_spring->Set_R(m_springC);

  // if we're using a custom spring...
  if(m_use_custom_spring)
  {
    m_custom_spring = ChSharedPtr<ChFunction_CustomSpring>(new ChFunction_CustomSpring);
    m_rot_spring->Set_K(1);
    m_rot_spring->Set_modul_K(m_custom_spring.get_ptr());
  }
  // add the link force to the rev joint
  m_armChassis_rev->SetForce_Rz(m_rot_spring);

  // add visualization assets to the roadwheel and arm
  AddVisualization();
}

// local_Csys is at the pin location between arm and chassis.
// z-axis defines axis of revolute joint rotation.
// Wheel rot is the same as local_Csys.
void TorsionArmSuspension::Initialize(ChSharedPtr<ChBodyAuxRef> chassis,
                                      const ChCoordsys<>& local_Csys)
{
  // correct armpin to wheel distance for left/right sides
  if(local_Csys.pos.z < 0)
    m_wheel_PosRel.z *= -1;

  // add collision geometry
  AddCollisionGeometry();

  // Express the revolute joint location in the absolute coordinate system.
  ChFrame<> rev_loc_to_abs(local_Csys);
  rev_loc_to_abs.ConcatenatePreTransformation(chassis->GetFrame_REF_to_abs());

  // wheel is offset from local csys, in local coordinates
  ChFrame<> wheel_pos_loc(local_Csys);
  wheel_pos_loc.SetPos(local_Csys.pos + GetWheelPosRel());
  ChFrame<> wheel_to_abs(wheel_pos_loc);
  wheel_to_abs.ConcatenatePreTransformation(chassis->GetFrame_REF_to_abs());

  // arm COG is between these two points.
  m_arm->SetPos( (rev_loc_to_abs.GetPos() + wheel_to_abs.GetPos() )/2.0 );
  // y-axis should point along length of arm, according to inertia tensor
  ChVector<> v = (rev_loc_to_abs.GetPos()-wheel_to_abs.GetPos()).GetNormalized();
  // use the z-axis from the wheel frame
  ChVector<> w = (wheel_to_abs.GetRot().GetZaxis()).GetNormalized();
  ChVector<> u = Vcross(v, w);
  u.Normalize();
  ChMatrix33<> rot;
  // z-axis of the wheel might not be exactly orthogonal to arm y-axis
  rot.Set_A_axis(u, v, Vcross(u,v));
  // should give the correct orientation to the arm
  m_arm->SetRot(rot);
  // pos, rot of arm set, add it to the system
  chassis->GetSystem()->Add(m_arm);

  // set the wheel in the correct position.
  m_wheel->SetPos(wheel_to_abs.GetPos());
  // inertia and visual assets have wheel width along z-axis locally.
  // No need to rotate the wheel.
  m_wheel->SetRot(wheel_to_abs.GetRot());
  chassis->GetSystem()->Add(m_wheel);

  // init and add the revolute joints
  // arm-chassis, z-axis is already in the lateral direction
  m_armChassis_rev->Initialize(m_arm, chassis, ChCoordsys<>(rev_loc_to_abs.GetPos(), rev_loc_to_abs.GetRot()) );
  // init and finish setting up the torsional spring, since it's part of this revolute constraint
  chassis->GetSystem()->AddLink(m_armChassis_rev);
  // wheel-arm, z-axis is already in the lateral direction
  m_armWheel_rev->Initialize(m_wheel, m_arm, ChCoordsys<>(wheel_to_abs.GetPos(), wheel_to_abs.GetRot()) );
  chassis->GetSystem()->AddLink(m_armWheel_rev);
}

/// add a cylinder to model the torsion bar arm and the wheel
void TorsionArmSuspension::AddVisualization()
{
  // add visualization assets
  switch (m_vis) {
  case VisualizationType::PRIMITIVES:
  {
    // define the wheel as two concentric cylinders with a gap
    ChSharedPtr<ChCylinderShape> cyl(new ChCylinderShape);
    cyl->GetCylinderGeometry().p1 = ChVector<>(0, 0, m_wheelWidth/2.0);
    cyl->GetCylinderGeometry().p2 = ChVector<>(0, 0, m_wheelWidthGap/2.0);
    cyl->GetCylinderGeometry().rad = m_wheelRadius;
    m_wheel->AddAsset(cyl);

    // second cylinder is a mirror of the first
    cyl->GetCylinderGeometry().p1.z = -m_wheelWidth/2.0;
    cyl->GetCylinderGeometry().p2.z = -m_wheelWidthGap/2.0;
    m_wheel->AddAsset(cyl);

    // put a texture on the wheel
    ChSharedPtr<ChTexture> tex(new ChTexture);
    tex->SetTextureFilename(GetChronoDataFile("bluwhite.png"));
    m_wheel->AddAsset(tex);

    // define the arm cylinder shape, link is along the y-axis
    double armLength = m_wheel_Pos.Length();
    ChVector<> p1_arm(0, armLength/2.0, 0);
    ChVector<> p2_arm(0, -armLength/2.0, 0);
    ChSharedPtr<ChCylinderShape> arm_cyl(new ChCylinderShape);
    arm_cyl->GetCylinderGeometry().p1 = p1_arm;
    arm_cyl->GetCylinderGeometry().p2 = p2_arm;
    arm_cyl->GetCylinderGeometry().rad = m_armRadius;
    m_arm->AddAsset(arm_cyl);
    break;
  }
   case VisualizationType::MESH:
  {
    /*
    geometry::ChTriangleMeshConnected trimesh;
    trimesh.LoadWavefrontMesh(getMeshFile(), false, false);

    ChSharedPtr<ChTriangleMeshShape> trimesh_shape(new ChTriangleMeshShape);
    trimesh_shape->SetMesh(trimesh);
    trimesh_shape->SetName(getMeshName());
    m_wheel->AddAsset(trimesh_shape);

    ChSharedPtr<ChColorAsset> mcolor(new ChColorAsset(0.5f, 0.1f, 0.4f));
    m_wheel->AddAsset(mcolor);
    */

    break;
  }
  } // end switch
}

/// only the road wheels are used for collision
void TorsionArmSuspension::AddCollisionGeometry()
{
  // add collision geometrey, if enabled. Warn if not
  m_wheel->SetCollide(true);
  m_wheel->GetCollisionModel()->ClearModel();

  switch (m_collide) {
  case CollisionType::NONE:
  {
    m_wheel->SetCollide(false);
    GetLog() << " !!! Road Wheel " << m_wheel->GetName() << " collision deactivated !!! \n\n";
  }
  case CollisionType::PRIMITIVES:
  {
    double half_cyl_width =  (m_wheelWidth - m_wheelWidthGap)/2.0;
    ChVector<> shape_offset =  ChVector<>(0, 0, half_cyl_width + m_wheelWidthGap/2.0);
    // use two simple cylinders. Default is along the y-axis, here we have z-axis relative to chassis.
    m_wheel->GetCollisionModel()->AddCylinder(m_wheelRadius, m_wheelRadius, half_cyl_width,
      shape_offset, Q_from_AngAxis(CH_C_PI_2,VECT_X) );

    // mirror first cylinder about the x-y plane
    shape_offset.z *= -1;
    m_wheel->GetCollisionModel()->AddCylinder(m_wheelRadius, m_wheelRadius, half_cyl_width,
      shape_offset,Q_from_AngAxis(CH_C_PI_2,VECT_X));
  }
  case CollisionType::MESH:
  {
    // use a triangle mesh
    /*

		geometry::ChTriangleMeshSoup temp_trianglemesh;

    // TODO: fill the triangleMesh here with some track shoe geometry

		m_wheel->GetCollisionModel()->SetSafeMargin(0.004);	// inward safe margin
		m_wheel->GetCollisionModel()->SetEnvelope(0.010);		// distance of the outward "collision envelope"
		m_wheel->GetCollisionModel()->ClearModel();

    // is there an offset??
    double shoelength = 0.2;
    ChVector<> mesh_displacement(shoelength*0.5,0,0);  // since mesh origin is not in body center of mass
    m_wheel->GetCollisionModel()->AddTriangleMesh(temp_trianglemesh, false, false, mesh_displacement);
    */

    break;
  }
  case CollisionType::CONVEXHULL:
  {
    /*
    // use convex hulls, loaded from file
    ChStreamInAsciiFile chull_file(GetChronoDataFile("drive_gear.chulls").c_str());
    // transform the collision geometry as needed
    double mangle = 45.0; // guess
    ChQuaternion<>rot;
    rot.Q_from_AngAxis(mangle*(CH_C_PI/180.),VECT_X);
    ChMatrix33<> rot_offset(rot);
    ChVector<> disp_offset(0,0,0);  // no displacement offset
    m_wheel->GetCollisionModel()->AddConvexHullsFromFile(chull_file, disp_offset, rot_offset);
    */

    break;
  }
  } // end switch

  // setup collision family, road wheel is a rolling element
  m_wheel->GetCollisionModel()->SetFamily((int)CollisionFam::WHEELS);

  // don't collide with the ground
  m_wheel->GetCollisionModel()->SetFamilyMaskNoCollisionWithFamily((int)CollisionFam::GROUND);

  m_wheel->GetCollisionModel()->BuildModel();
}

} // end namespace chrono
<commit_msg>set collision envelope, margin.<commit_after>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Justin Madsen
// =============================================================================
//
// model a single track chain system, as part of a tracked vehicle.
// Static variable values are based on a M113 model in the report by Shabana
//
// =============================================================================

#include <cstdio>

#include "subsys/suspension/TorsionArmSuspension.h"

#include "assets/ChCylinderShape.h"
#include "assets/ChTriangleMeshShape.h"
#include "assets/ChTexture.h"
#include "assets/ChColorAsset.h"

namespace chrono {

// static variables
const double TorsionArmSuspension::m_armMass = 75.26; // [kg]
const ChVector<> TorsionArmSuspension::m_armInertia(0.77, 0.37, 0.77);  // [kg-m2]
const double TorsionArmSuspension::m_armRadius = 0.1; // [m]

const double TorsionArmSuspension::m_wheelMass = 561.1; // [kg]
const ChVector<> TorsionArmSuspension::m_wheelInertia(19.82, 19.82, 26.06); // [kg-m2]
const double TorsionArmSuspension::m_wheelWidth = 0.16;  // [m]
const double TorsionArmSuspension::m_wheelWidthGap = 0.03;  // inner gap between outer cylinders .038?
const double TorsionArmSuspension::m_wheelRadius = 0.305; // [m]
const ChVector<> TorsionArmSuspension::m_wheel_Pos(-0.2034, -0.2271, 0.24475); // loc of right wheel COG in the local c-sys
const double TorsionArmSuspension::m_springK = 10000;	// torsional spring constant [N-m/rad]
const double TorsionArmSuspension::m_springC = 100;	// torsional damping constant [N-m-s/rad]
const double TorsionArmSuspension::m_TorquePreload = 10.0;  // torque preload [N-m]

TorsionArmSuspension::TorsionArmSuspension(const std::string& name,
                                           VisualizationType vis,
                                           CollisionType collide,
                                           bool use_custom_spring)
: m_vis(vis), m_collide(collide), m_use_custom_spring(use_custom_spring)
{
  // FILE* fp = fopen(filename.c_str(), "r");
  // char readBuffer[65536];
  // fclose(fp);

  Create(name);
}

// 1) load data from file, 2) create bodies using data
void TorsionArmSuspension::Create(const std::string& name)
{
/*
  // load data for the arm
  m_armMass = d["Arm"]["Mass"].GetDouble();
  m_armInertia = loadVector(d["Arm"]["Inertia"]);
  m_armRadius = d["Arm"]["Radius"].GetDouble();

  // load data for the wheel
  m_wheelMass = d["Wheel"]["Mass"].GetDouble();
  m_wheelInertia = loadVector(d["Wheel"]["Inertia"]);
  m_wheelRadius = d["Wheel"]["Radius"].GetDouble();
  m_wheelWidth = d["Wheel"]["Width"].GetDouble();
  m_wheelRelLoc = loadVector(d["Wheel"]["Location"]);

  // load data for the torsion bar
  m_springK = d["Torsion Bar"]["Stiffness"].GetDouble();
  m_springC = d["Torsion Bar"]["Damping"].GetDouble();

  */

  // create the suspension arm body
  m_arm = ChSharedPtr<ChBody>(new ChBody);
  m_arm->SetNameString(name + "_arm");
  m_arm->SetMass(m_armMass);
  m_arm->SetInertiaXX(m_armInertia);  // link distance along y-axis
  // create the roadwheel body
  m_wheel = ChSharedPtr<ChBody>(new ChBody);
  m_wheel->SetNameString(name + "_roadWheel");
  m_wheel->SetMass(m_wheelMass);
  m_wheel->SetInertiaXX(m_wheelInertia);  // wheel width along z-axis

  // relative distance from chassis/arm pin to wheel center
  // NOTE: correct for which side its on Initialize()
  m_wheel_PosRel = m_wheel_Pos;

  // create the constraints
  m_armChassis_rev = ChSharedPtr<ChLinkLockRevolute>(new ChLinkLockRevolute);
  m_armChassis_rev->SetName("_arm-chassis_revolute");
  m_armWheel_rev = ChSharedPtr<ChLinkLockRevolute>(new ChLinkLockRevolute);
  m_armWheel_rev->SetName("_arm-wheel-revolute");

  // create the torsional spring damper assembly
  m_rot_spring = new ChLinkForce;
  m_rot_spring->Set_active(1);
  m_rot_spring->Set_K(m_springK);
  m_rot_spring->Set_R(m_springC);

  // if we're using a custom spring...
  if(m_use_custom_spring)
  {
    m_custom_spring = ChSharedPtr<ChFunction_CustomSpring>(new ChFunction_CustomSpring);
    m_rot_spring->Set_K(1);
    m_rot_spring->Set_modul_K(m_custom_spring.get_ptr());
  }
  // add the link force to the rev joint
  m_armChassis_rev->SetForce_Rz(m_rot_spring);

  // add visualization assets to the roadwheel and arm
  AddVisualization();
}

// local_Csys is at the pin location between arm and chassis.
// z-axis defines axis of revolute joint rotation.
// Wheel rot is the same as local_Csys.
void TorsionArmSuspension::Initialize(ChSharedPtr<ChBodyAuxRef> chassis,
                                      const ChCoordsys<>& local_Csys)
{
  // correct armpin to wheel distance for left/right sides
  if(local_Csys.pos.z < 0)
    m_wheel_PosRel.z *= -1;

  // add collision geometry
  AddCollisionGeometry();

  // Express the revolute joint location in the absolute coordinate system.
  ChFrame<> rev_loc_to_abs(local_Csys);
  rev_loc_to_abs.ConcatenatePreTransformation(chassis->GetFrame_REF_to_abs());

  // wheel is offset from local csys, in local coordinates
  ChFrame<> wheel_pos_loc(local_Csys);
  wheel_pos_loc.SetPos(local_Csys.pos + GetWheelPosRel());
  ChFrame<> wheel_to_abs(wheel_pos_loc);
  wheel_to_abs.ConcatenatePreTransformation(chassis->GetFrame_REF_to_abs());

  // arm COG is between these two points.
  m_arm->SetPos( (rev_loc_to_abs.GetPos() + wheel_to_abs.GetPos() )/2.0 );
  // y-axis should point along length of arm, according to inertia tensor
  ChVector<> v = (rev_loc_to_abs.GetPos()-wheel_to_abs.GetPos()).GetNormalized();
  // use the z-axis from the wheel frame
  ChVector<> w = (wheel_to_abs.GetRot().GetZaxis()).GetNormalized();
  ChVector<> u = Vcross(v, w);
  u.Normalize();
  ChMatrix33<> rot;
  // z-axis of the wheel might not be exactly orthogonal to arm y-axis
  rot.Set_A_axis(u, v, Vcross(u,v));
  // should give the correct orientation to the arm
  m_arm->SetRot(rot);
  // pos, rot of arm set, add it to the system
  chassis->GetSystem()->Add(m_arm);

  // set the wheel in the correct position.
  m_wheel->SetPos(wheel_to_abs.GetPos());
  // inertia and visual assets have wheel width along z-axis locally.
  // No need to rotate the wheel.
  m_wheel->SetRot(wheel_to_abs.GetRot());
  chassis->GetSystem()->Add(m_wheel);

  // init and add the revolute joints
  // arm-chassis, z-axis is already in the lateral direction
  m_armChassis_rev->Initialize(m_arm, chassis, ChCoordsys<>(rev_loc_to_abs.GetPos(), rev_loc_to_abs.GetRot()) );
  // init and finish setting up the torsional spring, since it's part of this revolute constraint
  chassis->GetSystem()->AddLink(m_armChassis_rev);
  // wheel-arm, z-axis is already in the lateral direction
  m_armWheel_rev->Initialize(m_wheel, m_arm, ChCoordsys<>(wheel_to_abs.GetPos(), wheel_to_abs.GetRot()) );
  chassis->GetSystem()->AddLink(m_armWheel_rev);
}

/// add a cylinder to model the torsion bar arm and the wheel
void TorsionArmSuspension::AddVisualization()
{
  // add visualization assets
  switch (m_vis) {
  case VisualizationType::PRIMITIVES:
  {
    // define the wheel as two concentric cylinders with a gap
    ChSharedPtr<ChCylinderShape> cyl(new ChCylinderShape);
    cyl->GetCylinderGeometry().p1 = ChVector<>(0, 0, m_wheelWidth/2.0);
    cyl->GetCylinderGeometry().p2 = ChVector<>(0, 0, m_wheelWidthGap/2.0);
    cyl->GetCylinderGeometry().rad = m_wheelRadius;
    m_wheel->AddAsset(cyl);

    // second cylinder is a mirror of the first
    cyl->GetCylinderGeometry().p1.z = -m_wheelWidth/2.0;
    cyl->GetCylinderGeometry().p2.z = -m_wheelWidthGap/2.0;
    m_wheel->AddAsset(cyl);

    // put a texture on the wheel
    ChSharedPtr<ChTexture> tex(new ChTexture);
    tex->SetTextureFilename(GetChronoDataFile("bluwhite.png"));
    m_wheel->AddAsset(tex);

    // define the arm cylinder shape, link is along the y-axis
    double armLength = m_wheel_Pos.Length();
    ChVector<> p1_arm(0, armLength/2.0, 0);
    ChVector<> p2_arm(0, -armLength/2.0, 0);
    ChSharedPtr<ChCylinderShape> arm_cyl(new ChCylinderShape);
    arm_cyl->GetCylinderGeometry().p1 = p1_arm;
    arm_cyl->GetCylinderGeometry().p2 = p2_arm;
    arm_cyl->GetCylinderGeometry().rad = m_armRadius;
    m_arm->AddAsset(arm_cyl);
    break;
  }
   case VisualizationType::MESH:
  {
    /*
    geometry::ChTriangleMeshConnected trimesh;
    trimesh.LoadWavefrontMesh(getMeshFile(), false, false);

    ChSharedPtr<ChTriangleMeshShape> trimesh_shape(new ChTriangleMeshShape);
    trimesh_shape->SetMesh(trimesh);
    trimesh_shape->SetName(getMeshName());
    m_wheel->AddAsset(trimesh_shape);

    ChSharedPtr<ChColorAsset> mcolor(new ChColorAsset(0.5f, 0.1f, 0.4f));
    m_wheel->AddAsset(mcolor);
    */

    break;
  }
  } // end switch
}

/// only the road wheels are used for collision
void TorsionArmSuspension::AddCollisionGeometry()
{
  // add collision geometrey, if enabled. Warn if not
  m_wheel->SetCollide(true);
  m_wheel->GetCollisionModel()->ClearModel();

  // 1 cm outwards, 0.5 inwards for envelope and margin, respectfully.
  m_wheel->GetCollisionModel()->SetSafeMargin(0.005);	// inward safe margin
	m_wheel->GetCollisionModel()->SetEnvelope(0.010);		// distance of the outward "collision envelope"

  switch (m_collide) {
  case CollisionType::NONE:
  {
    m_wheel->SetCollide(false);
    GetLog() << " !!! Road Wheel " << m_wheel->GetName() << " collision deactivated !!! \n\n";
  }
  case CollisionType::PRIMITIVES:
  {
    double half_cyl_width =  (m_wheelWidth - m_wheelWidthGap)/2.0;
    ChVector<> shape_offset =  ChVector<>(0, 0, half_cyl_width + m_wheelWidthGap/2.0);
    // use two simple cylinders. Default is along the y-axis, here we have z-axis relative to chassis.
    m_wheel->GetCollisionModel()->AddCylinder(m_wheelRadius, m_wheelRadius, half_cyl_width,
      shape_offset, Q_from_AngAxis(CH_C_PI_2,VECT_X) );

    // mirror first cylinder about the x-y plane
    shape_offset.z *= -1;
    m_wheel->GetCollisionModel()->AddCylinder(m_wheelRadius, m_wheelRadius, half_cyl_width,
      shape_offset,Q_from_AngAxis(CH_C_PI_2,VECT_X));
  }
  case CollisionType::MESH:
  {
    // use a triangle mesh
    /*

		geometry::ChTriangleMeshSoup temp_trianglemesh;

    // TODO: fill the triangleMesh here with some track shoe geometry

    // is there an offset??
    double shoelength = 0.2;
    ChVector<> mesh_displacement(shoelength*0.5,0,0);  // since mesh origin is not in body center of mass
    m_wheel->GetCollisionModel()->AddTriangleMesh(temp_trianglemesh, false, false, mesh_displacement);
    */

    break;
  }
  case CollisionType::CONVEXHULL:
  {
    /*
    // use convex hulls, loaded from file
    ChStreamInAsciiFile chull_file(GetChronoDataFile("drive_gear.chulls").c_str());
    // transform the collision geometry as needed
    double mangle = 45.0; // guess
    ChQuaternion<>rot;
    rot.Q_from_AngAxis(mangle*(CH_C_PI/180.),VECT_X);
    ChMatrix33<> rot_offset(rot);
    ChVector<> disp_offset(0,0,0);  // no displacement offset
    m_wheel->GetCollisionModel()->AddConvexHullsFromFile(chull_file, disp_offset, rot_offset);
    */

    break;
  }
  } // end switch

  // setup collision family, road wheel is a rolling element
  m_wheel->GetCollisionModel()->SetFamily((int)CollisionFam::WHEELS);

  // don't collide with the ground
  m_wheel->GetCollisionModel()->SetFamilyMaskNoCollisionWithFamily((int)CollisionFam::GROUND);

  m_wheel->GetCollisionModel()->BuildModel();
}

} // end namespace chrono
<|endoftext|>


<commit_before>
// Copyright (c) 2014 Quanta Research Cambridge, Inc.

// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use, copy,
// modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
// BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

#include <MmRequestProxy.h>
#include <MmIndicationWrapper.h>
#include <MmDebugIndicationWrapper.h>
#include <MmDebugRequestProxy.h>
#include <DmaConfigProxy.h>
#include <GeneratedTypes.h>
//#include <DmaIndicationWrapper.h>
#include <StdDmaIndication.h>
#include <stdio.h>
#include <sys/mman.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <semaphore.h>
#include <pthread.h>
#include <errno.h>
#include <math.h> // frexp(), fabs()
#include <assert.h>
#include "portalmat.h"
#include "mnist.h"

static int verbose = 0;

class SigmoidIndication;
class MmIndication;
class MmDebugIndication;

RbmRequestProxy *rbmdevice = 0;
MmRequestProxy *mmdevice = 0;
MmDebugRequestProxy *mmdebug = 0;
SigmoidIndication *sigmoidindication = 0;
SigmoidRequestProxy *sigmoiddevice = 0;
TimerRequestProxy *timerdevice = 0;
MmIndication *mmdeviceIndication = 0;
MmDebugIndication *mmDebugIndication = 0;
TimerIndication *timerdeviceIndication = 0;
DmaConfigProxy *dmap = 0;
DmaIndicationWrapper *dmaIndication = 0;

long dotprod = 0;

void dump(const char *prefix, char *buf, size_t len)
{
    fprintf(stderr, "%s ", prefix);
    for (int i = 0; i < (len > 64 ? 64 : len) ; i++) {
	fprintf(stderr, "%02x", (unsigned char)buf[i]);
	if (i % 4 == 3)
	  fprintf(stderr, " ");
    }
    fprintf(stderr, "\n");
}

void *dbgThread(void *)
{
  while (1) {
    sleep(2);
    if (dmap) {
      //dmap->getStateDbg(ChannelType_Read);
    }
    if (mmdebug) {
      fprintf(stderr, "Calling mmdebug->debug()\n");
      mmdebug->debug();
    }
  }
  return 0;
}

int main(int argc, const char **argv)
{
  unsigned int srcGen = 0;

  fprintf(stderr, "%s %s\n", __DATE__, __TIME__);
  mmdevice = new MmRequestProxy(IfcNames_MmRequestPortal);
  mmdebug = new MmDebugRequestProxy(IfcNames_MmDebugRequestPortal);
  mmdeviceIndication = new MmIndication(IfcNames_MmIndicationPortal);
  mmDebugIndication = new MmDebugIndication(IfcNames_MmDebugIndicationPortal);
  timerdevice = new TimerRequestProxy(IfcNames_TimerRequestPortal);
  timerdeviceIndication = new TimerIndication(IfcNames_TimerIndicationPortal);

  dmap = new DmaConfigProxy(IfcNames_DmaConfigPortal);
  DmaManager *dma = new DmaManager(dmap);
  dmaIndication = new DmaIndication(dma, IfcNames_DmaIndicationPortal);

  if(sem_init(&mul_sem, 1, 0)){
    fprintf(stderr, "failed to init mul_sem\n");
    return -1;
  }

  pthread_t tid;
  fprintf(stderr, "creating exec thread\n");
  if(pthread_create(&tid, NULL,  portalExec, NULL)){
   fprintf(stderr, "error creating exec thread\n");
   exit(1);
  }

  pthread_t dbgtid;
  fprintf(stderr, "creating debug thread\n");
  if(pthread_create(&dbgtid, NULL,  dbgThread, NULL)){
   fprintf(stderr, "error creating debug thread\n");
   exit(1);
  }

  matAllocator = new PortalMatAllocator(dmap, dma);

#define LARGE_MAT
#ifdef LARGE_MAT
#ifdef BSIM
  int A = 32;
  int B = 512;
#else
  int A = 32;
  int B = 512;
#endif
  if (argc > 1) {
    B = strtoul(argv[1], 0, 0);
    A = 2*B;
  }
  cv::Mat m1(A,B,CV_32F);
  cv::Mat m2(B,A,CV_32F);
  float v = 0;
  for(int a = 0; a < A; a++){
    for(int b = 0; b < B; b++){
      m2.at<float>(b,a) = (A*B)+v;
      m1.at<float>(a,b) = v;
      v++;
    }
  }
#else
  cv::Mat m1 = (cv::Mat_<float>(4,8) <<
		11,12,13,14,15,16,17,18,
		21,22,23,24,25,26,27,28,
		31,32,33,34,35,36,37,38,
		41,42,43,44,45,46,47,48
		);
  cv::Mat m2 = (cv::Mat_<float>(8,4) <<
		51,62,53,54,
		55,56,57,58,
		61,62,63,64,
		65,66,67,68,
		71,72,73,74,
		75,76,77,78,
		81,82,83,84,
		85,86,87,88
		);
#endif

  FILE *octave_file = fopen("foo.m", "w");

  start_timer(0);
  fprintf(stderr, "OpenCV matmul\n");
  cv::Mat  m3 = m1 * m2;
  uint64_t opencv_hw_cycles = lap_timer(0);

  PortalMat tm3;
  fprintf(stderr, "Naive matmul\n");
  start_timer(0);
  tm3.naive_mul(m1,m2, octave_file);
  uint64_t naive_hw_cycles = lap_timer(0);

  bool sane = 1;
  if (1) {
    fprintf(stderr, "DumpMat\n");
    dumpMatOctave<float>("m1",  "%10.5f", m1,  octave_file);
    dumpMatOctave<float>("m2",  "%10.5f", m2,  octave_file);
    dumpMatOctave<float>("m3",  "%10.5f", m3,  octave_file);
    dumpMatOctave<float>("tm3", "%10.5f", tm3, octave_file);
    fclose(octave_file);
    sane = tm3.compare(m3, 0, 0, 0.0001, 0, false);
    fprintf(stderr, "sane=%d\n", sane);
    fflush(stdout);
  }

  fprintf(stderr, "pm1\n");
  PortalMat pm1(m1);
  fprintf(stderr, "pm2t\n");
  PortalMat pm2t(m2.t());
  PortalMat pm3;
  fprintf(stderr, "HW matmul\n");
  start_timer(0);
  pm3.multf(pm1, pm2t, mmdeviceIndication);
  uint64_t hw_cycles = lap_timer(0);
  uint64_t read_beats = dma->show_mem_stats(ChannelType_Read);
  uint64_t write_beats = dma->show_mem_stats(ChannelType_Write);
  float read_util = (float)read_beats/(float)mmdeviceIndication->ccnt;
  float write_util = (float)write_beats/(float)mmdeviceIndication->ccnt;
  fprintf(stderr, "memory read beats %lld utilization (beats/cycle): %f\n", read_beats, read_util);
  fprintf(stderr, "memory write beats %lld utilization (beats/cycle): %f\n", write_beats, write_util);
  fprintf(stderr, "opencv matmul %ld cycles (speedup %5.2ff), naive matmul %ld cycles (speedup %5.2f)\n",
	  opencv_hw_cycles, (float)opencv_hw_cycles/(float)hw_cycles,
	  naive_hw_cycles, (float)naive_hw_cycles/(float)hw_cycles);

  if (0) {
    dumpMat<float>("pm3", "%5.1f", pm3);
    dumpMat<float>(" m3", "%5.1f", m3);
  }
  //bool eq = std::equal(m3.begin<float>(), m3.end<float>(), pm3.begin<float>());
  bool eq = pm3.compare(pm3);
  fprintf(stderr, "eq=%d\n", eq);
  //device->finish();
  exit(!eq&&!sane);
}
<commit_msg>print more stats, set device freq<commit_after>
// Copyright (c) 2014 Quanta Research Cambridge, Inc.

// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use, copy,
// modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
// BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

#include <MmRequestProxy.h>
#include <MmIndicationWrapper.h>
#include <MmDebugIndicationWrapper.h>
#include <MmDebugRequestProxy.h>
#include <DmaConfigProxy.h>
#include <GeneratedTypes.h>
//#include <DmaIndicationWrapper.h>
#include <StdDmaIndication.h>
#include <stdio.h>
#include <sys/mman.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <semaphore.h>
#include <pthread.h>
#include <errno.h>
#include <math.h> // frexp(), fabs()
#include <assert.h>
#include "portalmat.h"
#include "mnist.h"

static int verbose = 0;

class SigmoidIndication;
class MmIndication;
class MmDebugIndication;

#define N 2

RbmRequestProxy *rbmdevice = 0;
MmRequestProxy *mmdevice = 0;
MmDebugRequestProxy *mmdebug = 0;
SigmoidIndication *sigmoidindication = 0;
SigmoidRequestProxy *sigmoiddevice = 0;
TimerRequestProxy *timerdevice = 0;
MmIndication *mmdeviceIndication = 0;
MmDebugIndication *mmDebugIndication = 0;
TimerIndication *timerdeviceIndication = 0;
DmaConfigProxy *dmap = 0;
DmaIndicationWrapper *dmaIndication = 0;

long dotprod = 0;

void dump(const char *prefix, char *buf, size_t len)
{
    fprintf(stderr, "%s ", prefix);
    for (int i = 0; i < (len > 64 ? 64 : len) ; i++) {
	fprintf(stderr, "%02x", (unsigned char)buf[i]);
	if (i % 4 == 3)
	  fprintf(stderr, " ");
    }
    fprintf(stderr, "\n");
}

void *dbgThread(void *)
{
  while (1) {
    sleep(2);
    if (dmap) {
      //dmap->getStateDbg(ChannelType_Read);
    }
    if (mmdebug) {
      fprintf(stderr, "Calling mmdebug->debug()\n");
      mmdebug->debug();
    }
  }
  return 0;
}

int main(int argc, const char **argv)
{
  unsigned int srcGen = 0;

  PortalPoller *poller = new PortalPoller();

  fprintf(stderr, "%s %s\n", __DATE__, __TIME__);
  mmdevice = new MmRequestProxy(IfcNames_MmRequestPortal);
  mmdebug = new MmDebugRequestProxy(IfcNames_MmDebugRequestPortal);
  mmdeviceIndication = new MmIndication(IfcNames_MmIndicationPortal);
  mmDebugIndication = new MmDebugIndication(IfcNames_MmDebugIndicationPortal);
  timerdevice = new TimerRequestProxy(IfcNames_TimerRequestPortal, poller);
  timerdeviceIndication = new TimerIndication(IfcNames_TimerIndicationPortal);

  dmap = new DmaConfigProxy(IfcNames_DmaConfigPortal);
  DmaManager *dma = new DmaManager(dmap);
  dmaIndication = new DmaIndication(dma, IfcNames_DmaIndicationPortal);

  if(sem_init(&mul_sem, 1, 0)){
    fprintf(stderr, "failed to init mul_sem\n");
    return -1;
  }

  pthread_t tid;
  fprintf(stderr, "creating exec thread\n");
  if(pthread_create(&tid, NULL,  portalExec, NULL)){
   fprintf(stderr, "error creating exec thread\n");
   exit(1);
  }

  long req_freq = 100000000;
  long freq = 0;
  poller->setClockFrequency(0, req_freq, &freq);
  fprintf(stderr, "Requested FCLK[0]=%d actually %d\n", req_freq, freq);

  matAllocator = new PortalMatAllocator(dmap, dma);

#define LARGE_MAT
#ifdef LARGE_MAT
#ifdef BSIM
  int A = 32;
  int B = 512;
#else
  int A = 256;
  int B = 2048;
#endif
  if (argc > 1) {
    B = strtoul(argv[1], 0, 0);
    A = 2*B;
  }
  cv::Mat m1(A,B,CV_32F);
  cv::Mat m2(B,A,CV_32F);
  float v = 0;
  for(int a = 0; a < A; a++){
    for(int b = 0; b < B; b++){
      m2.at<float>(b,a) = (A*B)+v;
      m1.at<float>(a,b) = v;
      v++;
    }
  }
#else
  cv::Mat m1 = (cv::Mat_<float>(4,8) <<
		11,12,13,14,15,16,17,18,
		21,22,23,24,25,26,27,28,
		31,32,33,34,35,36,37,38,
		41,42,43,44,45,46,47,48
		);
  cv::Mat m2 = (cv::Mat_<float>(8,4) <<
		51,62,53,54,
		55,56,57,58,
		61,62,63,64,
		65,66,67,68,
		71,72,73,74,
		75,76,77,78,
		81,82,83,84,
		85,86,87,88
		);
#endif

  FILE *octave_file = fopen("foo.m", "w");

  fprintf(stderr, "OpenCV matmul\n");
  start_timer(0);
  cv::Mat  m3 = m1 * m2;
  uint64_t opencv_hw_cycles = lap_timer(0);

  PortalMat tm3;
  fprintf(stderr, "Naive matmul\n");
  start_timer(0);
  tm3.naive_mul(m1,m2, octave_file);
  uint64_t naive_hw_cycles = lap_timer(0);

  bool sane = 1;
  if (1) {
    fprintf(stderr, "DumpMat\n");
    dumpMatOctave<float>("m1",  "%10.5f", m1,  octave_file);
    dumpMatOctave<float>("m2",  "%10.5f", m2,  octave_file);
    dumpMatOctave<float>("m3",  "%10.5f", m3,  octave_file);
    dumpMatOctave<float>("tm3", "%10.5f", tm3, octave_file);
    fclose(octave_file);
    sane = tm3.compare(m3, 0, 0, 0.0001, 0, false);
    fprintf(stderr, "sane=%d\n", sane);
    fflush(stdout);
  }

  fprintf(stderr, "pm1\n");
  PortalMat pm1(m1);
  fprintf(stderr, "pm2t\n");
  PortalMat pm2t(m2.t());
  PortalMat pm3;

  // now reference the matrices so we do not count that in the timer
  pm1.reference();
  pm2t.reference();
  pm3.create(m1.rows, m2.cols, CV_32F);
  pm3.reference();

  pthread_t dbgtid;
  fprintf(stderr, "creating debug thread\n");
  if(pthread_create(&dbgtid, NULL,  dbgThread, NULL)){
   fprintf(stderr, "error creating debug thread\n");
   exit(1);
  }

  fprintf(stderr, "HW matmul\n");
  start_timer(0);
  pm3.multf(pm1, pm2t, mmdeviceIndication);
  uint64_t hw_cycles = lap_timer(0);
  uint64_t read_beats = dma->show_mem_stats(ChannelType_Read);
  uint64_t write_beats = dma->show_mem_stats(ChannelType_Write);
  float read_util = (float)read_beats/(float)mmdeviceIndication->ccnt;
  float write_util = (float)write_beats/(float)mmdeviceIndication->ccnt;
  float read_bw = read_util * N * 4 * freq / 1.0e9;
  float write_bw = write_util * N * 4 * freq / 1.0e9;
  float macs = m1.rows * m2.rows * m2.cols;
  fprintf(stderr, "memory read beats %lld utilization (beats/cycle): bandwidth %5.2f GB/s\n", read_beats, read_util, read_bw);
  fprintf(stderr, "memory write beats %lld utilization (beats/cycle): %f bandwidth %5.2f\n", write_beats, write_util, write_bw);
  fprintf(stderr, "macs/cycle %5.2f dev %5.2f GFLOP/s %5.2f dev %5.2f\n",
	  (float)macs / (float)hw_cycles, (float)macs / (float)mmdeviceIndication->ccnt,
	  (float)macs / (float)hw_cycles * freq / 1.0e9, (float)macs / (float)mmdeviceIndication->ccnt * freq / 1.0e9);
  fprintf(stderr, "hw_cycles %5.1f dev cycles %5.1f opencv matmul %5.1f cycles (speedup %5.2f dev %5.2f), naive matmul %5.1f cycles (speedup %5.2f dev %5.2f)\n",
	  (float)hw_cycles, (float)mmdeviceIndication->ccnt,
	  (float)opencv_hw_cycles, (float)opencv_hw_cycles/(float)hw_cycles, (float)opencv_hw_cycles/(float)mmdeviceIndication->ccnt,
	  (float)naive_hw_cycles, (float)naive_hw_cycles/(float)hw_cycles, (float)naive_hw_cycles/(float)mmdeviceIndication->ccnt);

  if (0) {
    dumpMat<float>("pm3", "%5.1f", pm3);
    dumpMat<float>(" m3", "%5.1f", m3);
  }
  //bool eq = std::equal(m3.begin<float>(), m3.end<float>(), pm3.begin<float>());
  bool eq = pm3.compare(pm3);
  fprintf(stderr, "eq=%d\n", eq);
  //device->finish();
  exit(!eq&&!sane);
}
<|endoftext|>