<commit_before>/*
 @ 0xCCCCCCCC
*/

#include <cstring>
#include <iostream>

#include "catch2/catch.hpp"

#include "kbase/basic_macros.h"
#include "kbase/string_view.h"

namespace kbase {

TEST_CASE("Complex constructions", "[StringView]")
{
    // for default constructor
    {
        StringView empty_view;
        REQUIRE(empty_view.empty());
        REQUIRE(nullptr == empty_view.data());
        REQUIRE(0 == empty_view.length());
    }

    // for BasicStringView(const CharT* str, size_type count)
    {
        const char* s = "hello, world";
        size_t len = strlen(s);
        StringView s_v(s, len);
        REQUIRE_FALSE(s_v.empty());
        std::cout << s_v.data() << std::endl << s_v.length() << std::endl;
        REQUIRE(s == s_v.data());
        REQUIRE(len == s_v.length());

        std::string str = "this is a test text";
        StringView s_v2(str.data(), str.length());
        REQUIRE_FALSE(s_v2.empty());
        std::cout << s_v2.data() << std::endl << s_v2.length() << std::endl;
        REQUIRE(str.data() == s_v2.data());
        REQUIRE(str.length() == s_v2.length());
    }

    // for copy constructor
    {
        std::string str = "this is a test text";
        StringView s_v(str.data(), str.length());
        StringView s_v_copy(s_v);
        REQUIRE(s_v.data() == s_v_copy.data());
        REQUIRE(s_v.length() == s_v_copy.length());
    }

    // for BasicStringView(const CharT* str)
    {
        const char* s = "hello, world";
        size_t len = strlen(s);
        StringView s_v(s);
        REQUIRE(s == s_v.data());
        REQUIRE(len == s_v.length());
    }

    // for BasicStringView(const std::basic_string<CharT>& str)
    {
        std::string str = "this is a test text";
        StringView s_v(str);
        REQUIRE(str.data() == s_v.data());
        REQUIRE(str.length() == s_v.length());
    }

    // compile-time evaluations.
    {
        constexpr StringView s1;
        constexpr bool empty = s1.empty();
        REQUIRE(empty);

        constexpr StringView s2 = "this is a test text";
        constexpr bool not_empty = s2.empty();
        REQUIRE_FALSE(not_empty);
        constexpr char ft = s2.front();
        constexpr char bk = s2.back();
        constexpr auto sub = s2.substr(5);
        constexpr const char* ss = sub.data();

        UNUSED_VAR(ft);
        UNUSED_VAR(bk);
        UNUSED_VAR(ss);
    }
}

TEST_CASE("Assignment", "[StringView]")
{
    StringView v = "Hello, world";
    StringView v_ex = "this is a test text";
    REQUIRE_FALSE(v.length() == v_ex.length());
    v = v_ex;
    REQUIRE(v.length() == v_ex.length());
}

TEST_CASE("Max size", "[StringView]")
{
    StringView view;
    auto max_size = std::numeric_limits<size_t>::max();
    REQUIRE(max_size == view.max_size());
}

TEST_CASE("Iterator usages", "[StringView]")
{
    const char* raw_str = "hello world";
    StringView view = raw_str;
    std::string str(view.begin(), view.end());
    std::cout << str << std::endl;
    REQUIRE(std::string(raw_str) == str);

    std::string rstr(view.rbegin(), view.rend());
    std::cout << rstr << std::endl;
    std::reverse(str.begin(), str.end());
    REQUIRE(str == rstr);
}

TEST_CASE("Accessing elements", "[StringView]")
{
    StringView view = "hello world";

    // for operator[]
    REQUIRE('h' == view[0]);
    REQUIRE('d' == view[view.length() - 1]);

    // for at
    REQUIRE('h' == view.at(0));
    REQUIRE('d' == view.at(view.length() - 1));
    REQUIRE_THROWS_AS(view.at(view.size()), std::out_of_range);

    // for front
    REQUIRE('h' == view.front());

    // for back
    REQUIRE('d' == view.back());
}

TEST_CASE("Mutating a view", "[StringView]")
{
    StringView view = "hello world";
    size_t space_pos = std::distance(view.begin(), std::find(view.begin(), view.end(), ' '));
    std::cout << space_pos << std::endl;
    REQUIRE(space_pos <= view.length());

    auto v_prefix = view;
    v_prefix.RemovePrefix(space_pos + 1);
    REQUIRE(std::string("world") == std::string(v_prefix.data(), v_prefix.length()));

    auto v_suffix = view;
    v_suffix.RemoveSuffix(view.length() - space_pos);
    REQUIRE(std::string("hello") == std::string(v_suffix.data(), v_suffix.length()));

    StringView v_1 = "hello";
    StringView v_2 = "world";
    v_1.swap(v_2);
    REQUIRE(std::string("world") == std::string(v_1.data(), v_1.length()));
    REQUIRE(std::string("hello") == std::string(v_2.data(), v_2.length()));
}

TEST_CASE("To std string", "[StringView]")
{
    std::string str = "hello, world";
    StringView view = str;
    REQUIRE(str == view.ToString());

    StringView empty_view;
    REQUIRE(std::string() == empty_view.ToString());
}

TEST_CASE("Copying", "[StringView]")
{
    StringView view = "hello, world";
    std::vector<char> buf(32);

    {
        size_t count_copied = view.copy(buf.data(), 5);
        REQUIRE(5 == count_copied);
        REQUIRE(strcmp("hello", buf.data()) == 0);
    }

    buf.clear(); buf.resize(32);
    {
        size_t count_copied = view.copy(buf.data(), 10, 7);
        REQUIRE(10 != count_copied);
        REQUIRE(strcmp("world", buf.data()) == 0);
    }

    buf.clear(); buf.resize(32);
    {
        REQUIRE_THROWS_AS(view.copy(buf.data(), 5, view.length() + 2), std::out_of_range);
    }
}

TEST_CASE("Substring", "[StringView]")
{
    StringView view = "hello, world";

    REQUIRE(std::string(", world") == view.substr(5).ToString());
    REQUIRE(std::string("hello") == view.substr(0, 5).ToString());
    REQUIRE_THROWS_AS(view.substr(view.length() + 2), std::out_of_range);
}

TEST_CASE("Comparisons", "[StringView]")
{
    StringView v_1 = "hello";
    StringView v_2 = "hell";
    REQUIRE(v_1.compare(v_2) > 0);

    REQUIRE(v_1.compare(0, 4, v_2) == 0);

    REQUIRE(v_1.compare(2, 2, v_2, 2, 2) == 0);

    REQUIRE(v_1.compare("he") > 0);

    REQUIRE(v_1.compare(0, 2, "he") == 0);

    REQUIRE(v_1.compare(0, 2, "hell", 2) == 0);
}

TEST_CASE("Finding operations", "[StringView]")
{
    SECTION("find and rfind")
    {
        StringView view = "hello, world";
        StringView view_ex = "where there is a will, there is a way";
        StringView view_ng = "This is a string";
        auto npos = decltype(view)::npos;

        // for find
        REQUIRE(0 == view.find("hell"));
        REQUIRE(8 == view.find("or"));
        REQUIRE(8 == view.find("or", 7));
        REQUIRE(npos == view.find("joke"));
        REQUIRE(npos == view.find("world", 10));
        REQUIRE(4 == view.find('o'));
        REQUIRE(0 == view.find("here", 0, 2));

        // for rfind
        REQUIRE(10 == view.rfind('l'));
        REQUIRE(npos == view.rfind('k'));
        REQUIRE(23 == view_ex.rfind("there"));
        REQUIRE(17 == view_ex.rfind("will", 22));
        REQUIRE(5 == view_ng.rfind("is"));
        REQUIRE(2 == view_ng.rfind("is", 4));
    }

    SECTION("find_first_of and find_last_of")
    {
        StringView view = "where there is a will, there is a way";
        auto npos = decltype(view)::npos;

        // for find_first_of
        REQUIRE(5 == view.find_first_of(" ,"));
        REQUIRE(2 == view.find_first_of("aeiou"));

        // for find_last_of
        StringView view_1 = "abcd-1234-abcd-1234";
        REQUIRE(13 == view_1.find_last_of("d", 14));
        REQUIRE(npos == view_1.find_last_of("x"));

        StringView view_2 = "ABCD-1234-ABCD-1234";
        REQUIRE(11 == view_2.find_last_of("B1", 12));
        REQUIRE(16 == view_2.find_last_of("D2"));

        StringView view_3 = "456-EFG-456-EFG";
        REQUIRE(4 == view_3.find_last_of("5E", 8));

        StringView view_4 = "12-ab-12-ab";
        REQUIRE(4 == view_4.find_last_of("ba3", 8));
        REQUIRE(9 == view_4.find_last_of("a2"));
    }

    SECTION("find not of")
    {
        {
            StringView view_1 = "xddd-1234-abcd";
            REQUIRE(4 == view_1.find_first_not_of("d", 2));
            REQUIRE(1 == view_1.find_first_not_of("x"));

            StringView view_2 = "BBB-1111";
            REQUIRE(StringView::npos == view_2.find_first_not_of("B1", 6));
            REQUIRE(3 == view_2.find_first_not_of("B2"));

            StringView view_3 = "444-555-GGG";
            REQUIRE(3 == view_3.find_first_not_of("45G"));

            StringView view_4 = "12-ab-12-ab";
            REQUIRE(5 == view_4.find_first_not_of("ba3", 5));
            REQUIRE(2 == view_4.find_first_not_of("12"));
        }

        {
            StringView view_1 = "dddd-1dd4-abdd";
            REQUIRE(5 == view_1.find_last_not_of("d", 7));
            REQUIRE(11 == view_1.find_last_not_of("d"));

            StringView view_2 = "BBB-1111";
            REQUIRE(3 == view_2.find_last_not_of("B1", 6));
            REQUIRE(StringView::npos == view_2.find_last_not_of("B-1"));

            StringView view_3 = "444-555-GGG";
            REQUIRE(7 == view_3.find_last_not_of("45G"));
            REQUIRE(3 == view_3.find_last_not_of("45G", 6, 6));

            StringView view_4 = "12-ab-12-ab";
            REQUIRE(1 == view_4.find_last_not_of("b-a", 5));
            REQUIRE(10 == view_4.find_last_not_of("12"));
        }
    }
}

TEST_CASE("Operator comparisons", "[StringUtil]")
{
    StringView view_1 = "abc";
    StringView view_2 = "adc";
    REQUIRE_FALSE(view_1 == view_2);
    REQUIRE(view_1 != view_2);

    std::string str_1 = "abc";
    const char kStr[] = "def";
    REQUIRE(view_1 == str_1);
    REQUIRE(view_2 != kStr);
}

TEST_CASE("Output to stream", "[StringUtil]")
{
    StringView v = "hello world";
    WStringView w = L"test text";
    std::cout << v << std::endl;
    std::wcout << w << std::endl;
}

TEST_CASE("Hash support", "[StringUtil]")
{
    StringView v = "hello world";
    WStringView w = L"hello world";
    StringView vx = "This is a test text";
    WStringView wx = L"This is a test text";

    REQUIRE(std::hash<StringView>()(v) == std::hash<StringView>()(v));
    REQUIRE(std::hash<WStringView>()(w) == std::hash<WStringView>()(w));
    REQUIRE(std::hash<StringView>()(v) != std::hash<StringView>()(vx));
    REQUIRE(std::hash<WStringView>()(w) != std::hash<WStringView>()(wx));
}

}   // namespace kbase
<commit_msg>Fix an incorrect use of StringView::find_last_not_of() in unittest<commit_after>/*
 @ 0xCCCCCCCC
*/

#include <cstring>
#include <iostream>

#include "catch2/catch.hpp"

#include "kbase/basic_macros.h"
#include "kbase/string_view.h"

namespace kbase {

TEST_CASE("Complex constructions", "[StringView]")
{
    // for default constructor
    {
        StringView empty_view;
        REQUIRE(empty_view.empty());
        REQUIRE(nullptr == empty_view.data());
        REQUIRE(0 == empty_view.length());
    }

    // for BasicStringView(const CharT* str, size_type count)
    {
        const char* s = "hello, world";
        size_t len = strlen(s);
        StringView s_v(s, len);
        REQUIRE_FALSE(s_v.empty());
        std::cout << s_v.data() << std::endl << s_v.length() << std::endl;
        REQUIRE(s == s_v.data());
        REQUIRE(len == s_v.length());

        std::string str = "this is a test text";
        StringView s_v2(str.data(), str.length());
        REQUIRE_FALSE(s_v2.empty());
        std::cout << s_v2.data() << std::endl << s_v2.length() << std::endl;
        REQUIRE(str.data() == s_v2.data());
        REQUIRE(str.length() == s_v2.length());
    }

    // for copy constructor
    {
        std::string str = "this is a test text";
        StringView s_v(str.data(), str.length());
        StringView s_v_copy(s_v);
        REQUIRE(s_v.data() == s_v_copy.data());
        REQUIRE(s_v.length() == s_v_copy.length());
    }

    // for BasicStringView(const CharT* str)
    {
        const char* s = "hello, world";
        size_t len = strlen(s);
        StringView s_v(s);
        REQUIRE(s == s_v.data());
        REQUIRE(len == s_v.length());
    }

    // for BasicStringView(const std::basic_string<CharT>& str)
    {
        std::string str = "this is a test text";
        StringView s_v(str);
        REQUIRE(str.data() == s_v.data());
        REQUIRE(str.length() == s_v.length());
    }

    // compile-time evaluations.
    {
        constexpr StringView s1;
        constexpr bool empty = s1.empty();
        REQUIRE(empty);

        constexpr StringView s2 = "this is a test text";
        constexpr bool not_empty = s2.empty();
        REQUIRE_FALSE(not_empty);
        constexpr char ft = s2.front();
        constexpr char bk = s2.back();
        constexpr auto sub = s2.substr(5);
        constexpr const char* ss = sub.data();

        UNUSED_VAR(ft);
        UNUSED_VAR(bk);
        UNUSED_VAR(ss);
    }
}

TEST_CASE("Assignment", "[StringView]")
{
    StringView v = "Hello, world";
    StringView v_ex = "this is a test text";
    REQUIRE_FALSE(v.length() == v_ex.length());
    v = v_ex;
    REQUIRE(v.length() == v_ex.length());
}

TEST_CASE("Max size", "[StringView]")
{
    StringView view;
    auto max_size = std::numeric_limits<size_t>::max();
    REQUIRE(max_size == view.max_size());
}

TEST_CASE("Iterator usages", "[StringView]")
{
    const char* raw_str = "hello world";
    StringView view = raw_str;
    std::string str(view.begin(), view.end());
    std::cout << str << std::endl;
    REQUIRE(std::string(raw_str) == str);

    std::string rstr(view.rbegin(), view.rend());
    std::cout << rstr << std::endl;
    std::reverse(str.begin(), str.end());
    REQUIRE(str == rstr);
}

TEST_CASE("Accessing elements", "[StringView]")
{
    StringView view = "hello world";

    // for operator[]
    REQUIRE('h' == view[0]);
    REQUIRE('d' == view[view.length() - 1]);

    // for at
    REQUIRE('h' == view.at(0));
    REQUIRE('d' == view.at(view.length() - 1));
    REQUIRE_THROWS_AS(view.at(view.size()), std::out_of_range);

    // for front
    REQUIRE('h' == view.front());

    // for back
    REQUIRE('d' == view.back());
}

TEST_CASE("Mutating a view", "[StringView]")
{
    StringView view = "hello world";
    size_t space_pos = std::distance(view.begin(), std::find(view.begin(), view.end(), ' '));
    std::cout << space_pos << std::endl;
    REQUIRE(space_pos <= view.length());

    auto v_prefix = view;
    v_prefix.RemovePrefix(space_pos + 1);
    REQUIRE(std::string("world") == std::string(v_prefix.data(), v_prefix.length()));

    auto v_suffix = view;
    v_suffix.RemoveSuffix(view.length() - space_pos);
    REQUIRE(std::string("hello") == std::string(v_suffix.data(), v_suffix.length()));

    StringView v_1 = "hello";
    StringView v_2 = "world";
    v_1.swap(v_2);
    REQUIRE(std::string("world") == std::string(v_1.data(), v_1.length()));
    REQUIRE(std::string("hello") == std::string(v_2.data(), v_2.length()));
}

TEST_CASE("To std string", "[StringView]")
{
    std::string str = "hello, world";
    StringView view = str;
    REQUIRE(str == view.ToString());

    StringView empty_view;
    REQUIRE(std::string() == empty_view.ToString());
}

TEST_CASE("Copying", "[StringView]")
{
    StringView view = "hello, world";
    std::vector<char> buf(32);

    {
        size_t count_copied = view.copy(buf.data(), 5);
        REQUIRE(5 == count_copied);
        REQUIRE(strcmp("hello", buf.data()) == 0);
    }

    buf.clear(); buf.resize(32);
    {
        size_t count_copied = view.copy(buf.data(), 10, 7);
        REQUIRE(10 != count_copied);
        REQUIRE(strcmp("world", buf.data()) == 0);
    }

    buf.clear(); buf.resize(32);
    {
        REQUIRE_THROWS_AS(view.copy(buf.data(), 5, view.length() + 2), std::out_of_range);
    }
}

TEST_CASE("Substring", "[StringView]")
{
    StringView view = "hello, world";

    REQUIRE(std::string(", world") == view.substr(5).ToString());
    REQUIRE(std::string("hello") == view.substr(0, 5).ToString());
    REQUIRE_THROWS_AS(view.substr(view.length() + 2), std::out_of_range);
}

TEST_CASE("Comparisons", "[StringView]")
{
    StringView v_1 = "hello";
    StringView v_2 = "hell";
    REQUIRE(v_1.compare(v_2) > 0);

    REQUIRE(v_1.compare(0, 4, v_2) == 0);

    REQUIRE(v_1.compare(2, 2, v_2, 2, 2) == 0);

    REQUIRE(v_1.compare("he") > 0);

    REQUIRE(v_1.compare(0, 2, "he") == 0);

    REQUIRE(v_1.compare(0, 2, "hell", 2) == 0);
}

TEST_CASE("Finding operations", "[StringView]")
{
    SECTION("find and rfind")
    {
        StringView view = "hello, world";
        StringView view_ex = "where there is a will, there is a way";
        StringView view_ng = "This is a string";
        auto npos = decltype(view)::npos;

        // for find
        REQUIRE(0 == view.find("hell"));
        REQUIRE(8 == view.find("or"));
        REQUIRE(8 == view.find("or", 7));
        REQUIRE(npos == view.find("joke"));
        REQUIRE(npos == view.find("world", 10));
        REQUIRE(4 == view.find('o'));
        REQUIRE(0 == view.find("here", 0, 2));

        // for rfind
        REQUIRE(10 == view.rfind('l'));
        REQUIRE(npos == view.rfind('k'));
        REQUIRE(23 == view_ex.rfind("there"));
        REQUIRE(17 == view_ex.rfind("will", 22));
        REQUIRE(5 == view_ng.rfind("is"));
        REQUIRE(2 == view_ng.rfind("is", 4));
    }

    SECTION("find_first_of and find_last_of")
    {
        StringView view = "where there is a will, there is a way";
        auto npos = decltype(view)::npos;

        // for find_first_of
        REQUIRE(5 == view.find_first_of(" ,"));
        REQUIRE(2 == view.find_first_of("aeiou"));

        // for find_last_of
        StringView view_1 = "abcd-1234-abcd-1234";
        REQUIRE(13 == view_1.find_last_of("d", 14));
        REQUIRE(npos == view_1.find_last_of("x"));

        StringView view_2 = "ABCD-1234-ABCD-1234";
        REQUIRE(11 == view_2.find_last_of("B1", 12));
        REQUIRE(16 == view_2.find_last_of("D2"));

        StringView view_3 = "456-EFG-456-EFG";
        REQUIRE(4 == view_3.find_last_of("5E", 8));

        StringView view_4 = "12-ab-12-ab";
        REQUIRE(4 == view_4.find_last_of("ba3", 8));
        REQUIRE(9 == view_4.find_last_of("a2"));
    }

    SECTION("find not of")
    {
        {
            StringView view_1 = "xddd-1234-abcd";
            REQUIRE(4 == view_1.find_first_not_of("d", 2));
            REQUIRE(1 == view_1.find_first_not_of("x"));

            StringView view_2 = "BBB-1111";
            REQUIRE(StringView::npos == view_2.find_first_not_of("B1", 6));
            REQUIRE(3 == view_2.find_first_not_of("B2"));

            StringView view_3 = "444-555-GGG";
            REQUIRE(3 == view_3.find_first_not_of("45G"));

            StringView view_4 = "12-ab-12-ab";
            REQUIRE(5 == view_4.find_first_not_of("ba3", 5));
            REQUIRE(2 == view_4.find_first_not_of("12"));
        }

        {
            StringView view_1 = "dddd-1dd4-abdd";
            REQUIRE(5 == view_1.find_last_not_of("d", 7));
            REQUIRE(11 == view_1.find_last_not_of("d"));

            StringView view_2 = "BBB-1111";
            REQUIRE(3 == view_2.find_last_not_of("B1", 6));
            REQUIRE(StringView::npos == view_2.find_last_not_of("B-1"));

            StringView view_3 = "444-555-GGG";
            auto pos1 = view_3.find_last_not_of("45G");
            INFO("pos1 = " << pos1);
            REQUIRE(7 == pos1);
            auto pos2 = view_3.find_last_not_of("45G", 6, 3);
            INFO("pos2 = " << pos2);
            REQUIRE(3 == pos2);

            StringView view_4 = "12-ab-12-ab";
            REQUIRE(1 == view_4.find_last_not_of("b-a", 5));
            REQUIRE(10 == view_4.find_last_not_of("12"));
        }
    }
}

TEST_CASE("Operator comparisons", "[StringUtil]")
{
    StringView view_1 = "abc";
    StringView view_2 = "adc";
    REQUIRE_FALSE(view_1 == view_2);
    REQUIRE(view_1 != view_2);

    std::string str_1 = "abc";
    const char kStr[] = "def";
    REQUIRE(view_1 == str_1);
    REQUIRE(view_2 != kStr);
}

TEST_CASE("Output to stream", "[StringUtil]")
{
    StringView v = "hello world";
    WStringView w = L"test text";
    std::cout << v << std::endl;
    std::wcout << w << std::endl;
}

TEST_CASE("Hash support", "[StringUtil]")
{
    StringView v = "hello world";
    WStringView w = L"hello world";
    StringView vx = "This is a test text";
    WStringView wx = L"This is a test text";

    REQUIRE(std::hash<StringView>()(v) == std::hash<StringView>()(v));
    REQUIRE(std::hash<WStringView>()(w) == std::hash<WStringView>()(w));
    REQUIRE(std::hash<StringView>()(v) != std::hash<StringView>()(vx));
    REQUIRE(std::hash<WStringView>()(w) != std::hash<WStringView>()(wx));
}

}   // namespace kbase
<|endoftext|>


<commit_before>/*Copyright 2014-2015 George Karagoulis

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.*/

#include "comportwatcher.h"
#include <QSerialPortInfo>
#include <QTimerEvent>
#include <gutil/macros.h>

NAMESPACE_GUTIL1(Qt);

QStringList COMPortWatcher::AvailablePorts()
{
    QStringList ret;
    for(const QSerialPortInfo &i : QSerialPortInfo::availablePorts())
        ret << i.portName();
    return ret;
}

COMPortWatcher::COMPortWatcher(QObject *parent)
    :QObject(parent),
      m_tid(-1)
{}

void COMPortWatcher::StartWatching(int interval_ms)
{
    Q_ASSERT(-1 == m_tid);
    m_tid = startTimer(interval_ms);
}

void COMPortWatcher::StopWatching()
{
    Q_ASSERT(-1 != m_tid);
    killTimer(m_tid);
    m_tid = -1;
    m_availablePorts.clear();
    emit NotifyAvailableCOMPortsChanged();
}

void COMPortWatcher::timerEvent(QTimerEvent *ev)
{
    Q_UNUSED(ev);

    bool updated = false;
    QStringList ap = AvailablePorts();
    m_lock.lock();
    if(ap != m_availablePorts){
        m_availablePorts = ap;
        updated = true;
    }
    m_lock.unlock();

    if(updated)
        emit NotifyAvailableCOMPortsChanged();
}

QStringList COMPortWatcher::GetAvailablePorts()
{
    QStringList ret;
    m_lock.lock();
    ret = m_availablePorts;
    m_lock.unlock();
    return ret;
}

END_NAMESPACE_GUTIL1;
<commit_msg>Don't crash if they stop watching twice<commit_after>/*Copyright 2014-2015 George Karagoulis

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.*/

#include "comportwatcher.h"
#include <QSerialPortInfo>
#include <QTimerEvent>
#include <gutil/macros.h>

NAMESPACE_GUTIL1(Qt);

QStringList COMPortWatcher::AvailablePorts()
{
    QStringList ret;
    for(const QSerialPortInfo &i : QSerialPortInfo::availablePorts())
        ret << i.portName();
    return ret;
}

COMPortWatcher::COMPortWatcher(QObject *parent)
    :QObject(parent),
      m_tid(-1)
{}

void COMPortWatcher::StartWatching(int interval_ms)
{
    Q_ASSERT(-1 == m_tid);
    m_tid = startTimer(interval_ms);
}

void COMPortWatcher::StopWatching()
{
    if(-1 != m_tid){
        killTimer(m_tid);
        m_tid = -1;
        m_availablePorts.clear();
        emit NotifyAvailableCOMPortsChanged();
    }
}

void COMPortWatcher::timerEvent(QTimerEvent *ev)
{
    Q_UNUSED(ev);

    bool updated = false;
    QStringList ap = AvailablePorts();
    m_lock.lock();
    if(ap != m_availablePorts){
        m_availablePorts = ap;
        updated = true;
    }
    m_lock.unlock();

    if(updated)
        emit NotifyAvailableCOMPortsChanged();
}

QStringList COMPortWatcher::GetAvailablePorts()
{
    QStringList ret;
    m_lock.lock();
    ret = m_availablePorts;
    m_lock.unlock();
    return ret;
}

END_NAMESPACE_GUTIL1;
<|endoftext|>


<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <windows.h>
#include <mmsystem.h>
#include <process.h>

#include "base/time.h"
#include "testing/gtest/include/gtest/gtest.h"

using base::Time;
using base::TimeDelta;
using base::TimeTicks;

namespace {

class MockTimeTicks : public TimeTicks {
 public:
  static DWORD Ticker() {
    return static_cast<int>(InterlockedIncrement(&ticker_));
  }

  static void InstallTicker() {
    old_tick_function_ = SetMockTickFunction(&Ticker);
    ticker_ = -5;
  }

  static void UninstallTicker() {
    SetMockTickFunction(old_tick_function_);
  }

 private:
  static volatile LONG ticker_;
  static TickFunctionType old_tick_function_;
};

volatile LONG MockTimeTicks::ticker_;
MockTimeTicks::TickFunctionType MockTimeTicks::old_tick_function_;

HANDLE g_rollover_test_start;

unsigned __stdcall RolloverTestThreadMain(void* param) {
  int64 counter = reinterpret_cast<int64>(param);
  DWORD rv = WaitForSingleObject(g_rollover_test_start, INFINITE);
  EXPECT_EQ(rv, WAIT_OBJECT_0);

  TimeTicks last = TimeTicks::Now();
  for (int index = 0; index < counter; index++) {
    TimeTicks now = TimeTicks::Now();
    int64 milliseconds = (now - last).InMilliseconds();
    // This is a tight loop; we could have looped faster than our
    // measurements, so the time might be 0 millis.
    EXPECT_GE(milliseconds, 0);
    EXPECT_LT(milliseconds, 250);
    last = now;
  }
  return 0;
}

}  // namespace

TEST(TimeTicks, WinRollover) {
  // The internal counter rolls over at ~49days.  We'll use a mock
  // timer to test this case.
  // Basic test algorithm:
  //   1) Set clock to rollover - N
  //   2) Create N threads
  //   3) Start the threads
  //   4) Each thread loops through TimeTicks() N times
  //   5) Each thread verifies integrity of result.

  const int kThreads = 8;
  // Use int64 so we can cast into a void* without a compiler warning.
  const int64 kChecks = 10;

  // It takes a lot of iterations to reproduce the bug!
  // (See bug 1081395)
  for (int loop = 0; loop < 4096; loop++) {
    // Setup
    MockTimeTicks::InstallTicker();
    g_rollover_test_start = CreateEvent(0, TRUE, FALSE, 0);
    HANDLE threads[kThreads];

    for (int index = 0; index < kThreads; index++) {
      void* argument = reinterpret_cast<void*>(kChecks);
      unsigned thread_id;
      threads[index] = reinterpret_cast<HANDLE>(
        _beginthreadex(NULL, 0, RolloverTestThreadMain, argument, 0,
          &thread_id));
      EXPECT_NE((HANDLE)NULL, threads[index]);
    }

    // Start!
    SetEvent(g_rollover_test_start);

    // Wait for threads to finish
    for (int index = 0; index < kThreads; index++) {
      DWORD rv = WaitForSingleObject(threads[index], INFINITE);
      EXPECT_EQ(rv, WAIT_OBJECT_0);
    }

    CloseHandle(g_rollover_test_start);

    // Teardown
    MockTimeTicks::UninstallTicker();
  }
}

TEST(TimeTicks, SubMillisecondTimers) {
  // Loop for a bit getting timers quickly.  We want to
  // see at least one case where we get a new sample in
  // less than one millisecond.
  bool saw_submillisecond_timer = false;
  int64 min_timer = 1000;
  TimeTicks last_time = TimeTicks::HighResNow();
  for (int index = 0; index < 1000; index++) {
    TimeTicks now = TimeTicks::HighResNow();
    TimeDelta delta = now - last_time;
    if (delta.InMicroseconds() > 0 &&
        delta.InMicroseconds() < 1000) {
      if (min_timer > delta.InMicroseconds())
        min_timer = delta.InMicroseconds();
      saw_submillisecond_timer = true;
    }
    last_time = now;
  }
  EXPECT_TRUE(saw_submillisecond_timer);
  printf("Min timer is: %ldus\n", static_cast<long>(min_timer));
}

TEST(TimeTicks, TimeGetTimeCaps) {
  // Test some basic assumptions that we expect about how timeGetDevCaps works.

  TIMECAPS caps;
  MMRESULT status = timeGetDevCaps(&caps, sizeof(caps));
  EXPECT_EQ(TIMERR_NOERROR, status);
  if (status != TIMERR_NOERROR) {
    printf("Could not get timeGetDevCaps\n");
    return;
  }

  EXPECT_GE(static_cast<int>(caps.wPeriodMin), 1);
  EXPECT_GT(static_cast<int>(caps.wPeriodMax), 1);
  EXPECT_GE(static_cast<int>(caps.wPeriodMin), 1);
  EXPECT_GT(static_cast<int>(caps.wPeriodMax), 1);
  printf("timeGetTime range is %d to %dms\n", caps.wPeriodMin,
    caps.wPeriodMax);
}

TEST(TimeTicks, QueryPerformanceFrequency) {
  // Test some basic assumptions that we expect about QPC.

  LARGE_INTEGER frequency;
  BOOL rv = QueryPerformanceFrequency(&frequency);
  EXPECT_EQ(TRUE, rv);
  EXPECT_GT(frequency.QuadPart, 1000000);  // Expect at least 1MHz
  printf("QueryPerformanceFrequency is %5.2fMHz\n",
    frequency.QuadPart / 1000000.0);
}

TEST(TimeTicks, TimerPerformance) {
  // Verify that various timer mechanisms can always complete quickly.
  // Note:  This is a somewhat arbitrary test.
  const int kLoops = 10000;
  // Due to the fact that these run on bbots, which are horribly slow,
  // we can't really make any guarantees about minimum runtime.
  // Really, we want these to finish in ~10ms, and that is generous.
  const int kMaxTime = 35;  // Maximum acceptible milliseconds for test.

  typedef TimeTicks (*TestFunc)();
  struct TestCase {
    TestFunc func;
    char *description;
  };
  // Cheating a bit here:  assumes sizeof(TimeTicks) == sizeof(Time)
  // in order to create a single test case list.
  COMPILE_ASSERT(sizeof(TimeTicks) == sizeof(Time),
                 test_only_works_with_same_sizes);
  TestCase cases[] = {
    { reinterpret_cast<TestFunc>(Time::Now), "Time::Now" },
    { TimeTicks::Now, "TimeTicks::Now" },
    { TimeTicks::HighResNow, "TimeTicks::HighResNow" },
    { NULL, "" }
  };

  int test_case = 0;
  while (cases[test_case].func) {
    TimeTicks start = TimeTicks::HighResNow();
    for (int index = 0; index < kLoops; index++)
      cases[test_case].func();
    TimeTicks stop = TimeTicks::HighResNow();
    // Turning off the check for acceptible delays.  Without this check,
    // the test really doesn't do much other than measure.  But the
    // measurements are still useful for testing timers on various platforms.
    // The reason to remove the check is because the tests run on many
    // buildbots, some of which are VMs.  These machines can run horribly
    // slow, and there is really no value for checking against a max timer.
    //EXPECT_LT((stop - start).InMilliseconds(), kMaxTime);
    printf("%s: %1.2fus per call\n", cases[test_case].description,
      (stop - start).InMillisecondsF() * 1000 / kLoops);
    test_case++;
  }
}
<commit_msg>Mark TimeTicks.SubMillisecondTimers as flaky.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <windows.h>
#include <mmsystem.h>
#include <process.h>

#include "base/time.h"
#include "testing/gtest/include/gtest/gtest.h"

using base::Time;
using base::TimeDelta;
using base::TimeTicks;

namespace {

class MockTimeTicks : public TimeTicks {
 public:
  static DWORD Ticker() {
    return static_cast<int>(InterlockedIncrement(&ticker_));
  }

  static void InstallTicker() {
    old_tick_function_ = SetMockTickFunction(&Ticker);
    ticker_ = -5;
  }

  static void UninstallTicker() {
    SetMockTickFunction(old_tick_function_);
  }

 private:
  static volatile LONG ticker_;
  static TickFunctionType old_tick_function_;
};

volatile LONG MockTimeTicks::ticker_;
MockTimeTicks::TickFunctionType MockTimeTicks::old_tick_function_;

HANDLE g_rollover_test_start;

unsigned __stdcall RolloverTestThreadMain(void* param) {
  int64 counter = reinterpret_cast<int64>(param);
  DWORD rv = WaitForSingleObject(g_rollover_test_start, INFINITE);
  EXPECT_EQ(rv, WAIT_OBJECT_0);

  TimeTicks last = TimeTicks::Now();
  for (int index = 0; index < counter; index++) {
    TimeTicks now = TimeTicks::Now();
    int64 milliseconds = (now - last).InMilliseconds();
    // This is a tight loop; we could have looped faster than our
    // measurements, so the time might be 0 millis.
    EXPECT_GE(milliseconds, 0);
    EXPECT_LT(milliseconds, 250);
    last = now;
  }
  return 0;
}

}  // namespace

TEST(TimeTicks, WinRollover) {
  // The internal counter rolls over at ~49days.  We'll use a mock
  // timer to test this case.
  // Basic test algorithm:
  //   1) Set clock to rollover - N
  //   2) Create N threads
  //   3) Start the threads
  //   4) Each thread loops through TimeTicks() N times
  //   5) Each thread verifies integrity of result.

  const int kThreads = 8;
  // Use int64 so we can cast into a void* without a compiler warning.
  const int64 kChecks = 10;

  // It takes a lot of iterations to reproduce the bug!
  // (See bug 1081395)
  for (int loop = 0; loop < 4096; loop++) {
    // Setup
    MockTimeTicks::InstallTicker();
    g_rollover_test_start = CreateEvent(0, TRUE, FALSE, 0);
    HANDLE threads[kThreads];

    for (int index = 0; index < kThreads; index++) {
      void* argument = reinterpret_cast<void*>(kChecks);
      unsigned thread_id;
      threads[index] = reinterpret_cast<HANDLE>(
        _beginthreadex(NULL, 0, RolloverTestThreadMain, argument, 0,
          &thread_id));
      EXPECT_NE((HANDLE)NULL, threads[index]);
    }

    // Start!
    SetEvent(g_rollover_test_start);

    // Wait for threads to finish
    for (int index = 0; index < kThreads; index++) {
      DWORD rv = WaitForSingleObject(threads[index], INFINITE);
      EXPECT_EQ(rv, WAIT_OBJECT_0);
    }

    CloseHandle(g_rollover_test_start);

    // Teardown
    MockTimeTicks::UninstallTicker();
  }
}

// Flaky, http://crbug.com/42850.
TEST(TimeTicks, FLAKY_SubMillisecondTimers) {
  // Loop for a bit getting timers quickly.  We want to
  // see at least one case where we get a new sample in
  // less than one millisecond.
  bool saw_submillisecond_timer = false;
  int64 min_timer = 1000;
  TimeTicks last_time = TimeTicks::HighResNow();
  for (int index = 0; index < 1000; index++) {
    TimeTicks now = TimeTicks::HighResNow();
    TimeDelta delta = now - last_time;
    if (delta.InMicroseconds() > 0 &&
        delta.InMicroseconds() < 1000) {
      if (min_timer > delta.InMicroseconds())
        min_timer = delta.InMicroseconds();
      saw_submillisecond_timer = true;
    }
    last_time = now;
  }
  EXPECT_TRUE(saw_submillisecond_timer);
  printf("Min timer is: %ldus\n", static_cast<long>(min_timer));
}

TEST(TimeTicks, TimeGetTimeCaps) {
  // Test some basic assumptions that we expect about how timeGetDevCaps works.

  TIMECAPS caps;
  MMRESULT status = timeGetDevCaps(&caps, sizeof(caps));
  EXPECT_EQ(TIMERR_NOERROR, status);
  if (status != TIMERR_NOERROR) {
    printf("Could not get timeGetDevCaps\n");
    return;
  }

  EXPECT_GE(static_cast<int>(caps.wPeriodMin), 1);
  EXPECT_GT(static_cast<int>(caps.wPeriodMax), 1);
  EXPECT_GE(static_cast<int>(caps.wPeriodMin), 1);
  EXPECT_GT(static_cast<int>(caps.wPeriodMax), 1);
  printf("timeGetTime range is %d to %dms\n", caps.wPeriodMin,
    caps.wPeriodMax);
}

TEST(TimeTicks, QueryPerformanceFrequency) {
  // Test some basic assumptions that we expect about QPC.

  LARGE_INTEGER frequency;
  BOOL rv = QueryPerformanceFrequency(&frequency);
  EXPECT_EQ(TRUE, rv);
  EXPECT_GT(frequency.QuadPart, 1000000);  // Expect at least 1MHz
  printf("QueryPerformanceFrequency is %5.2fMHz\n",
    frequency.QuadPart / 1000000.0);
}

TEST(TimeTicks, TimerPerformance) {
  // Verify that various timer mechanisms can always complete quickly.
  // Note:  This is a somewhat arbitrary test.
  const int kLoops = 10000;
  // Due to the fact that these run on bbots, which are horribly slow,
  // we can't really make any guarantees about minimum runtime.
  // Really, we want these to finish in ~10ms, and that is generous.
  const int kMaxTime = 35;  // Maximum acceptible milliseconds for test.

  typedef TimeTicks (*TestFunc)();
  struct TestCase {
    TestFunc func;
    char *description;
  };
  // Cheating a bit here:  assumes sizeof(TimeTicks) == sizeof(Time)
  // in order to create a single test case list.
  COMPILE_ASSERT(sizeof(TimeTicks) == sizeof(Time),
                 test_only_works_with_same_sizes);
  TestCase cases[] = {
    { reinterpret_cast<TestFunc>(Time::Now), "Time::Now" },
    { TimeTicks::Now, "TimeTicks::Now" },
    { TimeTicks::HighResNow, "TimeTicks::HighResNow" },
    { NULL, "" }
  };

  int test_case = 0;
  while (cases[test_case].func) {
    TimeTicks start = TimeTicks::HighResNow();
    for (int index = 0; index < kLoops; index++)
      cases[test_case].func();
    TimeTicks stop = TimeTicks::HighResNow();
    // Turning off the check for acceptible delays.  Without this check,
    // the test really doesn't do much other than measure.  But the
    // measurements are still useful for testing timers on various platforms.
    // The reason to remove the check is because the tests run on many
    // buildbots, some of which are VMs.  These machines can run horribly
    // slow, and there is really no value for checking against a max timer.
    //EXPECT_LT((stop - start).InMilliseconds(), kMaxTime);
    printf("%s: %1.2fus per call\n", cases[test_case].description,
      (stop - start).InMillisecondsF() * 1000 / kLoops);
    test_case++;
  }
}
<|endoftext|>


<commit_before>/*
Highly Optimized Object-oriented Many-particle Dynamics -- Blue Edition
(HOOMD-blue) Open Source Software License Copyright 2009-2014 The Regents of
the University of Michigan All rights reserved.

HOOMD-blue may contain modifications ("Contributions") provided, and to which
copyright is held, by various Contributors who have granted The Regents of the
University of Michigan the right to modify and/or distribute such Contributions.

You may redistribute, use, and create derivate works of HOOMD-blue, in source
and binary forms, provided you abide by the following conditions:

* Redistributions of source code must retain the above copyright notice, this
list of conditions, and the following disclaimer both in the code and
prominently in any materials provided with the distribution.

* Redistributions in binary form must reproduce the above copyright notice, this
list of conditions, and the following disclaimer in the documentation and/or
other materials provided with the distribution.

* All publications and presentations based on HOOMD-blue, including any reports
or published results obtained, in whole or in part, with HOOMD-blue, will
acknowledge its use according to the terms posted at the time of submission on:
http://codeblue.umich.edu/hoomd-blue/citations.html

* Any electronic documents citing HOOMD-Blue will link to the HOOMD-Blue website:
http://codeblue.umich.edu/hoomd-blue/

* Apart from the above required attributions, neither the name of the copyright
holder nor the names of HOOMD-blue's contributors may be used to endorse or
promote products derived from this software without specific prior written
permission.

Disclaimer

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND/OR ANY
WARRANTIES THAT THIS SOFTWARE IS FREE OF INFRINGEMENT ARE DISCLAIMED.

IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#ifdef WIN32
#pragma warning( push )
#pragma warning( disable : 4103 4244 )
#endif

//! label the boost test module
#define BOOST_TEST_MODULE GridshiftCorrectionTests
#include "boost_utf_configure.h"

#include "HOOMDMath.h"
#include "VectorMath.h"
#include "System.h"
#include "ParticleData.h"

#include <math.h>
#include <boost/shared_ptr.hpp>

/*! \file test_gridshift_correct.cc
    \brief Unit tests for the ParticleData class in response to origin shifts
    \ingroup unit_tests
*/

//! boost test case to verify proper operation of ZeroMomentumUpdater
BOOST_AUTO_TEST_CASE( ParticleDataGridShiftGetMethods )
    {
    // create a simple particle data to test with
    boost::shared_ptr<SystemDefinition> sysdef(new SystemDefinition(3, BoxDim(10.0), 4));
    boost::shared_ptr<ParticleData> pdata = sysdef->getParticleData();
    BoxDim box = pdata->getBox();
    {
    ArrayHandle<Scalar4> h_pos(pdata->getPositions(), access_location::host, access_mode::readwrite);
    ArrayHandle<Scalar4> h_vel(pdata->getVelocities(), access_location::host, access_mode::readwrite);

    h_pos.data[0].x = h_pos.data[0].y = h_pos.data[0].z = 0.0;
    h_pos.data[1].x = h_pos.data[1].y = h_pos.data[1].z = 1.0;
    }

    // compute a shift and apply it to all particles, and origin
    Scalar3 shift = make_scalar3(0.5,0.125,0.75);
    pdata->translateOrigin(shift);
    {
    ArrayHandle<Scalar4> h_pos(pdata->getPositions(), access_location::host, access_mode::readwrite);
    ArrayHandle<int3> h_img(pdata->getImages(), access_location::host, access_mode::readwrite);

    for (unsigned int i = 0; i < pdata->getN(); i++)
        {
        // read in the current position and orientation
        Scalar4 pos_i = h_pos.data[i];
        vec3<Scalar> r_i = vec3<Scalar>(pos_i); // translation from local to global coordinates
        r_i += vec3<Scalar>(shift);
        h_pos.data[i] = vec_to_scalar4(r_i, pos_i.w);
        box.wrap(h_pos.data[i], h_img.data[i]);
        }
    }

    // check that the particle positions are still the original ones
    Scalar3 pos = pdata->getPosition(0);
    MY_BOOST_CHECK_SMALL(pos.x-0.0, tol_small);
    MY_BOOST_CHECK_SMALL(pos.y-0.0, tol_small);
    MY_BOOST_CHECK_SMALL(pos.z-0.0, tol_small);
    pos = pdata->getPosition(1);
    MY_BOOST_CHECK_SMALL(pos.x-1.0, tol_small);
    MY_BOOST_CHECK_SMALL(pos.y-1.0, tol_small);
    MY_BOOST_CHECK_SMALL(pos.z-1.0, tol_small);

    int3 pimg = pdata->getImage(0);
    BOOST_CHECK_EQUAL(pimg.x, 0);
    BOOST_CHECK_EQUAL(pimg.y, 0);
    BOOST_CHECK_EQUAL(pimg.z, 0);
    pimg = pdata->getImage(0);
    BOOST_CHECK_EQUAL(pimg.x, 0);
    BOOST_CHECK_EQUAL(pimg.y, 0);
    BOOST_CHECK_EQUAL(pimg.z, 0);

    // compute a shift that will shift the image of the box
    Scalar3 shift_img = make_scalar3(10.5,10.125,10.75);
    pdata->translateOrigin(shift_img);
    {
    ArrayHandle<Scalar4> h_pos(pdata->getPositions(), access_location::host, access_mode::readwrite);
    ArrayHandle<int3> h_img(pdata->getImages(), access_location::host, access_mode::readwrite);

    for (unsigned int i = 0; i < pdata->getN(); i++)
        {
        // read in the current position and orientation
        Scalar4 pos_i = h_pos.data[i];
        vec3<Scalar> r_i = vec3<Scalar>(pos_i); // translation from local to global coordinates
        r_i += vec3<Scalar>(shift_img);
        h_pos.data[i] = vec_to_scalar4(r_i, pos_i.w);
        box.wrap(h_pos.data[i], h_img.data[i]);
        }
    }

    // check that the particle positions are still the original ones
    pos = pdata->getPosition(0);
    MY_BOOST_CHECK_SMALL(pos.x-0.0, tol_small);
    MY_BOOST_CHECK_SMALL(pos.y-0.0, tol_small);
    MY_BOOST_CHECK_SMALL(pos.z-0.0, tol_small);
    pos = pdata->getPosition(1);
    MY_BOOST_CHECK_SMALL(pos.x-1.0, tol_small);
    MY_BOOST_CHECK_SMALL(pos.y-1.0, tol_small);
    MY_BOOST_CHECK_SMALL(pos.z-1.0, tol_small);

    pimg = pdata->getImage(0);
    BOOST_CHECK_EQUAL(pimg.x, 0);
    BOOST_CHECK_EQUAL(pimg.y, 0);
    BOOST_CHECK_EQUAL(pimg.z, 0);
    pimg = pdata->getImage(0);
    BOOST_CHECK_EQUAL(pimg.x, 0);
    BOOST_CHECK_EQUAL(pimg.y, 0);
    BOOST_CHECK_EQUAL(pimg.z, 0);
    }

BOOST_AUTO_TEST_CASE( ParticleDataGridShiftSetMethods )
    {
    // create a simple particle data to test with
    boost::shared_ptr<SystemDefinition> sysdef(new SystemDefinition(3, BoxDim(10.0), 4));
    boost::shared_ptr<ParticleData> pdata = sysdef->getParticleData();
    BoxDim box = pdata->getBox();
    {
    ArrayHandle<Scalar4> h_pos(pdata->getPositions(), access_location::host, access_mode::readwrite);
    ArrayHandle<Scalar4> h_vel(pdata->getVelocities(), access_location::host, access_mode::readwrite);

    h_pos.data[0].x = h_pos.data[0].y = h_pos.data[0].z = 0.0;
    h_pos.data[1].x = h_pos.data[1].y = h_pos.data[1].z = 1.0;
    }

    // compute a shift that will shift the image of the box
    Scalar3 shift_img =  make_scalar3(10.5,10.125,10.75);
    pdata->translateOrigin(shift_img);
    {
    ArrayHandle<Scalar4> h_pos(pdata->getPositions(), access_location::host, access_mode::readwrite);
    ArrayHandle<int3> h_img(pdata->getImages(), access_location::host, access_mode::readwrite);

    for (unsigned int i = 0; i < pdata->getN(); i++)
        {
        // read in the current position and orientation
        Scalar4 pos_i = h_pos.data[i];
        vec3<Scalar> r_i = vec3<Scalar>(pos_i); // translation from local to global coordinates
        r_i += vec3<Scalar>(shift_img);
        h_pos.data[i] = vec_to_scalar4(r_i, pos_i.w);
        box.wrap(h_pos.data[i], h_img.data[i]);
        }
    }

    // check that the particle positions are still the original ones
    Scalar3 pos = pdata->getPosition(0);
    MY_BOOST_CHECK_SMALL(pos.x-0.0, tol_small);
    MY_BOOST_CHECK_SMALL(pos.y-0.0, tol_small);
    MY_BOOST_CHECK_SMALL(pos.z-0.0, tol_small);
    pos = pdata->getPosition(1);
    MY_BOOST_CHECK_SMALL(pos.x-1.0, tol_small);
    MY_BOOST_CHECK_SMALL(pos.y-1.0, tol_small);
    MY_BOOST_CHECK_SMALL(pos.z-1.0, tol_small);

    int3 pimg = pdata->getImage(0);
    BOOST_CHECK_EQUAL(pimg.x, 0);
    BOOST_CHECK_EQUAL(pimg.y, 0);
    BOOST_CHECK_EQUAL(pimg.z, 0);
    pimg = pdata->getImage(1);
    BOOST_CHECK_EQUAL(pimg.x, 0);
    BOOST_CHECK_EQUAL(pimg.y, 0);
    BOOST_CHECK_EQUAL(pimg.z, 0);

    //OK, now we set the positions using the particle data proxy
    Scalar3 new_pos0 = make_scalar3(0.1,0.5,0.7);
    pdata->setPosition(0,new_pos0);
    Scalar3 new_pos1 = make_scalar3(0.4,0.1,2.75);
    pdata->setPosition(1,new_pos1);

    Scalar3 ret_pos0 = pdata->getPosition(0);
    MY_BOOST_CHECK_SMALL(ret_pos0.x-new_pos0.x, tol_small);
    MY_BOOST_CHECK_SMALL(ret_pos0.y-new_pos0.y, tol_small);
    MY_BOOST_CHECK_SMALL(ret_pos0.z-new_pos0.z, tol_small);

    Scalar3 ret_pos1 = pdata->getPosition(1);
    MY_BOOST_CHECK_SMALL(ret_pos1.x-new_pos1.x, tol_small);
    MY_BOOST_CHECK_SMALL(ret_pos1.y-new_pos1.y, tol_small);
    MY_BOOST_CHECK_SMALL(ret_pos1.z-new_pos1.z, tol_small);

    //OK, now do the same with the images
    int3 new_img0 = make_int3(1,-5,7);
    pdata->setImage(0,new_img0);
    int3 new_img1 = make_int3(4,1,10);
    pdata->setImage(1,new_img1);

    int3 ret_img0 = pdata->getImage(0);
    BOOST_CHECK_EQUAL(ret_img0.x-new_img0.x, 0);
    BOOST_CHECK_EQUAL(ret_img0.y-new_img0.y, 0);
    BOOST_CHECK_EQUAL(ret_img0.z-new_img0.z, 0);

    int3 ret_img1 = pdata->getImage(1);
    BOOST_CHECK_EQUAL(ret_img1.x-new_img1.x, 0);
    BOOST_CHECK_EQUAL(ret_img1.y-new_img1.y, 0);
    BOOST_CHECK_EQUAL(ret_img1.z-new_img1.z, 0);
    }

#ifdef WIN32
#pragma warning( pop )
#endif
<commit_msg>Fix compile error in test_gridshift<commit_after>/*
Highly Optimized Object-oriented Many-particle Dynamics -- Blue Edition
(HOOMD-blue) Open Source Software License Copyright 2009-2014 The Regents of
the University of Michigan All rights reserved.

HOOMD-blue may contain modifications ("Contributions") provided, and to which
copyright is held, by various Contributors who have granted The Regents of the
University of Michigan the right to modify and/or distribute such Contributions.

You may redistribute, use, and create derivate works of HOOMD-blue, in source
and binary forms, provided you abide by the following conditions:

* Redistributions of source code must retain the above copyright notice, this
list of conditions, and the following disclaimer both in the code and
prominently in any materials provided with the distribution.

* Redistributions in binary form must reproduce the above copyright notice, this
list of conditions, and the following disclaimer in the documentation and/or
other materials provided with the distribution.

* All publications and presentations based on HOOMD-blue, including any reports
or published results obtained, in whole or in part, with HOOMD-blue, will
acknowledge its use according to the terms posted at the time of submission on:
http://codeblue.umich.edu/hoomd-blue/citations.html

* Any electronic documents citing HOOMD-Blue will link to the HOOMD-Blue website:
http://codeblue.umich.edu/hoomd-blue/

* Apart from the above required attributions, neither the name of the copyright
holder nor the names of HOOMD-blue's contributors may be used to endorse or
promote products derived from this software without specific prior written
permission.

Disclaimer

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND/OR ANY
WARRANTIES THAT THIS SOFTWARE IS FREE OF INFRINGEMENT ARE DISCLAIMED.

IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#ifdef WIN32
#pragma warning( push )
#pragma warning( disable : 4103 4244 )
#endif

//! label the boost test module
#define BOOST_TEST_MODULE GridshiftCorrectionTests
#include "boost_utf_configure.h"

#include "HOOMDMath.h"
#include "VectorMath.h"
#include "System.h"
#include "ParticleData.h"

#include <math.h>
#include <boost/shared_ptr.hpp>

/*! \file test_gridshift_correct.cc
    \brief Unit tests for the ParticleData class in response to origin shifts
    \ingroup unit_tests
*/

//! boost test case to verify proper operation of ZeroMomentumUpdater
BOOST_AUTO_TEST_CASE( ParticleDataGridShiftGetMethods )
    {
    // create a simple particle data to test with
    boost::shared_ptr<SystemDefinition> sysdef(new SystemDefinition(3, BoxDim(10.0), 4));
    boost::shared_ptr<ParticleData> pdata = sysdef->getParticleData();
    BoxDim box = pdata->getBox();
    {
    ArrayHandle<Scalar4> h_pos(pdata->getPositions(), access_location::host, access_mode::readwrite);
    ArrayHandle<Scalar4> h_vel(pdata->getVelocities(), access_location::host, access_mode::readwrite);

    h_pos.data[0].x = h_pos.data[0].y = h_pos.data[0].z = 0.0;
    h_pos.data[1].x = h_pos.data[1].y = h_pos.data[1].z = 1.0;
    }

    // compute a shift and apply it to all particles, and origin
    Scalar3 shift = make_scalar3(0.5,0.125,0.75);
    pdata->translateOrigin(shift);
    {
    ArrayHandle<Scalar4> h_pos(pdata->getPositions(), access_location::host, access_mode::readwrite);
    ArrayHandle<int3> h_img(pdata->getImages(), access_location::host, access_mode::readwrite);

    for (unsigned int i = 0; i < pdata->getN(); i++)
        {
        // read in the current position and orientation
        Scalar4 pos_i = h_pos.data[i];
        vec3<Scalar> r_i = vec3<Scalar>(pos_i); // translation from local to global coordinates
        r_i += vec3<Scalar>(shift);
        h_pos.data[i] = vec_to_scalar4(r_i, pos_i.w);
        box.wrap(h_pos.data[i], h_img.data[i]);
        }
    }

    // check that the particle positions are still the original ones
    Scalar3 pos = pdata->getPosition(0);
    MY_BOOST_CHECK_SMALL(Scalar(pos.x-0.0), tol_small);
    MY_BOOST_CHECK_SMALL(Scalar(pos.y-0.0), tol_small);
    MY_BOOST_CHECK_SMALL(Scalar(pos.z-0.0), tol_small);
    pos = pdata->getPosition(1);
    MY_BOOST_CHECK_SMALL(Scalar(pos.x-1.0), tol_small);
    MY_BOOST_CHECK_SMALL(Scalar(pos.y-1.0), tol_small);
    MY_BOOST_CHECK_SMALL(Scalar(pos.z-1.0), tol_small);

    int3 pimg = pdata->getImage(0);
    BOOST_CHECK_EQUAL(pimg.x, 0);
    BOOST_CHECK_EQUAL(pimg.y, 0);
    BOOST_CHECK_EQUAL(pimg.z, 0);
    pimg = pdata->getImage(0);
    BOOST_CHECK_EQUAL(pimg.x, 0);
    BOOST_CHECK_EQUAL(pimg.y, 0);
    BOOST_CHECK_EQUAL(pimg.z, 0);

    // compute a shift that will shift the image of the box
    Scalar3 shift_img = make_scalar3(10.5,10.125,10.75);
    pdata->translateOrigin(shift_img);
    {
    ArrayHandle<Scalar4> h_pos(pdata->getPositions(), access_location::host, access_mode::readwrite);
    ArrayHandle<int3> h_img(pdata->getImages(), access_location::host, access_mode::readwrite);

    for (unsigned int i = 0; i < pdata->getN(); i++)
        {
        // read in the current position and orientation
        Scalar4 pos_i = h_pos.data[i];
        vec3<Scalar> r_i = vec3<Scalar>(pos_i); // translation from local to global coordinates
        r_i += vec3<Scalar>(shift_img);
        h_pos.data[i] = vec_to_scalar4(r_i, pos_i.w);
        box.wrap(h_pos.data[i], h_img.data[i]);
        }
    }

    // check that the particle positions are still the original ones
    pos = pdata->getPosition(0);
    MY_BOOST_CHECK_SMALL(pos.x-0.0, tol_small);
    MY_BOOST_CHECK_SMALL(pos.y-0.0, tol_small);
    MY_BOOST_CHECK_SMALL(pos.z-0.0, tol_small);
    pos = pdata->getPosition(1);
    MY_BOOST_CHECK_SMALL(pos.x-1.0, tol_small);
    MY_BOOST_CHECK_SMALL(pos.y-1.0, tol_small);
    MY_BOOST_CHECK_SMALL(pos.z-1.0, tol_small);

    pimg = pdata->getImage(0);
    BOOST_CHECK_EQUAL(pimg.x, 0);
    BOOST_CHECK_EQUAL(pimg.y, 0);
    BOOST_CHECK_EQUAL(pimg.z, 0);
    pimg = pdata->getImage(0);
    BOOST_CHECK_EQUAL(pimg.x, 0);
    BOOST_CHECK_EQUAL(pimg.y, 0);
    BOOST_CHECK_EQUAL(pimg.z, 0);
    }

BOOST_AUTO_TEST_CASE( ParticleDataGridShiftSetMethods )
    {
    // create a simple particle data to test with
    boost::shared_ptr<SystemDefinition> sysdef(new SystemDefinition(3, BoxDim(10.0), 4));
    boost::shared_ptr<ParticleData> pdata = sysdef->getParticleData();
    BoxDim box = pdata->getBox();
    {
    ArrayHandle<Scalar4> h_pos(pdata->getPositions(), access_location::host, access_mode::readwrite);
    ArrayHandle<Scalar4> h_vel(pdata->getVelocities(), access_location::host, access_mode::readwrite);

    h_pos.data[0].x = h_pos.data[0].y = h_pos.data[0].z = 0.0;
    h_pos.data[1].x = h_pos.data[1].y = h_pos.data[1].z = 1.0;
    }

    // compute a shift that will shift the image of the box
    Scalar3 shift_img =  make_scalar3(10.5,10.125,10.75);
    pdata->translateOrigin(shift_img);
    {
    ArrayHandle<Scalar4> h_pos(pdata->getPositions(), access_location::host, access_mode::readwrite);
    ArrayHandle<int3> h_img(pdata->getImages(), access_location::host, access_mode::readwrite);

    for (unsigned int i = 0; i < pdata->getN(); i++)
        {
        // read in the current position and orientation
        Scalar4 pos_i = h_pos.data[i];
        vec3<Scalar> r_i = vec3<Scalar>(pos_i); // translation from local to global coordinates
        r_i += vec3<Scalar>(shift_img);
        h_pos.data[i] = vec_to_scalar4(r_i, pos_i.w);
        box.wrap(h_pos.data[i], h_img.data[i]);
        }
    }

    // check that the particle positions are still the original ones
    Scalar3 pos = pdata->getPosition(0);
    MY_BOOST_CHECK_SMALL(pos.x-0.0, tol_small);
    MY_BOOST_CHECK_SMALL(pos.y-0.0, tol_small);
    MY_BOOST_CHECK_SMALL(pos.z-0.0, tol_small);
    pos = pdata->getPosition(1);
    MY_BOOST_CHECK_SMALL(pos.x-1.0, tol_small);
    MY_BOOST_CHECK_SMALL(pos.y-1.0, tol_small);
    MY_BOOST_CHECK_SMALL(pos.z-1.0, tol_small);

    int3 pimg = pdata->getImage(0);
    BOOST_CHECK_EQUAL(pimg.x, 0);
    BOOST_CHECK_EQUAL(pimg.y, 0);
    BOOST_CHECK_EQUAL(pimg.z, 0);
    pimg = pdata->getImage(1);
    BOOST_CHECK_EQUAL(pimg.x, 0);
    BOOST_CHECK_EQUAL(pimg.y, 0);
    BOOST_CHECK_EQUAL(pimg.z, 0);

    //OK, now we set the positions using the particle data proxy
    Scalar3 new_pos0 = make_scalar3(0.1,0.5,0.7);
    pdata->setPosition(0,new_pos0);
    Scalar3 new_pos1 = make_scalar3(0.4,0.1,2.75);
    pdata->setPosition(1,new_pos1);

    Scalar3 ret_pos0 = pdata->getPosition(0);
    MY_BOOST_CHECK_SMALL(ret_pos0.x-new_pos0.x, tol_small);
    MY_BOOST_CHECK_SMALL(ret_pos0.y-new_pos0.y, tol_small);
    MY_BOOST_CHECK_SMALL(ret_pos0.z-new_pos0.z, tol_small);

    Scalar3 ret_pos1 = pdata->getPosition(1);
    MY_BOOST_CHECK_SMALL(ret_pos1.x-new_pos1.x, tol_small);
    MY_BOOST_CHECK_SMALL(ret_pos1.y-new_pos1.y, tol_small);
    MY_BOOST_CHECK_SMALL(ret_pos1.z-new_pos1.z, tol_small);

    //OK, now do the same with the images
    int3 new_img0 = make_int3(1,-5,7);
    pdata->setImage(0,new_img0);
    int3 new_img1 = make_int3(4,1,10);
    pdata->setImage(1,new_img1);

    int3 ret_img0 = pdata->getImage(0);
    BOOST_CHECK_EQUAL(ret_img0.x-new_img0.x, 0);
    BOOST_CHECK_EQUAL(ret_img0.y-new_img0.y, 0);
    BOOST_CHECK_EQUAL(ret_img0.z-new_img0.z, 0);

    int3 ret_img1 = pdata->getImage(1);
    BOOST_CHECK_EQUAL(ret_img1.x-new_img1.x, 0);
    BOOST_CHECK_EQUAL(ret_img1.y-new_img1.y, 0);
    BOOST_CHECK_EQUAL(ret_img1.z-new_img1.z, 0);
    }

#ifdef WIN32
#pragma warning( pop )
#endif
<|endoftext|>


<commit_before>/***********
AUTHORS: Stephen McCamant

BEGIN DATE: Feb, 2015

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 "stp/c_interface.h"
#include <gtest/gtest.h>

void test(void) {
    VC vc = vc_createValidityChecker();
    vc_setInterfaceFlags(vc, (ifaceflag_t)0, 0);
    vc_push(vc);
    Type ty_bv8 = vc_bvType(vc, 8);
    Type ty_bv16 = vc_bvType(vc, 16);
    Type ty_bv32 = vc_bvType(vc, 32);

    Expr var_i00 = vc_varExpr(vc, "i00", ty_bv8);

    Expr var_is4a = vc_varExpr(vc, "is4a", ty_bv16);
    Expr var_is48 = vc_varExpr(vc, "is48", ty_bv16);
    Expr var_iw48 = vc_varExpr(vc, "iw48", ty_bv32);

    Expr var_t343 = vc_varExpr(vc, "t343", ty_bv32);

    Expr const_0_8 = vc_bvConstExprFromInt(vc, 8, 0);
    Expr const_0_16 = vc_bvConstExprFromInt(vc, 16, 0);
    Expr const_0_32 = vc_bvConstExprFromInt(vc, 32, 0);

    Expr const_1_1 = vc_bvConstExprFromInt(vc, 1, 1);

    Expr const_42_32 = vc_bvConstExprFromLL(vc, 32, 42);
    Expr const_68_32 = vc_bvConstExprFromLL(vc, 32, 68);
    Expr const_69_32 = vc_bvConstExprFromLL(vc, 32, 69);

    Expr e_concat_35 = vc_bvConcatExpr(vc, const_0_16, var_is48);
    Expr e_concat_36 = vc_bvConcatExpr(vc, const_0_16, var_is4a);

    Expr e_concat_52 = vc_bvConcatExpr(vc, e_concat_36, const_0_16);
    Expr e_extract_50 = vc_bvExtract(vc, e_concat_52, 31, 0);

    Expr e_simp_5 = vc_simplify(vc, e_extract_50);
    Expr e_bvor_3 = vc_bvOrExpr(vc, e_concat_35, e_simp_5);
    Expr e_eq_69 = vc_eqExpr(vc, var_iw48, e_bvor_3);
    Expr e_boolbv_3 = vc_boolToBVExpr(vc, e_eq_69);
    Expr e_simp_6 = vc_simplify(vc, e_boolbv_3);
    Expr e_extract_67 = vc_bvExtract(vc, e_simp_6, 0, 0);
    Expr e_eq_70 = vc_eqExpr(vc, e_extract_67, const_1_1);
    vc_assertFormula(vc, e_eq_70);

    Expr e_bvplus = vc_bvPlusExpr(vc, 32, var_iw48, const_69_32);
    Expr e_sx = vc_bvSignExtend(vc, e_bvplus, 64);
    Expr const_2_64 = vc_bvConstExprFromLL(vc, 64, 2);
    Expr e_sbvmod = vc_sbvModExpr(vc, 64, e_sx, const_2_64);
    Expr e_extract_68 = vc_bvExtract(vc, e_sbvmod, 31, 0);
    Expr e_bvplus_2 = vc_bvPlusExpr(vc, 32, e_extract_68, const_42_32);
    Expr e_eq_71 = vc_eqExpr(vc, var_t343, e_bvplus_2);
    Expr e_boolbv_4 = vc_boolToBVExpr(vc, e_eq_71);
    Expr e_simp_7 = vc_simplify(vc, e_boolbv_4);
    Expr e_extract_69 = vc_bvExtract(vc, e_simp_7, 0, 0);
    Expr e_eq_72 = vc_eqExpr(vc, e_extract_69, const_1_1);
    vc_assertFormula(vc, e_eq_72);

    Expr e_eq_73 = vc_eqExpr(vc, var_t343, const_0_32);
    Expr e_boolbv_5 = vc_boolToBVExpr(vc, e_eq_73);

    Expr e_bvplus_3 = vc_bvPlusExpr(vc, 32, var_iw48, const_68_32);
    Expr e_eq_142 = vc_eqExpr(vc, e_bvplus_3, const_0_32);
    Expr e_boolbv_74 = vc_boolToBVExpr(vc, e_eq_142);

    Expr e_bvand_69 = vc_bvAndExpr(vc, e_boolbv_5, e_boolbv_74);
    Expr e_extract_70 = vc_bvExtract(vc, e_bvand_69, 0, 0);
    Expr e_eq_143 = vc_eqExpr(vc, e_extract_70, const_1_1);
    Expr e_not = vc_notExpr(vc, e_eq_143);
    Expr e_simp_9 = vc_simplify(vc, e_not);
    int ret = vc_query(vc, e_simp_9);
    ASSERT_TRUE(ret);
}

int main(int argc, char **argv) {
    test();
    return 0;
}
<commit_msg>No need for gtest here<commit_after>/***********
AUTHORS: Stephen McCamant

BEGIN DATE: Feb, 2015

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 "stp/c_interface.h"

void test(void) {
    VC vc = vc_createValidityChecker();
    vc_setInterfaceFlags(vc, (ifaceflag_t)0, 0);
    vc_push(vc);
    Type ty_bv8 = vc_bvType(vc, 8);
    Type ty_bv16 = vc_bvType(vc, 16);
    Type ty_bv32 = vc_bvType(vc, 32);

    Expr var_i00 = vc_varExpr(vc, "i00", ty_bv8);

    Expr var_is4a = vc_varExpr(vc, "is4a", ty_bv16);
    Expr var_is48 = vc_varExpr(vc, "is48", ty_bv16);
    Expr var_iw48 = vc_varExpr(vc, "iw48", ty_bv32);

    Expr var_t343 = vc_varExpr(vc, "t343", ty_bv32);

    Expr const_0_8 = vc_bvConstExprFromInt(vc, 8, 0);
    Expr const_0_16 = vc_bvConstExprFromInt(vc, 16, 0);
    Expr const_0_32 = vc_bvConstExprFromInt(vc, 32, 0);

    Expr const_1_1 = vc_bvConstExprFromInt(vc, 1, 1);

    Expr const_42_32 = vc_bvConstExprFromLL(vc, 32, 42);
    Expr const_68_32 = vc_bvConstExprFromLL(vc, 32, 68);
    Expr const_69_32 = vc_bvConstExprFromLL(vc, 32, 69);

    Expr e_concat_35 = vc_bvConcatExpr(vc, const_0_16, var_is48);
    Expr e_concat_36 = vc_bvConcatExpr(vc, const_0_16, var_is4a);

    Expr e_concat_52 = vc_bvConcatExpr(vc, e_concat_36, const_0_16);
    Expr e_extract_50 = vc_bvExtract(vc, e_concat_52, 31, 0);

    Expr e_simp_5 = vc_simplify(vc, e_extract_50);
    Expr e_bvor_3 = vc_bvOrExpr(vc, e_concat_35, e_simp_5);
    Expr e_eq_69 = vc_eqExpr(vc, var_iw48, e_bvor_3);
    Expr e_boolbv_3 = vc_boolToBVExpr(vc, e_eq_69);
    Expr e_simp_6 = vc_simplify(vc, e_boolbv_3);
    Expr e_extract_67 = vc_bvExtract(vc, e_simp_6, 0, 0);
    Expr e_eq_70 = vc_eqExpr(vc, e_extract_67, const_1_1);
    vc_assertFormula(vc, e_eq_70);

    Expr e_bvplus = vc_bvPlusExpr(vc, 32, var_iw48, const_69_32);
    Expr e_sx = vc_bvSignExtend(vc, e_bvplus, 64);
    Expr const_2_64 = vc_bvConstExprFromLL(vc, 64, 2);
    Expr e_sbvmod = vc_sbvModExpr(vc, 64, e_sx, const_2_64);
    Expr e_extract_68 = vc_bvExtract(vc, e_sbvmod, 31, 0);
    Expr e_bvplus_2 = vc_bvPlusExpr(vc, 32, e_extract_68, const_42_32);
    Expr e_eq_71 = vc_eqExpr(vc, var_t343, e_bvplus_2);
    Expr e_boolbv_4 = vc_boolToBVExpr(vc, e_eq_71);
    Expr e_simp_7 = vc_simplify(vc, e_boolbv_4);
    Expr e_extract_69 = vc_bvExtract(vc, e_simp_7, 0, 0);
    Expr e_eq_72 = vc_eqExpr(vc, e_extract_69, const_1_1);
    vc_assertFormula(vc, e_eq_72);

    Expr e_eq_73 = vc_eqExpr(vc, var_t343, const_0_32);
    Expr e_boolbv_5 = vc_boolToBVExpr(vc, e_eq_73);

    Expr e_bvplus_3 = vc_bvPlusExpr(vc, 32, var_iw48, const_68_32);
    Expr e_eq_142 = vc_eqExpr(vc, e_bvplus_3, const_0_32);
    Expr e_boolbv_74 = vc_boolToBVExpr(vc, e_eq_142);

    Expr e_bvand_69 = vc_bvAndExpr(vc, e_boolbv_5, e_boolbv_74);
    Expr e_extract_70 = vc_bvExtract(vc, e_bvand_69, 0, 0);
    Expr e_eq_143 = vc_eqExpr(vc, e_extract_70, const_1_1);
    Expr e_not = vc_notExpr(vc, e_eq_143);
    Expr e_simp_9 = vc_simplify(vc, e_not);
    int ret = vc_query(vc, e_simp_9);
    ASSERT_TRUE(ret);
}

int main(int argc, char **argv) {
    test();
    return 0;
}
<|endoftext|>


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

// the class BlockMatrixArray had no local type value_type that is
// needed in some places. in particular, this is needed for
// PreconditionBlockSSOR
//
// this test doesn't do anything particularly useful, it just makes sure that
// we can compile this kind of code

#include <base/logstream.h>
#include <lac/block_matrix_array.h>
#include <lac/sparse_matrix.h>
#include <iostream>
#include <fstream>

int main ()
{
  std::ofstream logfile("block_matrix_array_02.output");
  deallog.attach(logfile);
  deallog.depth_console(0);

  BlockMatrixArray<SparseMatrix<double> >::value_type i = 1.0;
  deallog << i << std::endl;

  return 0;
}
<commit_msg>Remove test again -- Guido is right.<commit_after><|endoftext|>


<commit_before>#include <iostream>
#include <ctime>
#include <cstdlib>
#include <RandomNumberGenerator.h>
#include "Sampler.h"
#include "Models/SimpleExample.h"

using namespace std;
using namespace DNest3;

int main()
{
	// Initialise RNG and seed with time
	RandomNumberGenerator::initialise_instance();
	RandomNumberGenerator::get_instance().set_seed(time(0));

	Sampler<SimpleExample> sampler(1000, 1000, 0.01, 100);
	sampler.initialise();

	for(int i=0; i<1000000; i++)
	{
		sampler.explore();
		sampler.refresh();
	}

	return 0;
}

<commit_msg>Run forever<commit_after>#include <iostream>
#include <ctime>
#include <cstdlib>
#include <RandomNumberGenerator.h>
#include "Sampler.h"
#include "Models/SimpleExample.h"

using namespace std;
using namespace DNest3;

int main()
{
	// Initialise RNG and seed with time
	RandomNumberGenerator::initialise_instance();
	RandomNumberGenerator::get_instance().set_seed(time(0));

	Sampler<SimpleExample> sampler(1000, 1000, 0.01, 100);
	sampler.initialise();

	while(true)
	{
		sampler.explore();
		sampler.refresh();
	}

	return 0;
}

<|endoftext|>


<commit_before>#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<cstring>
#define lli long long int
using namespace std ;

lli a[100002];
int main()
{
	lli n,q,t;
	scanf("%lld%lld",&n,&q);
	for(lli i=0;i<n;i++)
	{
		scanf("%lld",&a[i]);

	}
	sort(a,a+n);
	while(q--)
	{
		scanf("%lld",&t);
		if(a[0]<=t&&a[n-1]>=t)
		{
			printf("Yes\n");
		}
		else
		{
			printf("No\n");
		}
	}
	return 0;
}

<commit_msg>Delete DEVARRAYY.cpp<commit_after><|endoftext|>


<commit_before>/*
   Copyright 2012 Tzvetan Mikov <tmikov@gmail.com>
   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.
*/

#ifndef FASTINPUT_HPP
#define	FASTINPUT_HPP

#include "base.hpp"

#include "boost/scoped_array.hpp"

class io_error : public std::runtime_error
{
public:
  io_error ( const std::string & what ) : runtime_error( what ) {};
};

template<typename ELEM, typename RES, RES _EOF>
class FastInput
{
protected:
  ELEM * m_buf,  * m_head, * m_tail;
  off_t m_bufOffset;

  FastInput ( ELEM * buf )
  {
    m_buf = m_head = m_tail = buf;
    m_bufOffset = 0;
  }

public:
  static const RES EOFVAL = _EOF;

  virtual ~FastInput () {};

  __forceinline RES get ()
  {
    if (likely(m_head != m_tail))
      return *m_head++;
    else
      return slowGet();
  }

  __forceinline size_t read ( ELEM * dest, size_t count )
  {
    if (likely(m_tail - m_head >= count))
    {
      std::memcpy( dest, m_head, count*sizeof(ELEM) );
      m_head += count;
      return count;
    }
    else
      return slowRead( dest, count );
  }

  __forceinline RES peek ()
  {
    if (likely(m_head != m_tail))
      return *m_head;
    else
      return slowPeek();
  }

  size_t available () const { return m_tail - m_head; }
  const ELEM * head () const { return m_head; }
  const ELEM * tail () const { return m_tail; }

  void advance ( size_t len )
  {
    assert( len <= m_tail - m_head );
    m_head += len;
  }

  /**
   * Return the offset of the next character (head)
   */
  off_t offset () const
  {
    return m_bufOffset + (m_head - m_buf);
  }

  virtual size_t fillBuffer () = 0;

private:
  RES    slowGet ();
  RES    slowPeek ();
  size_t slowRead ( ELEM * dest, size_t count );
};

template<typename ELEM, typename RES, RES _EOF>
__neverinline RES FastInput<ELEM,RES,_EOF>::slowGet ()
{
  return fillBuffer() != 0 ? *m_head++ : EOFVAL;
}

template<typename ELEM, typename RES, RES _EOF>
__neverinline RES FastInput<ELEM,RES,_EOF>::slowPeek ()
{
  return fillBuffer() != 0 ? *m_head : EOFVAL;
}

template<typename ELEM, typename RES, RES _EOF>
__neverinline size_t FastInput<ELEM,RES,_EOF>::slowRead ( ELEM * dest, size_t count )
{
  assert( count != 0 );
  size_t res = 0;
  for(;;)
  {
    size_t len = std::min( available(), count );
    std::memcpy( dest, m_head, len * sizeof(ELEM) );
    dest += len;
    m_head += len;
    res += len;
    count -= len;
    if (!count || !fillBuffer())
      break;
  }
  return res;
}

typedef FastInput<unsigned char,int,-1> FastCharInput;

class CharBufInput : public FastCharInput
{
public:
  CharBufInput ( const char * str, size_t len );
  CharBufInput ( const char * str );
  CharBufInput ( const std::string & str );
  virtual size_t fillBuffer ();

  /**
   * Puts back one character. Must only be used for actual characters that have been read and must
   * always out back the character that was read.
   * @param x The character to put back
   */
  void unget ( int x )
  {
    assert( m_head > m_buf && (int)*(m_head-1) == x );
    --m_head;
  }
};

template<typename ELEM, typename RES, RES _EOF>
class BufferedInput : public FastInput<ELEM,RES,_EOF>
{
  typedef FastInput<ELEM,RES,_EOF> Super;

  boost::scoped_array<ELEM> m_bufCleaner;

protected:
  static const unsigned DEFAULT_BUFSIZE = 4096;
  size_t m_bufSize;

  BufferedInput ( size_t bufSize = DEFAULT_BUFSIZE )
    : Super( new ELEM[bufSize] ), m_bufCleaner( Super::m_buf ), m_bufSize(bufSize)
  {
    assert( bufSize > UNGET_LIMIT );
  };

public:
  static const unsigned UNGET_LIMIT = 8;

  /**
   * Puts back one character. No more than {@code UNGET_LIMIT} characters can
   * be put back
   * @param x The character to put back
   */
  void unget ( RES x )
  {
    assert( Super::m_head > Super::m_buf );
    *--Super::m_head = (ELEM)x;
  }

  virtual size_t fillBuffer ();
protected:
  /**
   * Read up to len bytes into m_tail and advance m_tail. Throw io_error on error.
   * @param len
   */
  virtual void doRead ( size_t len ) = 0;
};

template<typename ELEM, typename RES, RES _EOF>
size_t BufferedInput<ELEM,RES,_EOF>::fillBuffer ()
{
  if (Super::m_head < Super::m_tail) // Do we have unread data?
  {
    if (Super::m_head > Super::m_buf + UNGET_LIMIT) // Do we need to shift?
    {
      Super::m_bufOffset += Super::m_head - Super::m_buf - UNGET_LIMIT;
      size_t avail;
      memmove( Super::m_buf + UNGET_LIMIT, Super::m_head, (avail = Super::m_tail - Super::m_head)*sizeof(ELEM) );
      Super::m_head = Super::m_buf + UNGET_LIMIT;
      Super::m_tail = Super::m_head + avail;
    }
  }
  else
  {
    Super::m_bufOffset += Super::m_head - Super::m_buf - UNGET_LIMIT;
    Super::m_head = Super::m_tail = Super::m_buf + UNGET_LIMIT;
  }

  doRead( Super::m_buf + m_bufSize - Super::m_tail );

  return Super::available();
}

typedef BufferedInput<unsigned char,int,-1> BufferedCharInput;

#endif	/* FASTINPUT_HPP */

<commit_msg>FastInput: forceinline unget()<commit_after>/*
   Copyright 2012 Tzvetan Mikov <tmikov@gmail.com>
   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.
*/

#ifndef FASTINPUT_HPP
#define	FASTINPUT_HPP

#include "base.hpp"

#include "boost/scoped_array.hpp"

class io_error : public std::runtime_error
{
public:
  io_error ( const std::string & what ) : runtime_error( what ) {};
};

template<typename ELEM, typename RES, RES _EOF>
class FastInput
{
protected:
  ELEM * m_buf,  * m_head, * m_tail;
  off_t m_bufOffset;

  FastInput ( ELEM * buf )
  {
    m_buf = m_head = m_tail = buf;
    m_bufOffset = 0;
  }

public:
  static const RES EOFVAL = _EOF;

  virtual ~FastInput () {};

  __forceinline RES get ()
  {
    if (likely(m_head != m_tail))
      return *m_head++;
    else
      return slowGet();
  }

  __forceinline size_t read ( ELEM * dest, size_t count )
  {
    if (likely(m_tail - m_head >= count))
    {
      std::memcpy( dest, m_head, count*sizeof(ELEM) );
      m_head += count;
      return count;
    }
    else
      return slowRead( dest, count );
  }

  __forceinline RES peek ()
  {
    if (likely(m_head != m_tail))
      return *m_head;
    else
      return slowPeek();
  }

  size_t available () const { return m_tail - m_head; }
  const ELEM * head () const { return m_head; }
  const ELEM * tail () const { return m_tail; }

  void advance ( size_t len )
  {
    assert( len <= m_tail - m_head );
    m_head += len;
  }

  /**
   * Return the offset of the next character (head)
   */
  off_t offset () const
  {
    return m_bufOffset + (m_head - m_buf);
  }

  virtual size_t fillBuffer () = 0;

private:
  RES    slowGet ();
  RES    slowPeek ();
  size_t slowRead ( ELEM * dest, size_t count );
};

template<typename ELEM, typename RES, RES _EOF>
__neverinline RES FastInput<ELEM,RES,_EOF>::slowGet ()
{
  return fillBuffer() != 0 ? *m_head++ : EOFVAL;
}

template<typename ELEM, typename RES, RES _EOF>
__neverinline RES FastInput<ELEM,RES,_EOF>::slowPeek ()
{
  return fillBuffer() != 0 ? *m_head : EOFVAL;
}

template<typename ELEM, typename RES, RES _EOF>
__neverinline size_t FastInput<ELEM,RES,_EOF>::slowRead ( ELEM * dest, size_t count )
{
  assert( count != 0 );
  size_t res = 0;
  for(;;)
  {
    size_t len = std::min( available(), count );
    std::memcpy( dest, m_head, len * sizeof(ELEM) );
    dest += len;
    m_head += len;
    res += len;
    count -= len;
    if (!count || !fillBuffer())
      break;
  }
  return res;
}

typedef FastInput<unsigned char,int,-1> FastCharInput;

class CharBufInput : public FastCharInput
{
public:
  CharBufInput ( const char * str, size_t len );
  CharBufInput ( const char * str );
  CharBufInput ( const std::string & str );
  virtual size_t fillBuffer ();

  /**
   * Puts back one character. Must only be used for actual characters that have been read and must
   * always out back the character that was read.
   * @param x The character to put back
   */
  void unget ( int x )
  {
    assert( m_head > m_buf && (int)*(m_head-1) == x );
    --m_head;
  }
};

template<typename ELEM, typename RES, RES _EOF>
class BufferedInput : public FastInput<ELEM,RES,_EOF>
{
  typedef FastInput<ELEM,RES,_EOF> Super;

  boost::scoped_array<ELEM> m_bufCleaner;

protected:
  static const unsigned DEFAULT_BUFSIZE = 4096;
  size_t m_bufSize;

  BufferedInput ( size_t bufSize = DEFAULT_BUFSIZE )
    : Super( new ELEM[bufSize] ), m_bufCleaner( Super::m_buf ), m_bufSize(bufSize)
  {
    assert( bufSize > UNGET_LIMIT );
  };

public:
  static const unsigned UNGET_LIMIT = 8;

  /**
   * Puts back one character. No more than {@code UNGET_LIMIT} characters can
   * be put back
   * @param x The character to put back
   */
  __forceinline void unget ( RES x )
  {
    assert( Super::m_head > Super::m_buf );
    *--Super::m_head = (ELEM)x;
  }

  virtual size_t fillBuffer ();
protected:
  /**
   * Read up to len bytes into m_tail and advance m_tail. Throw io_error on error.
   * @param len
   */
  virtual void doRead ( size_t len ) = 0;
};

template<typename ELEM, typename RES, RES _EOF>
size_t BufferedInput<ELEM,RES,_EOF>::fillBuffer ()
{
  if (Super::m_head < Super::m_tail) // Do we have unread data?
  {
    if (Super::m_head > Super::m_buf + UNGET_LIMIT) // Do we need to shift?
    {
      Super::m_bufOffset += Super::m_head - Super::m_buf - UNGET_LIMIT;
      size_t avail;
      memmove( Super::m_buf + UNGET_LIMIT, Super::m_head, (avail = Super::m_tail - Super::m_head)*sizeof(ELEM) );
      Super::m_head = Super::m_buf + UNGET_LIMIT;
      Super::m_tail = Super::m_head + avail;
    }
  }
  else
  {
    Super::m_bufOffset += Super::m_head - Super::m_buf - UNGET_LIMIT;
    Super::m_head = Super::m_tail = Super::m_buf + UNGET_LIMIT;
  }

  doRead( Super::m_buf + m_bufSize - Super::m_tail );

  return Super::available();
}

typedef BufferedInput<unsigned char,int,-1> BufferedCharInput;

#endif	/* FASTINPUT_HPP */

<|endoftext|>


<commit_before>#include <istream>
#include <iostream>
#include <assimp/scene.h>
#include <assimp/Importer.hpp>
#include <assimp/postprocess.h>
#include <fstream>
#include "GPUBuffer.hh"

GRand::GPUBuffer::GPUBuffer() : _vbo(0), _scene(NULL) {
}

GRand::GPUBuffer::GPUBuffer(const GPUBuffer& o_) : _vbo(o_._vbo) {
    if (_vbo == 0) {
	_vertexArray = o_._vertexArray;
    }
}

void GRand::GPUBuffer::operator=(const GPUBuffer& o_) {
    _vbo = o_._vbo;
    if (_vbo) {
	return;
    }
    _vertexArray = o_._vertexArray;
}

bool GRand::GPUBuffer::loadFile(std::string const &name) {
    Assimp::Importer importer;

    std::ifstream fin(name.c_str());
    if (!fin.fail()) {
	fin.close();
    } else {
	std::cout << "Couldn't open file: " << name << std::endl;
	return false;
    }
    _scene = importer.ReadFile(name.c_str(), aiProcessPreset_TargetRealtime_Quality | aiProcess_Triangulate);
    if (!_scene) {
	std::cout << importer.GetErrorString() << std::endl;
	return false;
    }
    getAllFaces(_scene, _scene->mRootNode);
    return true;
}

void GRand::GPUBuffer::getAllFaces(const struct aiScene *sc, const struct aiNode* nd) {
    unsigned int n = 0;

    for (; n < nd->mNumMeshes; ++n) {
	const struct aiMesh* mesh = sc->mMeshes[nd->mMeshes[n]];
	unsigned int *faceArray;
	faceArray = (unsigned int *)malloc(sizeof(unsigned int) * mesh->mNumFaces * 3);
	unsigned int faceIndex = 0;
	if (_vertexArray.size() + mesh->mNumFaces * 6 > _vertexArray.capacity()) {
	    _vertexArray.reserve(_vertexArray.capacity() + mesh->mNumFaces * 6);
	}
	for (unsigned int i = 0; i < mesh->mNumVertices; i++) {
//	    std::cout << i << ":" << mesh->mVertices[i].x << " " << mesh->mVertices[i].y << " " << mesh->mVertices[i].z << std::endl;
	    _vertexArray.push_back(mesh->mVertices[i].x);
	    _vertexArray.push_back(mesh->mVertices[i].y);
	    _vertexArray.push_back(mesh->mVertices[i].z);
	    //_vertexArray.push_back(mesh->mNormals[i].x);
	    //_vertexArray.push_back(mesh->mNormals[i].y);
	    //_vertexArray.push_back(mesh->mNormals[i].z);
	}
	//if (_elementArray.size() + mesh->mNumFaces > _elementArray.capacity()) {
	//    _elementArray.reserve(_elementArray.capacity() + mesh->mNumFaces);
	//}
	for (unsigned int t = 0; t < mesh->mNumFaces; ++t) {
	    const struct aiFace* face = &mesh->mFaces[t];
	    for (unsigned int i = 0; i < face->mNumIndices; i++) { // go through all vertices in face
		_elementArray.push_back(face->mIndices[i]);
		std::cout << "hey" << _elementArray.back() << std::endl;
	    }
	}
    }
    for (n = 0; n < nd->mNumChildren; ++n) {
	getAllFaces(sc, nd->mChildren[n]);
	if (_elementArray.size() > 1)
		std::cout << "plopi" << _elementArray.back() << std::endl;
    }
}

void GRand::GPUBuffer::generateVBOAndVertexArray() {
    GLfloat vertices[] = {
	-0.5f,  0.5f, 0.f, // Top-left
	0.5f,  0.5f, 0.f, // Top-right
	0.5f, -0.5f, 0.f, // Bottom-right
	-0.5f, -0.5f, 0.f // Bottom-left
    };
    GLuint elements[] = {
        0, 1, 2,
        2, 3, 0
    };
    if (_vbo) {
	glDeleteBuffers(1, &_vbo);
    }
	if (_elementArray.size() > 1)
		std::cout << "plopi" << _elementArray.back() << std::endl;
    //_vertexArray = b_;
    glGenBuffers(1, &_vbo);
    glBindBuffer(GL_ARRAY_BUFFER, _vbo);
    glBufferData(GL_ARRAY_BUFFER, _vertexArray.size() * sizeof(decltype(_vertexArray)::value_type), &(_vertexArray[0]), GL_STATIC_DRAW);
    //glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

    glGenBuffers(1, &_ebo);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _ebo);
    //glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(elements), elements, GL_STATIC_DRAW);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, _elementArray.size() * sizeof(decltype(_vertexArray)::value_type), &(_elementArray[0]), GL_STATIC_DRAW);
	if (_elementArray.size() > 1)
		std::cout << "plopi" << _elementArray.back() << std::endl;
    std::cout << "ELEMENT ARRAY:";
    for (std::vector<GLuint>::iterator it = _elementArray.begin(); it != _elementArray.end(); it++) {
	std::cout << *it << " ";
    }
    std::cout << std::endl;
    int i = 0;
    for (std::vector<GLfloat>::iterator it = _vertexArray.begin(); it != _vertexArray.end(); it++) {
	i++;
	std::cout << *it << " ";
	if (i % 3 == 0) {
	    std::cout << std::endl;
	}
    }
}

void GRand::GPUBuffer::setBuffer(const decltype(_vertexArray)& b_) {
    if (_vbo) {
	glDeleteBuffers(1, &_vbo);
    }
    _vertexArray = b_;
    glGenBuffers(1, &_vbo);
    glBindBuffer(GL_ARRAY_BUFFER, _vbo);
    glBufferData(GL_ARRAY_BUFFER, _vertexArray.size() * sizeof(decltype(_vertexArray)::value_type), &_vertexArray[0], GL_STATIC_DRAW);
}

GRand::GPUBuffer::~GPUBuffer() {
}

void GRand::GPUBuffer::draw(GLenum drawStyle_) const noexcept {
    glEnableVertexAttribArray(0); // enable vertex shader parameter value
    glEnableVertexAttribArray(1); // enable normal shader parameter value
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _ebo);
    glBindBuffer(GL_ARRAY_BUFFER, _vbo);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(decltype(_vertexArray)::value_type), (void*)0);

    // when normal enabled
    // glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(decltype(_vertexArray)::value_type), (void*)0); // vertex
    // glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(decltype(_vertexArray)::value_type), 3 * sizeof(decltype(_vertexArray)::value_type)); //normal

    // with vertex color enabled
    // glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 9 * sizeof(decltype(_vertexArray)::value_type), (void*)0); // vertex
    // glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 9 * sizeof(decltype(_vertexArray)::value_type), 3 * sizeof(decltype(_vertexArray)::value_type)); // normal
    // glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 9 * sizeof(decltype(_vertexArray)::value_type), 6 * sizeof(decltype(_vertexArray)::value_type)); // vertex color

    // draw the polygon with the shader on the OpenGL draw buffer
    //glDrawArrays(drawStyle_, 0, _vertexArray.size());
    glDrawElements(drawStyle_, _elementArray.size(), GL_UNSIGNED_INT, 0);
    //glDrawElements(drawStyle_, 6, GL_UNSIGNED_INT, 0);
    //glDrawArrays(drawStyle_, 0, 4);
    glDisableVertexAttribArray(0);
    glDisableVertexAttribArray(1);
}
<commit_msg>easier to see like that<commit_after>#include <istream>
#include <iostream>
#include <assimp/scene.h>
#include <assimp/Importer.hpp>
#include <assimp/postprocess.h>
#include <fstream>
#include "GPUBuffer.hh"

GRand::GPUBuffer::GPUBuffer() : _vbo(0), _scene(NULL) {
}

GRand::GPUBuffer::GPUBuffer(const GPUBuffer& o_) : _vbo(o_._vbo) {
    if (_vbo == 0) {
	_vertexArray = o_._vertexArray;
    }
}

void GRand::GPUBuffer::operator=(const GPUBuffer& o_) {
    _vbo = o_._vbo;
    if (_vbo) {
	return;
    }
    _vertexArray = o_._vertexArray;
}

bool GRand::GPUBuffer::loadFile(std::string const &name) {
    Assimp::Importer importer;

    std::ifstream fin(name.c_str());
    if (!fin.fail()) {
	fin.close();
    } else {
	std::cout << "Couldn't open file: " << name << std::endl;
	return false;
    }
    _scene = importer.ReadFile(name.c_str(), aiProcessPreset_TargetRealtime_Quality | aiProcess_Triangulate);
    if (!_scene) {
	std::cout << importer.GetErrorString() << std::endl;
	return false;
    }
    getAllFaces(_scene, _scene->mRootNode);
    std::cout << "ea size once file loaded:" << _elementArray.size() << std::endl;
    return true;
}

void GRand::GPUBuffer::getAllFaces(const struct aiScene *sc, const struct aiNode* nd) {
    unsigned int n = 0;

    for (; n < nd->mNumMeshes; ++n) {
	const struct aiMesh* mesh = sc->mMeshes[nd->mMeshes[n]];
	unsigned int *faceArray;
	faceArray = (unsigned int *)malloc(sizeof(unsigned int) * mesh->mNumFaces * 3);
	if (_vertexArray.size() + mesh->mNumFaces * 6 > _vertexArray.capacity()) {
	    _vertexArray.reserve(_vertexArray.capacity() + mesh->mNumFaces * 6);
	}
	for (unsigned int i = 0; i < mesh->mNumVertices; i++) {
//	    std::cout << i << ":" << mesh->mVertices[i].x << " " << mesh->mVertices[i].y << " " << mesh->mVertices[i].z << std::endl;
	    _vertexArray.push_back(mesh->mVertices[i].x);
	    _vertexArray.push_back(mesh->mVertices[i].y);
	    _vertexArray.push_back(mesh->mVertices[i].z);
	    //_vertexArray.push_back(mesh->mNormals[i].x);
	    //_vertexArray.push_back(mesh->mNormals[i].y);
	    //_vertexArray.push_back(mesh->mNormals[i].z);
	}
	//if (_elementArray.size() + mesh->mNumFaces > _elementArray.capacity()) {
	//    _elementArray.reserve(_elementArray.capacity() + mesh->mNumFaces);
	//}
	for (unsigned int t = 0; t < mesh->mNumFaces; ++t) {
	    const struct aiFace* face = &mesh->mFaces[t];
	    for (unsigned int i = 0; i < face->mNumIndices; i++) { // go through all vertices in face
		unsigned int tmp = face->mIndices[i];
		_elementArray.push_back(tmp);
	    }
	}
    }
    for (n = 0; n < nd->mNumChildren; ++n) {
	getAllFaces(sc, nd->mChildren[n]);
    }
}

void GRand::GPUBuffer::generateVBOAndVertexArray() {
    /*GLfloat vertices[] = {
	-0.5f,  0.5f, 0.f, // Top-left
	0.5f,  0.5f, 0.f, // Top-right
	0.5f, -0.5f, 0.f, // Bottom-right
	-0.5f, -0.5f, 0.f // Bottom-left
    };
    GLuint elements[] = {
    0, 1, 2, 18, 0, 2, 3, 4, 5, 19, 3, 5, 6, 7, 8, 20, 6, 8, 9, 10, 11, 21, 9, 11, 12, 13, 14, 22, 12, 14, 15, 16, 17, 23, 15, 17
    };*/
    if (_vbo) {
	glDeleteBuffers(1, &_vbo);
    }
    std::cout << "ea size on generate ebo:" << _elementArray.size() << std::endl;
    //_vertexArray = b_;
    glGenBuffers(1, &_vbo);
    glBindBuffer(GL_ARRAY_BUFFER, _vbo);
    glBufferData(GL_ARRAY_BUFFER, _vertexArray.size() * sizeof(decltype(_vertexArray)::value_type), &(_vertexArray[0]), GL_STATIC_DRAW);
    //glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

    glGenBuffers(1, &_ebo);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _ebo);
    //glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(elements), elements, GL_STATIC_DRAW);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, _elementArray.size() * sizeof(decltype(_vertexArray)::value_type), &(_elementArray[0]), GL_STATIC_DRAW);
    std::cout << "ELEMENT ARRAY:";
    for (std::vector<GLuint>::iterator it = _elementArray.begin(); it != _elementArray.end(); it++) {
	std::cout << *it << " ";
    }
    std::cout << std::endl;
    /*int i = 0;
    for (std::vector<GLfloat>::iterator it = _vertexArray.begin(); it != _vertexArray.end(); it++) {
	i++;
	std::cout << *it << " ";
	if (i % 3 == 0) {
	    std::cout << std::endl;
	}
    }*/
}

void GRand::GPUBuffer::setBuffer(const decltype(_vertexArray)& b_) {
    if (_vbo) {
	glDeleteBuffers(1, &_vbo);
    }
    _vertexArray = b_;
    glGenBuffers(1, &_vbo);
    glBindBuffer(GL_ARRAY_BUFFER, _vbo);
    glBufferData(GL_ARRAY_BUFFER, _vertexArray.size() * sizeof(decltype(_vertexArray)::value_type), &_vertexArray[0], GL_STATIC_DRAW);
}

GRand::GPUBuffer::~GPUBuffer() {
}

void GRand::GPUBuffer::draw(GLenum drawStyle_) const noexcept {
    glEnableVertexAttribArray(0); // enable vertex shader parameter value
    glEnableVertexAttribArray(1); // enable normal shader parameter value
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _ebo);
    glBindBuffer(GL_ARRAY_BUFFER, _vbo);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(decltype(_vertexArray)::value_type), (void*)0);

    // when normal enabled
    // glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(decltype(_vertexArray)::value_type), (void*)0); // vertex
    // glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(decltype(_vertexArray)::value_type), 3 * sizeof(decltype(_vertexArray)::value_type)); //normal

    // with vertex color enabled
    // glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 9 * sizeof(decltype(_vertexArray)::value_type), (void*)0); // vertex
    // glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 9 * sizeof(decltype(_vertexArray)::value_type), 3 * sizeof(decltype(_vertexArray)::value_type)); // normal
    // glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 9 * sizeof(decltype(_vertexArray)::value_type), 6 * sizeof(decltype(_vertexArray)::value_type)); // vertex color

    // draw the polygon with the shader on the OpenGL draw buffer
    //glDrawArrays(drawStyle_, 0, _vertexArray.size());
    //std::cout << "ea size:" << _elementArray.size() << std::endl;
    glDrawElements(drawStyle_, _elementArray.size(), GL_UNSIGNED_INT, 0);
    //glDrawElements(drawStyle_, 6, GL_UNSIGNED_INT, 0);
    //glDrawArrays(drawStyle_, 0, 4);
    glDisableVertexAttribArray(0);
    glDisableVertexAttribArray(1);
}
<|endoftext|>