<commit_before>/*
 * Copyright 2012 Open Source Robotics Foundation
 *
 * 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.
 *
*/
/* Desc: Specification of a contact
 * Author: Nate Koenig
 * Date: 10 Nov 2009
 */

#include "gazebo/physics/physics.hh"
#include "gazebo/physics/Collision.hh"
#include "gazebo/physics/Contact.hh"

using namespace gazebo;
using namespace physics;

//////////////////////////////////////////////////
Contact::Contact()
{
  this->count = 0;
}

//////////////////////////////////////////////////
Contact::Contact(const Contact &_c)
{
  *this = _c;
}

//////////////////////////////////////////////////
Contact::~Contact()
{
}

//////////////////////////////////////////////////
Contact &Contact::operator =(const Contact &_contact)
{
  this->world = _contact.world;
  this->collision1 = _contact.collision1;
  this->collision2 = _contact.collision2;
  this->collisionPtr1 = _contact.collisionPtr1;
  this->collisionPtr2 = _contact.collisionPtr2;

  this->count = _contact.count;
  for (int i = 0; i < MAX_CONTACT_JOINTS; i++)
  {
    this->wrench[i] = _contact.wrench[i];
    this->positions[i] = _contact.positions[i];
    this->normals[i] = _contact.normals[i];
    this->depths[i] = _contact.depths[i];
  }

  this->time = _contact.time;

  return *this;
}

//////////////////////////////////////////////////
Contact &Contact::operator =(const msgs::Contact &_contact)
{
  this->count = 0;

  this->world = physics::get_world(_contact.world());
  this->collision1 = _contact.collision1();
  this->collision2 = _contact.collision2();

  if (world)
  {
    this->collisionPtr1 = boost::dynamic_pointer_cast<Collision>(
        this->world->GetEntity(this->collision1)).get();
    this->collisionPtr2 = boost::dynamic_pointer_cast<Collision>(
      this->world->GetEntity(this->collision2)).get();
  }
  else
  {
    gzwarn << "World: " << _contact.world() << " not found,"
           << "contact collision pointers will be NULL";
  }

  for (int j = 0; j < _contact.position_size(); ++j)
  {
    this->positions[j] = msgs::Convert(_contact.position(j));

    this->normals[j] = msgs::Convert(_contact.normal(j));

    this->depths[j] = _contact.depth(j);

    this->wrench[j].body1Force =
      msgs::Convert(_contact.wrench(j).body_1_force());

    this->wrench[j].body2Force =
      msgs::Convert(_contact.wrench(j).body_2_force());

    this->wrench[j].body1Torque =
      msgs::Convert(_contact.wrench(j).body_1_torque());

    this->wrench[j].body2Torque =
      msgs::Convert(_contact.wrench(j).body_2_torque());

    this->count++;
  }

  this->time = msgs::Convert(_contact.time());

  return *this;
}

//////////////////////////////////////////////////
void Contact::Reset()
{
  this->count = 0;
}

//////////////////////////////////////////////////
std::string Contact::DebugString() const
{
  std::ostringstream stream;

  stream << "World [" << this->world->GetName() << "]\n"
         << "Collision 1[" << this->collision1 << "]\n"
         << "Collision 2[" << this->collision2 << "]\n"
         << "Time[" << this->time << "]\n"
         << "Contact Count[" << this->count << "]\n";

  for (int i = 0; i < this->count; ++i)
  {
    stream << "--- Contact[" << i << "]\n";
    stream << "  Depth[" << this->depths[i] << "]\n"
           << "  Position[" << this->positions[i] << "]\n"
           << "  Normal[" << this->normals[i] << "]\n"
           << "  Force1[" << this->wrench[i].body1Force << "]\n"
           << "  Force2[" << this->wrench[i].body2Force << "]\n"
           << "  Torque1[" << this->wrench[i].body1Torque << "]\n"
           << "  Torque2[" << this->wrench[i].body2Torque << "]\n";
  }

  return stream.str();
}

//////////////////////////////////////////////////
void Contact::FillMsg(msgs::Contact &_msg) const
{
  _msg.set_world(this->world->GetName());
  _msg.set_collision1(this->collision1);
  _msg.set_collision2(this->collision2);
  msgs::Set(_msg.mutable_time(), this->time);

  for (int j = 0; j < this->count; ++j)
  {
    _msg.add_depth(this->depths[j]);

    msgs::Set(_msg.add_position(), this->positions[j]);
    msgs::Set(_msg.add_normal(), this->normals[j]);

    msgs::JointWrench *jntWrench = _msg.add_wrench();
    jntWrench->set_body_1_name(this->collision1);
    jntWrench->set_body_2_name(this->collision2);
    msgs::Set(jntWrench->mutable_body_1_force(), this->wrench[j].body1Force);
    msgs::Set(jntWrench->mutable_body_2_force(), this->wrench[j].body2Force);
    msgs::Set(jntWrench->mutable_body_1_torque(), this->wrench[j].body1Torque);
    msgs::Set(jntWrench->mutable_body_2_torque(), this->wrench[j].body2Torque);
  }
}
<commit_msg>added includes for forward depend<commit_after>/*
 * Copyright 2012 Open Source Robotics Foundation
 *
 * 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.
 *
*/
/* Desc: Specification of a contact
 * Author: Nate Koenig
 * Date: 10 Nov 2009
 */

#include "gazebo/physics/Physics.hh"
#include "gazebo/physics/Collision.hh"
#include "gazebo/physics/Contact.hh"
#include "gazebo/physics/PhysicsTypes.hh"

using namespace gazebo;
using namespace physics;

//////////////////////////////////////////////////
Contact::Contact()
{
  this->count = 0;
}

//////////////////////////////////////////////////
Contact::Contact(const Contact &_c)
{
  *this = _c;
}

//////////////////////////////////////////////////
Contact::~Contact()
{
}

//////////////////////////////////////////////////
Contact &Contact::operator =(const Contact &_contact)
{
  this->world = _contact.world;
  this->collision1 = _contact.collision1;
  this->collision2 = _contact.collision2;
  this->collisionPtr1 = _contact.collisionPtr1;
  this->collisionPtr2 = _contact.collisionPtr2;

  this->count = _contact.count;
  for (int i = 0; i < MAX_CONTACT_JOINTS; i++)
  {
    this->wrench[i] = _contact.wrench[i];
    this->positions[i] = _contact.positions[i];
    this->normals[i] = _contact.normals[i];
    this->depths[i] = _contact.depths[i];
  }

  this->time = _contact.time;

  return *this;
}

//////////////////////////////////////////////////
Contact &Contact::operator =(const msgs::Contact &_contact)
{
  this->count = 0;

  this->world = physics::get_world(_contact.world());
  this->collision1 = _contact.collision1();
  this->collision2 = _contact.collision2();

  if (world)
  {
    this->collisionPtr1 = boost::dynamic_pointer_cast<Collision>(
        this->world->GetEntity(this->collision1)).get();
    this->collisionPtr2 = boost::dynamic_pointer_cast<Collision>(
      this->world->GetEntity(this->collision2)).get();
  }
  else
  {
    gzwarn << "World: " << _contact.world() << " not found,"
           << "contact collision pointers will be NULL";
  }

  for (int j = 0; j < _contact.position_size(); ++j)
  {
    this->positions[j] = msgs::Convert(_contact.position(j));

    this->normals[j] = msgs::Convert(_contact.normal(j));

    this->depths[j] = _contact.depth(j);

    this->wrench[j].body1Force =
      msgs::Convert(_contact.wrench(j).body_1_force());

    this->wrench[j].body2Force =
      msgs::Convert(_contact.wrench(j).body_2_force());

    this->wrench[j].body1Torque =
      msgs::Convert(_contact.wrench(j).body_1_torque());

    this->wrench[j].body2Torque =
      msgs::Convert(_contact.wrench(j).body_2_torque());

    this->count++;
  }

  this->time = msgs::Convert(_contact.time());

  return *this;
}

//////////////////////////////////////////////////
void Contact::Reset()
{
  this->count = 0;
}

//////////////////////////////////////////////////
std::string Contact::DebugString() const
{
  std::ostringstream stream;

  stream << "World [" << this->world->GetName() << "]\n"
         << "Collision 1[" << this->collision1 << "]\n"
         << "Collision 2[" << this->collision2 << "]\n"
         << "Time[" << this->time << "]\n"
         << "Contact Count[" << this->count << "]\n";

  for (int i = 0; i < this->count; ++i)
  {
    stream << "--- Contact[" << i << "]\n";
    stream << "  Depth[" << this->depths[i] << "]\n"
           << "  Position[" << this->positions[i] << "]\n"
           << "  Normal[" << this->normals[i] << "]\n"
           << "  Force1[" << this->wrench[i].body1Force << "]\n"
           << "  Force2[" << this->wrench[i].body2Force << "]\n"
           << "  Torque1[" << this->wrench[i].body1Torque << "]\n"
           << "  Torque2[" << this->wrench[i].body2Torque << "]\n";
  }

  return stream.str();
}

//////////////////////////////////////////////////
void Contact::FillMsg(msgs::Contact &_msg) const
{
  _msg.set_world(this->world->GetName());
  _msg.set_collision1(this->collision1);
  _msg.set_collision2(this->collision2);
  msgs::Set(_msg.mutable_time(), this->time);

  for (int j = 0; j < this->count; ++j)
  {
    _msg.add_depth(this->depths[j]);

    msgs::Set(_msg.add_position(), this->positions[j]);
    msgs::Set(_msg.add_normal(), this->normals[j]);

    msgs::JointWrench *jntWrench = _msg.add_wrench();
    jntWrench->set_body_1_name(this->collision1);
    jntWrench->set_body_2_name(this->collision2);
    msgs::Set(jntWrench->mutable_body_1_force(), this->wrench[j].body1Force);
    msgs::Set(jntWrench->mutable_body_2_force(), this->wrench[j].body2Force);
    msgs::Set(jntWrench->mutable_body_1_torque(), this->wrench[j].body1Torque);
    msgs::Set(jntWrench->mutable_body_2_torque(), this->wrench[j].body2Torque);
  }
}
<|endoftext|>


<commit_before>#include <Python.h>

#define UNICODE
#include <Windows.h>

#include "core.hpp"

#define WGL_CONTEXT_PROFILE_MASK 0x9126
#define WGL_CONTEXT_CORE_PROFILE_BIT 0x0001
#define WGL_CONTEXT_MAJOR_VERSION 0x2091
#define WGL_CONTEXT_MINOR_VERSION 0x2092

typedef HGLRC (WINAPI * PFNWGLCREATECONTEXTATTRIBSARBPROC)(HDC hDC, HGLRC hShareContext, const int * attribList);
typedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC)(int interval);

HINSTANCE hinst;

struct MyWindow {
    CRITICAL_SECTION lock;
    HANDLE ready;

    HWND hwnd;
    HDC hdc;
    HGLRC hrc;

    bool key_down[110];
    wchar_t text_input[100];
    int text_input_size;
    int mouse_wheel;

    long long freq;
    long long start;
    bool alive;
};

MyWindow window;

PIXELFORMATDESCRIPTOR pfd = {sizeof(PIXELFORMATDESCRIPTOR), 1, PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_GENERIC_ACCELERATED | PFD_DOUBLEBUFFER, 0, 24};

int keyid(int code) {
    if ('A' <= code && code <= 'Z') {
        return 27 + code - 'A';
    }
    if ('0' <= code && code <= '9') {
        return 53 + code - '0';
    }
    if (VK_F1 <= code && code <= VK_F12) {
        return 63 + code - VK_F1;
    }
    switch (code) {
        case VK_CONTROL: return 1;
        case VK_MENU: return 2;
        case VK_SHIFT: return 3;
        case VK_RETURN: return 4;
        case VK_SPACE: return 5;
        case VK_ESCAPE: return 6;
        case VK_TAB: return 7;
        case VK_BACK: return 8;
        case VK_UP: return 9;
        case VK_DOWN: return 10;
        case VK_LEFT: return 11;
        case VK_RIGHT: return 12;
        case VK_OEM_PLUS: return 13;
        case VK_OEM_MINUS: return 14;
        case VK_OEM_2: return 15;
        case VK_OEM_5: return 16;
        case VK_OEM_PERIOD: return 17;
        case VK_OEM_COMMA: return 18;
        case VK_OEM_3: return 19;
        case VK_INSERT: return 20;
        case VK_DELETE: return 21;
        case VK_HOME: return 22;
        case VK_END: return 23;
        case VK_PRIOR: return 24;
        case VK_NEXT: return 25;
        case VK_CAPITAL: return 26;
        default: return 0;
    }
}

LRESULT CALLBACK WindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
    switch (uMsg) {
        case WM_CLOSE: {
            DestroyWindow(hWnd);
            return 0;
        }
        case WM_DESTROY: {
            EnterCriticalSection(&window.lock);
            window.alive = false;
            LeaveCriticalSection(&window.lock);
            PostQuitMessage(0);
            return 0;
        }
        case WM_LBUTTONDOWN: {
            EnterCriticalSection(&window.lock);
            window.key_down[101] = true;
            LeaveCriticalSection(&window.lock);
            break;
        }
        case WM_LBUTTONUP: {
            EnterCriticalSection(&window.lock);
            window.key_down[101] = false;
            LeaveCriticalSection(&window.lock);
            break;
        }
        case WM_RBUTTONDOWN: {
            EnterCriticalSection(&window.lock);
            window.key_down[102] = true;
            LeaveCriticalSection(&window.lock);
            break;
        }
        case WM_RBUTTONUP: {
            EnterCriticalSection(&window.lock);
            window.key_down[102] = false;
            LeaveCriticalSection(&window.lock);
            break;
        }
        case WM_MBUTTONDOWN: {
            EnterCriticalSection(&window.lock);
            window.key_down[103] = true;
            LeaveCriticalSection(&window.lock);
            break;
        }
        case WM_MBUTTONUP: {
            EnterCriticalSection(&window.lock);
            window.key_down[103] = false;
            LeaveCriticalSection(&window.lock);
            break;
        }
        case WM_MOUSEWHEEL: {
            EnterCriticalSection(&window.lock);
            window.mouse_wheel += GET_WHEEL_DELTA_WPARAM(wParam);
            LeaveCriticalSection(&window.lock);
            break;
        }
        case WM_KEYDOWN: {
            EnterCriticalSection(&window.lock);
            window.key_down[keyid((int)wParam)] = true;
            LeaveCriticalSection(&window.lock);
            break;
        }
        case WM_KEYUP: {
            EnterCriticalSection(&window.lock);
            window.key_down[keyid((int)wParam)] = false;
            LeaveCriticalSection(&window.lock);
            break;
        }
        case WM_CHAR: {
            EnterCriticalSection(&window.lock);
            if (window.text_input_size < 100) {
                window.text_input[window.text_input_size++] = (wchar_t)wParam;
            }
            LeaveCriticalSection(&window.lock);
            break;
        }
        case WM_SYSKEYDOWN:
        case WM_SYSKEYUP: {
            EnterCriticalSection(&window.lock);
            static bool sys_alt = false;
            if (wParam == VK_MENU) {
                sys_alt = (uMsg == WM_SYSKEYDOWN);
            } else if (sys_alt && uMsg == WM_SYSKEYDOWN && wParam == VK_F4) {
                DestroyWindow(hWnd);
            }
            LeaveCriticalSection(&window.lock);
            return 0;
        }
        case WM_USER: {
            ShowCursor(!wParam);
            return 0;
        }
    }
    return DefWindowProc(hWnd, uMsg, wParam, lParam);
}

void window_thread(void * arg) {
    RawData * data = (RawData *)arg;
    data->window = &window;

    if (!hinst) {
        return;
    }

    HCURSOR hcursor = (HCURSOR)LoadCursor(NULL, IDC_ARROW);
    HCURSOR hicon1 = (HICON)LoadIcon(hinst, MAKEINTRESOURCE(10001));
    HCURSOR hicon2 = (HICON)LoadIcon(hinst, MAKEINTRESOURCE(10002));

    WNDCLASSEXW wnd_class = {sizeof(WNDCLASSEXW), CS_OWNDC, WindowProc, 0, 0, hinst, hicon1, hcursor, NULL, NULL, L"glwindow", hicon2};

    if (!RegisterClassEx(&wnd_class)) {
        return;
    }

    int style = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU;
    int sw = GetSystemMetrics(SM_CXSCREEN);
    int sh = GetSystemMetrics(SM_CYSCREEN);

    RECT rect = {};
    rect.right = data->width;
    rect.bottom = data->height;

    AdjustWindowRect(&rect, style, false);

    int adjusted_width = rect.right - rect.left;
    int adjusted_height = rect.bottom - rect.top;

    int x = (sw - adjusted_width) / 2;
    int y = (sh - adjusted_height) / 2;

    window.hwnd = CreateWindowEx(WS_EX_APPWINDOW, L"glwindow", (LPCWSTR)data->title, style, x, y, data->width, data->height, NULL, NULL, hinst, data);

    if (!window.hwnd) {
        return;
    }

    window.hdc = GetDC(window.hwnd);

    if (!window.hdc) {
        return;
    }

    int pixelformat = ChoosePixelFormat(window.hdc, &pfd);
    if (!pixelformat) {
        return;
    }

    if (!SetPixelFormat(window.hdc, pixelformat, &pfd)) {
        return;
    }

   window.hrc = wglCreateContext(window.hdc);
    if (!window.hrc) {
        return;
    }

    if (data->glversion) {
        if (!wglMakeCurrent(window.hdc, window.hrc)) {
            return;
        }

        PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC)wglGetProcAddress("wglCreateContextAttribsARB");
        if (!wglCreateContextAttribsARB) {
            return;
        }

        if (!wglMakeCurrent(NULL, NULL)) {
            return;
        }

        if (!wglDeleteContext(window.hrc)) {
            return;
        }

        int attribs[] = {
            WGL_CONTEXT_PROFILE_MASK, WGL_CONTEXT_CORE_PROFILE_BIT,
            WGL_CONTEXT_MAJOR_VERSION, data->glversion / 100 % 10,
            WGL_CONTEXT_MINOR_VERSION, data->glversion / 10 % 10,
            0, 0,
        };

        window.hrc = wglCreateContextAttribsARB(window.hdc, NULL, attribs);
    }

    if (!window.hrc) {
        return;
    }

    SetEvent(window.ready);

    MSG msg;
	while (GetMessage(&msg, NULL, 0, 0)) {
		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}
}

bool create_window(void * arg) {
    window.ready = CreateEvent(NULL, true, false, NULL);
    InitializeCriticalSection(&window.lock);
    window.alive = true;

    HANDLE thread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)window_thread, arg, 0, NULL);

    HANDLE objects[2] = {
        window.ready,
        thread,
    };

    WaitForMultipleObjects(2, objects, false, INFINITE);

    if (WaitForSingleObject(window.ready, 0)) {
        PyErr_BadInternalCall();
        return false;
    }

    if (!wglMakeCurrent(window.hdc, window.hrc)) {
        PyErr_BadInternalCall();
        return false;
    }

    PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = (PFNWGLSWAPINTERVALEXTPROC)wglGetProcAddress("wglSwapIntervalEXT");
    if (!wglSwapIntervalEXT) {
        PyErr_BadInternalCall();
        return false;
    }

    wglSwapIntervalEXT(1);

    QueryPerformanceFrequency((LARGE_INTEGER *)&window.freq);
    QueryPerformanceCounter((LARGE_INTEGER *)&window.start);

    ShowWindow(window.hwnd, SW_SHOW);
	SetForegroundWindow(window.hwnd);
	SetActiveWindow(window.hwnd);
	SetFocus(window.hwnd);
    return true;
}

bool update_window(void * arg) {
    RawData * data = (RawData *)arg;

    EnterCriticalSection(&window.lock);

    if (!window.alive) {
        LeaveCriticalSection(&window.lock);
        return false;
    }

    SwapBuffers(window.hdc);

    RECT rect;
    GetWindowRect(window.hwnd, &rect);

    if (data->grab != data->old_grab) {
        if (data->grab) {
            POINT point;
            GetCursorPos(&point);
            data->mx = point.x;
            data->my = point.y;
            SetCursorPos((rect.left + rect.right) / 2, (rect.top + rect.bottom) / 2);
        } else {
            SetCursorPos(data->mx, data->my);
        }
    }

    memcpy(data->key_down, window.key_down, 110);
    memcpy(data->text_input, window.text_input, window.text_input_size * 2);
    data->text_input_size = window.text_input_size;
    data->mw = window.mouse_wheel;

    LeaveCriticalSection(&window.lock);

    if (data->grab != data->old_grab) {
        SendMessage(window.hwnd, WM_USER, data->grab, 0);
    }

    POINT point;
    GetCursorPos(&point);

    if (data->grab) {
        SetCursorPos((rect.left + rect.right) / 2, (rect.top + rect.bottom) / 2);
        data->dmx = point.x - (rect.left + rect.right) / 2;
        data->dmy = point.y - (rect.top + rect.bottom) / 2;
    } else {
        data->mx = point.x - rect.left;
        data->my = point.y - rect.top;
    }

    long long now;
    QueryPerformanceCounter((LARGE_INTEGER *)&now);
    data->time = (double)(now - window.start) / window.freq;
    return true;
}

BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) {
    if (fdwReason == DLL_PROCESS_ATTACH) {
        hinst = hinstDLL;
    }
    return true;
}
<commit_msg>organize code<commit_after>#include <Python.h>

#define UNICODE
#include <Windows.h>

#include "core.hpp"

#define WGL_CONTEXT_PROFILE_MASK 0x9126
#define WGL_CONTEXT_CORE_PROFILE_BIT 0x0001
#define WGL_CONTEXT_MAJOR_VERSION 0x2091
#define WGL_CONTEXT_MINOR_VERSION 0x2092

typedef HGLRC (WINAPI * PFNWGLCREATECONTEXTATTRIBSARBPROC)(HDC hDC, HGLRC hShareContext, const int * attribList);
typedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC)(int interval);

HINSTANCE hinst;

struct StaticWindow {
    CRITICAL_SECTION lock;
    HANDLE ready;

    HANDLE thread;
    HWND hwnd;
    HDC hdc;
    HGLRC hrc;

    const char * error;

    bool key_down[110];
    wchar_t text_input[100];
    int text_input_size;
    int mouse_wheel;

    long long freq;
    long long start;
    bool alive;
} window;

int keyid(int code) {
    if ('A' <= code && code <= 'Z') {
        return 27 + code - 'A';
    }
    if ('0' <= code && code <= '9') {
        return 53 + code - '0';
    }
    if (VK_F1 <= code && code <= VK_F12) {
        return 63 + code - VK_F1;
    }
    switch (code) {
        case VK_CONTROL: return 1;
        case VK_MENU: return 2;
        case VK_SHIFT: return 3;
        case VK_RETURN: return 4;
        case VK_SPACE: return 5;
        case VK_ESCAPE: return 6;
        case VK_TAB: return 7;
        case VK_BACK: return 8;
        case VK_UP: return 9;
        case VK_DOWN: return 10;
        case VK_LEFT: return 11;
        case VK_RIGHT: return 12;
        case VK_OEM_PLUS: return 13;
        case VK_OEM_MINUS: return 14;
        case VK_OEM_2: return 15;
        case VK_OEM_5: return 16;
        case VK_OEM_PERIOD: return 17;
        case VK_OEM_COMMA: return 18;
        case VK_OEM_3: return 19;
        case VK_INSERT: return 20;
        case VK_DELETE: return 21;
        case VK_HOME: return 22;
        case VK_END: return 23;
        case VK_PRIOR: return 24;
        case VK_NEXT: return 25;
        case VK_CAPITAL: return 26;
        default: return 0;
    }
}

LRESULT CALLBACK WindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
    switch (uMsg) {
        case WM_CLOSE: {
            DestroyWindow(hWnd);
            return 0;
        }
        case WM_DESTROY: {
            EnterCriticalSection(&window.lock);
            window.alive = false;
            LeaveCriticalSection(&window.lock);
            PostQuitMessage(0);
            return 0;
        }
        case WM_LBUTTONDOWN: {
            EnterCriticalSection(&window.lock);
            window.key_down[101] = true;
            LeaveCriticalSection(&window.lock);
            break;
        }
        case WM_LBUTTONUP: {
            EnterCriticalSection(&window.lock);
            window.key_down[101] = false;
            LeaveCriticalSection(&window.lock);
            break;
        }
        case WM_RBUTTONDOWN: {
            EnterCriticalSection(&window.lock);
            window.key_down[102] = true;
            LeaveCriticalSection(&window.lock);
            break;
        }
        case WM_RBUTTONUP: {
            EnterCriticalSection(&window.lock);
            window.key_down[102] = false;
            LeaveCriticalSection(&window.lock);
            break;
        }
        case WM_MBUTTONDOWN: {
            EnterCriticalSection(&window.lock);
            window.key_down[103] = true;
            LeaveCriticalSection(&window.lock);
            break;
        }
        case WM_MBUTTONUP: {
            EnterCriticalSection(&window.lock);
            window.key_down[103] = false;
            LeaveCriticalSection(&window.lock);
            break;
        }
        case WM_MOUSEWHEEL: {
            EnterCriticalSection(&window.lock);
            window.mouse_wheel += GET_WHEEL_DELTA_WPARAM(wParam);
            LeaveCriticalSection(&window.lock);
            break;
        }
        case WM_KEYDOWN: {
            EnterCriticalSection(&window.lock);
            window.key_down[keyid((int)wParam)] = true;
            LeaveCriticalSection(&window.lock);
            break;
        }
        case WM_KEYUP: {
            EnterCriticalSection(&window.lock);
            window.key_down[keyid((int)wParam)] = false;
            LeaveCriticalSection(&window.lock);
            break;
        }
        case WM_CHAR: {
            EnterCriticalSection(&window.lock);
            if (window.text_input_size < 100) {
                window.text_input[window.text_input_size++] = (wchar_t)wParam;
            }
            LeaveCriticalSection(&window.lock);
            break;
        }
        case WM_SYSKEYDOWN:
        case WM_SYSKEYUP: {
            EnterCriticalSection(&window.lock);
            static bool sys_alt = false;
            if (wParam == VK_MENU) {
                sys_alt = (uMsg == WM_SYSKEYDOWN);
            } else if (sys_alt && uMsg == WM_SYSKEYDOWN && wParam == VK_F4) {
                DestroyWindow(hWnd);
            }
            LeaveCriticalSection(&window.lock);
            return 0;
        }
        case WM_USER: {
            ShowCursor(!wParam);
            return 0;
        }
    }
    return DefWindowProc(hWnd, uMsg, wParam, lParam);
}

void window_thread(void * arg) {
    RawData * data = (RawData *)arg;
    data->window = &window;

    if (!hinst) {
        window.error = "hinstance is NULL";
        SetEvent(window.ready);
        return;
    }

    HCURSOR hcursor = (HCURSOR)LoadCursor(NULL, IDC_ARROW);
    HCURSOR hicon1 = (HICON)LoadIcon(hinst, MAKEINTRESOURCE(10001));
    HCURSOR hicon2 = (HICON)LoadIcon(hinst, MAKEINTRESOURCE(10002));

    WNDCLASSEXW wnd_class = {
        sizeof(WNDCLASSEXW), CS_OWNDC, WindowProc, 0, 0, hinst, hicon1, hcursor, NULL, NULL, L"glwindow", hicon2,
    };

    if (!RegisterClassEx(&wnd_class)) {
        window.error = "RegisterClassEx failed";
        SetEvent(window.ready);
        return;
    }

    int style = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU;
    int sw = GetSystemMetrics(SM_CXSCREEN);
    int sh = GetSystemMetrics(SM_CYSCREEN);

    RECT rect = {};
    rect.right = data->width;
    rect.bottom = data->height;

    AdjustWindowRect(&rect, style, false);

    int width = rect.right - rect.left;
    int height = rect.bottom - rect.top;

    int x = (sw - width) / 2;
    int y = (sh - height) / 2;

    window.hwnd = CreateWindowEx(
        WS_EX_APPWINDOW, L"glwindow", (LPCWSTR)data->title, style, x, y, width, height, NULL, NULL, hinst, data
    );

    if (!window.hwnd) {
        window.error = "CreateWindowEx failed";
        SetEvent(window.ready);
        return;
    }

    window.hdc = GetDC(window.hwnd);
    if (!window.hdc) {
        window.error = "GetDC failed";
        SetEvent(window.ready);
        return;
    }

    PIXELFORMATDESCRIPTOR pfd = {
        sizeof(PIXELFORMATDESCRIPTOR),
        1,
        PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_GENERIC_ACCELERATED | PFD_DOUBLEBUFFER,
        0,
        24,
    };

    int pixelformat = ChoosePixelFormat(window.hdc, &pfd);
    if (!pixelformat) {
        window.error = "ChoosePixelFormat failed";
        SetEvent(window.ready);
        return;
    }

    if (!SetPixelFormat(window.hdc, pixelformat, &pfd)) {
        window.error = "SetPixelFormat failed";
        SetEvent(window.ready);
        return;
    }

   window.hrc = wglCreateContext(window.hdc);
    if (!window.hrc) {
        window.error = "wglCreateContext failed";
        SetEvent(window.ready);
        return;
    }

    if (data->glversion) {
        if (!wglMakeCurrent(window.hdc, window.hrc)) {
            window.error = "wglMakeCurrent failed";
            SetEvent(window.ready);
            return;
        }

        FARPROC proc = wglGetProcAddress("wglCreateContextAttribsARB");
        PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC)proc;
        if (!wglCreateContextAttribsARB) {
            window.error = "wglCreateContextAttribsARB is missing";
            SetEvent(window.ready);
            return;
        }

        if (!wglMakeCurrent(NULL, NULL)) {
            window.error = "wglMakeCurrent failed";
            SetEvent(window.ready);
            return;
        }

        if (!wglDeleteContext(window.hrc)) {
            window.error = "wglDeleteContext failed";
            SetEvent(window.ready);
            return;
        }

        int attribs[] = {
            WGL_CONTEXT_PROFILE_MASK, WGL_CONTEXT_CORE_PROFILE_BIT,
            WGL_CONTEXT_MAJOR_VERSION, data->glversion / 100 % 10,
            WGL_CONTEXT_MINOR_VERSION, data->glversion / 10 % 10,
            0, 0,
        };

        window.hrc = wglCreateContextAttribsARB(window.hdc, NULL, attribs);
        if (!window.hrc) {
            window.error = "wglCreateContextAttribsARB failed";
            SetEvent(window.ready);
            return;
        }
    }

    SetEvent(window.ready);

    MSG msg;
    while (GetMessage(&msg, NULL, 0, 0)) {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
}

bool create_window(void * arg) {
    window.ready = CreateEvent(NULL, true, false, NULL);
    InitializeCriticalSection(&window.lock);
    window.alive = true;

    window.thread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)window_thread, arg, 0, NULL);
    WaitForSingleObject(window.ready, INFINITE);

    if (window.error) {
        PyErr_Format(PyExc_Exception, window.error);
        return false;
    }

    if (!wglMakeCurrent(window.hdc, window.hrc)) {
        PyErr_BadInternalCall();
        return false;
    }

    PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = (PFNWGLSWAPINTERVALEXTPROC)wglGetProcAddress("wglSwapIntervalEXT");
    if (!wglSwapIntervalEXT) {
        PyErr_BadInternalCall();
        return false;
    }

    wglSwapIntervalEXT(1);

    QueryPerformanceFrequency((LARGE_INTEGER *)&window.freq);
    QueryPerformanceCounter((LARGE_INTEGER *)&window.start);

    ShowWindow(window.hwnd, SW_SHOW);
    SetForegroundWindow(window.hwnd);
    SetActiveWindow(window.hwnd);
    SetFocus(window.hwnd);
    return true;
}

bool update_window(void * arg) {
    RawData * data = (RawData *)arg;

    EnterCriticalSection(&window.lock);

    if (!window.alive) {
        LeaveCriticalSection(&window.lock);
        return false;
    }

    SwapBuffers(window.hdc);

    RECT rect;
    GetWindowRect(window.hwnd, &rect);

    if (data->grab != data->old_grab) {
        if (data->grab) {
            POINT point;
            GetCursorPos(&point);
            data->mx = point.x;
            data->my = point.y;
            SetCursorPos((rect.left + rect.right) / 2, (rect.top + rect.bottom) / 2);
        } else {
            SetCursorPos(data->mx, data->my);
        }
    }

    memcpy(data->key_down, window.key_down, 110);
    memcpy(data->text_input, window.text_input, window.text_input_size * 2);
    data->text_input_size = window.text_input_size;
    data->mw = window.mouse_wheel;

    LeaveCriticalSection(&window.lock);

    if (data->grab != data->old_grab) {
        SendMessage(window.hwnd, WM_USER, data->grab, 0);
    }

    POINT point;
    GetCursorPos(&point);

    if (data->grab) {
        SetCursorPos((rect.left + rect.right) / 2, (rect.top + rect.bottom) / 2);
        data->dmx = point.x - (rect.left + rect.right) / 2;
        data->dmy = point.y - (rect.top + rect.bottom) / 2;
    } else {
        data->mx = point.x - rect.left;
        data->my = point.y - rect.top;
    }

    long long now;
    QueryPerformanceCounter((LARGE_INTEGER *)&now);
    data->time = (double)(now - window.start) / window.freq;
    return true;
}

BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) {
    if (fdwReason == DLL_PROCESS_ATTACH) {
        hinst = hinstDLL;
    }
    return true;
}
<|endoftext|>


<commit_before>//
//  ftDrawForces.cpp
//  ofxFlowToolsExample
//
//  Created by Ties East on 18/6/15.
//
//

#include "ftDrawInputForces.h"

namespace flowTools {

	ftDrawInputForces::ftDrawInputForces() {
		ofAddListener(ofEvents().mouseMoved, this, &ftDrawInputForces::mouseMoved);
		ofAddListener(ofEvents().mouseDragged, this, &ftDrawInputForces::mouseDragged);
		ofAddListener( ofEvents().touchMoved, this, &ftDrawInputForces::touchMoved );
		ofAddListener( ofEvents().touchDown, this, &ftDrawInputForces::touchDown );
	}

    ftDrawInputForces::~ftDrawInputForces() {
        ofRemoveListener(ofEvents().mouseMoved, this, &ftDrawInputForces::mouseMoved);
        ofRemoveListener(ofEvents().mouseDragged, this, &ftDrawInputForces::mouseDragged);
		ofRemoveListener( ofEvents().touchMoved, this, &ftDrawInputForces::touchMoved );
		ofRemoveListener( ofEvents().touchDown, this, &ftDrawInputForces::touchDown );
    }

	void ftDrawInputForces::setup(int _simulationWidth, int _simulationHeight, int _densityWidth, int _densityHeight) {
		simulationWidth = _simulationWidth;
		simulationHeight = _simulationHeight;
		densityWidth = (!_densityWidth)? simulationWidth : _densityWidth;
		densityHeight = (!_densityHeight)? simulationHeight: _densityHeight;

		numDrawForces = 12;
		drawForces = new ftDrawForce[numDrawForces];
		drawForces[0].setup(densityWidth, densityHeight, FT_DENSITY, true);
		drawForces[0].setName("draw full res");
		drawForces[1].setup(simulationWidth, simulationHeight, FT_VELOCITY, true);
		drawForces[1].setName("draw flow res 1");
		drawForces[2].setup(simulationWidth, simulationHeight, FT_TEMPERATURE, true);
		drawForces[2].setName("draw flow res 2");
		drawForces[3].setup(densityWidth, densityHeight, FT_DENSITY, false);
		drawForces[3].setName("draw full res");
		drawForces[4].setup(simulationWidth, simulationHeight, FT_VELOCITY, false);
		drawForces[4].setName("draw flow res 1");
		drawForces[5].setup(simulationWidth, simulationHeight, FT_TEMPERATURE, false);
		drawForces[5].setName("draw flow res 2");
		drawForces[6].setup(densityWidth, densityHeight, FT_DENSITY, true);
		drawForces[6].setName("draw full res");
		drawForces[7].setup(simulationWidth, simulationHeight, FT_VELOCITY, true);
		drawForces[7].setName("draw flow res 1");
		drawForces[8].setup(simulationWidth, simulationHeight, FT_TEMPERATURE, true);
		drawForces[8].setName("draw flow res 2");
		drawForces[ 9 ].setup( densityWidth, densityHeight, FT_DENSITY, true );
		drawForces[ 9 ].setName( "draw full res" );
		drawForces[ 10 ].setup( simulationWidth, simulationHeight, FT_VELOCITY, true );
		drawForces[ 10 ].setName( "draw flow res 1" );
		drawForces[ 11 ].setup( simulationWidth, simulationHeight, FT_TEMPERATURE, true );
		drawForces[ 11 ].setName( "draw flow res 2" );

		leftButtonParameters.setName("mouse left button");
		leftButtonParameters.add(doResetDrawForces.set("reset", false));
		rightButtonParameters.setName("mouse right button");
		rightButtonParameters.add(doResetDrawForces.set("reset", false));
		middleButtonParameters.setName("mouse middle button");
		middleButtonParameters.add(doResetDrawForces.set("reset", false));
		singleTouchParameters.setName( "single touch" );
		singleTouchParameters.add( doResetDrawForces.set( "reset", false ) );
		doResetDrawForces.addListener(this, &ftDrawInputForces::resetDrawForcesListner);
		for (int i=0; i<3; i++) {
			leftButtonParameters.add(drawForces[i].parameters);
			rightButtonParameters.add(drawForces[i+3].parameters);
			middleButtonParameters.add(drawForces[i+6].parameters);
			singleTouchParameters.add( drawForces[ i + 9 ].parameters );
		}
	}

	void ftDrawInputForces::update(float _deltaTime) {
		deltaTime = _deltaTime;

		for (int i=0; i<numDrawForces; i++) {
			drawForces[i].update();
		}
	}

	void ftDrawInputForces::invertForce(int _index) {
		ofVec4f force = drawForces[_index].getForce();
		force.x = 1.0 - force.x;
		force.y = 1.0 - force.y;
		force.z = 1.0 - force.z;

		drawForces[_index].setForce(force);
	}

	//--------------------------------------------------------------
	bool ftDrawInputForces::didChange(int _index) {
		if (_index < 0 || _index >= numDrawForces) {
			ofLogWarning("ftDrawInputForces::getDrawForceType: index out of range");
			return false;
		}
		else
			return drawForces[_index].didChange();
	}

	//--------------------------------------------------------------
	ftDrawForceType ftDrawInputForces::getType(int _index) {
		if (_index < 0 || _index >= numDrawForces) {
			ofLogWarning("ftDrawInputForces::getDrawForceType: index out of range");
			return FT_NONE;
		}
		else
			return drawForces[_index].getType();
	}

	//--------------------------------------------------------------
	ofTexture& ftDrawInputForces::getTextureReference(int _index) {
		if (_index < 0 || _index >= numDrawForces) {
			ofLogError("ftDrawInputForces::getTexture: index out of range");
		}
		else
			return drawForces[_index].getTexture();

	}

	//--------------------------------------------------------------
	float ftDrawInputForces::getStrength(int _index) {
		if (_index < 0 || _index >= numDrawForces) {
			ofLogWarning("ftDrawInputForces::getStrength: index out of range");
			return 0;
		}
		else {
			if (drawForces[_index].getIsTemporary()) {
				return drawForces[_index].getStrength();
			}
			else {
				return drawForces[_index].getStrength() * deltaTime;;
			}
		}
	}

	//--------------------------------------------------------------
	void ftDrawInputForces::mouseDragged( ofMouseEventArgs& mouse ) {
		ofVec2f normalizedMouse;

		normalizedMouse.set(mouse.x / (float)ofGetWindowWidth(), mouse.y / (float)ofGetWindowHeight());

		ofVec2f velocity = normalizedMouse - lastNormalizedMouse;
		//velocity.normalize();

		if (mouse.button == 0) {

			for (int i=0; i<3; i++) {
				if (drawForces[i].getType() == FT_VELOCITY)
					drawForces[i].setForce(velocity);
				drawForces[i].applyForce(normalizedMouse);
			}
		}
		else if(mouse.button == 2)
		{

			for (int i=3; i<6; i++) {
				if (drawForces[i].getType() == FT_VELOCITY)
					drawForces[i].setForce(velocity);
				drawForces[i].applyForce(normalizedMouse);
			}
		}
		else if (mouse.button == 1)
		{
			for (int i = 6; i<numDrawForces; i++) {
				if (drawForces[i].getType() == FT_VELOCITY)
					drawForces[i].setForce(velocity);
				drawForces[i].applyForce(normalizedMouse);
			}
		}
		lastNormalizedMouse.set(normalizedMouse);

	}

	//---------------------------------------------------------------------------------------------
	void ftDrawInputForces::mouseMoved( ofMouseEventArgs& mouse ){
		ofVec2f normalizedMouse;

		normalizedMouse.set ( mouse.x / (float)ofGetWindowWidth()
							, mouse.y / (float)ofGetWindowHeight()
							);

		lastNormalizedMouse.set(normalizedMouse);
	}

	//---------------------------------------------------------------------------------------------
	void ftDrawInputForces::touchDown( ofTouchEventArgs& touch)
	{
		ofVec2f normalizedTouch;
		normalizedTouch.set  ( touch.x / (float)ofGetWindowWidth()
							 , touch.y / (float)ofGetWindowHeight()
							);
		lastNormalizedTouch.set( normalizedTouch );
	}

	//---------------------------------------------------------------------------------------------
	void ftDrawInputForces::touchMoved( ofTouchEventArgs& touch)
	{
		ofVec2f normalizedTouch;
		normalizedTouch.set( touch.x / (float)ofGetWindowWidth()
							 , touch.y / (float)ofGetWindowHeight()
		);

		ofVec2f normalizedTouchSpeed;
		normalizedTouchSpeed.set( touch.xspeed / (float)ofGetWindowWidth()
							 , touch.yspeed / (float)ofGetWindowHeight()
		);

		ofVec2f normalizedTouchAccel;
		normalizedTouchAccel.set( touch.xaccel / (float)ofGetWindowWidth()
							 , touch.yaccel / (float)ofGetWindowHeight()
		);

		ofVec2f velocity = normalizedTouch - lastNormalizedTouch;
		//ofVec2f velocity = normalizedTouchSpeed;
		ofVec2f acceleration = normalizedTouchAccel;

		for( int i = 0; i<3; i++ )
		{
			if( drawForces[ i ].getType() == FT_VELOCITY )
				drawForces[ i ].setForce( velocity );
			drawForces[ i ].applyForce( normalizedTouch );
		}

		lastNormalizedTouch.set( normalizedTouch );
	}

}<commit_msg>otw - Fixed bug with middle mouse button creating white/black ink.<commit_after>//
//  ftDrawForces.cpp
//  ofxFlowToolsExample
//
//  Created by Ties East on 18/6/15.
//
//

#include "ftDrawInputForces.h"

namespace flowTools {

	ftDrawInputForces::ftDrawInputForces() {
		ofAddListener(ofEvents().mouseMoved, this, &ftDrawInputForces::mouseMoved);
		ofAddListener(ofEvents().mouseDragged, this, &ftDrawInputForces::mouseDragged);
		ofAddListener( ofEvents().touchMoved, this, &ftDrawInputForces::touchMoved );
		ofAddListener( ofEvents().touchDown, this, &ftDrawInputForces::touchDown );
	}

    ftDrawInputForces::~ftDrawInputForces() {
        ofRemoveListener(ofEvents().mouseMoved, this, &ftDrawInputForces::mouseMoved);
        ofRemoveListener(ofEvents().mouseDragged, this, &ftDrawInputForces::mouseDragged);
		ofRemoveListener( ofEvents().touchMoved, this, &ftDrawInputForces::touchMoved );
		ofRemoveListener( ofEvents().touchDown, this, &ftDrawInputForces::touchDown );
    }

	void ftDrawInputForces::setup(int _simulationWidth, int _simulationHeight, int _densityWidth, int _densityHeight) {
		simulationWidth = _simulationWidth;
		simulationHeight = _simulationHeight;
		densityWidth = (!_densityWidth)? simulationWidth : _densityWidth;
		densityHeight = (!_densityHeight)? simulationHeight: _densityHeight;

		numDrawForces = 12;
		drawForces = new ftDrawForce[numDrawForces];
		drawForces[0].setup(densityWidth, densityHeight, FT_DENSITY, true);
		drawForces[0].setName("draw full res");
		drawForces[1].setup(simulationWidth, simulationHeight, FT_VELOCITY, true);
		drawForces[1].setName("draw flow res 1");
		drawForces[2].setup(simulationWidth, simulationHeight, FT_TEMPERATURE, true);
		drawForces[2].setName("draw flow res 2");
		drawForces[3].setup(densityWidth, densityHeight, FT_DENSITY, false);
		drawForces[3].setName("draw full res");
		drawForces[4].setup(simulationWidth, simulationHeight, FT_VELOCITY, false);
		drawForces[4].setName("draw flow res 1");
		drawForces[5].setup(simulationWidth, simulationHeight, FT_TEMPERATURE, false);
		drawForces[5].setName("draw flow res 2");
		drawForces[6].setup(densityWidth, densityHeight, FT_DENSITY, true);
		drawForces[6].setName("draw full res");
		drawForces[7].setup(simulationWidth, simulationHeight, FT_VELOCITY, true);
		drawForces[7].setName("draw flow res 1");
		drawForces[8].setup(simulationWidth, simulationHeight, FT_TEMPERATURE, true);
		drawForces[8].setName("draw flow res 2");
		drawForces[ 9 ].setup( densityWidth, densityHeight, FT_DENSITY, true );
		drawForces[ 9 ].setName( "draw full res" );
		drawForces[ 10 ].setup( simulationWidth, simulationHeight, FT_VELOCITY, true );
		drawForces[ 10 ].setName( "draw flow res 1" );
		drawForces[ 11 ].setup( simulationWidth, simulationHeight, FT_TEMPERATURE, true );
		drawForces[ 11 ].setName( "draw flow res 2" );

		leftButtonParameters.setName("mouse left button");
		leftButtonParameters.add(doResetDrawForces.set("reset", false));
		rightButtonParameters.setName("mouse right button");
		rightButtonParameters.add(doResetDrawForces.set("reset", false));
		middleButtonParameters.setName("mouse middle button");
		middleButtonParameters.add(doResetDrawForces.set("reset", false));
		singleTouchParameters.setName( "single touch" );
		singleTouchParameters.add( doResetDrawForces.set( "reset", false ) );
		doResetDrawForces.addListener(this, &ftDrawInputForces::resetDrawForcesListner);
		for (int i=0; i<3; i++) {
			leftButtonParameters.add(drawForces[i].parameters);
			rightButtonParameters.add(drawForces[i+3].parameters);
			middleButtonParameters.add(drawForces[i+6].parameters);
			singleTouchParameters.add( drawForces[ i + 9 ].parameters );
		}
	}

	void ftDrawInputForces::update(float _deltaTime) {
		deltaTime = _deltaTime;

		for (int i=0; i<numDrawForces; i++) {
			drawForces[i].update();
		}
	}

	void ftDrawInputForces::invertForce(int _index) {
		ofVec4f force = drawForces[_index].getForce();
		force.x = 1.0 - force.x;
		force.y = 1.0 - force.y;
		force.z = 1.0 - force.z;

		drawForces[_index].setForce(force);
	}

	//--------------------------------------------------------------
	bool ftDrawInputForces::didChange(int _index) {
		if (_index < 0 || _index >= numDrawForces) {
			ofLogWarning("ftDrawInputForces::getDrawForceType: index out of range");
			return false;
		}
		else
			return drawForces[_index].didChange();
	}

	//--------------------------------------------------------------
	ftDrawForceType ftDrawInputForces::getType(int _index) {
		if (_index < 0 || _index >= numDrawForces) {
			ofLogWarning("ftDrawInputForces::getDrawForceType: index out of range");
			return FT_NONE;
		}
		else
			return drawForces[_index].getType();
	}

	//--------------------------------------------------------------
	ofTexture& ftDrawInputForces::getTextureReference(int _index) {
		if (_index < 0 || _index >= numDrawForces) {
			ofLogError("ftDrawInputForces::getTexture: index out of range");
		}
		else
			return drawForces[_index].getTexture();

	}

	//--------------------------------------------------------------
	float ftDrawInputForces::getStrength(int _index) {
		if (_index < 0 || _index >= numDrawForces) {
			ofLogWarning("ftDrawInputForces::getStrength: index out of range");
			return 0;
		}
		else {
			if (drawForces[_index].getIsTemporary()) {
				return drawForces[_index].getStrength();
			}
			else {
				return drawForces[_index].getStrength() * deltaTime;;
			}
		}
	}

	//--------------------------------------------------------------
	void ftDrawInputForces::mouseDragged( ofMouseEventArgs& mouse ) {
		ofVec2f normalizedMouse;

		normalizedMouse.set(mouse.x / (float)ofGetWindowWidth(), mouse.y / (float)ofGetWindowHeight());

		ofVec2f velocity = normalizedMouse - lastNormalizedMouse;
		//velocity.normalize();

		if (mouse.button == 0) {

			for (int i=0; i<3; i++) {
				if (drawForces[i].getType() == FT_VELOCITY)
					drawForces[i].setForce(velocity);
				drawForces[i].applyForce(normalizedMouse);
			}
		}
		else if(mouse.button == 2)
		{

			for (int i=3; i<6; i++) {
				if (drawForces[i].getType() == FT_VELOCITY)
					drawForces[i].setForce(velocity);
				drawForces[i].applyForce(normalizedMouse);
			}
		}
		else if (mouse.button == 1)
		{
			for (int i = 6; i<9; i++) {
				if (drawForces[i].getType() == FT_VELOCITY)
					drawForces[i].setForce(velocity);
				drawForces[i].applyForce(normalizedMouse);
			}
		}
		lastNormalizedMouse.set(normalizedMouse);

	}

	//---------------------------------------------------------------------------------------------
	void ftDrawInputForces::mouseMoved( ofMouseEventArgs& mouse ){
		ofVec2f normalizedMouse;

		normalizedMouse.set ( mouse.x / (float)ofGetWindowWidth()
							, mouse.y / (float)ofGetWindowHeight()
							);

		lastNormalizedMouse.set(normalizedMouse);
	}

	//---------------------------------------------------------------------------------------------
	void ftDrawInputForces::touchDown( ofTouchEventArgs& touch)
	{
		ofVec2f normalizedTouch;
		normalizedTouch.set  ( touch.x / (float)ofGetWindowWidth()
							 , touch.y / (float)ofGetWindowHeight()
							);
		lastNormalizedTouch.set( normalizedTouch );
	}

	//---------------------------------------------------------------------------------------------
	void ftDrawInputForces::touchMoved( ofTouchEventArgs& touch)
	{
		ofVec2f normalizedTouch;
		normalizedTouch.set( touch.x / (float)ofGetWindowWidth()
							 , touch.y / (float)ofGetWindowHeight()
		);

		ofVec2f normalizedTouchSpeed;
		normalizedTouchSpeed.set( touch.xspeed / (float)ofGetWindowWidth()
							 , touch.yspeed / (float)ofGetWindowHeight()
		);

		ofVec2f normalizedTouchAccel;
		normalizedTouchAccel.set( touch.xaccel / (float)ofGetWindowWidth()
							 , touch.yaccel / (float)ofGetWindowHeight()
		);

		ofVec2f velocity = normalizedTouch - lastNormalizedTouch;
		//ofVec2f velocity = normalizedTouchSpeed;
		ofVec2f acceleration = normalizedTouchAccel;

		for( int i = 0; i<3; i++ )
		{
			if( drawForces[ i ].getType() == FT_VELOCITY )
				drawForces[ i ].setForce( velocity );
			drawForces[ i ].applyForce( normalizedTouch );
		}

		lastNormalizedTouch.set( normalizedTouch );
	}

}<|endoftext|>


<commit_before>/**************************************************************************

 The MIT License (MIT)

 Copyright (c) 2015 Dmitry Sovetov

 https://github.com/dmsovetov

 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 "Entity.h"

DC_BEGIN_DREEMCHEST

namespace Ecs {

// ** Entity::Entity
Entity::Entity( void ) : m_flags( 0 )
{

}

// ** Entity::setEcs
void Entity::setEcs( EcsWPtr value )
{
	m_ecs = value;
}

// ** Entity::ecs
EcsWPtr Entity::ecs( void ) const
{
	return m_ecs;
}

// ** Entity::setId
void Entity::setId( const EntityId& value )
{
	m_id = value;
}

// ** Entity::id
const EntityId& Entity::id( void ) const
{
	return m_id;
}

// ** Entity::clear
void Entity::clear( void )
{
    m_components.clear();
}

// ** Entity::isSerializable
bool Entity::isSerializable( void ) const
{
    return m_flags.is( Serializable );
}

// ** Entity::setSerializable
void Entity::setSerializable( bool value )
{
    m_flags.set( Serializable, value );
}

// ** Entity::mask
const Bitset& Entity::mask( void ) const
{
	return m_mask;
}

// ** Entity::components
const Entity::Components& Entity::components( void ) const
{
	return m_components;
}

// ** Entity::components
Entity::Components& Entity::components( void )
{
	return m_components;
}

// ** Entity::queueRemoval
void Entity::queueRemoval( void )
{
	m_ecs->removeEntity( m_id );
}

// ** Entity::markAsRemoved
void Entity::markAsRemoved( void )
{
	m_flags.on( Removed );
}

// ** Entity::flags
u8 Entity::flags( void ) const
{
	return m_flags;
}

// ** Entity::setFlags
void Entity::setFlags( u8 value )
{
	m_flags = value;
}

// ** Entity::updateComponentBit
void Entity::updateComponentBit( u32 bit, bool value )
{
	if( value ) {
		m_mask.set( bit );
	} else {
		m_mask.clear( bit );
	}

	if( m_ecs.valid() ) {
		m_ecs->notifyEntityChanged( m_id );
	}
}

// ** Entity::detachById
void Entity::detachById( TypeIdx id )
{
	DC_BREAK_IF( m_flags.is( Removed ) );

	Components::iterator i = m_components.find( id );
	DC_BREAK_IF( i == m_components.end() );
	updateComponentBit( i->second->typeIndex(), false );
    i->second->setParentEntity( NULL );
	m_components.erase( i );
}

#if DC_ECS_ENTITY_CLONING

// ** Entity::deepCopy
EntityPtr Entity::deepCopy( const EntityId& id ) const
{
    // Create entity instance
    Ecs*      ecs    = const_cast<Ecs*>( m_ecs.get() );
    EntityPtr entity = id.isNull() ? ecs->createEntity() : ecs->createEntity( id );

    // Now clone components
    for( Components::const_iterator i = m_components.begin(), end = m_components.end(); i != end; ++i ) {
        entity->attachComponent( i->second->deepCopy().get() );
    }

    return entity;
}

#endif  /*  DC_ECS_ENTITY_CLONING   */

#ifndef DC_ECS_NO_SERIALIZATION

// ** Entity::read
void Entity::read( const Io::Storage* storage )
{
	Io::KeyValue ar;
    ar.read( storage );

    SerializationContext ctx( ecs() );
    deserialize( ctx, ar );
}

// ** Entity::write
void Entity::write( Io::Storage* storage ) const
{
    SerializationContext ctx( ecs() );
    Io::KeyValue ar;

    serialize( ctx, ar );
	ar.write( storage );
}

// ** Entity::serialize
void Entity::serialize( SerializationContext& ctx, Io::KeyValue& ar ) const
{
	ar = Io::KeyValue::object();

	ar["Type"]  = typeName();
	ar["_id"]   = id()/*.toString()*/;
    ar["flags"] = static_cast<u8>( m_flags );

	const Components& items = components();

	for( Components::const_iterator i = items.begin(), end = items.end(); i != end; ++i ) {
		CString      key = i->second->typeName();
		Io::KeyValue component;

        i->second->serialize( ctx, component );

		if( component.isNull() ) {
			continue;
		}

		ar[key] = component;
	}
}

// ** Entity::deserialize
void Entity::deserialize( SerializationContext& ctx, const Io::KeyValue& ar )
{
	DC_BREAK_IF( ar.get( "Type", "" ).asString() != typeName() );

	Components& items = components();

    // Set flags
    m_flags = ar["flags"].asUByte();

	// Load all attached components
	for( Components::iterator i = items.begin(), end = items.end(); i != end; ++i ) {
		CString key = i->second->typeName();
        const Io::KeyValue& kv = ar.get( key );

        if( kv.isNull() ) {
            log::verbose( "Entity::deserialize : no data for component '%s'\n", key );
            continue;
        }

        i->second->deserialize( ctx, kv );
	}

	// Create components from key-value archive
	const Io::KeyValue::Properties& kv = ar.properties();

	for( Io::KeyValue::Properties::const_iterator i = kv.begin(); i != kv.end(); ++i ) {
		if( i->first == "Type" || i->first == "_id" || i->first == "flags" ) {
			continue;
		}

		bool hasComponent = false;

		for( Components::iterator j = items.begin(); j != items.end(); ++j ) {
			if( j->second->typeName() == i->first ) {
				hasComponent = true;
				break;
			}
		}

		if( hasComponent ) {
			continue;
		}

		if( i->second.isNull() ) {
			continue;
		}

		ComponentPtr component = ctx.createComponent( i->first );
        component->deserialize( ctx, i->second );
		attachComponent( component.get() );
	}
}

#endif  /*  !DC_ECS_NO_SERIALIZATION    */

} // namespace Ecs

DC_END_DREEMCHEST<commit_msg>Removed: deprecated debug break macro<commit_after>/**************************************************************************

 The MIT License (MIT)

 Copyright (c) 2015 Dmitry Sovetov

 https://github.com/dmsovetov

 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 "Entity.h"

DC_BEGIN_DREEMCHEST

namespace Ecs {

// ** Entity::Entity
Entity::Entity( void ) : m_flags( 0 )
{

}

// ** Entity::setEcs
void Entity::setEcs( EcsWPtr value )
{
	m_ecs = value;
}

// ** Entity::ecs
EcsWPtr Entity::ecs( void ) const
{
	return m_ecs;
}

// ** Entity::setId
void Entity::setId( const EntityId& value )
{
	m_id = value;
}

// ** Entity::id
const EntityId& Entity::id( void ) const
{
	return m_id;
}

// ** Entity::clear
void Entity::clear( void )
{
    m_components.clear();
}

// ** Entity::isSerializable
bool Entity::isSerializable( void ) const
{
    return m_flags.is( Serializable );
}

// ** Entity::setSerializable
void Entity::setSerializable( bool value )
{
    m_flags.set( Serializable, value );
}

// ** Entity::mask
const Bitset& Entity::mask( void ) const
{
	return m_mask;
}

// ** Entity::components
const Entity::Components& Entity::components( void ) const
{
	return m_components;
}

// ** Entity::components
Entity::Components& Entity::components( void )
{
	return m_components;
}

// ** Entity::queueRemoval
void Entity::queueRemoval( void )
{
	m_ecs->removeEntity( m_id );
}

// ** Entity::markAsRemoved
void Entity::markAsRemoved( void )
{
	m_flags.on( Removed );
}

// ** Entity::flags
u8 Entity::flags( void ) const
{
	return m_flags;
}

// ** Entity::setFlags
void Entity::setFlags( u8 value )
{
	m_flags = value;
}

// ** Entity::updateComponentBit
void Entity::updateComponentBit( u32 bit, bool value )
{
	if( value ) {
		m_mask.set( bit );
	} else {
		m_mask.clear( bit );
	}

	if( m_ecs.valid() ) {
		m_ecs->notifyEntityChanged( m_id );
	}
}

// ** Entity::detachById
void Entity::detachById( TypeIdx id )
{
	DC_BREAK_IF( m_flags.is( Removed ) );

	Components::iterator i = m_components.find( id );
	DC_BREAK_IF( i == m_components.end() );
	updateComponentBit( i->second->typeIndex(), false );
    i->second->setParentEntity( NULL );
	m_components.erase( i );
}

#if DC_ECS_ENTITY_CLONING

// ** Entity::deepCopy
EntityPtr Entity::deepCopy( const EntityId& id ) const
{
    // Create entity instance
    Ecs*      ecs    = const_cast<Ecs*>( m_ecs.get() );
    EntityPtr entity = id.isNull() ? ecs->createEntity() : ecs->createEntity( id );

    // Now clone components
    for( Components::const_iterator i = m_components.begin(), end = m_components.end(); i != end; ++i ) {
        entity->attachComponent( i->second->deepCopy().get() );
    }

    return entity;
}

#endif  /*  DC_ECS_ENTITY_CLONING   */

#ifndef DC_ECS_NO_SERIALIZATION

// ** Entity::read
void Entity::read( const Io::Storage* storage )
{
	Io::KeyValue ar;
    ar.read( storage );

    SerializationContext ctx( ecs() );
    deserialize( ctx, ar );
}

// ** Entity::write
void Entity::write( Io::Storage* storage ) const
{
    SerializationContext ctx( ecs() );
    Io::KeyValue ar;

    serialize( ctx, ar );
	ar.write( storage );
}

// ** Entity::serialize
void Entity::serialize( SerializationContext& ctx, Io::KeyValue& ar ) const
{
	ar = Io::KeyValue::object();

	ar["Type"]  = typeName();
	ar["_id"]   = id()/*.toString()*/;
    ar["flags"] = static_cast<u8>( m_flags );

	const Components& items = components();

	for( Components::const_iterator i = items.begin(), end = items.end(); i != end; ++i ) {
		CString      key = i->second->typeName();
		Io::KeyValue component;

        i->second->serialize( ctx, component );

		if( component.isNull() ) {
			continue;
		}

		ar[key] = component;
	}
}

// ** Entity::deserialize
void Entity::deserialize( SerializationContext& ctx, const Io::KeyValue& ar )
{
//	DC_BREAK_IF( ar.get( "Type", "" ).asString() != typeName() );

	Components& items = components();

    // Set flags
    m_flags = ar["flags"].asUByte();

	// Load all attached components
	for( Components::iterator i = items.begin(), end = items.end(); i != end; ++i ) {
		CString key = i->second->typeName();
        const Io::KeyValue& kv = ar.get( key );

        if( kv.isNull() ) {
            log::verbose( "Entity::deserialize : no data for component '%s'\n", key );
            continue;
        }

        i->second->deserialize( ctx, kv );
	}

	// Create components from key-value archive
	const Io::KeyValue::Properties& kv = ar.properties();

	for( Io::KeyValue::Properties::const_iterator i = kv.begin(); i != kv.end(); ++i ) {
		if( i->first == "Type" || i->first == "_id" || i->first == "flags" ) {
			continue;
		}

		bool hasComponent = false;

		for( Components::iterator j = items.begin(); j != items.end(); ++j ) {
			if( j->second->typeName() == i->first ) {
				hasComponent = true;
				break;
			}
		}

		if( hasComponent ) {
			continue;
		}

		if( i->second.isNull() ) {
			continue;
		}

		ComponentPtr component = ctx.createComponent( i->first );
        component->deserialize( ctx, i->second );
		attachComponent( component.get() );
	}
}

#endif  /*  !DC_ECS_NO_SERIALIZATION    */

} // namespace Ecs

DC_END_DREEMCHEST<|endoftext|>


<commit_before>#include "movepicker.h"
#include "eval.h"
#include "defs.h"

// Indexed by [victimValue][attackerValue]
int MovePicker::_mvvLvaTable[5][6];

void MovePicker::init() {
  int currScore = 0;
  PieceType victimsLoToHi[] = {PAWN, KNIGHT, BISHOP, ROOK, QUEEN};
  PieceType attackersHiToLo[] = {KING, QUEEN, ROOK, BISHOP, KNIGHT, PAWN};

  // Iterate over victims (low to high)
  for (auto victim : victimsLoToHi) {
    // Iterate over attackers (high to low)
    for (auto attacker : attackersHiToLo) {
      _mvvLvaTable[victim][attacker] = currScore;
      currScore ++;
    }
  }
}

MovePicker::MovePicker(const OrderingInfo* orderingInfo, const Board* board, MoveList* moveList) {
  _orderingInfo = orderingInfo;
  _moves = moveList;
  _board = board;
  _currHead = 0;
  _scoreMoves();
}

void MovePicker::_scoreMoves() {
  const TranspTableEntry* ttEntry = _orderingInfo->getTt()->getEntry(_board->getZKey());
  Move pvMove;
  if (ttEntry) {
    pvMove = ttEntry->getBestMove();
  }

  for (auto &move : *_moves) {
    Board tempBoard = *_board;
    tempBoard.doMove(move);

    if (move == pvMove) {
      move.setValue(INF);
    } else if (move.getFlags() & Move::CAPTURE) {
      move.setValue(CAPTURE_BONUS + _mvvLvaTable[move.getCapturedPieceType()][move.getPieceType()]);
    } else if (move.getFlags() & Move::PROMOTION) {
      move.setValue(PROMOTION_BONUS + Eval::getMaterialValue(move.getPromotionPieceType()));
    } else if (move == _orderingInfo->getKiller1(_orderingInfo->getPly())) {
      move.setValue(KILLER1_BONUS);
    } else if (move == _orderingInfo->getKiller2(_orderingInfo->getPly())) {
      move.setValue(KILLER2_BONUS);
    } else { // Quiet
      move.setValue(QUIET_BONUS + _orderingInfo->getHistory(_board->getActivePlayer(), move.getFrom(), move.getTo()));
    }
  }
}

bool MovePicker::hasNext() const {
  return _currHead < _moves->size();
}

Move MovePicker::getNext() {
  size_t bestIndex;
  int bestScore = -INF;

  for (size_t i=_currHead;i<_moves->size();i++) {
    if (_moves->at(i).getValue() > bestScore) {
      bestScore = _moves->at(i).getValue();
      bestIndex = i;
    }
  }

  std::swap(_moves->at(_currHead), _moves->at(bestIndex));
  _currHead ++;
  return _moves->at(_currHead-1);
}<commit_msg>Inline ++ operators in movepicker.cc<commit_after>#include "movepicker.h"
#include "eval.h"
#include "defs.h"

// Indexed by [victimValue][attackerValue]
int MovePicker::_mvvLvaTable[5][6];

void MovePicker::init() {
  int currScore = 0;
  PieceType victimsLoToHi[] = {PAWN, KNIGHT, BISHOP, ROOK, QUEEN};
  PieceType attackersHiToLo[] = {KING, QUEEN, ROOK, BISHOP, KNIGHT, PAWN};

  // Iterate over victims (low to high)
  for (auto victim : victimsLoToHi) {
    // Iterate over attackers (high to low)
    for (auto attacker : attackersHiToLo) {
      _mvvLvaTable[victim][attacker] = currScore++;
    }
  }
}

MovePicker::MovePicker(const OrderingInfo* orderingInfo, const Board* board, MoveList* moveList) {
  _orderingInfo = orderingInfo;
  _moves = moveList;
  _board = board;
  _currHead = 0;
  _scoreMoves();
}

void MovePicker::_scoreMoves() {
  const TranspTableEntry* ttEntry = _orderingInfo->getTt()->getEntry(_board->getZKey());
  Move pvMove;
  if (ttEntry) {
    pvMove = ttEntry->getBestMove();
  }

  for (auto &move : *_moves) {
    Board tempBoard = *_board;
    tempBoard.doMove(move);

    if (move == pvMove) {
      move.setValue(INF);
    } else if (move.getFlags() & Move::CAPTURE) {
      move.setValue(CAPTURE_BONUS + _mvvLvaTable[move.getCapturedPieceType()][move.getPieceType()]);
    } else if (move.getFlags() & Move::PROMOTION) {
      move.setValue(PROMOTION_BONUS + Eval::getMaterialValue(move.getPromotionPieceType()));
    } else if (move == _orderingInfo->getKiller1(_orderingInfo->getPly())) {
      move.setValue(KILLER1_BONUS);
    } else if (move == _orderingInfo->getKiller2(_orderingInfo->getPly())) {
      move.setValue(KILLER2_BONUS);
    } else { // Quiet
      move.setValue(QUIET_BONUS + _orderingInfo->getHistory(_board->getActivePlayer(), move.getFrom(), move.getTo()));
    }
  }
}

bool MovePicker::hasNext() const {
  return _currHead < _moves->size();
}

Move MovePicker::getNext() {
  size_t bestIndex;
  int bestScore = -INF;

  for (size_t i=_currHead;i<_moves->size();i++) {
    if (_moves->at(i).getValue() > bestScore) {
      bestScore = _moves->at(i).getValue();
      bestIndex = i;
    }
  }

  std::swap(_moves->at(_currHead), _moves->at(bestIndex));
  return _moves->at(_currHead++);
}<|endoftext|>


<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2013-2016.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://www.opensource.org/licenses/MIT)
//=======================================================================

#include <cstdio>
#include <cstring>

#include <list.hpp>
#include <algorithms.hpp>

#include "test.hpp"

namespace {

void test_base(){
    std::list<int> a{1, 0, 0, 2, 3, 4};

    check(a.size() == 6, "Invalid list:size");
    check(a.front()== 1, "Invalid list:[]");
    check(a.back() == 4, "Invalid list:[]");

    check(*a.begin() == 1);
}

template<typename Iterator>
Iterator advance(Iterator it, size_t n){
    for(size_t i = 0; i < n; ++i){
        ++it;
    }

    return it;
}

void test_erase(){
    std::list<int> a{1, 0, 0, 2, 3, 4};

    a.erase(advance(a.begin(), 2));

    check(a.size() == 5, "Invalid list:size");
    check(a.front() == 1, "Invalid list:front()");
    check(a.back() == 4, "Invalid list:back()");

    check(*a.begin() == 1, "erase: Invalid element 0");
    check(*advance(a.begin(),1) == 0, "erase: Invalid element 1");
    check(*advance(a.begin(),2) == 2, "erase: Invalid element 2");
    check(*advance(a.begin(),3) == 3, "erase: Invalid element 3");
    check(*advance(a.begin(),4) == 4, "erase: Invalid element 4");

    a.erase(a.begin());

    check(a.size() == 4, "erase: Invalid list:size");
    check(a.front() == 0, "erase: Invalid list:front()");
    check(a.back() == 4, "erase: Invalid list:back()");

    check(*a.begin() == 0, "erase: Invalid element 0 ");
    check(*advance(a.begin(),1) == 2, "erase: Invalid element 1");
    check(*advance(a.begin(),2) == 3, "erase: Invalid element 2");
    check(*advance(a.begin(),3) == 4, "erase: Invalid element 3");
}

void test_erase_range(){
    std::list<int> a{1, 0, 0, 2, 3, 4};

    a.erase(advance(a.begin(), 1), advance(a.begin(), 4));

    check(a.size() == 3, "erase_range: Invalid list:size");
    check(a.front() == 1, "erase_range: Invalid list:[]");
    check(a.back() == 4, "erase_range: Invalid list:[]");

    check(*a.begin() == 1);
}

void test_erase_remove(){
    std::list<int> a{1, 0, 0, 2, 3, 4};

    a.erase(std::remove(a.begin(), a.end(), 0), a.end());

    check(a.size() == 4, "erase_remove: Invalid list:size");
    check(a.front() == 1, "erase_remove: Invalid list:front()");
    check(a.back() == 4, "erase_remove: Invalid list:back()");

    check(*a.begin() == 1, "erase_remove: Invalid begin()");
}

void test_erase_remove_if(){
    std::list<int> a{1, 0, 0, 2, 3, 4};

    a.erase(std::remove_if(a.begin(), a.end(), [](int value){
        return value == 1 || value == 3;
    }), a.end());

    check(a.size() == 4, "erase_remove_if: Invalid list:size");
    check(a.front() == 0, "erase_remove_if: Invalid list:front()");
    check(a.back() == 4, "erase_remove_if: Invalid list:back()");

    check(*a.begin() == 0);
}

void test_push_front(){
    std::list<int> a{1, 0, 0, 2, 3, 4};

    a.push_front(99);

    check(a.size() == 7, "Invalid list:size");
    check(a.front() == 99, "Invalid list:[]");
    check(a.back() == 4, "Invalid list:[]");

    check(*a.begin() == 99);
}

void test_iterator(){
    std::list<int> a{1, 0, 0, 2, 3, 4};

    auto it = a.begin();
    auto end = a.end();

    check(it != end, "Invalid iterator");
    check(*it == 1, "Invalid iterator");

    ++it;
    check(it != end, "Invalid iterator");
    check(*it == 0, "Invalid iterator");

    ++it;
    check(it != end, "Invalid iterator");
    check(*it == 0, "Invalid iterator");

    ++it;
    check(it != end, "Invalid iterator");
    check(*it == 2, "Invalid iterator");

    ++it;
    check(it != end, "Invalid iterator");
    check(*it == 3, "Invalid iterator");

    ++it;
    check(it != end, "Invalid iterator");
    check(*it == 4, "Invalid iterator");

    ++it;
    check(it == end, "Invalid iterator");
}

void test_reverse_iterator(){
    std::list<int> a{1, 0, 0, 2, 3, 4};

    auto it = a.rbegin();
    auto end = a.rend();

    check(it != end, "Invalid reverse iterator");
    check(*it == 4, "Invalid reverse iterator");

    ++it;
    check(it != end, "Invalid reverse iterator");
    check(*it == 3, "Invalid reverse iterator");

    ++it;
    check(it != end, "Invalid reverse iterator");
    check(*it == 2, "Invalid reverse iterator");

    ++it;
    check(it != end, "Invalid reverse iterator");
    check(*it == 0, "Invalid reverse iterator");

    ++it;
    check(it != end, "Invalid reverse iterator");
    check(*it == 0, "Invalid reverse iterator");

    ++it;
    check(it != end, "Invalid reverse iterator");
    check(*it == 1, "Invalid reverse iterator");

    ++it;
    check(it == end, "Invalid reverse iterator");
}

} //end of anonymous namespace

void list_tests(){
    test_base();
    test_erase();
    test_erase_range();
    test_erase_remove();
    test_erase_remove_if();
    test_push_front();
    test_iterator();
    test_reverse_iterator();
}
<commit_msg>More tests for std::list<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2013-2016.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://www.opensource.org/licenses/MIT)
//=======================================================================

#include <cstdio>
#include <cstring>

#include <list.hpp>
#include <algorithms.hpp>

#include "test.hpp"

namespace {

void test_base(){
    std::list<int> a{1, 0, 0, 2, 3, 4};

    check(a.size() == 6, "Invalid list:size");
    check(a.front()== 1, "Invalid list:[]");
    check(a.back() == 4, "Invalid list:[]");

    check(*a.begin() == 1);
}

template<typename Iterator>
Iterator advance(Iterator it, size_t n){
    for(size_t i = 0; i < n; ++i){
        ++it;
    }

    return it;
}

void test_erase(){
    std::list<int> a{1, 0, 0, 2, 3, 4};

    a.erase(advance(a.begin(), 2));

    check(a.size() == 5, "Invalid list:size");
    check(a.front() == 1, "Invalid list:front()");
    check(a.back() == 4, "Invalid list:back()");

    check(*a.begin() == 1, "erase: Invalid element 0");
    check(*advance(a.begin(),1) == 0, "erase: Invalid element 1");
    check(*advance(a.begin(),2) == 2, "erase: Invalid element 2");
    check(*advance(a.begin(),3) == 3, "erase: Invalid element 3");
    check(*advance(a.begin(),4) == 4, "erase: Invalid element 4");

    a.erase(a.begin());

    check(a.size() == 4, "erase: Invalid list:size");
    check(a.front() == 0, "erase: Invalid list:front()");
    check(a.back() == 4, "erase: Invalid list:back()");

    check(*a.begin() == 0, "erase: Invalid element 0 ");
    check(*advance(a.begin(),1) == 2, "erase: Invalid element 1");
    check(*advance(a.begin(),2) == 3, "erase: Invalid element 2");
    check(*advance(a.begin(),3) == 4, "erase: Invalid element 3");
}

void test_erase_range(){
    std::list<int> a{1, 0, 0, 2, 3, 4};

    a.erase(advance(a.begin(), 1), advance(a.begin(), 4));

    check(a.size() == 3, "erase_range: Invalid list:size");
    check(a.front() == 1, "erase_range: Invalid list:[]");
    check(a.back() == 4, "erase_range: Invalid list:[]");

    check(*a.begin() == 1);
}

void test_erase_remove(){
    std::list<int> a{1, 0, 0, 2, 3, 4};

    a.erase(std::remove(a.begin(), a.end(), 0), a.end());

    check(a.size() == 4, "erase_remove: Invalid list:size");
    check(a.front() == 1, "erase_remove: Invalid list:front()");
    check(a.back() == 4, "erase_remove: Invalid list:back()");

    check(*a.begin() == 1, "erase_remove: Invalid begin()");
}

void test_erase_remove_if(){
    std::list<int> a{1, 0, 0, 2, 3, 4};

    a.erase(std::remove_if(a.begin(), a.end(), [](int value){
        return value == 1 || value == 3;
    }), a.end());

    check(a.size() == 4, "erase_remove_if: Invalid list:size");
    check(a.front() == 0, "erase_remove_if: Invalid list:front()");
    check(a.back() == 4, "erase_remove_if: Invalid list:back()");

    check(*a.begin() == 0);
}

void test_push_front(){
    std::list<int> a{1, 0, 0, 2, 3, 4};

    a.push_front(99);

    check(a.size() == 7, "Invalid list:size");
    check(a.front() == 99, "Invalid list:[]");
    check(a.back() == 4, "Invalid list:[]");

    check(*a.begin() == 99);
}

void test_push_back(){
    std::list<int> a{1, 0, 0, 2, 3, 4};

    a.push_back(99);

    check(a.size() == 7, "Invalid list:size");
    check(a.front() == 1, "Invalid list:[]");
    check(a.back() == 99, "Invalid list:[]");

    check(*a.begin() == 1);
}

void test_iterator(){
    std::list<int> a{1, 0, 0, 2, 3, 4};

    auto it = a.begin();
    auto end = a.end();

    check(it != end, "Invalid iterator");
    check(*it == 1, "Invalid iterator");

    ++it;
    check(it != end, "Invalid iterator");
    check(*it == 0, "Invalid iterator");

    ++it;
    check(it != end, "Invalid iterator");
    check(*it == 0, "Invalid iterator");

    ++it;
    check(it != end, "Invalid iterator");
    check(*it == 2, "Invalid iterator");

    ++it;
    check(it != end, "Invalid iterator");
    check(*it == 3, "Invalid iterator");

    ++it;
    check(it != end, "Invalid iterator");
    check(*it == 4, "Invalid iterator");

    ++it;
    check(it == end, "Invalid iterator");
}

void test_reverse_iterator(){
    std::list<int> a{1, 0, 0, 2, 3, 4};

    auto it = a.rbegin();
    auto end = a.rend();

    check(it != end, "Invalid reverse iterator");
    check(*it == 4, "Invalid reverse iterator");

    ++it;
    check(it != end, "Invalid reverse iterator");
    check(*it == 3, "Invalid reverse iterator");

    ++it;
    check(it != end, "Invalid reverse iterator");
    check(*it == 2, "Invalid reverse iterator");

    ++it;
    check(it != end, "Invalid reverse iterator");
    check(*it == 0, "Invalid reverse iterator");

    ++it;
    check(it != end, "Invalid reverse iterator");
    check(*it == 0, "Invalid reverse iterator");

    ++it;
    check(it != end, "Invalid reverse iterator");
    check(*it == 1, "Invalid reverse iterator");

    ++it;
    check(it == end, "Invalid reverse iterator");
}

void test_lots() {
    std::list<size_t> vec;

    for(size_t i = 0; i < 1000; ++i){
        vec.push_back(i);
    }

    for(size_t i = 10000; i < 11000; ++i){
        vec.push_front(i);
    }

    auto it = vec.begin();
    for(size_t i = 0; i < 1000; ++i){
        check_equals(*it, 10999 - i, "test_lots: invalid iterator");
        ++it;
    }

    for(size_t i = 1000; i < 2000; ++i){
        check_equals(*it, i - 1000, "test_lots: invalid iterator");
        ++it;
    }

    check_equals(vec.size(), 2000, "test_lots: invalid size()");
    check_equals(vec.front(), 10999, "test_lots: invalid front()");
    check_equals(vec.back(), 999, "test_lots: invalid back()");

    for(size_t i = 0; i < 1000; ++i){
        vec.pop_back();
    }

    check_equals(vec.size(), 1000, "test_lots: invalid size()");
    check_equals(vec.front(), 10999, "test_lots: invalid front()");
    check_equals(vec.back(), 10000, "test_lots: invalid back()");

    for(size_t i = 0; i < 500; ++i){
        vec.pop_front();
    }

    check_equals(vec.size(), 500, "test_lots: invalid size()");
    check_equals(vec.front(), 10499, "test_lots: invalid front()");
    check_equals(vec.back(), 10000, "test_lots: invalid back()");
}

} //end of anonymous namespace

void list_tests(){
    test_base();
    test_erase();
    test_erase_range();
    test_erase_remove();
    test_erase_remove_if();
    test_push_front();
    test_push_back();
    test_iterator();
    test_reverse_iterator();
    test_lots();
}
<|endoftext|>


<commit_before>#include "./label_collision_force.h"
#include <vector>
#include <QDebug>
#include "../math/aabb2d.h"
#include "./label_state.h"

namespace Forces
{
LabelCollisionForce::LabelCollisionForce() : Force("Label Collision", 1.0f)
{
}

Eigen::Vector2f LabelCollisionForce::calculate(LabelState &label,
                                               std::vector<LabelState> &labels)
{
  Eigen::Vector2f result(0, 0);

  for (auto &otherLabel : labels)
  {
    if (otherLabel.id == label.id)
      continue;

    Math::Aabb2d aabb(label.labelPosition2D, 0.5f * label.size);
    Math::Aabb2d otherAabb(otherLabel.labelPosition2D, 0.5f * otherLabel.size);

    if (aabb.testAabb(otherAabb))
    {
      qWarning() << "Collision between:" << label.text.c_str() << "and"
                 << otherLabel.text.c_str();
      Eigen::Vector2f diff = label.labelPosition2D - otherLabel.labelPosition2D;
      result += diff.normalized();
    }
  }

  return result;
}
}  // namespace Forces
<commit_msg>Fix linting error.<commit_after>#include "./label_collision_force.h"
#include <QDebug>
#include <vector>
#include "../math/aabb2d.h"
#include "./label_state.h"

namespace Forces
{
LabelCollisionForce::LabelCollisionForce() : Force("Label Collision", 1.0f)
{
}

Eigen::Vector2f LabelCollisionForce::calculate(LabelState &label,
                                               std::vector<LabelState> &labels)
{
  Eigen::Vector2f result(0, 0);

  for (auto &otherLabel : labels)
  {
    if (otherLabel.id == label.id)
      continue;

    Math::Aabb2d aabb(label.labelPosition2D, 0.5f * label.size);
    Math::Aabb2d otherAabb(otherLabel.labelPosition2D, 0.5f * otherLabel.size);

    if (aabb.testAabb(otherAabb))
    {
      qWarning() << "Collision between:" << label.text.c_str() << "and"
                 << otherLabel.text.c_str();
      Eigen::Vector2f diff = label.labelPosition2D - otherLabel.labelPosition2D;
      result += diff.normalized();
    }
  }

  return result;
}
}  // namespace Forces
<|endoftext|>