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

#include <pistache/http.h>
#include <pistache/description.h>
#include <pistache/client.h>
#include <pistache/endpoint.h>

using namespace std;
using namespace Pistache;

struct TestSet {
    TestSet()
        : bytes(0)
          , expectedCode(Http::Code::Ok)
          , actualCode(Http::Code::Ok)
    { }

    TestSet(size_t b, Http::Code c)
        : bytes(b)
          , expectedCode(c)
          , actualCode(Http::Code::Ok)
    { }

    size_t      bytes;
    Http::Code  expectedCode;
    Http::Code  actualCode;
};

typedef std::vector<TestSet> PayloadTestSets;

void testPayloads(std::string url, PayloadTestSets & testPayloads) {
   // Client tests to make sure the payload is enforced
    std::mutex resultsetMutex;
    PayloadTestSets test_results;
    Http::Client client;
    auto client_opts = Http::Client::options()
                         .threads(1)
                         .maxConnectionsPerHost(1);
    client.init(client_opts);
    auto rb = client.post(url);
    for (auto & t : testPayloads) {
        std::string payload(t.bytes, 'A');
        std::vector<Async::Promise<Http::Response> > responses;
        auto response = rb.body(payload).send();
        response.then([t,&test_results,&resultsetMutex](Http::Response rsp) {
                TestSet res(t);
                res.actualCode = rsp.code();
                {
                    std::unique_lock<std::mutex> lock(resultsetMutex);
                    test_results.push_back(res);
                }
                }, Async::IgnoreException);
        responses.push_back(std::move(response));
        auto sync = Async::whenAll(responses.begin(), responses.end());
        Async::Barrier<std::vector<Http::Response>> barrier(sync);
        barrier.wait_for(std::chrono::seconds(5));
    }
    client.shutdown();

    for (auto & result : test_results) {
        ASSERT_EQ(result.expectedCode, result.actualCode);
    }
}

void handleEcho(const Rest::Request&req, Http::ResponseWriter response) {
    response.send(Http::Code::Ok, req.body(), MIME(Text, Plain));
}

TEST(payload_test, from_description)
{
    Address addr(Ipv4::any(), 9084);
    const size_t threads = 20;
    const size_t maxPayload = 1024; // very small

    std::shared_ptr<Http::Endpoint> endpoint;
    Rest::Description desc("Rest Description Test", "v1");
    Rest::Router router;

    desc
        .route(desc.post("/echo"))
        .bind(&handleEcho)
        .response(Http::Code::Ok, "Response to the /ready call");

    router.initFromDescription(desc);

    auto flags = Tcp::Options::InstallSignalHandler | Tcp::Options::ReuseAddr;

    auto opts = Http::Endpoint::options()
        .threads(threads)
        .flags(flags)
        .maxPayload(maxPayload);
        ;

    endpoint = std::make_shared<Pistache::Http::Endpoint>(addr);
    endpoint->init(opts);
    endpoint->setHandler(router.handler());

    endpoint->serveThreaded();

    PayloadTestSets payloads{
       {800, Http::Code::Ok}
       , {1024, Http::Code::Request_Entity_Too_Large}
        ,{2048, Http::Code::Request_Entity_Too_Large}
    };

    testPayloads("127.0.0.1:9084/echo", payloads);
    endpoint->shutdown();
}

TEST(payload_test, manual_construction) {
    class MyHandler : public Http::Handler {
        HTTP_PROTOTYPE(MyHandler)

        void onRequest(
                const Http::Request& req,
                Http::ResponseWriter response)
        {
            if (req.resource() == "/echo") {
                if (req.method() == Http::Method::Post) {
                    response.send(Http::Code::Ok, req.body(), MIME(Text, Plain));
                } else {
                    response.send(Http::Code::Method_Not_Allowed);
                }
            } else {
                response.send(Http::Code::Not_Found);
            }

        }
    private:
        tag placeholder;
    };

    Port port(9080);
    int thr = 20;
    Address addr(Ipv4::any(), port);
    auto endpoint = std::make_shared<Http::Endpoint>(addr);
    size_t maxPayload = 2048;

    auto opts = Http::Endpoint::options()
        .threads(thr)
        .flags(Tcp::Options::InstallSignalHandler)
        .maxPayload(maxPayload);

    endpoint->init(opts);
    endpoint->setHandler(Http::make_handler<MyHandler>());
    endpoint->serveThreaded();

    PayloadTestSets payloads{
       {1024, Http::Code::Ok}
       , {1800, Http::Code::Ok}
       , {2048, Http::Code::Request_Entity_Too_Large}
       , {4096, Http::Code::Request_Entity_Too_Large}
    };

    testPayloads("127.0.0.1:9080/echo", payloads);

}

<commit_msg>Using forks to avoid shared global state between endpoints and clients<commit_after>#include "gtest/gtest.h"

#include <pistache/http.h>
#include <pistache/description.h>
#include <pistache/client.h>
#include <pistache/endpoint.h>

using namespace std;
using namespace Pistache;

struct TestSet {
    TestSet()
        : bytes(0)
          , expectedCode(Http::Code::Ok)
          , actualCode(Http::Code::Ok)
    { }

    TestSet(size_t b, Http::Code c)
        : bytes(b)
          , expectedCode(c)
          , actualCode(Http::Code::Ok)
    { }

    size_t      bytes;
    Http::Code  expectedCode;
    Http::Code  actualCode;
};

typedef std::vector<TestSet> PayloadTestSets;

static const uint16_t PORT = 9080;

void testPayloads(Http::Client & client, std::string url, PayloadTestSets & testPayloads) {
   // Client tests to make sure the payload is enforced
    std::mutex resultsetMutex;
    PayloadTestSets test_results;
    std::vector<Async::Promise<Http::Response> > responses;
    for (auto & t : testPayloads) {
        std::string payload(t.bytes, 'A');
        auto response = client.post(url).body(payload).send();
        response.then([t,&test_results,&resultsetMutex](Http::Response rsp) {
                TestSet res(t);
                res.actualCode = rsp.code();
                {
                    std::unique_lock<std::mutex> lock(resultsetMutex);
                    test_results.push_back(res);
                }
                }, Async::IgnoreException);
        responses.push_back(std::move(response));
    }

    auto sync = Async::whenAll(responses.begin(), responses.end());
    Async::Barrier<std::vector<Http::Response>> barrier(sync);
    barrier.wait_for(std::chrono::milliseconds(500));

    for (auto & result : test_results) {
        ASSERT_EQ(result.expectedCode, result.actualCode);
    }
}

void handleEcho(const Rest::Request&req, Http::ResponseWriter response) {
    UNUSED(req);
    response.send(Http::Code::Ok, "", MIME(Text, Plain));
}

TEST(payload, from_description)
{
    Http::Client client;
    auto client_opts = Http::Client::options()
        .threads(3)
        .maxConnectionsPerHost(3);
    client.init(client_opts);

    Address addr(Ipv4::any(), 9080);
    const size_t threads = 20;
    const size_t maxPayload = 1024; // very small

    auto pid = fork();
    if ( pid == 0) {
        std::shared_ptr<Http::Endpoint> endpoint;
        Rest::Description desc("Rest Description Test", "v1");
        Rest::Router router;

        desc
            .route(desc.post("/"))
            .bind(&handleEcho)
            .response(Http::Code::Ok, "Response to the /ready call");

        router.initFromDescription(desc);

        auto flags = Tcp::Options::InstallSignalHandler | Tcp::Options::ReuseAddr;

        auto opts = Http::Endpoint::options()
            .threads(threads)
            .flags(flags)
            .maxPayload(maxPayload);
            ;

        endpoint = std::make_shared<Pistache::Http::Endpoint>(addr);
        endpoint->init(opts);
        endpoint->setHandler(router.handler());
        endpoint->serve();
        endpoint->shutdown();
        return;
    }
    std::this_thread::sleep_for(std::chrono::milliseconds(150));
    PayloadTestSets payloads{
       {800, Http::Code::Ok}
       , {1024, Http::Code::Request_Entity_Too_Large}
        ,{2048, Http::Code::Request_Entity_Too_Large}
    };

    testPayloads(client, "127.0.0.1:" + std::to_string(PORT), payloads);
    kill(pid, SIGTERM);
    int r;
    waitpid(pid, &r, 0);
    client.shutdown();
}

TEST(payload, manual_construction) {
    class MyHandler : public Http::Handler {
        public:
        HTTP_PROTOTYPE(MyHandler)

        void onRequest(
                const Http::Request& req,
                Http::ResponseWriter response)
        {
            UNUSED(req);
            response.send(Http::Code::Ok, "All good");
        }
    private:
        tag placeholder;
    };

    Http::Client client;
    auto client_opts = Http::Client::options()
        .threads(3)
        .maxConnectionsPerHost(3);
    client.init(client_opts);

    Port    port(PORT);
    Address addr(Ipv4::any(), port);
    int     threads = 20;
    auto    flags = Tcp::Options::InstallSignalHandler | Tcp::Options::ReuseAddr;
    size_t  maxPayload = 2048;

    auto pid = fork();
    if (pid == 0) {
        auto endpoint = std::make_shared<Http::Endpoint>(addr);
        auto opts = Http::Endpoint::options()
            .threads(threads)
            .flags(flags)
            .maxPayload(maxPayload);
            ;

        endpoint->init(opts);
        endpoint->setHandler(Http::make_handler<MyHandler>());
        endpoint->serve();
        endpoint->shutdown();
        return;
    }

    PayloadTestSets payloads{
       {1024, Http::Code::Ok}
       , {1800, Http::Code::Ok}
       , {2048, Http::Code::Request_Entity_Too_Large}
       , {4096, Http::Code::Request_Entity_Too_Large}
    };
    testPayloads(client, "127.0.0.1:" + std::to_string(PORT), payloads);

    // Cleanup
    kill(pid, SIGTERM);
    int r;
    waitpid(pid, &r, 0);
    client.shutdown();
}
<|endoftext|>


<commit_before>
/*
 * Copyright (c) 2012 Aldebaran Robotics. All rights reserved.
 * Use of this source code is governed by a BSD-style license that can be
 * found in the COPYING file.
 */

#include <qi/log/journaldloghandler.hpp>

#include <qi/log.hpp>
#include <systemd/sd-journal.h>
#include <iostream>

namespace qi
{
namespace log
{
  void JournaldLogHandler::log(const qi::LogLevel verb,
                               const char* category,
                               const char* msg,
                               const char* file,
                               const char* fct,
                               const int line)
  {
    // systemd uses the log level defined by syslog.
    // Here is how we mix both.
    // LOG_EMERG(0)   LogLevel_Fatal(1)
    // LOG_ALERT(1)
    // LOG_CRIT(2)
    // LOG_ERR(3)     LogLevel_Error(2)
    // LOG_WARNING(4) LogLevel_Warning(3)
    // LOG_NOTICE(5)  LogLevel_Info(4)
    // LOG_INFO(6)    LogLevel_Verbose(5)
    // LOG_DEBUG(7)   LogLevel_Debug(6)
    int _verb = static_cast<int>(verb);
    if (_verb == 1) _verb = 0;
    else _verb += 1;

    int i = sd_journal_send("MESSAGE=%s",     msg,
                            "QI_CATEGORY=%s", category,
                            "PRIORITY=%i",    _verb,
                            "CODE_FILE=%s",   file,
                            "CODE_LINE=%i",   line,
                            "CODE_FUNC=%s",   fct,
                            NULL
                           );
    if (i == 0)
      return;

    // If it fail try to do a simpler call to journald
    int j = sd_journal_print(_verb, "%s; %s", category, msg);
    if (j == 0)
      return;

    // If it fail again print an error message
    std::cerr << "Can't set message to journald." << std::endl;
  }
}
}
<commit_msg>journaldloghandler: improve error message<commit_after>
/*
 * Copyright (c) 2012 Aldebaran Robotics. All rights reserved.
 * Use of this source code is governed by a BSD-style license that can be
 * found in the COPYING file.
 */

#include <qi/log/journaldloghandler.hpp>

#include <qi/log.hpp>
#include <systemd/sd-journal.h>
#include <iostream>

namespace qi
{
namespace log
{
  void JournaldLogHandler::log(const qi::LogLevel verb,
                               const char* category,
                               const char* msg,
                               const char* file,
                               const char* fct,
                               const int line)
  {
    // systemd uses the log level defined by syslog.
    // Here is how we mix both.
    // LOG_EMERG(0)   LogLevel_Fatal(1)
    // LOG_ALERT(1)
    // LOG_CRIT(2)
    // LOG_ERR(3)     LogLevel_Error(2)
    // LOG_WARNING(4) LogLevel_Warning(3)
    // LOG_NOTICE(5)  LogLevel_Info(4)
    // LOG_INFO(6)    LogLevel_Verbose(5)
    // LOG_DEBUG(7)   LogLevel_Debug(6)
    int _verb = static_cast<int>(verb);
    if (_verb == 1) _verb = 0;
    else _verb += 1;

    int i = sd_journal_send("MESSAGE=%s",     msg,
                            "QI_CATEGORY=%s", category,
                            "PRIORITY=%i",    _verb,
                            "CODE_FILE=%s",   file,
                            "CODE_LINE=%i",   line,
                            "CODE_FUNC=%s",   fct,
                            NULL
                           );
    if (i == 0)
      return;

    // If it fail try to do a simpler call to journald
    int j = sd_journal_print(_verb, "%s; %s", category, msg);
    if (j == 0)
      return;

    // If it fail again print an error message
    std::cerr << "Can't send message to journald." << std::endl;
  }
}
}
<|endoftext|>


<commit_before>#include <catch.hpp>

#include "stack.hpp"

TEST_CASE("Stack can be instantiated by various types", "[instantiation]") {
	REQUIRE_NOTHROW(stack<int> st1);
	REQUIRE_NOTHROW(stack<double> st1);
	REQUIRE_NOTHROW(stack<char> st1);
	REQUIRE_NOTHROW(stack<int*> st1);
	REQUIRE_NOTHROW(stack<stack<int>> st1);
}
TEST_CASE("Push, pop", "[push_pop]") {
	stack<int> st;
	st.push(1);
	st.push(2);
	REQUIRE(st.pop() == 2);
	REQUIRE(st.pop() == 1);
}
TEST_CASE("count", "[count]") {
	stack<int> st;
	REQUIRE(st.count() == 0);
	st.push(1);
	REQUIRE(st.count() == 1);
	st.push(2);
	REQUIRE(st.count() == 2);
	st.pop();
	REQUIRE(st.count() == 1);
	st.pop();
	REQUIRE(st.count() == 0);
}
TEST_CASE("Copy constructor, =", "[copy_ctr, =]") {
	stack<int> st1;
	st1.push(1);
	st1.push(2);
	REQUIRE_NOTHROW(stack<int> st2 = st1);
	REQUIRE_NOTHROW(stack<int> st2;
		st2 = st1);

	stack<int> st3 = st1;
	REQUIRE(st1.pop() == 2);
	REQUIRE(st3.pop() == 2);
	st3.pop();
	REQUIRE(st3.count() == 0);
	REQUIRE(st1.pop() == 1);
}
<commit_msg>Update init.cpp<commit_after>TEST_CASE("Stack can be instantiated by various types", "[instantiation]") {
	REQUIRE_NOTHROW(stack<int> st1);
	REQUIRE_NOTHROW(stack<double> st1);
	REQUIRE_NOTHROW(stack<char> st1);
	REQUIRE_NOTHROW(stack<int*> st1);
	REQUIRE_NOTHROW(stack<stack<int>> st1);
}
TEST_CASE("Push, pop, top", "[push_pop_top]") {
	stack<int> st;
	st.push(1);
	st.push(2);
	REQUIRE(st.top() == 2);
	st.pop();
	REQUIRE(st.top() == 1);
}
TEST_CASE("count", "[count]") {
	stack<int> st;
	REQUIRE(st.count() == 0);
	st.push(1);
	REQUIRE(st.count() == 1);
	st.push(2);
	REQUIRE(st.count() == 2);
	st.pop();
	REQUIRE(st.count() == 1);
	st.pop();
	REQUIRE(st.count() == 0);
}
TEST_CASE("Copy constructor, =", "[copy_ctr, =]") {
	stack<int> st1;
	st1.push(1);
	st1.push(2);
	REQUIRE_NOTHROW(stack<int> st2 = st1);
	REQUIRE_NOTHROW(stack<int> st2;
	st2 = st1);

	stack<int> st3 = st1;
	stack<int> st4 = st1;
	REQUIRE(st1.top() == 2);
	REQUIRE(st3.top() == 2);
	st3.pop();
	REQUIRE(st3.top() == 1);
	REQUIRE(st4.top() == 2);
	st4.pop();
	REQUIRE(st4.top() == 1);
}
<|endoftext|>


<commit_before>// Copyright (c) 2013 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 "content/browser/web_contents/aura/window_slider.h"

#include "base/bind.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/aura/root_window.h"
#include "ui/aura/test/aura_test_base.h"
#include "ui/aura/test/event_generator.h"
#include "ui/aura/test/test_window_delegate.h"
#include "ui/aura/window.h"
#include "ui/base/hit_test.h"

namespace content {

void DispatchEventDuringScrollCallback(aura::RootWindow* root_window,
                                       ui::Event* event,
                                       ui::EventType type,
                                       const gfx::Vector2dF& delta) {
  if (type != ui::ET_GESTURE_SCROLL_UPDATE)
    return;
  aura::RootWindowHostDelegate* delegate =
      root_window->AsRootWindowHostDelegate();
  if (event->IsMouseEvent())
    delegate->OnHostMouseEvent(static_cast<ui::MouseEvent*>(event));
  else if (event->IsKeyEvent())
    delegate->OnHostKeyEvent(static_cast<ui::KeyEvent*>(event));
}

void ChangeSliderOwnerDuringScrollCallback(scoped_ptr<aura::Window>* window,
                                           WindowSlider* slider,
                                           ui::EventType type,
                                           const gfx::Vector2dF& delta) {
  if (type != ui::ET_GESTURE_SCROLL_UPDATE)
    return;
  aura::Window* new_window = new aura::Window(NULL);
  new_window->Init(ui::LAYER_TEXTURED);
  new_window->Show();
  slider->ChangeOwner(new_window);
  (*window)->parent()->AddChild(new_window);
  window->reset(new_window);
}

// The window delegate does not receive any events.
class NoEventWindowDelegate : public aura::test::TestWindowDelegate {
 public:
  NoEventWindowDelegate() {
  }
  virtual ~NoEventWindowDelegate() {}

 private:
  // Overridden from aura::WindowDelegate:
  virtual bool HasHitTestMask() const OVERRIDE { return true; }

  DISALLOW_COPY_AND_ASSIGN(NoEventWindowDelegate);
};

class WindowSliderDelegateTest : public WindowSlider::Delegate {
 public:
  WindowSliderDelegateTest()
      : created_back_layer_(false),
        created_front_layer_(false),
        slide_completed_(false),
        slide_aborted_(false),
        slider_destroyed_(false) {
  }
  virtual ~WindowSliderDelegateTest() {}

  void Reset() {
    created_back_layer_ = false;
    created_front_layer_ = false;
    slide_completed_ = false;
    slide_aborted_ = false;
    slider_destroyed_ = false;
  }

  bool created_back_layer() const { return created_back_layer_; }
  bool created_front_layer() const { return created_front_layer_; }
  bool slide_completed() const { return slide_completed_; }
  bool slide_aborted() const { return slide_aborted_; }
  bool slider_destroyed() const { return slider_destroyed_; }

 private:
  ui::Layer* CreateLayerForTest() {
    ui::Layer* layer = new ui::Layer(ui::LAYER_SOLID_COLOR);
    layer->SetColor(SK_ColorRED);
    return layer;
  }

  // Overridden from WindowSlider::Delegate:
  virtual ui::Layer* CreateBackLayer() OVERRIDE {
    created_back_layer_ = true;
    return CreateLayerForTest();
  }

  virtual ui::Layer* CreateFrontLayer() OVERRIDE {
    created_front_layer_ = true;
    return CreateLayerForTest();
  }

  virtual void OnWindowSlideComplete() OVERRIDE {
    slide_completed_ = true;
  }

  virtual void OnWindowSlideAborted() OVERRIDE {
    slide_aborted_ = true;
  }

  virtual void OnWindowSliderDestroyed() OVERRIDE {
    slider_destroyed_ = true;
  }

  bool created_back_layer_;
  bool created_front_layer_;
  bool slide_completed_;
  bool slide_aborted_;
  bool slider_destroyed_;

  DISALLOW_COPY_AND_ASSIGN(WindowSliderDelegateTest);
};

typedef aura::test::AuraTestBase WindowSliderTest;

TEST_F(WindowSliderTest, WindowSlideUsingGesture) {
  scoped_ptr<aura::Window> window(CreateNormalWindow(0, root_window(), NULL));
  window->SetBounds(gfx::Rect(0, 0, 400, 400));
  WindowSliderDelegateTest slider_delegate;

  aura::test::EventGenerator generator(root_window());

  // Generate a horizontal overscroll.
  new WindowSlider(&slider_delegate, root_window(), window.get());
  generator.GestureScrollSequence(gfx::Point(10, 10),
                                  gfx::Point(160, 10),
                                  base::TimeDelta::FromMilliseconds(10),
                                  10);
  EXPECT_TRUE(slider_delegate.created_back_layer());
  EXPECT_TRUE(slider_delegate.slide_completed());
  EXPECT_FALSE(slider_delegate.created_front_layer());
  EXPECT_FALSE(slider_delegate.slide_aborted());
  EXPECT_TRUE(slider_delegate.slider_destroyed());
  slider_delegate.Reset();
  window->SetTransform(gfx::Transform());

  // Since the slider has been destroyed, recreate a new one.
  new WindowSlider(&slider_delegate, root_window(), window.get());

  // Generat a horizontal overscroll in the reverse direction.
  generator.GestureScrollSequence(gfx::Point(160, 10),
                                  gfx::Point(10, 10),
                                  base::TimeDelta::FromMilliseconds(10),
                                  10);
  EXPECT_TRUE(slider_delegate.created_front_layer());
  EXPECT_TRUE(slider_delegate.slide_completed());
  EXPECT_FALSE(slider_delegate.created_back_layer());
  EXPECT_FALSE(slider_delegate.slide_aborted());
  EXPECT_TRUE(slider_delegate.slider_destroyed());
  slider_delegate.Reset();

  // Since the slider has been destroyed, recreate a new one.
  new WindowSlider(&slider_delegate, root_window(), window.get());

  // Generate a vertical overscroll.
  generator.GestureScrollSequence(gfx::Point(10, 10),
                                  gfx::Point(10, 80),
                                  base::TimeDelta::FromMilliseconds(10),
                                  10);
  EXPECT_FALSE(slider_delegate.created_back_layer());
  EXPECT_FALSE(slider_delegate.slide_completed());
  EXPECT_FALSE(slider_delegate.created_front_layer());
  EXPECT_FALSE(slider_delegate.slide_aborted());
  slider_delegate.Reset();

  // Generate a horizontal scroll that starts overscroll, but doesn't scroll
  // enough to complete it.
  generator.GestureScrollSequence(gfx::Point(10, 10),
                                  gfx::Point(60, 10),
                                  base::TimeDelta::FromMilliseconds(10),
                                  10);
  EXPECT_TRUE(slider_delegate.created_back_layer());
  EXPECT_TRUE(slider_delegate.slide_aborted());
  EXPECT_FALSE(slider_delegate.created_front_layer());
  EXPECT_FALSE(slider_delegate.slide_completed());
  EXPECT_FALSE(slider_delegate.slider_destroyed());
  slider_delegate.Reset();

  // Destroy the window. This should destroy the slider.
  window.reset();
  EXPECT_TRUE(slider_delegate.slider_destroyed());
}

// Tests that the window slide is cancelled when a different type of event
// happens.
TEST_F(WindowSliderTest, WindowSlideIsCancelledOnEvent) {
  scoped_ptr<aura::Window> window(CreateNormalWindow(0, root_window(), NULL));
  WindowSliderDelegateTest slider_delegate;

  ui::Event* events[] = {
    new ui::MouseEvent(ui::ET_MOUSE_MOVED,
                       gfx::Point(55, 10),
                       gfx::Point(55, 10),
                       0),
    new ui::KeyEvent(ui::ET_KEY_PRESSED,
                     ui::VKEY_A,
                     0,
                     true),
    NULL
  };

  new WindowSlider(&slider_delegate, root_window(), window.get());
  for (int i = 0; events[i]; ++i) {
    // Generate a horizontal overscroll.
    aura::test::EventGenerator generator(root_window());
    generator.GestureScrollSequenceWithCallback(
        gfx::Point(10, 10),
        gfx::Point(80, 10),
        base::TimeDelta::FromMilliseconds(10),
        1,
        base::Bind(&DispatchEventDuringScrollCallback,
                   root_window(),
                   base::Owned(events[i])));
    EXPECT_TRUE(slider_delegate.created_back_layer());
    EXPECT_TRUE(slider_delegate.slide_aborted());
    EXPECT_FALSE(slider_delegate.created_front_layer());
    EXPECT_FALSE(slider_delegate.slide_completed());
    EXPECT_FALSE(slider_delegate.slider_destroyed());
    slider_delegate.Reset();
  }
  window.reset();
  EXPECT_TRUE(slider_delegate.slider_destroyed());
}

// Tests that the slide works correctly when the owner of the window changes
// during the duration of the slide.
TEST_F(WindowSliderTest, OwnerWindowChangesDuringWindowSlide) {
  scoped_ptr<aura::Window> parent(CreateNormalWindow(0, root_window(), NULL));

  NoEventWindowDelegate window_delegate;
  window_delegate.set_window_component(HTNOWHERE);
  scoped_ptr<aura::Window> window(CreateNormalWindow(1, parent.get(),
                                                     &window_delegate));

  WindowSliderDelegateTest slider_delegate;
  WindowSlider* slider = new WindowSlider(&slider_delegate, parent.get(),
                                          window.get());

  // Generate a horizontal scroll, and change the owner in the middle of the
  // scroll.
  aura::test::EventGenerator generator(root_window());
  aura::Window* old_window = window.get();
  generator.GestureScrollSequenceWithCallback(
      gfx::Point(10, 10),
      gfx::Point(80, 10),
      base::TimeDelta::FromMilliseconds(10),
      1,
      base::Bind(&ChangeSliderOwnerDuringScrollCallback,
                 base::Unretained(&window),
                 slider));
  aura::Window* new_window = window.get();
  EXPECT_NE(old_window, new_window);

  EXPECT_TRUE(slider_delegate.created_back_layer());
  EXPECT_TRUE(slider_delegate.slide_completed());
  EXPECT_FALSE(slider_delegate.created_front_layer());
  EXPECT_FALSE(slider_delegate.slide_aborted());
  EXPECT_TRUE(slider_delegate.slider_destroyed());
}

}  // namespace content
<commit_msg>Disable Aura tests on windows since the fail on Win Aura (2) bot.<commit_after>// Copyright (c) 2013 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 "content/browser/web_contents/aura/window_slider.h"

#include "base/bind.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/aura/root_window.h"
#include "ui/aura/test/aura_test_base.h"
#include "ui/aura/test/event_generator.h"
#include "ui/aura/test/test_window_delegate.h"
#include "ui/aura/window.h"
#include "ui/base/hit_test.h"

namespace content {

void DispatchEventDuringScrollCallback(aura::RootWindow* root_window,
                                       ui::Event* event,
                                       ui::EventType type,
                                       const gfx::Vector2dF& delta) {
  if (type != ui::ET_GESTURE_SCROLL_UPDATE)
    return;
  aura::RootWindowHostDelegate* delegate =
      root_window->AsRootWindowHostDelegate();
  if (event->IsMouseEvent())
    delegate->OnHostMouseEvent(static_cast<ui::MouseEvent*>(event));
  else if (event->IsKeyEvent())
    delegate->OnHostKeyEvent(static_cast<ui::KeyEvent*>(event));
}

void ChangeSliderOwnerDuringScrollCallback(scoped_ptr<aura::Window>* window,
                                           WindowSlider* slider,
                                           ui::EventType type,
                                           const gfx::Vector2dF& delta) {
  if (type != ui::ET_GESTURE_SCROLL_UPDATE)
    return;
  aura::Window* new_window = new aura::Window(NULL);
  new_window->Init(ui::LAYER_TEXTURED);
  new_window->Show();
  slider->ChangeOwner(new_window);
  (*window)->parent()->AddChild(new_window);
  window->reset(new_window);
}

// The window delegate does not receive any events.
class NoEventWindowDelegate : public aura::test::TestWindowDelegate {
 public:
  NoEventWindowDelegate() {
  }
  virtual ~NoEventWindowDelegate() {}

 private:
  // Overridden from aura::WindowDelegate:
  virtual bool HasHitTestMask() const OVERRIDE { return true; }

  DISALLOW_COPY_AND_ASSIGN(NoEventWindowDelegate);
};

class WindowSliderDelegateTest : public WindowSlider::Delegate {
 public:
  WindowSliderDelegateTest()
      : created_back_layer_(false),
        created_front_layer_(false),
        slide_completed_(false),
        slide_aborted_(false),
        slider_destroyed_(false) {
  }
  virtual ~WindowSliderDelegateTest() {}

  void Reset() {
    created_back_layer_ = false;
    created_front_layer_ = false;
    slide_completed_ = false;
    slide_aborted_ = false;
    slider_destroyed_ = false;
  }

  bool created_back_layer() const { return created_back_layer_; }
  bool created_front_layer() const { return created_front_layer_; }
  bool slide_completed() const { return slide_completed_; }
  bool slide_aborted() const { return slide_aborted_; }
  bool slider_destroyed() const { return slider_destroyed_; }

 private:
  ui::Layer* CreateLayerForTest() {
    ui::Layer* layer = new ui::Layer(ui::LAYER_SOLID_COLOR);
    layer->SetColor(SK_ColorRED);
    return layer;
  }

  // Overridden from WindowSlider::Delegate:
  virtual ui::Layer* CreateBackLayer() OVERRIDE {
    created_back_layer_ = true;
    return CreateLayerForTest();
  }

  virtual ui::Layer* CreateFrontLayer() OVERRIDE {
    created_front_layer_ = true;
    return CreateLayerForTest();
  }

  virtual void OnWindowSlideComplete() OVERRIDE {
    slide_completed_ = true;
  }

  virtual void OnWindowSlideAborted() OVERRIDE {
    slide_aborted_ = true;
  }

  virtual void OnWindowSliderDestroyed() OVERRIDE {
    slider_destroyed_ = true;
  }

  bool created_back_layer_;
  bool created_front_layer_;
  bool slide_completed_;
  bool slide_aborted_;
  bool slider_destroyed_;

  DISALLOW_COPY_AND_ASSIGN(WindowSliderDelegateTest);
};

typedef aura::test::AuraTestBase WindowSliderTest;

#if defined(OS_WIN)
// This test currently fails on the Win Aura (2) bot. http://crbug.com/249634
#define MAYBE_WindowSlideUsingGesture DISABLED_WindowSlideUsingGesture
#else
#define MAYBE_WindowSlideUsingGesture WindowSlideUsingGesture
#endif

TEST_F(WindowSliderTest, MAYBE_WindowSlideUsingGesture) {
  scoped_ptr<aura::Window> window(CreateNormalWindow(0, root_window(), NULL));
  window->SetBounds(gfx::Rect(0, 0, 400, 400));
  WindowSliderDelegateTest slider_delegate;

  aura::test::EventGenerator generator(root_window());

  // Generate a horizontal overscroll.
  new WindowSlider(&slider_delegate, root_window(), window.get());
  generator.GestureScrollSequence(gfx::Point(10, 10),
                                  gfx::Point(160, 10),
                                  base::TimeDelta::FromMilliseconds(10),
                                  10);
  EXPECT_TRUE(slider_delegate.created_back_layer());
  EXPECT_TRUE(slider_delegate.slide_completed());
  EXPECT_FALSE(slider_delegate.created_front_layer());
  EXPECT_FALSE(slider_delegate.slide_aborted());
  EXPECT_TRUE(slider_delegate.slider_destroyed());
  slider_delegate.Reset();
  window->SetTransform(gfx::Transform());

  // Since the slider has been destroyed, recreate a new one.
  new WindowSlider(&slider_delegate, root_window(), window.get());

  // Generat a horizontal overscroll in the reverse direction.
  generator.GestureScrollSequence(gfx::Point(160, 10),
                                  gfx::Point(10, 10),
                                  base::TimeDelta::FromMilliseconds(10),
                                  10);
  EXPECT_TRUE(slider_delegate.created_front_layer());
  EXPECT_TRUE(slider_delegate.slide_completed());
  EXPECT_FALSE(slider_delegate.created_back_layer());
  EXPECT_FALSE(slider_delegate.slide_aborted());
  EXPECT_TRUE(slider_delegate.slider_destroyed());
  slider_delegate.Reset();

  // Since the slider has been destroyed, recreate a new one.
  new WindowSlider(&slider_delegate, root_window(), window.get());

  // Generate a vertical overscroll.
  generator.GestureScrollSequence(gfx::Point(10, 10),
                                  gfx::Point(10, 80),
                                  base::TimeDelta::FromMilliseconds(10),
                                  10);
  EXPECT_FALSE(slider_delegate.created_back_layer());
  EXPECT_FALSE(slider_delegate.slide_completed());
  EXPECT_FALSE(slider_delegate.created_front_layer());
  EXPECT_FALSE(slider_delegate.slide_aborted());
  slider_delegate.Reset();

  // Generate a horizontal scroll that starts overscroll, but doesn't scroll
  // enough to complete it.
  generator.GestureScrollSequence(gfx::Point(10, 10),
                                  gfx::Point(60, 10),
                                  base::TimeDelta::FromMilliseconds(10),
                                  10);
  EXPECT_TRUE(slider_delegate.created_back_layer());
  EXPECT_TRUE(slider_delegate.slide_aborted());
  EXPECT_FALSE(slider_delegate.created_front_layer());
  EXPECT_FALSE(slider_delegate.slide_completed());
  EXPECT_FALSE(slider_delegate.slider_destroyed());
  slider_delegate.Reset();

  // Destroy the window. This should destroy the slider.
  window.reset();
  EXPECT_TRUE(slider_delegate.slider_destroyed());
}

#if defined(OS_WIN)
// This test currently fails on the Win Aura (2) bot. http://crbug.com/249634
#define MAYBE_WindowSlideIsCancelledOnEvent \
    DISABLED_WindowSlideIsCancelledOnEvent
#else
#define MAYBE_WindowSlideIsCancelledOnEvent WindowSlideIsCancelledOnEvent
#endif

// Tests that the window slide is cancelled when a different type of event
// happens.
TEST_F(WindowSliderTest, MAYBE_WindowSlideIsCancelledOnEvent) {
  scoped_ptr<aura::Window> window(CreateNormalWindow(0, root_window(), NULL));
  WindowSliderDelegateTest slider_delegate;

  ui::Event* events[] = {
    new ui::MouseEvent(ui::ET_MOUSE_MOVED,
                       gfx::Point(55, 10),
                       gfx::Point(55, 10),
                       0),
    new ui::KeyEvent(ui::ET_KEY_PRESSED,
                     ui::VKEY_A,
                     0,
                     true),
    NULL
  };

  new WindowSlider(&slider_delegate, root_window(), window.get());
  for (int i = 0; events[i]; ++i) {
    // Generate a horizontal overscroll.
    aura::test::EventGenerator generator(root_window());
    generator.GestureScrollSequenceWithCallback(
        gfx::Point(10, 10),
        gfx::Point(80, 10),
        base::TimeDelta::FromMilliseconds(10),
        1,
        base::Bind(&DispatchEventDuringScrollCallback,
                   root_window(),
                   base::Owned(events[i])));
    EXPECT_TRUE(slider_delegate.created_back_layer());
    EXPECT_TRUE(slider_delegate.slide_aborted());
    EXPECT_FALSE(slider_delegate.created_front_layer());
    EXPECT_FALSE(slider_delegate.slide_completed());
    EXPECT_FALSE(slider_delegate.slider_destroyed());
    slider_delegate.Reset();
  }
  window.reset();
  EXPECT_TRUE(slider_delegate.slider_destroyed());
}

// Tests that the slide works correctly when the owner of the window changes
// during the duration of the slide.
TEST_F(WindowSliderTest, OwnerWindowChangesDuringWindowSlide) {
  scoped_ptr<aura::Window> parent(CreateNormalWindow(0, root_window(), NULL));

  NoEventWindowDelegate window_delegate;
  window_delegate.set_window_component(HTNOWHERE);
  scoped_ptr<aura::Window> window(CreateNormalWindow(1, parent.get(),
                                                     &window_delegate));

  WindowSliderDelegateTest slider_delegate;
  WindowSlider* slider = new WindowSlider(&slider_delegate, parent.get(),
                                          window.get());

  // Generate a horizontal scroll, and change the owner in the middle of the
  // scroll.
  aura::test::EventGenerator generator(root_window());
  aura::Window* old_window = window.get();
  generator.GestureScrollSequenceWithCallback(
      gfx::Point(10, 10),
      gfx::Point(80, 10),
      base::TimeDelta::FromMilliseconds(10),
      1,
      base::Bind(&ChangeSliderOwnerDuringScrollCallback,
                 base::Unretained(&window),
                 slider));
  aura::Window* new_window = window.get();
  EXPECT_NE(old_window, new_window);

  EXPECT_TRUE(slider_delegate.created_back_layer());
  EXPECT_TRUE(slider_delegate.slide_completed());
  EXPECT_FALSE(slider_delegate.created_front_layer());
  EXPECT_FALSE(slider_delegate.slide_aborted());
  EXPECT_TRUE(slider_delegate.slider_destroyed());
}

}  // namespace content
<|endoftext|>


<commit_before>
#include "Buffer.cpp"

#include <thread>

void test1() {
	Buffer buf;

	auto producer = [&buf](){
		for(int i = 0; i < 100; ++i) {
			buf.push((uint8_t*)&i, sizeof(i));
		}
	};

	auto consumer = [&buf](){
		for(int i = 0; i < 100; ++i) {
			int ret;
			while(buf.size() < sizeof(ret)); // wait for entry
			size_t c = buf.pop((uint8_t*)&ret, sizeof(ret));
			assert(c == sizeof(ret));
			assert(ret == i);
		}
	};

	for(int i = 0; i < 1000; ++i) {
		producer();
		assert(buf.size() == 100 * sizeof(int));
		consumer();
		assert(buf.empty());
	}

	for(int i = 0; i < 1000; ++i) {
		std::thread t1(producer), t2(consumer);
		t1.join();
		t2.join();
		assert(buf.empty());
	}
}

int main() {
	test1();
}
<commit_msg>better test<commit_after>
#include "Buffer.cpp"

#include <thread>

void test1() {
	Buffer buf;

#define N 10000
	auto producer = [&buf](){
		for(uint32_t i = 0; i < N; ++i) {
			buf.push((uint8_t*)&i, sizeof(uint32_t));
		}
	};

	auto consumer = [&buf](){
		for(uint32_t i = 0; i < N; ++i) {
			int ret;
			while(buf.size() < sizeof(uint32_t)); // wait for entry
			size_t c = buf.pop((uint8_t*)&ret, sizeof(uint32_t));
			assert(c == sizeof(uint32_t));
			assert(ret == i);
		}
	};

	for(int i = 0; i < 3; ++i) {
		producer();
		assert(buf.size() == N * sizeof(int));
		consumer();
		assert(buf.empty());
	}

	for(int i = 0; i < 1000; ++i) {
		std::thread t1(producer), t2(consumer);
		t1.join();
		t2.join();
		assert(buf.empty());
	}
}

int main() {
	test1();
}
<|endoftext|>


<commit_before>#include "test_common.h"
#include <flags.h>
#include <thread>
#include <utils/exception.h>
#include <utils/utils.h>

namespace dariadb_test {
#undef NO_DATA

void checkAll(dariadb::Meas::MeasList res, std::string msg, dariadb::Time from,
              dariadb::Time to, dariadb::Time step) {

  dariadb::Id id_val(0);
  dariadb::Flag flg_val(0);
  for (auto i = from; i < to; i += step) {
    size_t count = 0;
    for (auto &m : res) {
      if ((m.id == id_val) &&
          ((m.flag == flg_val) || (m.flag == dariadb::Flags::_NO_DATA)) &&
          ((m.src == flg_val) || (m.src == dariadb::Flags::_NO_DATA))) {
        count++;
      }
    }

    if (count < copies_count) {
      throw MAKE_EXCEPTION("count < copies_count");
    }
    ++id_val;
    ++flg_val;
  }
}

void check_reader_of_all(dariadb::storage::Reader_ptr reader, dariadb::Time from,
                         dariadb::Time to, dariadb::Time step, size_t, size_t total_count,
                         std::string message) {
  dariadb::Meas::MeasList all{};
  reader->readAll(&all);

   std::map<dariadb::Id, dariadb::Meas::MeasList> _dict;
   for (auto &v : all) {
     _dict[v.id].push_back(v);
   }

  dariadb::Id cur_id = all.front().id;
  dariadb::Value cur_val = all.front().value;
  auto it = all.cbegin();
  ++it;
  for (; it != all.cend(); ++it) {
    auto cur_m = *it;
    if (cur_m.id != cur_id) {
      if (cur_m.id < cur_id) {
        throw MAKE_EXCEPTION("(it->id < cur_id)");
      } else {
        cur_id = cur_m.id;
        cur_val = cur_m.value;
        continue;
      }
    }
    if (cur_m.value < cur_val) {
      std::cout << cur_m.value << " => " << cur_val << std::endl;
      throw MAKE_EXCEPTION("(it->value < cur_val)");
    }
  }

  auto all_sz = all.size();
  if (all_sz != total_count) {
    throw MAKE_EXCEPTION("(all.size() != total_count)");
  }
  // TODO reset is sucks
  /*reader->reset();
  auto readed_ids = reader->getIds();
  if (readed_ids.size() != id_count) {
    throw MAKE_EXCEPTION("(readed_ids.size() != size_t((to - from) / step))");
  }*/

  checkAll(all, message, from, to, step);
}

void storage_test_check(dariadb::storage::MeasStorage *as, dariadb::Time from,
                        dariadb::Time to, dariadb::Time step) {
  auto m = dariadb::Meas::empty();
  size_t total_count = 0;

  dariadb::Id id_val(0);

  dariadb::Flag flg_val(0);
  dariadb::IdSet _all_ids_set;
  for (auto i = from; i < to; i += step) {
    _all_ids_set.insert(id_val);
    m.id = id_val;
    m.flag = flg_val;
    m.src = flg_val;
    m.time = i;
    m.value = 0;
    ++id_val;
    ++flg_val;
    for (size_t j = 1; j < copies_count + 1; j++) {
      if (as->append(m).writed != 1) {
        throw MAKE_EXCEPTION("->append(m).writed != 1");
      }
      total_count++;
      m.value = dariadb::Value(j);
      m.time++;
    }
  }

  dariadb::Meas::MeasList current_mlist;
  dariadb::IdArray _all_ids_array(_all_ids_set.begin(), _all_ids_set.end());
  as->currentValue(_all_ids_array, 0)->readAll(&current_mlist);
  if (current_mlist.size() == 0) {
    throw MAKE_EXCEPTION("current_mlist.size()>0");
  }

  as->flush();
  if (as->minTime() != from) {
	  throw MAKE_EXCEPTION("as->minTime() != from");
  }
  if (as->maxTime() < to) {
	  throw MAKE_EXCEPTION("as->maxTime() < to");
  }
  auto reader = as->readInterval(
      dariadb::storage::QueryInterval(_all_ids_array, 0, from, to + copies_count));
  check_reader_of_all(reader, from, to, step, id_val, total_count, "readAll error: ");

  auto cloned_reader = reader->clone();
  cloned_reader->reset();
  check_reader_of_all(cloned_reader, from, to, step, id_val, total_count,
                      "cloned readAll error: ");

  dariadb::IdArray ids(_all_ids_set.begin(), _all_ids_set.end());
  dariadb::Meas::MeasList all{};
  as->readInterval(dariadb::storage::QueryInterval(ids, 0, from, to + copies_count))
      ->readAll(&all);
  if (all.size() != total_count) {
    throw MAKE_EXCEPTION("all.size() != total_count");
  }

  checkAll(all, "read error: ", from, to, step);

  ids.clear();
  ids.push_back(2);
  dariadb::Meas::MeasList fltr_res{};
  as->readInterval(dariadb::storage::QueryInterval(ids, 0, from, to + copies_count))
      ->readAll(&fltr_res);

  if (fltr_res.size() != copies_count) {
    throw MAKE_EXCEPTION("fltr_res.size() != copies_count");
  }

  all.clear();
  auto qp = dariadb::storage::QueryTimePoint(
      dariadb::IdArray(_all_ids_set.begin(), _all_ids_set.end()), 0, to + copies_count);
  auto tp_reader = as->readInTimePoint(qp);
  tp_reader->readAll(&all);
  size_t ids_count = (size_t)((to - from) / step);
  if (all.size() < ids_count) {
    throw MAKE_EXCEPTION("all.size() < ids_count. must be GE");
  }

  tp_reader->reset();
  auto readed_ids = reader->getIds();
  if (readed_ids.size() != _all_ids_set.size()) {
	  throw MAKE_EXCEPTION("(eaded_ids.size() != _all_ids_set.size())");
  }

  fltr_res.clear();
  qp.time_point = to + copies_count;
  as->readInTimePoint(qp)->readAll(&fltr_res);
  if (fltr_res.size() < ids_count) {
    throw MAKE_EXCEPTION("fltr_res.size() < ids_count. must be GE");
  }

  dariadb::IdArray notExstsIDs{9999};
  fltr_res.clear();
  qp.ids = notExstsIDs;
  qp.time_point = to - 1;
  as->readInTimePoint(qp)->readAll(&fltr_res);
  if (fltr_res.size() != size_t(1)) { // must return NO_DATA
    throw MAKE_EXCEPTION("fltr_res.size() != size_t(1)");
  }

  if (fltr_res.front().flag != dariadb::Flags::_NO_DATA) {
    throw MAKE_EXCEPTION("fltr_res.front().flag != dariadb::Flags::NO_DATA");
  }
}

void readIntervalCommonTest(dariadb::storage::MeasStorage *ds) {
  dariadb::Meas m;
  {
    m.id = 1;
    m.time = 1;
    ds->append(m);
    m.id = 2;
    m.time = 2;
    ds->append(m);

    m.id = 4;
    m.time = 4;
    ds->append(m);
    m.id = 5;
    m.time = 5;
    ds->append(m);
    m.id = 55;
    m.time = 5;
    ds->append(m);

    dariadb::IdArray all_id = {1, 2, 4, 5, 55};
    {
      auto tp_reader = ds->readInTimePoint({all_id, 0, 6});
      dariadb::Meas::MeasList output_in_point{};
      tp_reader->readAll(&output_in_point);

      if (output_in_point.size() != size_t(5)) {
        throw MAKE_EXCEPTION("(output_in_point.size() != size_t(5))");
      }

      auto rdr = ds->readInterval(dariadb::storage::QueryInterval(all_id, 0, 0, 6));
      output_in_point.clear();
      rdr->readAll(&output_in_point);
      if (output_in_point.size() != size_t(5)) {
        throw MAKE_EXCEPTION("(output_in_point.size() != size_t(5))");
      }
    }
    {

      auto tp_reader = ds->readInTimePoint({all_id, 0, 3});
      dariadb::Meas::MeasList output_in_point{};
      tp_reader->readAll(&output_in_point);

      ///+ timepoint(3) with no_data
      if (output_in_point.size() != size_t(2 + 3)) {
        throw MAKE_EXCEPTION("(output_in_point.size() != size_t(2 + 3))");
      }
      for (auto v : output_in_point) {
        if (!(v.time <= 3)) {
          throw MAKE_EXCEPTION("!(v.time <= 3)");
        }
      }
    }
    auto reader = ds->readInterval(dariadb::storage::QueryInterval(all_id, 0, 3, 5));
    dariadb::Meas::MeasList output{};
    reader->readAll(&output);
    if (output.size() != size_t(5 + 3)) { //+ timepoint(3) with no_data
      throw MAKE_EXCEPTION("output.size() != size_t(5 + 3)");
    }
  }
  // from this point read not from firsts.
  {
    m.id = 1;
    m.time = 6;
    ds->append(m);
    m.id = 2;
    m.time = 7;
    ds->append(m);

    m.id = 4;
    m.time = 9;
    ds->append(m);
    m.id = 5;
    m.time = 10;
    ds->append(m);
    m.id = 6;
    m.time = 10;
    ds->append(m);
    dariadb::IdArray second_all_id = {1, 2, 4, 5, 6, 55};
    {

      auto tp_reader = ds->readInTimePoint({second_all_id, 0, 8});
      dariadb::Meas::MeasList output_in_point{};
      tp_reader->readAll(&output_in_point);

      ///+ timepoimt(8) with no_data
      if (output_in_point.size() != size_t(5 + 1)) {
        throw MAKE_EXCEPTION("(output_in_point.size() != size_t(5 + 1))");
      }
      for (auto v : output_in_point) {
        if (!(v.time <= 8)) {
          throw MAKE_EXCEPTION("!(v.time <= 8))");
        }
      }
    }

    auto reader = ds->readInterval(
        dariadb::storage::QueryInterval(dariadb::IdArray{1, 2, 4, 5, 55}, 0, 8, 10));
    dariadb::Meas::MeasList output{};
    reader->readAll(&output);
    if (output.size() != size_t(7)) {
      throw MAKE_EXCEPTION("output.size() != size_t(7)");
    }
    // expect: {1,8} {2,8} {4,8} {55,8} {4,9} {5,10}
    if (output.size() != size_t(7)) {
      std::cout << " ERROR!!!!" << std::endl;

      for (dariadb::Meas v : output) {
        std::cout << " id:" << v.id << " flg:" << v.flag << " v:" << v.value
                  << " t:" << v.time << std::endl;
      }
      throw MAKE_EXCEPTION("!!!");
    }
  }
}
}
<commit_msg>all tests passed.<commit_after>#include "test_common.h"
#include <flags.h>
#include <thread>
#include <utils/exception.h>
#include <utils/utils.h>

namespace dariadb_test {
#undef NO_DATA

void checkAll(dariadb::Meas::MeasList res, std::string msg, dariadb::Time from,
              dariadb::Time to, dariadb::Time step) {

  dariadb::Id id_val(0);
  dariadb::Flag flg_val(0);
  for (auto i = from; i < to; i += step) {
    size_t count = 0;
    for (auto &m : res) {
      if ((m.id == id_val) &&
          ((m.flag == flg_val) || (m.flag == dariadb::Flags::_NO_DATA)) &&
          ((m.src == flg_val) || (m.src == dariadb::Flags::_NO_DATA))) {
        count++;
      }
    }

    if (count < copies_count) {
      throw MAKE_EXCEPTION("count < copies_count");
    }
    ++id_val;
    ++flg_val;
  }
}

void check_reader_of_all(dariadb::storage::Reader_ptr reader, dariadb::Time from,
                         dariadb::Time to, dariadb::Time step, size_t, size_t total_count,
                         std::string message) {
  dariadb::Meas::MeasList all{};
  reader->readAll(&all);

   std::map<dariadb::Id, dariadb::Meas::MeasList> _dict;
   for (auto &v : all) {
     _dict[v.id].push_back(v);
   }

  dariadb::Id cur_id = all.front().id;
  dariadb::Value cur_val = all.front().value;
  auto it = all.cbegin();
  ++it;
  for (; it != all.cend(); ++it) {
    auto cur_m = *it;
    if (cur_m.id != cur_id) {
      if (cur_m.id < cur_id) {
        throw MAKE_EXCEPTION("(it->id < cur_id)");
      } else {
        cur_id = cur_m.id;
        cur_val = cur_m.value;
        continue;
      }
    }
    if (cur_m.value < cur_val) {
      std::cout << cur_m.value << " => " << cur_val << std::endl;
      throw MAKE_EXCEPTION("(it->value < cur_val)");
    }
  }

  auto all_sz = all.size();
  if (all_sz != total_count) {
    throw MAKE_EXCEPTION("(all.size() != total_count)");
  }
  // TODO reset is sucks
  /*reader->reset();
  auto readed_ids = reader->getIds();
  if (readed_ids.size() != id_count) {
    throw MAKE_EXCEPTION("(readed_ids.size() != size_t((to - from) / step))");
  }*/

  checkAll(all, message, from, to, step);
}

void storage_test_check(dariadb::storage::MeasStorage *as, dariadb::Time from,
                        dariadb::Time to, dariadb::Time step) {
  auto m = dariadb::Meas::empty();
  size_t total_count = 0;

  dariadb::Id id_val(0);

  dariadb::Flag flg_val(0);
  dariadb::IdSet _all_ids_set;
  for (auto i = from; i < to; i += step) {
    _all_ids_set.insert(id_val);
    m.id = id_val;
    m.flag = flg_val;
    m.src = flg_val;
    m.time = i;
    m.value = 0;
    ++id_val;
    ++flg_val;
    for (size_t j = 1; j < copies_count + 1; j++) {
      if (as->append(m).writed != 1) {
        throw MAKE_EXCEPTION("->append(m).writed != 1");
      }
      total_count++;
      m.value = dariadb::Value(j);
      m.time++;
    }
  }

  dariadb::Meas::MeasList current_mlist;
  dariadb::IdArray _all_ids_array(_all_ids_set.begin(), _all_ids_set.end());
  as->currentValue(_all_ids_array, 0)->readAll(&current_mlist);
  if (current_mlist.size() == 0) {
    throw MAKE_EXCEPTION("current_mlist.size()>0");
  }

  as->flush();
  if (as->minTime() != from) {
	  throw MAKE_EXCEPTION("as->minTime() != from");
  }
  if (as->maxTime() < to) {
	  throw MAKE_EXCEPTION("as->maxTime() < to");
  }
  auto reader = as->readInterval(
      dariadb::storage::QueryInterval(_all_ids_array, 0, from, to + copies_count));
  check_reader_of_all(reader, from, to, step, id_val, total_count, "readAll error: ");

  auto cloned_reader = reader->clone();
  cloned_reader->reset();
  check_reader_of_all(cloned_reader, from, to, step, id_val, total_count,
                      "cloned readAll error: ");

  dariadb::IdArray ids(_all_ids_set.begin(), _all_ids_set.end());
  dariadb::Meas::MeasList all{};
  as->readInterval(dariadb::storage::QueryInterval(ids, 0, from, to + copies_count))
      ->readAll(&all);
  if (all.size() != total_count) {
    throw MAKE_EXCEPTION("all.size() != total_count");
  }

  checkAll(all, "read error: ", from, to, step);

  ids.clear();
  ids.push_back(2);
  dariadb::Meas::MeasList fltr_res{};
  as->readInterval(dariadb::storage::QueryInterval(ids, 0, from, to + copies_count))
      ->readAll(&fltr_res);

  if (fltr_res.size() != copies_count) {
    throw MAKE_EXCEPTION("fltr_res.size() != copies_count");
  }

  all.clear();
  auto qp = dariadb::storage::QueryTimePoint(
      dariadb::IdArray(_all_ids_set.begin(), _all_ids_set.end()), 0, to + copies_count);
  auto tp_reader = as->readInTimePoint(qp);
  tp_reader->readAll(&all);
  size_t ids_count = (size_t)((to - from) / step);
  if (all.size() < ids_count) {
    throw MAKE_EXCEPTION("all.size() < ids_count. must be GE");
  }

  tp_reader->reset();
  auto readed_ids = tp_reader->getIds();
  if (readed_ids.size() != _all_ids_set.size()) {
	  throw MAKE_EXCEPTION("(eaded_ids.size() != _all_ids_set.size())");
  }

  fltr_res.clear();
  qp.time_point = to + copies_count;
  as->readInTimePoint(qp)->readAll(&fltr_res);
  if (fltr_res.size() < ids_count) {
    throw MAKE_EXCEPTION("fltr_res.size() < ids_count. must be GE");
  }

  dariadb::IdArray notExstsIDs{9999};
  fltr_res.clear();
  qp.ids = notExstsIDs;
  qp.time_point = to - 1;
  as->readInTimePoint(qp)->readAll(&fltr_res);
  if (fltr_res.size() != size_t(1)) { // must return NO_DATA
    throw MAKE_EXCEPTION("fltr_res.size() != size_t(1)");
  }

  if (fltr_res.front().flag != dariadb::Flags::_NO_DATA) {
    throw MAKE_EXCEPTION("fltr_res.front().flag != dariadb::Flags::NO_DATA");
  }
}

void readIntervalCommonTest(dariadb::storage::MeasStorage *ds) {
  dariadb::Meas m;
  {
    m.id = 1;
    m.time = 1;
    ds->append(m);
    m.id = 2;
    m.time = 2;
    ds->append(m);

    m.id = 4;
    m.time = 4;
    ds->append(m);
    m.id = 5;
    m.time = 5;
    ds->append(m);
    m.id = 55;
    m.time = 5;
    ds->append(m);

    dariadb::IdArray all_id = {1, 2, 4, 5, 55};
    {
      auto tp_reader = ds->readInTimePoint({all_id, 0, 6});
      dariadb::Meas::MeasList output_in_point{};
      tp_reader->readAll(&output_in_point);

      if (output_in_point.size() != size_t(5)) {
        throw MAKE_EXCEPTION("(output_in_point.size() != size_t(5))");
      }

      auto rdr = ds->readInterval(dariadb::storage::QueryInterval(all_id, 0, 0, 6));
      output_in_point.clear();
      rdr->readAll(&output_in_point);
      if (output_in_point.size() != size_t(5)) {
        throw MAKE_EXCEPTION("(output_in_point.size() != size_t(5))");
      }
    }
    {

      auto tp_reader = ds->readInTimePoint({all_id, 0, 3});
      dariadb::Meas::MeasList output_in_point{};
      tp_reader->readAll(&output_in_point);

      ///+ timepoint(3) with no_data
      if (output_in_point.size() != size_t(2 + 3)) {
        throw MAKE_EXCEPTION("(output_in_point.size() != size_t(2 + 3))");
      }
      for (auto v : output_in_point) {
        if (!(v.time <= 3)) {
          throw MAKE_EXCEPTION("!(v.time <= 3)");
        }
      }
    }
    auto reader = ds->readInterval(dariadb::storage::QueryInterval(all_id, 0, 3, 5));
    dariadb::Meas::MeasList output{};
    reader->readAll(&output);
    if (output.size() != size_t(5 + 3)) { //+ timepoint(3) with no_data
      throw MAKE_EXCEPTION("output.size() != size_t(5 + 3)");
    }
  }
  // from this point read not from firsts.
  {
    m.id = 1;
    m.time = 6;
    ds->append(m);
    m.id = 2;
    m.time = 7;
    ds->append(m);

    m.id = 4;
    m.time = 9;
    ds->append(m);
    m.id = 5;
    m.time = 10;
    ds->append(m);
    m.id = 6;
    m.time = 10;
    ds->append(m);
    dariadb::IdArray second_all_id = {1, 2, 4, 5, 6, 55};
    {

      auto tp_reader = ds->readInTimePoint({second_all_id, 0, 8});
      dariadb::Meas::MeasList output_in_point{};
      tp_reader->readAll(&output_in_point);

      ///+ timepoimt(8) with no_data
      if (output_in_point.size() != size_t(5 + 1)) {
        throw MAKE_EXCEPTION("(output_in_point.size() != size_t(5 + 1))");
      }
      for (auto v : output_in_point) {
        if (!(v.time <= 8)) {
          throw MAKE_EXCEPTION("!(v.time <= 8))");
        }
      }
    }

    auto reader = ds->readInterval(
        dariadb::storage::QueryInterval(dariadb::IdArray{1, 2, 4, 5, 55}, 0, 8, 10));
    dariadb::Meas::MeasList output{};
    reader->readAll(&output);
    if (output.size() != size_t(7)) {
      throw MAKE_EXCEPTION("output.size() != size_t(7)");
    }
    // expect: {1,8} {2,8} {4,8} {55,8} {4,9} {5,10}
    if (output.size() != size_t(7)) {
      std::cout << " ERROR!!!!" << std::endl;

      for (dariadb::Meas v : output) {
        std::cout << " id:" << v.id << " flg:" << v.flag << " v:" << v.value
                  << " t:" << v.time << std::endl;
      }
      throw MAKE_EXCEPTION("!!!");
    }
  }
}
}
<|endoftext|>


<commit_before>#include "stdafx.h"

#ifndef _MSC_VER
static int GetKeyState(char) {
	return 0x01;
}
#define VK_RETURN 0x0D
#endif

static float CalcRadius(const Mesh* m)
{
	const Block& b = m->GetRawDatas();
	float maxSq = 0;
	for (auto& it : b.vertices) {
		float sq = lengthSq(it.xyz);
		maxSq = std::max(maxSq, sq);
	}
	return sqrt(maxSq);
}

App::App() : radius(1), animationNumber(0), trackTime(0), meshTiny(nullptr)
{
	memset(mesh, 0, sizeof(mesh));
	lastTime = GetTime();
}

App::~App()
{
}

void App::ApplySky()
{
	switch(skyNum) {
	case 0:
		skyMan.Create("C:\\Program Files (x86)\\Microsoft DirectX SDK (August 2009)\\Samples\\C++\\Direct3D\\StateManager\\Media\\skybox02.dds", "sky_cubemap_high");
		break;
	case 1:
		skyMan.Create("C:\\Program Files (x86)\\Microsoft DirectX SDK (August 2009)\\Samples\\C++\\Direct3D\\StateManager\\Media\\skybox02.dds", "sky_cubemap");
		break;
	case 2:
		skyMan.Create("resource\\Tiny_skin.dds", "sky_spheremap");
		break;
	case 3:
		skyMan.Create("resource\\PANO_20141115_141959.dds", "sky_photosphere");
		break;
	case 4:
		skyMan.Create("resource\\Equirectangular-projection.jpg", "sky_photosphere");
		break;
	}
}

void App::Init(const char* fileName)
{
	Destroy();

	for (auto& it : rt) {
		it.Init(ivec2(SCR_W, SCR_H), AFDT_R8G8B8A8_UINT, AFDT_INVALID);
	}

	fontMan.Init();
	debugRenderer.Init();
	gridRenderer.Init();
	waterSurface.Init();
	postEffectMan.Create("post_effect_mono");
	computeShaderMan.Create("fx\\post_effect_cs.fx");
	computeShaderSkinning.Create("fx\\skin_cs.fx");

	g_type = "mesh";

	const char* meshFileName = "resource\\tiny.x";
	const char* ext = fileName ? strrchr(fileName, '.') : nullptr;
	if (ext && !_stricmp(ext, ".x")) {
		meshFileName = fileName;
	}

	meshTiny = new MeshX(meshFileName);

	if (ext && !_stricmp(ext, ".bvh")) {
		Bvh* bvh = new Bvh(fileName);
		mesh[0] = bvh;
		bvh->ResetAnim();
		meshTiny->SyncLocalAxisWithBvh(bvh, bind[0]);
	} else {
		const char* bvhNames[] = {
			"D:\\github\\aachan.bvh",
			"D:\\github\\kashiyuka.bvh",
			"D:\\github\\nocchi.bvh",
		};
		for (int i = 0; i < (int)dimof(bvhNames); i++) {
			Bvh* bvh = new Bvh(bvhNames[i]);
			mesh[i] = bvh;
			bvh->ResetAnim();
			meshTiny->SyncLocalAxisWithBvh(bvh, bind[i]);
		}
	}

	radius = CalcRadius(mesh[0]);
	float scale = std::max(0.00001f, radius);
	devCamera.SetDistance(scale * 3);
	devCamera.SetHeight(radius / 2);

	lastTime = GetTime();
	ApplySky();
}

inline Vec2 GetScreenPos(const Mat& mLocal)
{
	Mat mW, mV, mP, mViewport;
	matrixMan.Get(MatrixMan::WORLD, mW);
	matrixMan.Get(MatrixMan::VIEW, mV);
	matrixMan.Get(MatrixMan::PROJ, mP);
	mViewport._11 = SCR_W / 2;
	mViewport._22 = -SCR_H / 2;
	mViewport._41 = SCR_W / 2;
	mViewport._42 = SCR_H / 2;

	Mat m = mLocal * mW * mV * mP * mViewport;

	Vec2 p;
	p.x = m._41 / m._44;
	p.y = m._42 / m._44;
	return p;
}

void App::DrawBoneNames(Bvh* bvh)
{
	const std::vector<BvhFrame>& frames = bvh->GetFrames();
	for (auto& it : frames) {
		if (it.childId < 0) {
			continue;
		}
		Vec2 size = fontMan.MeasureString(12, it.name);
		Vec2 pos = GetScreenPos(it.result);
		pos -= size / 2;
		fontMan.DrawString(floor(pos), 12, it.name);
	}
}

void App::DrawBoneNames(const MeshX* meshX, const MeshXAnimResult& result)
{
	const std::vector<Frame>& frames = meshX->GetFrames();
	for (BONE_ID id = 0; id < (BONE_ID)frames.size(); id++) {
		const Frame& f = frames[id];
		Vec2 pos = floor(GetScreenPos(result.boneMat[id]));
		fontMan.DrawString(pos, 12, f.name[0] == '\0' ? "[NO NAME]" : f.name);
	}
}

void App::DrawCameraParams()
{
	Mat v;
	matrixMan.Get(MatrixMan::VIEW, v);
	Mat mInv = inv(v);

	char buf[128];
	Vec2 pos = { 5, 55 };
	snprintf(buf, sizeof(buf), "cam pos(via inv view):%f, %f, %f dir:%f, %f, %f", mInv._41, mInv._42, mInv._43, mInv._31, mInv._32, mInv._33);
	fontMan.DrawString(pos, 16, buf);

	mInv = fastInv(v);
	snprintf(buf, sizeof(buf), "cam pos(by fastInv):%f, %f, %f dir:%f, %f, %f", mInv._41, mInv._42, mInv._43, mInv._31, mInv._32, mInv._33);
	pos.y = 75;
	fontMan.DrawString(pos, 16, buf);

	snprintf(buf, sizeof(buf), "cam dir(view mtx direct): %f, %f, %f", v._13, v._23, v._33);
	pos.y = 95;
	fontMan.DrawString(pos, 16, buf);
}

void App::Update()
{
	if (GetKeyState(VK_F1) & 0x80) {
		skyNum = 0;
		ApplySky();
	}
	if (GetKeyState(VK_F2) & 0x80) {
		skyNum = 1;
		ApplySky();
	}
	if (GetKeyState(VK_F3) & 0x80) {
		skyNum = 2;
		ApplySky();
	}
	if (GetKeyState(VK_F4) & 0x80) {
		skyNum = 3;
		ApplySky();
	}
	if (GetKeyState(VK_F5) & 0x80) {
		skyNum = 4;
		ApplySky();
	}

	if (GetKeyState('P') & 0x80) {
		g_type = "pivot";
	}
	if (GetKeyState('M') & 0x80) {
		g_type = "mesh";
	}
	if (GetKeyState('B') & 0x80) {
		g_type = "bone";
	}
	static char v[] = "012349";
	for (auto& i : v) {
		if (i && GetKeyState(i) & 0x80) {
			animationNumber = i - '0';
		}
	}
}

void App::Draw()
{
//	fontMan.DrawString(Vec2(0, 110), 16, "TEXT SPRITE TEST!!!!!!!!!!!!!text sprite 1234567890");
//	fontMan.DrawString(Vec2(10, 130), 32, "@#$%^&*()");
//	fontMan.DrawString(Vec2(10, 170), 40, L"あいうえお한글漢字");

	ID3D11DeviceContext* context = deviceMan11.GetContext();
//	rt[0].BeginRenderToThis();
	AFRenderTarget defaultTarget;
	defaultTarget.InitForDefaultRenderTarget();
	defaultTarget.BeginRenderToThis();

	double currentTime = GetTime();
	double deltaTime = currentTime - lastTime;
	lastTime = currentTime;

	if (GetKeyState(VK_RETURN) & 0x01) {
		trackTime += deltaTime;
	}

	matrixMan.Set(MatrixMan::WORLD, Mat());
	matrixMan.Set(MatrixMan::VIEW, devCamera.CalcViewMatrix());

	//if (GetKeyState(VK_RETURN) & 0x01) {
	//	Mat dx = XMMatrixPerspectiveFovLH(45 * XM_PI / 180, (float)SCR_W / SCR_H, dist / 1000, dist * 1000);
	//}

	float dist = devCamera.GetDistance();

	float f = dist * 1000;
	float n = dist / 1000;

	matrixMan.Set(MatrixMan::PROJ, perspective(45, (float)SCR_W / SCR_H, n, f));

	skyMan.Draw();
//	gridRenderer.Draw();
//	waterSurface.Draw();

	for (int i = 0; i < (int)dimof(mesh); i++) {
		Mesh* it = mesh[i];
		MeshX* meshX = meshTiny;
		MeshXAnimResult meshXAnimResult;
		if (it && meshX) {

			Bvh* bvh = dynamic_cast<Bvh*>(it);

			if (bvh) {
				bvh->Draw(animationNumber == 9 ? 0 : animationNumber, trackTime);
				if (animationNumber == 9) {
					meshX->CalcAnimationFromBvh(bvh, bind[i], trackTime, meshXAnimResult, 270 / radius);
				} else {
					meshX->CalcAnimation(animationNumber, trackTime, meshXAnimResult);
				}
				meshX->Draw(meshXAnimResult);
				if (GetKeyState('T') & 0x01) {
					DrawBoneNames(bvh);
				}
			}
		}
		if (meshX && (GetKeyState('T') & 0x01)) {
			DrawBoneNames(meshX, meshXAnimResult);
		}
	}

	DrawCameraParams();

	char buf[20];
	sprintf(buf, "FPS: %f", fps.Get());
	Vec2 pos = { 5, 15 };
	fontMan.DrawString(pos, 16, buf);

	fontMan.Render();

//	computeShaderMan.Draw(rt[0].GetTexture(), rt[1].GetUnorderedAccessView());
//	postEffectMan.Draw(rt[1].GetTexture());

	deviceMan11.Present();

	fps.Update();
}

void App::Destroy()
{
	for (auto& it : mesh) {
		SAFE_DELETE(it);
	}
	SAFE_DELETE(meshTiny);
	for (auto& it : rt) {
		it.Destroy();
	}

	fontMan.Destroy();
	debugRenderer.Destroy();
	gridRenderer.Destroy();
	waterSurface.Destroy();
	postEffectMan.Destroy();
	computeShaderMan.Destroy();
	computeShaderSkinning.Destroy();
}

std::string g_type;
<commit_msg>zoom out<commit_after>#include "stdafx.h"

#ifndef _MSC_VER
static int GetKeyState(char) {
	return 0x01;
}
#define VK_RETURN 0x0D
#endif

static float CalcRadius(const Mesh* m)
{
	const Block& b = m->GetRawDatas();
	float maxSq = 0;
	for (auto& it : b.vertices) {
		float sq = lengthSq(it.xyz);
		maxSq = std::max(maxSq, sq);
	}
	return sqrt(maxSq);
}

App::App() : radius(1), animationNumber(0), trackTime(0), meshTiny(nullptr)
{
	memset(mesh, 0, sizeof(mesh));
	lastTime = GetTime();
}

App::~App()
{
}

void App::ApplySky()
{
	switch(skyNum) {
	case 0:
		skyMan.Create("C:\\Program Files (x86)\\Microsoft DirectX SDK (August 2009)\\Samples\\C++\\Direct3D\\StateManager\\Media\\skybox02.dds", "sky_cubemap_high");
		break;
	case 1:
		skyMan.Create("C:\\Program Files (x86)\\Microsoft DirectX SDK (August 2009)\\Samples\\C++\\Direct3D\\StateManager\\Media\\skybox02.dds", "sky_cubemap");
		break;
	case 2:
		skyMan.Create("resource\\Tiny_skin.dds", "sky_spheremap");
		break;
	case 3:
		skyMan.Create("resource\\PANO_20141115_141959.dds", "sky_photosphere");
		break;
	case 4:
		skyMan.Create("resource\\Equirectangular-projection.jpg", "sky_photosphere");
		break;
	}
}

void App::Init(const char* fileName)
{
	Destroy();

	for (auto& it : rt) {
		it.Init(ivec2(SCR_W, SCR_H), AFDT_R8G8B8A8_UINT, AFDT_INVALID);
	}

	fontMan.Init();
	debugRenderer.Init();
	gridRenderer.Init();
	waterSurface.Init();
	postEffectMan.Create("post_effect_mono");
	computeShaderMan.Create("fx\\post_effect_cs.fx");
	computeShaderSkinning.Create("fx\\skin_cs.fx");

	g_type = "mesh";

	const char* meshFileName = "resource\\tiny.x";
	const char* ext = fileName ? strrchr(fileName, '.') : nullptr;
	if (ext && !_stricmp(ext, ".x")) {
		meshFileName = fileName;
	}

	meshTiny = new MeshX(meshFileName);

	if (ext && !_stricmp(ext, ".bvh")) {
		Bvh* bvh = new Bvh(fileName);
		mesh[0] = bvh;
		bvh->ResetAnim();
		meshTiny->SyncLocalAxisWithBvh(bvh, bind[0]);
	} else {
		const char* bvhNames[] = {
			"D:\\github\\aachan.bvh",
			"D:\\github\\kashiyuka.bvh",
			"D:\\github\\nocchi.bvh",
		};
		for (int i = 0; i < (int)dimof(bvhNames); i++) {
			Bvh* bvh = new Bvh(bvhNames[i]);
			mesh[i] = bvh;
			bvh->ResetAnim();
			meshTiny->SyncLocalAxisWithBvh(bvh, bind[i]);
		}
	}

	radius = CalcRadius(mesh[0]);
	float scale = std::max(0.00001f, radius);
	devCamera.SetDistance(scale * 3);
	devCamera.SetHeight(radius / 2);

	lastTime = GetTime();
	ApplySky();
}

inline Vec2 GetScreenPos(const Mat& mLocal)
{
	Mat mW, mV, mP, mViewport;
	matrixMan.Get(MatrixMan::WORLD, mW);
	matrixMan.Get(MatrixMan::VIEW, mV);
	matrixMan.Get(MatrixMan::PROJ, mP);
	mViewport._11 = SCR_W / 2;
	mViewport._22 = -SCR_H / 2;
	mViewport._41 = SCR_W / 2;
	mViewport._42 = SCR_H / 2;

	Mat m = mLocal * mW * mV * mP * mViewport;

	Vec2 p;
	p.x = m._41 / m._44;
	p.y = m._42 / m._44;
	return p;
}

void App::DrawBoneNames(Bvh* bvh)
{
	const std::vector<BvhFrame>& frames = bvh->GetFrames();
	for (auto& it : frames) {
		if (it.childId < 0) {
			continue;
		}
		Vec2 size = fontMan.MeasureString(12, it.name);
		Vec2 pos = GetScreenPos(it.result);
		pos -= size / 2;
		fontMan.DrawString(floor(pos), 12, it.name);
	}
}

void App::DrawBoneNames(const MeshX* meshX, const MeshXAnimResult& result)
{
	const std::vector<Frame>& frames = meshX->GetFrames();
	for (BONE_ID id = 0; id < (BONE_ID)frames.size(); id++) {
		const Frame& f = frames[id];
		Vec2 pos = floor(GetScreenPos(result.boneMat[id]));
		fontMan.DrawString(pos, 12, f.name[0] == '\0' ? "[NO NAME]" : f.name);
	}
}

void App::DrawCameraParams()
{
	Mat v;
	matrixMan.Get(MatrixMan::VIEW, v);
	Mat mInv = inv(v);

	char buf[128];
	Vec2 pos = { 5, 55 };
	snprintf(buf, sizeof(buf), "cam pos(via inv view):%f, %f, %f dir:%f, %f, %f", mInv._41, mInv._42, mInv._43, mInv._31, mInv._32, mInv._33);
	fontMan.DrawString(pos, 16, buf);

	mInv = fastInv(v);
	snprintf(buf, sizeof(buf), "cam pos(by fastInv):%f, %f, %f dir:%f, %f, %f", mInv._41, mInv._42, mInv._43, mInv._31, mInv._32, mInv._33);
	pos.y = 75;
	fontMan.DrawString(pos, 16, buf);

	snprintf(buf, sizeof(buf), "cam dir(view mtx direct): %f, %f, %f", v._13, v._23, v._33);
	pos.y = 95;
	fontMan.DrawString(pos, 16, buf);
}

void App::Update()
{
	if (GetKeyState(VK_F1) & 0x80) {
		skyNum = 0;
		ApplySky();
	}
	if (GetKeyState(VK_F2) & 0x80) {
		skyNum = 1;
		ApplySky();
	}
	if (GetKeyState(VK_F3) & 0x80) {
		skyNum = 2;
		ApplySky();
	}
	if (GetKeyState(VK_F4) & 0x80) {
		skyNum = 3;
		ApplySky();
	}
	if (GetKeyState(VK_F5) & 0x80) {
		skyNum = 4;
		ApplySky();
	}

	if (GetKeyState('P') & 0x80) {
		g_type = "pivot";
	}
	if (GetKeyState('M') & 0x80) {
		g_type = "mesh";
	}
	if (GetKeyState('B') & 0x80) {
		g_type = "bone";
	}
	static char v[] = "012349";
	for (auto& i : v) {
		if (i && GetKeyState(i) & 0x80) {
			animationNumber = i - '0';
		}
	}
}

void App::Draw()
{
//	fontMan.DrawString(Vec2(0, 110), 16, "TEXT SPRITE TEST!!!!!!!!!!!!!text sprite 1234567890");
//	fontMan.DrawString(Vec2(10, 130), 32, "@#$%^&*()");
//	fontMan.DrawString(Vec2(10, 170), 40, L"あいうえお한글漢字");

	ID3D11DeviceContext* context = deviceMan11.GetContext();
//	rt[0].BeginRenderToThis();
	AFRenderTarget defaultTarget;
	defaultTarget.InitForDefaultRenderTarget();
	defaultTarget.BeginRenderToThis();

	double currentTime = GetTime();
	double deltaTime = currentTime - lastTime;
	lastTime = currentTime;

	if (GetKeyState(VK_RETURN) & 0x01) {
		trackTime += deltaTime;
	}

	matrixMan.Set(MatrixMan::WORLD, Mat());
	matrixMan.Set(MatrixMan::VIEW, devCamera.CalcViewMatrix());

	//if (GetKeyState(VK_RETURN) & 0x01) {
	//	Mat dx = XMMatrixPerspectiveFovLH(45 * XM_PI / 180, (float)SCR_W / SCR_H, dist / 1000, dist * 1000);
	//}

	float dist = devCamera.GetDistance();

	float f = dist * 1000;
	float n = dist / 1000;

	matrixMan.Set(MatrixMan::PROJ, perspective(60, (float)SCR_W / SCR_H, n, f));

	skyMan.Draw();
//	gridRenderer.Draw();
//	waterSurface.Draw();

	for (int i = 0; i < (int)dimof(mesh); i++) {
		Mesh* it = mesh[i];
		MeshX* meshX = meshTiny;
		MeshXAnimResult meshXAnimResult;
		if (it && meshX) {

			Bvh* bvh = dynamic_cast<Bvh*>(it);

			if (bvh) {
				bvh->Draw(animationNumber == 9 ? 0 : animationNumber, trackTime);
				if (animationNumber == 9) {
					meshX->CalcAnimationFromBvh(bvh, bind[i], trackTime, meshXAnimResult, 270 / radius);
				} else {
					meshX->CalcAnimation(animationNumber, trackTime, meshXAnimResult);
				}
				meshX->Draw(meshXAnimResult);
				if (GetKeyState('T') & 0x01) {
					DrawBoneNames(bvh);
				}
			}
		}
		if (meshX && (GetKeyState('T') & 0x01)) {
			DrawBoneNames(meshX, meshXAnimResult);
		}
	}

	DrawCameraParams();

	char buf[20];
	sprintf(buf, "FPS: %f", fps.Get());
	Vec2 pos = { 5, 15 };
	fontMan.DrawString(pos, 16, buf);

	fontMan.Render();

//	computeShaderMan.Draw(rt[0].GetTexture(), rt[1].GetUnorderedAccessView());
//	postEffectMan.Draw(rt[1].GetTexture());

	deviceMan11.Present();

	fps.Update();
}

void App::Destroy()
{
	for (auto& it : mesh) {
		SAFE_DELETE(it);
	}
	SAFE_DELETE(meshTiny);
	for (auto& it : rt) {
		it.Destroy();
	}

	fontMan.Destroy();
	debugRenderer.Destroy();
	gridRenderer.Destroy();
	waterSurface.Destroy();
	postEffectMan.Destroy();
	computeShaderMan.Destroy();
	computeShaderSkinning.Destroy();
}

std::string g_type;
<|endoftext|>


<commit_before>// Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include "Archive.h"
#include <iostream>

using namespace leap;

bool InputStreamAdapter::IsEof(void) const {
  return is.eof();
}

std::streamsize InputStreamAdapter::Read(void* pBuf, std::streamsize ncb) {
  is.read((char*)pBuf, ncb);
  return is ? is.gcount() : -1;
}

std::streamsize InputStreamAdapter::Skip(std::streamsize ncb) {
  is.ignore(ncb);
  return is ? is.gcount() : -1;
}

bool OutputStreamAdapter::Write(const void* pBuf, std::streamsize ncb) {
  return (bool)os.write((const char*)pBuf, ncb);
}

const char* leap::ToString(serial_atom atom) {
  switch (atom) {
  case serial_atom::ignored:
    return "[?]";
  case serial_atom::boolean:
    return "bool";
  case serial_atom::i8:
    return "i8";
  case serial_atom::ui8:
    return "ui8";
  case serial_atom::i16:
    return "i16";
  case serial_atom::ui16:
    return "ui16";
  case serial_atom::i32:
    return "i32";
  case serial_atom::ui32:
    return "ui32";
  case serial_atom::i64:
    return "i64";
  case serial_atom::ui64:
    return "ui64";
  case serial_atom::f32:
    return "f32";
  case serial_atom::f64:
    return "f64";
  case serial_atom::reference:
    return "ref";
  case serial_atom::array:
    return "array";
  case serial_atom::string:
    return "string";
  case serial_atom::map:
    return "map";
  case serial_atom::descriptor:
    return "descr";
  case serial_atom::finalized_descriptor:
    return "DESCR";
  }
  throw std::invalid_argument("Attempted to ToString an unrecognized serial atom type");
}
<commit_msg>Fix stream read behavior<commit_after>// Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include "Archive.h"
#include <iostream>

using namespace leap;

bool InputStreamAdapter::IsEof(void) const {
  return is.eof();
}

std::streamsize InputStreamAdapter::Read(void* pBuf, std::streamsize ncb) {
  is.read((char*)pBuf, ncb);
  if (is.fail() && !is.eof())
      return -1;
  return is.gcount();
}

std::streamsize InputStreamAdapter::Skip(std::streamsize ncb) {
  is.ignore(ncb);
  if (is.fail() && !is.eof())
    return -1;
  return is.gcount();
}

bool OutputStreamAdapter::Write(const void* pBuf, std::streamsize ncb) {
  return (bool)os.write((const char*)pBuf, ncb);
}

const char* leap::ToString(serial_atom atom) {
  switch (atom) {
  case serial_atom::ignored:
    return "[?]";
  case serial_atom::boolean:
    return "bool";
  case serial_atom::i8:
    return "i8";
  case serial_atom::ui8:
    return "ui8";
  case serial_atom::i16:
    return "i16";
  case serial_atom::ui16:
    return "ui16";
  case serial_atom::i32:
    return "i32";
  case serial_atom::ui32:
    return "ui32";
  case serial_atom::i64:
    return "i64";
  case serial_atom::ui64:
    return "ui64";
  case serial_atom::f32:
    return "f32";
  case serial_atom::f64:
    return "f64";
  case serial_atom::reference:
    return "ref";
  case serial_atom::array:
    return "array";
  case serial_atom::string:
    return "string";
  case serial_atom::map:
    return "map";
  case serial_atom::descriptor:
    return "descr";
  case serial_atom::finalized_descriptor:
    return "DESCR";
  }
  throw std::invalid_argument("Attempted to ToString an unrecognized serial atom type");
}
<|endoftext|>


<commit_before>#include "test_plugin.h"
#include "test.h"

#include <grpc++/grpc++.h>
#include <memory>
#include <sce.grpc.pb.h>
#include <sce.pb.h>
#include <thread>

static void test_rpc_call() {
    //class that implements the RPC functions
    constexpr auto test_response = "testresponse";
    class Rpc_server : public sce::proto::Query::Service {
        grpc::Status GetCurrentFile(grpc::ServerContext *context, const sce::proto::GetCurrentFileParams *request, sce::proto::String *response) override {
            response->set_text(test_response);
            return grpc::Status::OK;
        }
    };

    //create RPC server and run it in a thread
    constexpr auto rpc_address = "localhost:53676";
    Rpc_server rpc_server;
    auto server = grpc::ServerBuilder{}.AddListeningPort(rpc_address, grpc::InsecureServerCredentials()).RegisterService(&rpc_server).BuildAndStart();
    std::thread server_thread{[&server] { server->Wait(); }};

    //make an RPC call
    sce::proto::String reply;
    sce::proto::GetCurrentFileParams request({});
    grpc::ClientContext client_context;
    auto stub = sce::proto::Query::NewStub(grpc::CreateChannel(rpc_address, grpc::InsecureChannelCredentials()));
    auto status = stub->GetCurrentFile(&client_context, request, &reply);
    assert_true(status.ok());
    assert_equal(reply.text(), test_response);

    //shut down server
    server->Shutdown();
    server_thread.join();
}

void test_plugin() {
    GOOGLE_PROTOBUF_VERIFY_VERSION;

    test_rpc_call();

    google::protobuf::ShutdownProtobufLibrary();
}
<commit_msg>Supressing warnings.<commit_after>#include "test_plugin.h"
#include "test.h"

#include <grpc++/grpc++.h>
#include <memory>
#include <sce.grpc.pb.h>
#include <sce.pb.h>
#include <thread>

static void test_rpc_call() {
    //class that implements the RPC functions
    constexpr auto test_response = "testresponse";
    class Rpc_server : public sce::proto::Query::Service {
        grpc::Status GetCurrentFile([[maybe_unused]] grpc::ServerContext *context, [[maybe_unused]] const sce::proto::GetCurrentFileParams *request,
                                    sce::proto::String *response) override {
            response->set_text(test_response);
            return grpc::Status::OK;
        }
    };

    //create RPC server and run it in a thread
    constexpr auto rpc_address = "localhost:53676";
    Rpc_server rpc_server;
    auto server = grpc::ServerBuilder{}.AddListeningPort(rpc_address, grpc::InsecureServerCredentials()).RegisterService(&rpc_server).BuildAndStart();
    std::thread server_thread{[&server] { server->Wait(); }};

    //make an RPC call
    sce::proto::String reply;
    sce::proto::GetCurrentFileParams request({});
    grpc::ClientContext client_context;
    auto stub = sce::proto::Query::NewStub(grpc::CreateChannel(rpc_address, grpc::InsecureChannelCredentials()));
    auto status = stub->GetCurrentFile(&client_context, request, &reply);
    assert_true(status.ok());
    assert_equal(reply.text(), test_response);

    //shut down server
    server->Shutdown();
    server_thread.join();
}

void test_plugin() {
    GOOGLE_PROTOBUF_VERIFY_VERSION;

    test_rpc_call();

    google::protobuf::ShutdownProtobufLibrary();
}
<|endoftext|>


<commit_before>/*

    Copyright Eli Dupree and Isaac Dupree, 2011, 2012, 2013

    This file is part of Lasercake.

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

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

    You should have received a copy of the GNU General Public License
    along with Lasercake.  If not, see <http://www.gnu.org/licenses/>.

*/

#include "test_header.hpp"

#include "../units.hpp"

#include <iostream>
#include <boost/random/mersenne_twister.hpp>

typedef meters_t meter;
//constexpr auto kilograms = kilo*grams;

//typedef typename units_prod<kilo_t, grams_t>::type kilograms_t;
typedef typename units_prod<kilograms_t, meters_t,
  typename units_pow<seconds_t, -2>::type>::type newtons_t_A;
typedef typename units_prod<kilograms_t, meters_t,
  units_pow<seconds_t, -2>>::type newtons_t_B;

typedef typename units_prod<kilo_t, meters_t>::type kilometers_t;
typedef typename units_pow<kilometers_t, 6>::type kilometers6_t;
typedef typename units_pow<kilometers6_t, -2, 3>::type inverse_kilometers4_t;
typedef typename units_pow<meters_t, -4>::type inverse_meters4_t;

constexpr auto kilometers = kilometers_t();

BOOST_AUTO_TEST_CASE( unitses ) {
  const physical_quantity<int32_t, meter> foo = 1 * meter();
  const physical_quantity<int64_t, meter> foo64 = foo;
  const physical_quantity<int32_t, meter> foo3 = 3 * meter();
  const physical_quantity<int32_t, meter> foo5 = 5 * meters;
  foo + foo;
  auto bfoo = foo * foo;
  bfoo = bfoo * 3;

  foo64 + foo;

  const physical_quantity<double, meter> foofloating = foo;
  const physical_quantity<double, meter> foofloating2 = 1.0*meters;

  const physical_quantity<bounds_checked_int<int32_t>, meter> foobound(foo);
  const auto bfoobound = foobound * foobound;

  int yay = (bfoobound / foobound / foobound).get();
  const int32_t okayy1 = get(bfoo, meters*meters);
  const int32_t okayy2 = bfoo.get(meters*meters);
  BOOST_CHECK_EQUAL(okayy1, okayy2);

  meters*meters;
  units<dim::meter<2>> foofoo = meters*meters;
  meters/seconds;
  units<> dimless = meters/meters;
  2*dimless;
  2*(meters/meters);
  2*(meters*meters);
  ((2*meters)*meters) + (2*(meters*meters));

  1*meters*meters + 1*meters.pow<2>();

  // 1000*1000*1000*1000 doesn't fit into 32 bits, so this identity()
  // returns a 64 bit quantity.
  const physical_quantity<int64_t, inverse_kilometers4_t> invfoo4
    = 1/foo/foo/foo/foo
    * identity(inverse_kilometers4_t() / inverse_meters4_t());
  // This fits within fewer bits:
  const physical_quantity<int32_t, meters_t> thirtytwobits
    = 1 * kilometers * identity(meters / kilometers);

  const physical_quantity<int, newtons_t_A> newtonz =
    7 * kilograms * meters / seconds / seconds;
  newtonz + 1*newtons_t_B();

  auto scalar = 4*meters;
  auto pseudoscalar = scalar*pseudo;
  BOOST_CHECK_EQUAL(pseudoscalar, abs(pseudoscalar) * sign(pseudoscalar));
  scalar = pseudoscalar * pseudo;
  scalar = pseudoscalar / pseudo;
  pseudoscalar = scalar * pseudo;
  pseudoscalar = scalar / pseudo;
  pseudoscalar = pseudoscalar + pseudoscalar;

  1*pseudo + sign(pseudoscalar);
  auto useded = 1 + sign(scalar);

  scalar = imbue_sign(scalar, scalar);
  pseudoscalar = imbue_sign(scalar, pseudoscalar);
  pseudoscalar = imbue_sign(pseudoscalar, scalar);
  scalar = imbue_sign(pseudoscalar, pseudoscalar);

  std::cerr << (yay * foofoo * invfoo4 * thirtytwobits * useded) << '\n';

  rounding_strategy<round_down, negative_mirrors_positive> strat;
  divide(divide(foo, bfoo, strat), 3, strat) + divide(3, foo, strat);

  const auto ratty = make_non_normalized_rational_physical_quantity(bfoo, foo);
  const auto derat = make_units_split_rational(ratty);
  derat.numerator + foo;
  3 + derat.denominator;
  const auto rerat = make_non_normalized_rational_physical_quantity(
    derat.numerator, derat.denominator);
  BOOST_CHECK_EQUAL(ratty, rerat);
  derat + ratty;

  boost::mt19937 rng;
  const uniform_int_distribution<bounds_checked_int<int> > dist1(7, 11);
  bounds_checked_int<int> val1 = dist1(rng);
  BOOST_CHECK_GE(val1, 7);
  BOOST_CHECK_LE(val1, 11);
  const uniform_int_distribution<physical_quantity<int32_t, meter> > dist2(foo3, foo5);
  physical_quantity<int32_t, meter> val2 = dist2(rng);
  BOOST_CHECK_GE(val2, 3*meters);
  BOOST_CHECK_LE(val2, 5*meters);

  BOOST_CHECK_EQUAL(foo5 + foo3, 8*meters);
  BOOST_CHECK_EQUAL(foo5 - foo3, 2*meters);
  BOOST_CHECK_EQUAL(foo5 % foo3, 2*meters);
  BOOST_CHECK_EQUAL(foo3 % foo5, 3*meters);
  BOOST_CHECK_EQUAL((13*meters) % (5*meters), 3*meters);
  BOOST_CHECK_EQUAL(!!foo3, true);
  BOOST_CHECK_EQUAL(+foo3, 3*meters);
  BOOST_CHECK_EQUAL(-foo3, -3*meters);
  BOOST_CHECK_EQUAL(abs(foo3), 3*meters);
  BOOST_CHECK_EQUAL(abs(-foo3), 3*meters);
  BOOST_CHECK_EQUAL(foo5 == foo3, false);
  BOOST_CHECK_EQUAL(foo5 != foo3, true);
  BOOST_CHECK_EQUAL(foo5 > foo3, true);
  BOOST_CHECK_EQUAL(foo5 < foo3, false);
  BOOST_CHECK_EQUAL(foo5 <= foo3, false);
  BOOST_CHECK_EQUAL(foo5 >= foo3, true);
  BOOST_CHECK_EQUAL(foo5 << 3, 40*meters);
  BOOST_CHECK_EQUAL(foo5 >> 1, 2*meters);

  constexpr auto recipmeters = reciprocal(meters);
  const auto recipfoo3 = 9 / foo3;

  BOOST_CHECK_EQUAL(foo5 * foo3, 15*meters*meters);
  BOOST_CHECK_EQUAL(foo5 * 3, 15*meters);
  BOOST_CHECK_EQUAL(3 * foo5, 15*meters);
  BOOST_CHECK_EQUAL(foo5 * meters, 5*meters*meters);
  BOOST_CHECK_EQUAL(7 * meters, 7*meters);
  BOOST_CHECK_EQUAL(kilograms * meters, meters*kilograms);

  BOOST_CHECK_EQUAL(foo5 / foo3, 1);
  BOOST_CHECK_EQUAL(foo5 / 3, 1*meters);
  BOOST_CHECK_EQUAL(13 / foo5, 2/meters);
  BOOST_CHECK_EQUAL(foo5 / meters, 5);
  BOOST_CHECK_EQUAL(7 / meters, 7/meters);
  BOOST_CHECK_EQUAL(kilograms / meters, reciprocal(meters)*kilograms);

  BOOST_CHECK_EQUAL(foo5 * recipfoo3, 15);
  BOOST_CHECK_EQUAL(foo5 * recipmeters, 5);
  BOOST_CHECK_EQUAL(meters * recipmeters, trivial_units());

  BOOST_CHECK_EQUAL(foo5 / recipfoo3, 1*meters*meters);
  BOOST_CHECK_EQUAL(foo5 / recipmeters, 5*meters*meters);
  BOOST_CHECK_EQUAL(seconds / seconds, trivial_units());

  physical_quantity<int32_t, meter> mutfoo = 0;
  BOOST_CHECK_EQUAL(mutfoo, 0*meters);
  BOOST_CHECK_EQUAL(mutfoo += foo3, 3*meters);
  BOOST_CHECK_EQUAL(mutfoo += foo3, 6*meters);
  BOOST_CHECK_EQUAL(mutfoo -= foo3, 3*meters);
  BOOST_CHECK_EQUAL(mutfoo *= 7, 21*meters);
  BOOST_CHECK_EQUAL(mutfoo /= 2, 10*meters);
  BOOST_CHECK_EQUAL(mutfoo <<= 2, 40*meters);
  BOOST_CHECK_EQUAL(mutfoo >>= 2, 10*meters);
  BOOST_CHECK_EQUAL(mutfoo %= foo3, 1*meters);

  BOOST_CHECK_EQUAL(0*foo, 0*meters);
  BOOST_CHECK_EQUAL(foo*0, 0*meters);
  BOOST_CHECK(0*foo == 0);
  BOOST_CHECK(foo*0 == 0);
  BOOST_CHECK(!(foo == 0));
  BOOST_CHECK(foo != 0);
  BOOST_CHECK(-foo != 0);
  BOOST_CHECK(foo > 0);
  BOOST_CHECK(foo >= 0);
  BOOST_CHECK(-foo < 0);
  BOOST_CHECK(-foo <= 0);
  BOOST_CHECK(!(-foo > 0));
  BOOST_CHECK(0*foo >= 0);
  BOOST_CHECK(0*foo <= 0);
  BOOST_CHECK(!(0*foo > 0));
  BOOST_CHECK(!(0*foo < 0));
  BOOST_CHECK(0 != foo);
  BOOST_CHECK(0 != -foo);
  BOOST_CHECK(0 < foo);
  BOOST_CHECK(0 <= foo);
  BOOST_CHECK(0 > -foo);
  BOOST_CHECK(0 >= -foo);

  BOOST_CHECK_EQUAL(identity(grams / kilograms), (1000*units_factor<1, 1000>()));
  BOOST_CHECK_EQUAL(identity(grams / kilograms)*units_factor<1000>(), short(1000));
}
<commit_msg>eliminate units_tests.cpp warnings (for GCC 4.7 at least)<commit_after>/*

    Copyright Eli Dupree and Isaac Dupree, 2011, 2012, 2013

    This file is part of Lasercake.

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

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

    You should have received a copy of the GNU General Public License
    along with Lasercake.  If not, see <http://www.gnu.org/licenses/>.

*/

#include "test_header.hpp"

#include "../units.hpp"

#include <iostream>
#include <boost/random/mersenne_twister.hpp>

typedef meters_t meter;
//constexpr auto kilograms = kilo*grams;

//typedef typename units_prod<kilo_t, grams_t>::type kilograms_t;
typedef typename units_prod<kilograms_t, meters_t,
  typename units_pow<seconds_t, -2>::type>::type newtons_t_A;
typedef typename units_prod<kilograms_t, meters_t,
  units_pow<seconds_t, -2>>::type newtons_t_B;

typedef typename units_prod<kilo_t, meters_t>::type kilometers_t;
typedef typename units_pow<kilometers_t, 6>::type kilometers6_t;
typedef typename units_pow<kilometers6_t, -2, 3>::type inverse_kilometers4_t;
typedef typename units_pow<meters_t, -4>::type inverse_meters4_t;

constexpr auto kilometers = kilometers_t();

BOOST_AUTO_TEST_CASE( unitses ) {
  const physical_quantity<int32_t, meter> foo = 1 * meter();
  const physical_quantity<int64_t, meter> foo64 = foo;
  const physical_quantity<int32_t, meter> foo3 = 3 * meter();
  const physical_quantity<int32_t, meter> foo5 = 5 * meters;
  foo + foo;
  auto bfoo = foo * foo;
  bfoo = bfoo * 3;

  foo64 + foo;

  const physical_quantity<double, meter> foofloating = foo;
  const physical_quantity<double, meter> foofloating2 = 1.0*meters;
  foofloating + foofloating2;

  const physical_quantity<bounds_checked_int<int32_t>, meter> foobound(foo);
  const auto bfoobound = foobound * foobound;

  int yay = (bfoobound / foobound / foobound).get();
  const int32_t okayy1 = get(bfoo, meters*meters);
  const int32_t okayy2 = bfoo.get(meters*meters);
  BOOST_CHECK_EQUAL(okayy1, okayy2);

  meters*meters;
  units<dim::meter<2>> foofoo = meters*meters;
  meters/seconds;
  units<> dimless = meters/meters;
  2*dimless;
  2*(meters/meters);
  2*(meters*meters);
  ((2*meters)*meters) + (2*(meters*meters));

  1*meters*meters + 1*meters.pow<2>();

  // 1000*1000*1000*1000 doesn't fit into 32 bits, so this identity()
  // returns a 64 bit quantity.
  const physical_quantity<int64_t, inverse_kilometers4_t> invfoo4
    = 1/foo/foo/foo/foo
    * identity(inverse_kilometers4_t() / inverse_meters4_t());
  // This fits within fewer bits:
  const physical_quantity<int32_t, meters_t> thirtytwobits
    = 1 * kilometers * identity(meters / kilometers);

  const physical_quantity<int, newtons_t_A> newtonz =
    7 * kilograms * meters / seconds / seconds;
  newtonz + 1*newtons_t_B();

  auto scalar = 4*meters;
  auto pseudoscalar = scalar*pseudo;
  BOOST_CHECK_EQUAL(pseudoscalar, abs(pseudoscalar) * sign(pseudoscalar));
  scalar = pseudoscalar * pseudo;
  scalar = pseudoscalar / pseudo;
  pseudoscalar = scalar * pseudo;
  pseudoscalar = scalar / pseudo;
  pseudoscalar = pseudoscalar + pseudoscalar;

  1*pseudo + sign(pseudoscalar);
  auto useded = 1 + sign(scalar);

  scalar = imbue_sign(scalar, scalar);
  pseudoscalar = imbue_sign(scalar, pseudoscalar);
  pseudoscalar = imbue_sign(pseudoscalar, scalar);
  scalar = imbue_sign(pseudoscalar, pseudoscalar);

  std::cerr << (yay * foofoo * invfoo4 * thirtytwobits * useded) << '\n';

  rounding_strategy<round_down, negative_mirrors_positive> strat;
  divide(divide(foo, bfoo, strat), 3, strat) + divide(3, foo, strat);

  const auto ratty = make_non_normalized_rational_physical_quantity(bfoo, foo);
  const auto derat = make_units_split_rational(ratty);
  derat.numerator + foo;
  (void)(3 + derat.denominator);
  const auto rerat = make_non_normalized_rational_physical_quantity(
    derat.numerator, derat.denominator);
  BOOST_CHECK_EQUAL(ratty, rerat);
  derat + ratty;

  boost::mt19937 rng;
  const uniform_int_distribution<bounds_checked_int<int> > dist1(7, 11);
  bounds_checked_int<int> val1 = dist1(rng);
  BOOST_CHECK_GE(val1, 7);
  BOOST_CHECK_LE(val1, 11);
  const uniform_int_distribution<physical_quantity<int32_t, meter> > dist2(foo3, foo5);
  physical_quantity<int32_t, meter> val2 = dist2(rng);
  BOOST_CHECK_GE(val2, 3*meters);
  BOOST_CHECK_LE(val2, 5*meters);

  BOOST_CHECK_EQUAL(foo5 + foo3, 8*meters);
  BOOST_CHECK_EQUAL(foo5 - foo3, 2*meters);
  BOOST_CHECK_EQUAL(foo5 % foo3, 2*meters);
  BOOST_CHECK_EQUAL(foo3 % foo5, 3*meters);
  BOOST_CHECK_EQUAL((13*meters) % (5*meters), 3*meters);
  BOOST_CHECK_EQUAL(!!foo3, true);
  BOOST_CHECK_EQUAL(+foo3, 3*meters);
  BOOST_CHECK_EQUAL(-foo3, -3*meters);
  BOOST_CHECK_EQUAL(abs(foo3), 3*meters);
  BOOST_CHECK_EQUAL(abs(-foo3), 3*meters);
  BOOST_CHECK_EQUAL(foo5 == foo3, false);
  BOOST_CHECK_EQUAL(foo5 != foo3, true);
  BOOST_CHECK_EQUAL(foo5 > foo3, true);
  BOOST_CHECK_EQUAL(foo5 < foo3, false);
  BOOST_CHECK_EQUAL(foo5 <= foo3, false);
  BOOST_CHECK_EQUAL(foo5 >= foo3, true);
  BOOST_CHECK_EQUAL(foo5 << 3, 40*meters);
  BOOST_CHECK_EQUAL(foo5 >> 1, 2*meters);

  constexpr auto recipmeters = reciprocal(meters);
  const auto recipfoo3 = 9 / foo3;

  BOOST_CHECK_EQUAL(foo5 * foo3, 15*meters*meters);
  BOOST_CHECK_EQUAL(foo5 * 3, 15*meters);
  BOOST_CHECK_EQUAL(3 * foo5, 15*meters);
  BOOST_CHECK_EQUAL(foo5 * meters, 5*meters*meters);
  BOOST_CHECK_EQUAL(7 * meters, 7*meters);
  BOOST_CHECK_EQUAL(kilograms * meters, meters*kilograms);

  BOOST_CHECK_EQUAL(foo5 / foo3, 1);
  BOOST_CHECK_EQUAL(foo5 / 3, 1*meters);
  BOOST_CHECK_EQUAL(13 / foo5, 2/meters);
  BOOST_CHECK_EQUAL(foo5 / meters, 5);
  BOOST_CHECK_EQUAL(7 / meters, 7/meters);
  BOOST_CHECK_EQUAL(kilograms / meters, reciprocal(meters)*kilograms);

  BOOST_CHECK_EQUAL(foo5 * recipfoo3, 15);
  BOOST_CHECK_EQUAL(foo5 * recipmeters, 5);
  BOOST_CHECK_EQUAL(meters * recipmeters, trivial_units());

  BOOST_CHECK_EQUAL(foo5 / recipfoo3, 1*meters*meters);
  BOOST_CHECK_EQUAL(foo5 / recipmeters, 5*meters*meters);
  BOOST_CHECK_EQUAL(seconds / seconds, trivial_units());

  physical_quantity<int32_t, meter> mutfoo = 0;
  BOOST_CHECK_EQUAL(mutfoo, 0*meters);
  BOOST_CHECK_EQUAL(mutfoo += foo3, 3*meters);
  BOOST_CHECK_EQUAL(mutfoo += foo3, 6*meters);
  BOOST_CHECK_EQUAL(mutfoo -= foo3, 3*meters);
  BOOST_CHECK_EQUAL(mutfoo *= 7, 21*meters);
  BOOST_CHECK_EQUAL(mutfoo /= 2, 10*meters);
  BOOST_CHECK_EQUAL(mutfoo <<= 2, 40*meters);
  BOOST_CHECK_EQUAL(mutfoo >>= 2, 10*meters);
  BOOST_CHECK_EQUAL(mutfoo %= foo3, 1*meters);

  BOOST_CHECK_EQUAL(0*foo, 0*meters);
  BOOST_CHECK_EQUAL(foo*0, 0*meters);
  BOOST_CHECK(0*foo == 0);
  BOOST_CHECK(foo*0 == 0);
  BOOST_CHECK(!(foo == 0));
  BOOST_CHECK(foo != 0);
  BOOST_CHECK(-foo != 0);
  BOOST_CHECK(foo > 0);
  BOOST_CHECK(foo >= 0);
  BOOST_CHECK(-foo < 0);
  BOOST_CHECK(-foo <= 0);
  BOOST_CHECK(!(-foo > 0));
  BOOST_CHECK(0*foo >= 0);
  BOOST_CHECK(0*foo <= 0);
  BOOST_CHECK(!(0*foo > 0));
  BOOST_CHECK(!(0*foo < 0));
  BOOST_CHECK(0 != foo);
  BOOST_CHECK(0 != -foo);
  BOOST_CHECK(0 < foo);
  BOOST_CHECK(0 <= foo);
  BOOST_CHECK(0 > -foo);
  BOOST_CHECK(0 >= -foo);

  BOOST_CHECK_EQUAL(identity(grams / kilograms), (1000*units_factor<1, 1000>()));
  BOOST_CHECK_EQUAL(identity(grams / kilograms)*units_factor<1000>(), short(1000));
}
<|endoftext|>


<commit_before><commit_msg>handle case of SRCDIR == BUILDDIR<commit_after><|endoftext|>