<commit_before>#ifndef PYTHONIC_NUMPY_CONCATENATE_HPP
#define PYTHONIC_NUMPY_CONCATENATE_HPP

#include "pythonic/utils/proxy.hpp"
#include "pythonic/types/ndarray.hpp"

namespace pythonic {

    namespace numpy {
        template<class T, size_t N, size_t M>
            types::ndarray<T,N> concatenate(types::array<types::ndarray<T,N>, M> const & ai) {
                long n = 0;
                long shape[N];
                shape[0] = 0L;
                for(auto const& a : ai) {
                    shape[0] += a.shape[0];
                    n += a.flat_size();
                }
                std::copy(ai[0].shape.begin() +1 , ai[0].shape.end(), &shape[1]);

                T* buffer = (T*)malloc(sizeof(T) * n);
                T* iter = buffer;
                for(auto const& a : ai) {
                    iter = std::copy(a.fbegin(), a.fend(), iter);
                }

                return types::ndarray<T,N>(buffer, shape);
            }

        template<class T, size_t N, class A>
            void _concatenate_helper(types::array<T, N>& a, A const& t, utils::int_<1>) {
                a[N - 1] = std::get<N-1>(t);
            }
        template<class T, size_t N, class A, size_t M>
            void _concatenate_helper(types::array<T, N>& a, A const& t, utils::int_<M>) {
                a[N - M] = std::get<N-M>(t);
                _concatenate_helper(a, t, utils::int_<M-1>());
            }
        template<class... Types>
            typename assignable<typename __combined<Types...>::type>::type
            concatenate(std::tuple<Types...> const& args) {
                types::array<typename assignable<typename __combined<Types...>::type>::type, sizeof...(Types)> params;
                _concatenate_helper(params, args, utils::int_<sizeof...(Types)>());
                return concatenate(params);
            }
        PROXY(pythonic::numpy, concatenate);

    }

}

#endif

<commit_msg>Improve concatenate implementation<commit_after>#ifndef PYTHONIC_NUMPY_CONCATENATE_HPP
#define PYTHONIC_NUMPY_CONCATENATE_HPP

#include "pythonic/utils/proxy.hpp"
#include "pythonic/types/ndarray.hpp"
#include "pythonic/__builtin__/sum.hpp"

namespace pythonic {

    namespace numpy {
        template<class T, size_t N, size_t M>
            types::ndarray<T,N> concatenate(types::array<types::ndarray<T,N>, M> const & ai) {
                long n = 0;
                long shape[N];
                shape[0] = 0L;
                for(auto const& a : ai) {
                    shape[0] += a.shape[0];
                    n += a.flat_size();
                }
                std::copy(ai[0].shape.begin() +1 , ai[0].shape.end(), &shape[1]);

                T* buffer = (T*)malloc(sizeof(T) * n);
                T* iter = buffer;
                for(auto const& a : ai) {
                    iter = std::copy(a.fbegin(), a.fend(), iter);
                }

                return types::ndarray<T,N>(buffer, shape);
            }

        namespace details {

            template<class ...Types>
                void concatenate(std::tuple<Types...> const& a, typename assignable<typename __combined<Types...>::type>::type::dtype* iter, utils::int_<1>)
                {
                    typename types::numpy_expr_to_ndarray<typename std::tuple_element<sizeof...(Types) - 1, std::tuple<Types...>>::type>::type t = std::get<sizeof...(Types) - 1>(a); // We force evaluation of the ndarray
                    std::copy(t.fbegin(), t.fend(), iter);
                }

            template<size_t M, class ...Types>
                void concatenate(std::tuple<Types...> const& a, typename assignable<typename __combined<Types...>::type>::type::dtype* iter, utils::int_<M>)
                {
                    typename types::numpy_expr_to_ndarray<typename std::tuple_element<sizeof...(Types) - M, std::tuple<Types...>>::type>::type t = std::get<sizeof...(Types) - M>(a); // We force evaluation of the ndarray
                    iter = std::copy(t.fbegin(), t.fend(), iter);
                    concatenate(a, iter, utils::int_<M-1>());
                }

            template<size_t N>
                long first_dim(types::array<long, N> const& fake_shape)
                {
                    // FIXME This is a hack to force list.fake_shape evaluation to types::array
                    return fake_shape[0];
                }

            template<class... Types, int... I>
                size_t concatenate_size(std::tuple<Types...> const& args, utils::seq<I...>)
                {
                    return __builtin__::sum(std::make_tuple(first_dim<std::tuple_element<0, std::tuple<Types...>>::type::value>(std::get<I-1>(args).shape)...));
                }

        }

        template<class... Types>
            typename assignable<typename __combined<Types...>::type>::type
            concatenate(std::tuple<Types...> const& args) {

                using return_type = typename assignable<typename __combined<Types...>::type>::type;
                using T = typename return_type::dtype;

                types::array<long, return_type::value> shape = std::get<0>(args).shape;
                size_t n = shape[0];
                shape[0] = details::concatenate_size(args, typename utils::gens<1+sizeof...(Types)>::type{});
                n = size_t(std::get<0>(args).flat_size() * shape[0] / double(n));

                T* buffer = (T*)malloc(sizeof(T) * n);
                details::concatenate(args, buffer, utils::int_<sizeof...(Types)>());

                return types::ndarray<T,return_type::value>(buffer, shape);
            }

        PROXY(pythonic::numpy, concatenate);

    }

}

#endif
<|endoftext|>


<commit_before>// Copyright (c) 2014 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/browser/ui/views/menu_bar.h"

#if defined(USE_X11)
#include "gtk/gtk.h"
#endif

#include "atom/browser/ui/views/menu_delegate.h"
#include "atom/browser/ui/views/submenu_button.h"
#include "ui/base/models/menu_model.h"
#include "ui/views/background.h"
#include "ui/views/layout/box_layout.h"

#if defined(OS_WIN)
#include "ui/gfx/color_utils.h"
#elif defined(USE_X11)
#include "chrome/browser/ui/libgtkui/skia_utils_gtk.h"
#endif

namespace atom {

namespace {

const char kViewClassName[] = "ElectronMenuBar";

// Default color of the menu bar.
const SkColor kDefaultColor = SkColorSetARGB(255, 233, 233, 233);

#if defined(USE_X11)
void GetMenuBarColor(SkColor* enabled, SkColor* disabled, SkColor* highlight,
                     SkColor* hover, SkColor* background) {
  GtkWidget* menu_bar = gtk_menu_bar_new();

  GtkStyle* style = gtk_rc_get_style(menu_bar);
  *enabled = libgtkui::GdkColorToSkColor(style->fg[GTK_STATE_NORMAL]);
  *disabled = libgtkui::GdkColorToSkColor(style->fg[GTK_STATE_INSENSITIVE]);
  *highlight = libgtkui::GdkColorToSkColor(style->fg[GTK_STATE_SELECTED]);
  *hover = libgtkui::GdkColorToSkColor(style->fg[GTK_STATE_PRELIGHT]);
  *background = libgtkui::GdkColorToSkColor(style->bg[GTK_STATE_NORMAL]);

  gtk_widget_destroy(menu_bar);
}
#endif

}  // namespace

MenuBar::MenuBar(NativeWindow* window)
    : background_color_(kDefaultColor),
      menu_model_(NULL),
      window_(window) {
  UpdateMenuBarColor();
  SetLayoutManager(new views::BoxLayout(views::BoxLayout::kHorizontal));
}

MenuBar::~MenuBar() {
}

void MenuBar::SetMenu(AtomMenuModel* model) {
  menu_model_ = model;
  RemoveAllChildViews(true);

  for (int i = 0; i < model->GetItemCount(); ++i) {
    SubmenuButton* button = new SubmenuButton(model->GetLabelAt(i),
                                              this,
                                              background_color_);
    button->set_tag(i);

#if defined(USE_X11)
    button->SetTextColor(views::Button::STATE_NORMAL, enabled_color_);
    button->SetTextColor(views::Button::STATE_DISABLED, disabled_color_);
    button->SetTextColor(views::Button::STATE_PRESSED, highlight_color_);
    button->SetTextColor(views::Button::STATE_HOVERED, hover_color_);
    button->SetUnderlineColor(enabled_color_);
#elif defined(OS_WIN)
    button->SetUnderlineColor(color_utils::GetSysSkColor(COLOR_GRAYTEXT));
#endif

    AddChildView(button);
  }
}

void MenuBar::SetAcceleratorVisibility(bool visible) {
  for (int i = 0; i < child_count(); ++i)
    static_cast<SubmenuButton*>(child_at(i))->SetAcceleratorVisibility(visible);
}

int MenuBar::GetAcceleratorIndex(base::char16 key) {
  for (int i = 0; i < child_count(); ++i) {
    SubmenuButton* button = static_cast<SubmenuButton*>(child_at(i));
    if (button->accelerator() == key)
      return i;
  }
  return -1;
}

void MenuBar::ActivateAccelerator(base::char16 key) {
  int i = GetAcceleratorIndex(key);
  if (i != -1)
    static_cast<SubmenuButton*>(child_at(i))->Activate(nullptr);
}

int MenuBar::GetItemCount() const {
  return menu_model_->GetItemCount();
}

bool MenuBar::GetMenuButtonFromScreenPoint(const gfx::Point& point,
                                           AtomMenuModel** menu_model,
                                           views::MenuButton** button) {
  gfx::Point location(point);
  views::View::ConvertPointFromScreen(this, &location);

  if (location.x() < 0 || location.x() >= width() || location.y() < 0 ||
      location.y() >= height())
    return false;

  for (int i = 0; i < child_count(); ++i) {
    views::View* view = child_at(i);
    if (view->GetMirroredBounds().Contains(location) &&
        (menu_model_->GetTypeAt(i) == AtomMenuModel::TYPE_SUBMENU)) {
      *menu_model = menu_model_->GetSubmenuModelAt(i);
      *button = static_cast<views::MenuButton*>(view);
      return true;
    }
  }

  return false;
}

const char* MenuBar::GetClassName() const {
  return kViewClassName;
}

void MenuBar::OnMenuButtonClicked(views::MenuButton* source,
                                  const gfx::Point& point,
                                  const ui::Event* event) {
  // Hide the accelerator when a submenu is activated.
  SetAcceleratorVisibility(false);

  if (!menu_model_)
    return;

  if (!window_->IsFocused())
    window_->Focus(true);

  int id = source->tag();
  AtomMenuModel::ItemType type = menu_model_->GetTypeAt(id);
  if (type != AtomMenuModel::TYPE_SUBMENU) {
    menu_model_->ActivatedAt(id, 0);
    return;
  }

  // Deleted in MenuDelegate::OnMenuClosed
  MenuDelegate* menu_delegate = new MenuDelegate(this);
  menu_delegate->RunMenu(menu_model_->GetSubmenuModelAt(id), source);
}

void MenuBar::OnNativeThemeChanged(const ui::NativeTheme* theme) {
  UpdateMenuBarColor();
}

void MenuBar::UpdateMenuBarColor() {
#if defined(OS_WIN)
  background_color_ = color_utils::GetSysSkColor(COLOR_MENUBAR);
#elif defined(USE_X11)
  GetMenuBarColor(&enabled_color_, &disabled_color_, &highlight_color_,
                  &hover_color_, &background_color_);
#endif
  set_background(views::Background::CreateSolidBackground(background_color_));
}

}  // namespace atom
<commit_msg>Clean up views::Background.<commit_after>// Copyright (c) 2014 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/browser/ui/views/menu_bar.h"

#if defined(USE_X11)
#include "gtk/gtk.h"
#endif

#include "atom/browser/ui/views/menu_delegate.h"
#include "atom/browser/ui/views/submenu_button.h"
#include "ui/base/models/menu_model.h"
#include "ui/views/background.h"
#include "ui/views/layout/box_layout.h"

#if defined(OS_WIN)
#include "ui/gfx/color_utils.h"
#elif defined(USE_X11)
#include "chrome/browser/ui/libgtkui/skia_utils_gtk.h"
#endif

namespace atom {

namespace {

const char kViewClassName[] = "ElectronMenuBar";

// Default color of the menu bar.
const SkColor kDefaultColor = SkColorSetARGB(255, 233, 233, 233);

#if defined(USE_X11)
void GetMenuBarColor(SkColor* enabled, SkColor* disabled, SkColor* highlight,
                     SkColor* hover, SkColor* background) {
  GtkWidget* menu_bar = gtk_menu_bar_new();

  GtkStyle* style = gtk_rc_get_style(menu_bar);
  *enabled = libgtkui::GdkColorToSkColor(style->fg[GTK_STATE_NORMAL]);
  *disabled = libgtkui::GdkColorToSkColor(style->fg[GTK_STATE_INSENSITIVE]);
  *highlight = libgtkui::GdkColorToSkColor(style->fg[GTK_STATE_SELECTED]);
  *hover = libgtkui::GdkColorToSkColor(style->fg[GTK_STATE_PRELIGHT]);
  *background = libgtkui::GdkColorToSkColor(style->bg[GTK_STATE_NORMAL]);

  gtk_widget_destroy(menu_bar);
}
#endif

}  // namespace

MenuBar::MenuBar(NativeWindow* window)
    : background_color_(kDefaultColor),
      menu_model_(NULL),
      window_(window) {
  UpdateMenuBarColor();
  SetLayoutManager(new views::BoxLayout(views::BoxLayout::kHorizontal));
}

MenuBar::~MenuBar() {
}

void MenuBar::SetMenu(AtomMenuModel* model) {
  menu_model_ = model;
  RemoveAllChildViews(true);

  for (int i = 0; i < model->GetItemCount(); ++i) {
    SubmenuButton* button = new SubmenuButton(model->GetLabelAt(i),
                                              this,
                                              background_color_);
    button->set_tag(i);

#if defined(USE_X11)
    button->SetTextColor(views::Button::STATE_NORMAL, enabled_color_);
    button->SetTextColor(views::Button::STATE_DISABLED, disabled_color_);
    button->SetTextColor(views::Button::STATE_PRESSED, highlight_color_);
    button->SetTextColor(views::Button::STATE_HOVERED, hover_color_);
    button->SetUnderlineColor(enabled_color_);
#elif defined(OS_WIN)
    button->SetUnderlineColor(color_utils::GetSysSkColor(COLOR_GRAYTEXT));
#endif

    AddChildView(button);
  }
}

void MenuBar::SetAcceleratorVisibility(bool visible) {
  for (int i = 0; i < child_count(); ++i)
    static_cast<SubmenuButton*>(child_at(i))->SetAcceleratorVisibility(visible);
}

int MenuBar::GetAcceleratorIndex(base::char16 key) {
  for (int i = 0; i < child_count(); ++i) {
    SubmenuButton* button = static_cast<SubmenuButton*>(child_at(i));
    if (button->accelerator() == key)
      return i;
  }
  return -1;
}

void MenuBar::ActivateAccelerator(base::char16 key) {
  int i = GetAcceleratorIndex(key);
  if (i != -1)
    static_cast<SubmenuButton*>(child_at(i))->Activate(nullptr);
}

int MenuBar::GetItemCount() const {
  return menu_model_->GetItemCount();
}

bool MenuBar::GetMenuButtonFromScreenPoint(const gfx::Point& point,
                                           AtomMenuModel** menu_model,
                                           views::MenuButton** button) {
  gfx::Point location(point);
  views::View::ConvertPointFromScreen(this, &location);

  if (location.x() < 0 || location.x() >= width() || location.y() < 0 ||
      location.y() >= height())
    return false;

  for (int i = 0; i < child_count(); ++i) {
    views::View* view = child_at(i);
    if (view->GetMirroredBounds().Contains(location) &&
        (menu_model_->GetTypeAt(i) == AtomMenuModel::TYPE_SUBMENU)) {
      *menu_model = menu_model_->GetSubmenuModelAt(i);
      *button = static_cast<views::MenuButton*>(view);
      return true;
    }
  }

  return false;
}

const char* MenuBar::GetClassName() const {
  return kViewClassName;
}

void MenuBar::OnMenuButtonClicked(views::MenuButton* source,
                                  const gfx::Point& point,
                                  const ui::Event* event) {
  // Hide the accelerator when a submenu is activated.
  SetAcceleratorVisibility(false);

  if (!menu_model_)
    return;

  if (!window_->IsFocused())
    window_->Focus(true);

  int id = source->tag();
  AtomMenuModel::ItemType type = menu_model_->GetTypeAt(id);
  if (type != AtomMenuModel::TYPE_SUBMENU) {
    menu_model_->ActivatedAt(id, 0);
    return;
  }

  // Deleted in MenuDelegate::OnMenuClosed
  MenuDelegate* menu_delegate = new MenuDelegate(this);
  menu_delegate->RunMenu(menu_model_->GetSubmenuModelAt(id), source);
}

void MenuBar::OnNativeThemeChanged(const ui::NativeTheme* theme) {
  UpdateMenuBarColor();
}

void MenuBar::UpdateMenuBarColor() {
#if defined(OS_WIN)
  background_color_ = color_utils::GetSysSkColor(COLOR_MENUBAR);
#elif defined(USE_X11)
  GetMenuBarColor(&enabled_color_, &disabled_color_, &highlight_color_,
                  &hover_color_, &background_color_);
#endif
  SetBackground(views::CreateSolidBackground(background_color_));
}

}  // namespace atom
<|endoftext|>


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

#ifndef __LIBSTUDIO_FUNDAMENTALS_HPP__
#define __LIBSTUDIO_FUNDAMENTALS_HPP__

#include <cmath>

namespace studio
{
	namespace math
	{
		inline long double __abs(long double ld)
		{
			if (ld < 0) return -ld;
			return ld;
		}

		template <size_t width, size_t height>
		class MatrixBase
		{
		protected:
			long double m_data[width*height];
		public:
			enum
			{
				my_width = width,
				my_height = height
			};
			long double at(size_t x, size_t y) const { return m_data[x + y * width]; }
			long double& at(size_t x, size_t y) { return m_data[x + y * width]; }
		};

		template <size_t common, size_t width, size_t height>
		void matrix_multiply(MatrixBase<width, height>& out, const MatrixBase<common, height>& lhs, const MatrixBase<width, common>& rhs)
		{
			for (size_t w = 0; w < width; ++w)
			{
				for (size_t h = 0; h < height; ++h)
				{
					out.at(w, h) = 0;
					for (size_t c = 0; c < common; ++c)
					{
						out.at(w, h) += lhs.at(c, h) * rhs.at(w, c);
					}
				}
			}
		}

#define MATRIX_OPS(Type) \
	typedef Type my_t; \
	Type(const Type& rhs) \
	{ \
		for (size_t i = 0; i < sizeof(m_data) / sizeof(m_data[0]); ++i) \
			m_data[i] = rhs.m_data[i]; \
	} \
\
	Type(Type&& rhs) \
	{ \
		for (size_t i = 0; i < sizeof(m_data) / sizeof(m_data[0]); ++i) \
		{\
			m_data[i] = rhs.m_data[i]; \
			rhs.m_data[i] = 0; \
		}\
	} \
\
	Type& operator = (const Type& rhs) \
	{ \
		for (size_t i = 0; i < sizeof(m_data) / sizeof(m_data[0]); ++i) \
			m_data[i] = rhs.m_data[i]; \
		return *this; \
	} \
\
	Type& operator = (Type && rhs) \
	{ \
		for (size_t i = 0; i < sizeof(m_data) / sizeof(m_data[0]); ++i) \
		{\
			m_data[i] = rhs.m_data[i]; \
			rhs.m_data[i] = 0; \
		}\
		return *this; \
	} \
\
	my_t& set_at(size_t x, size_t y, long double val) { m_data[x + y * my_width] = val; return *this; }

#define MATRIX_PROP(name, pos) \
	long double name() const { return m_data[pos]; } \
	long double& name() { return m_data[pos]; } \
	my_t& set_ ## name(long double val) { m_data[pos] = val; return *this; }

		class Matrix : public MatrixBase<4, 4>
		{
		public:
			Matrix()
			{
				// identity
				for (size_t i = 0; i < sizeof(m_data) / sizeof(m_data[0]); ++i)
					m_data[i] = i % 15 ? 0 : 1;
			}

			MATRIX_OPS(Matrix)

			static Matrix identity() { return Matrix(); }
			static Matrix translate(long double dx, long double dy = 0, long double dz = 0)
			{
				return Matrix().set_at(3, 0, dx).set_at(3, 1, dy).set_at(3, 2, dz);
			}
			static Matrix scale(long double sx, long double sy = 0, long double sz = 0)
			{
				if (__abs(sy) < 0.00001) sy = sx;
				if (__abs(sz) < 0.00001) sz = sy;
				return Matrix().set_at(0, 0, sx).set_at(1, 1, sy).set_at(2, 2, sz);
			}
			static Matrix rotateX(long double theta)
			{
				long double cosTheta = std::cos(theta);
				long double sinTheta = std::sin(theta);
				return Matrix().set_at(2, 2, cosTheta).set_at(3, 2, -sinTheta).set_at(2, 3, sinTheta).set_at(3, 3, cosTheta);
			}
			static Matrix rotateY(long double theta)
			{
				long double cosTheta = std::cos(theta);
				long double sinTheta = std::sin(theta);
				return Matrix().set_at(0, 0, cosTheta).set_at(3, 0, sinTheta).set_at(0, 3, -sinTheta).set_at(3, 3, cosTheta);
			}
			static Matrix rotateZ(long double theta)
			{
				long double cosTheta = std::cos(theta);
				long double sinTheta = std::sin(theta);
				return Matrix().set_at(0, 0, cosTheta).set_at(1, 0, -sinTheta).set_at(0, 1, sinTheta).set_at(1, 1, cosTheta);
			}
		};

		class Vertex : public MatrixBase<1, 4>
		{
		public:
			Vertex()
			{
				for (size_t i = 0; i < my_height - 1; ++i)
					m_data[i] = 0;
				m_data[my_height - 1] = 1;
			}
			Vertex(long double x, long double y, long double z)
			{
				m_data[0] = x;
				m_data[1] = y;
				m_data[2] = z;
				m_data[3] = 1;
			}
			MATRIX_OPS(Vertex);
			MATRIX_PROP(x, 0);
			MATRIX_PROP(y, 1);
			MATRIX_PROP(z, 2);
		};

		class Vector : public MatrixBase<1, 4>
		{
		public:
			Vector()
			{
				for (size_t i = 0; i < my_height; ++i)
					m_data[i] = i == my_height - 1 ? 1 : 0;
			}
			Vector(long double i, long double j, long double k)
			{
				m_data[0] = i;
				m_data[1] = j;
				m_data[2] = k;
				m_data[3] = 1;
			}
			MATRIX_OPS(Vector);
			MATRIX_PROP(i, 0);
			MATRIX_PROP(j, 1);
			MATRIX_PROP(k, 2);

			long double length() const { return std::sqrt(lengthSquared()); }
			long double lengthSquared() const { return dotProduct(*this, *this); }

#define COORD(next, prev) (lhs.next() * rhs.prev() - rhs.next() * lhs.prev())
			static Vector crossProduct(const Vector& lhs, const Vector& rhs)
			{
				return { COORD(j, k), COORD(k, i), COORD(i, j) };
			}
#undef COORD

			static long double dotProduct(const Vector& lhs, const Vector& rhs)
			{
				return lhs.i() * rhs.i() + lhs.j() * rhs.j() + lhs.k() * rhs.k();
			}

			static long double cosTheta(const Vector& lhs, const Vector& rhs);
		};

		inline Vector operator - (const Vertex& lhs, const Vertex& rhs)
		{
			return { lhs.x() - rhs.x(), lhs.y() - rhs.y(), lhs.z() - rhs.z() };
		}

		inline Vector operator* (const Matrix& lhs, const Vector& rhs)
		{
			Vector v;
			matrix_multiply(v, lhs, rhs);
			return v;
		}

		inline Vertex operator* (const Matrix& lhs, const Vertex& rhs)
		{
			Vertex v;
			matrix_multiply(v, lhs, rhs);
			return v;
		}

		inline Matrix operator* (const Matrix& lhs, const Matrix& rhs)
		{
			Matrix m;
			matrix_multiply(m, lhs, rhs);
			return m;
		}

	}
}

#endif //__LIBSTUDIO_FUNDAMENTALS_HPP__<commit_msg>Fixing identity matrix<commit_after>/*
 * Copyright (C) 2013 Marcin Zdun
 *
 * 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.
 */

#ifndef __LIBSTUDIO_FUNDAMENTALS_HPP__
#define __LIBSTUDIO_FUNDAMENTALS_HPP__

#include <cmath>

namespace studio
{
	namespace math
	{
		inline long double __abs(long double ld)
		{
			if (ld < 0) return -ld;
			return ld;
		}

		template <size_t width, size_t height>
		class MatrixBase
		{
		protected:
			long double m_data[width*height];
		public:
			enum
			{
				my_width = width,
				my_height = height
			};
			long double at(size_t x, size_t y) const { return m_data[x + y * width]; }
			long double& at(size_t x, size_t y) { return m_data[x + y * width]; }
		};

		template <size_t common, size_t width, size_t height>
		void matrix_multiply(MatrixBase<width, height>& out, const MatrixBase<common, height>& lhs, const MatrixBase<width, common>& rhs)
		{
			for (size_t w = 0; w < width; ++w)
			{
				for (size_t h = 0; h < height; ++h)
				{
					out.at(w, h) = 0;
					for (size_t c = 0; c < common; ++c)
					{
						out.at(w, h) += lhs.at(c, h) * rhs.at(w, c);
					}
				}
			}
		}

#define MATRIX_OPS(Type) \
	typedef Type my_t; \
	Type(const Type& rhs) \
	{ \
		for (size_t i = 0; i < sizeof(m_data) / sizeof(m_data[0]); ++i) \
			m_data[i] = rhs.m_data[i]; \
	} \
\
	Type(Type&& rhs) \
	{ \
		for (size_t i = 0; i < sizeof(m_data) / sizeof(m_data[0]); ++i) \
		{\
			m_data[i] = rhs.m_data[i]; \
			rhs.m_data[i] = 0; \
		}\
	} \
\
	Type& operator = (const Type& rhs) \
	{ \
		for (size_t i = 0; i < sizeof(m_data) / sizeof(m_data[0]); ++i) \
			m_data[i] = rhs.m_data[i]; \
		return *this; \
	} \
\
	Type& operator = (Type && rhs) \
	{ \
		for (size_t i = 0; i < sizeof(m_data) / sizeof(m_data[0]); ++i) \
		{\
			m_data[i] = rhs.m_data[i]; \
			rhs.m_data[i] = 0; \
		}\
		return *this; \
	} \
\
	my_t& set_at(size_t x, size_t y, long double val) { m_data[x + y * my_width] = val; return *this; }

#define MATRIX_PROP(name, pos) \
	long double name() const { return m_data[pos]; } \
	long double& name() { return m_data[pos]; } \
	my_t& set_ ## name(long double val) { m_data[pos] = val; return *this; }

		class Matrix : public MatrixBase<4, 4>
		{
		public:
			Matrix()
			{
				// identity
				for (size_t i = 0; i < sizeof(m_data) / sizeof(m_data[0]); ++i)
					m_data[i] = i % 5 ? 0 : 1;
			}

			MATRIX_OPS(Matrix)

			static Matrix identity() { return Matrix(); }
			static Matrix translate(long double dx, long double dy = 0, long double dz = 0)
			{
				return Matrix().set_at(3, 0, dx).set_at(3, 1, dy).set_at(3, 2, dz);
			}
			static Matrix scale(long double sx, long double sy = 0, long double sz = 0)
			{
				if (__abs(sy) < 0.00001) sy = sx;
				if (__abs(sz) < 0.00001) sz = sy;
				return Matrix().set_at(0, 0, sx).set_at(1, 1, sy).set_at(2, 2, sz);
			}
			static Matrix rotateX(long double theta)
			{
				long double cosTheta = std::cos(theta);
				long double sinTheta = std::sin(theta);
				return Matrix().set_at(2, 2, cosTheta).set_at(3, 2, -sinTheta).set_at(2, 3, sinTheta).set_at(3, 3, cosTheta);
			}
			static Matrix rotateY(long double theta)
			{
				long double cosTheta = std::cos(theta);
				long double sinTheta = std::sin(theta);
				return Matrix().set_at(0, 0, cosTheta).set_at(3, 0, sinTheta).set_at(0, 3, -sinTheta).set_at(3, 3, cosTheta);
			}
			static Matrix rotateZ(long double theta)
			{
				long double cosTheta = std::cos(theta);
				long double sinTheta = std::sin(theta);
				return Matrix().set_at(0, 0, cosTheta).set_at(1, 0, -sinTheta).set_at(0, 1, sinTheta).set_at(1, 1, cosTheta);
			}
		};

		class Vertex : public MatrixBase<1, 4>
		{
		public:
			Vertex()
			{
				for (size_t i = 0; i < my_height - 1; ++i)
					m_data[i] = 0;
				m_data[my_height - 1] = 1;
			}
			Vertex(long double x, long double y, long double z)
			{
				m_data[0] = x;
				m_data[1] = y;
				m_data[2] = z;
				m_data[3] = 1;
			}
			MATRIX_OPS(Vertex);
			MATRIX_PROP(x, 0);
			MATRIX_PROP(y, 1);
			MATRIX_PROP(z, 2);
		};

		class Vector : public MatrixBase<1, 4>
		{
		public:
			Vector()
			{
				for (size_t i = 0; i < my_height; ++i)
					m_data[i] = i == my_height - 1 ? 1 : 0;
			}
			Vector(long double i, long double j, long double k)
			{
				m_data[0] = i;
				m_data[1] = j;
				m_data[2] = k;
				m_data[3] = 1;
			}
			MATRIX_OPS(Vector);
			MATRIX_PROP(i, 0);
			MATRIX_PROP(j, 1);
			MATRIX_PROP(k, 2);

			long double length() const { return std::sqrt(lengthSquared()); }
			long double lengthSquared() const { return dotProduct(*this, *this); }

#define COORD(next, prev) (lhs.next() * rhs.prev() - rhs.next() * lhs.prev())
			static Vector crossProduct(const Vector& lhs, const Vector& rhs)
			{
				return { COORD(j, k), COORD(k, i), COORD(i, j) };
			}
#undef COORD

			static long double dotProduct(const Vector& lhs, const Vector& rhs)
			{
				return lhs.i() * rhs.i() + lhs.j() * rhs.j() + lhs.k() * rhs.k();
			}

			static long double cosTheta(const Vector& lhs, const Vector& rhs);
		};

		inline Vector operator - (const Vertex& lhs, const Vertex& rhs)
		{
			return { lhs.x() - rhs.x(), lhs.y() - rhs.y(), lhs.z() - rhs.z() };
		}

		inline Vector operator* (const Matrix& lhs, const Vector& rhs)
		{
			Vector v;
			matrix_multiply(v, lhs, rhs);
			return v;
		}

		inline Vertex operator* (const Matrix& lhs, const Vertex& rhs)
		{
			Vertex v;
			matrix_multiply(v, lhs, rhs);
			return v;
		}

		inline Matrix operator* (const Matrix& lhs, const Matrix& rhs)
		{
			Matrix m;
			matrix_multiply(m, lhs, rhs);
			return m;
		}

	}
}

#endif //__LIBSTUDIO_FUNDAMENTALS_HPP__<|endoftext|>


<commit_before>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited
// Copyright (c) 2014 Francois Beaune, The appleseedhq Organization
//
// 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.
//

// Interface header.
#include "minimizebutton.h"

// Qt headers.
#include <QAction>
#include <QDockWidget>
#include <QMouseEvent>
#include <QStyle>

namespace appleseed {
namespace studio {

//
// MinimizeButton class implementation.
//

MinimizeButton::MinimizeButton(QDockWidget* dock_widget, QWidget* parent)
  : QPushButton(dock_widget->windowTitle(), parent)
  , m_dock_widget(dock_widget)
  , m_on(true)
  , m_minimized(false)
{
    setObjectName(QString::fromUtf8("ToggleButtonOn"));
    connect(
        m_dock_widget->toggleViewAction(), SIGNAL(toggled(bool)),
        SLOT(slot_minimize()));
}

bool MinimizeButton::is_on() const
{
    return m_on;
}

void MinimizeButton::set_fullscreen(const bool on)
{
    if (on)
    {
        // Setting fullscreen on
        m_minimized = m_on;
        if (!m_on)
            m_dock_widget->toggleViewAction()->activate(QAction::Trigger);
    }
    else
    {
        // Deactivating fullscreen
        // Keep state before fullscreen
        if (!m_minimized)
            m_dock_widget->toggleViewAction()->activate(QAction::Trigger);
    }
}

void MinimizeButton::mousePressEvent(QMouseEvent* event)
{
    if (event->buttons() & Qt::LeftButton)
        m_dock_widget->toggleViewAction()->activate(QAction::Trigger);
}

void MinimizeButton::slot_minimize()
{
    m_on = !m_on;
    if (m_on)
        setObjectName(QString::fromUtf8("ToggleButtonOn"));
    else
        setObjectName(QString::fromUtf8("ToggleButtonOff"));

    // Force stylesheet reloading for this widget
    style()->unpolish(this);
    style()->polish(this);
}

}   // namespace studio
}   // namespace appleseed
<commit_msg>minor code tweaks.<commit_after>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited
// Copyright (c) 2014 Francois Beaune, The appleseedhq Organization
//
// 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.
//

// Interface header.
#include "minimizebutton.h"

// Qt headers.
#include <QAction>
#include <QDockWidget>
#include <QMouseEvent>
#include <QStyle>

namespace appleseed {
namespace studio {

//
// MinimizeButton class implementation.
//

MinimizeButton::MinimizeButton(QDockWidget* dock_widget, QWidget* parent)
  : QPushButton(dock_widget->windowTitle(), parent)
  , m_dock_widget(dock_widget)
  , m_on(true)
  , m_minimized(false)
{
    setObjectName(QString::fromUtf8("ToggleButtonOn"));
    connect(
        m_dock_widget->toggleViewAction(), SIGNAL(toggled(bool)),
        SLOT(slot_minimize()));
}

bool MinimizeButton::is_on() const
{
    return m_on;
}

void MinimizeButton::set_fullscreen(const bool on)
{
    if (on)
    {
        // Setting fullscreen on.
        m_minimized = m_on;
        if (!m_on)
            m_dock_widget->toggleViewAction()->activate(QAction::Trigger);
    }
    else
    {
        // Deactivating fullscreen. Keep state before fullscreen.
        if (!m_minimized)
            m_dock_widget->toggleViewAction()->activate(QAction::Trigger);
    }
}

void MinimizeButton::mousePressEvent(QMouseEvent* event)
{
    if (event->buttons() & Qt::LeftButton)
        m_dock_widget->toggleViewAction()->activate(QAction::Trigger);
}

void MinimizeButton::slot_minimize()
{
    m_on = !m_on;

    setObjectName(QString::fromUtf8(m_on ? "ToggleButtonOn" : "ToggleButtonOff"));

    // Force stylesheet reloading for this widget.
    style()->unpolish(this);
    style()->polish(this);
}

}   // namespace studio
}   // namespace appleseed
<|endoftext|>


<commit_before>/* mbed Microcontroller Library
 * Copyright (c) 2006-2015 ARM Limited
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "mbed-drivers/mbed.h"
#include "ble/BLE.h"
#include "ble/services/iBeacon.h"

static iBeacon* ibeaconPtr;

/**
 * This function is called when the ble initialization process has failled
 */
void onBleInitError(BLE &ble, ble_error_t error)
{
    /* Initialization error handling should go here */
}

/**
 * Callback triggered when the ble initialization process has finished
 */
void bleInitComplete(BLE::InitializationCompleteCallbackContext *params)
{
    BLE&        ble   = params->ble;
    ble_error_t error = params->error;

    if (error != BLE_ERROR_NONE) {
        /* In case of error, forward the error handling to onBleInitError */
        onBleInitError(ble, error);
        return;
    }

    /* Ensure that it is the default instance of BLE */
    if(ble.getInstanceID() != BLE::DEFAULT_INSTANCE) {
        return;
    }

    /**
     * The Beacon payload has the following composition:
     * 128-Bit / 16byte UUID = E2 0A 39 F4 73 F5 4B C4 A1 2F 17 D1 AD 07 A9 61
     * Major/Minor  = 0x1122 / 0x3344
     * Tx Power     = 0xC8 = 200, 2's compliment is 256-200 = (-56dB)
     *
     * Note: please remember to calibrate your beacons TX Power for more accurate results.
     */
    static const uint8_t uuid[] = {0xE2, 0x0A, 0x39, 0xF4, 0x73, 0xF5, 0x4B, 0xC4,
                            0xA1, 0x2F, 0x17, 0xD1, 0xAD, 0x07, 0xA9, 0x61};
    uint16_t majorNumber = 1122;
    uint16_t minorNumber = 3344;
    uint16_t txPower     = 0xC8;
    ibeaconPtr = new iBeacon(ble, uuid, majorNumber, minorNumber, txPower);

    ble.gap().setAdvertisingInterval(1000); /* 1000ms. */
    ble.gap().startAdvertising();
}

void app_start(int, char**)
{
    BLE &ble = BLE::Instance();
    ble.init(bleInitComplete);
}
<commit_msg>Fixed indentation in BLE_Beacon demo source<commit_after>/* mbed Microcontroller Library
 * Copyright (c) 2006-2015 ARM Limited
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "mbed-drivers/mbed.h"
#include "ble/BLE.h"
#include "ble/services/iBeacon.h"

static iBeacon* ibeaconPtr;

/**
 * This function is called when the ble initialization process has failled
 */
void onBleInitError(BLE &ble, ble_error_t error)
{
    /* Initialization error handling should go here */
}

/**
 * Callback triggered when the ble initialization process has finished
 */
void bleInitComplete(BLE::InitializationCompleteCallbackContext *params)
{
    BLE&        ble   = params->ble;
    ble_error_t error = params->error;

    if (error != BLE_ERROR_NONE) {
        /* In case of error, forward the error handling to onBleInitError */
        onBleInitError(ble, error);
        return;
    }

    /* Ensure that it is the default instance of BLE */
    if(ble.getInstanceID() != BLE::DEFAULT_INSTANCE) {
        return;
    }

    /**
     * The Beacon payload has the following composition:
     * 128-Bit / 16byte UUID = E2 0A 39 F4 73 F5 4B C4 A1 2F 17 D1 AD 07 A9 61
     * Major/Minor  = 0x1122 / 0x3344
     * Tx Power     = 0xC8 = 200, 2's compliment is 256-200 = (-56dB)
     *
     * Note: please remember to calibrate your beacons TX Power for more accurate results.
     */
    static const uint8_t uuid[] = {0xE2, 0x0A, 0x39, 0xF4, 0x73, 0xF5, 0x4B, 0xC4,
                                   0xA1, 0x2F, 0x17, 0xD1, 0xAD, 0x07, 0xA9, 0x61};
    uint16_t majorNumber = 1122;
    uint16_t minorNumber = 3344;
    uint16_t txPower     = 0xC8;
    ibeaconPtr = new iBeacon(ble, uuid, majorNumber, minorNumber, txPower);

    ble.gap().setAdvertisingInterval(1000); /* 1000ms. */
    ble.gap().startAdvertising();
}

void app_start(int, char**)
{
    BLE &ble = BLE::Instance();
    ble.init(bleInitComplete);
}
<|endoftext|>


<commit_before>//===--- Backend.cpp - Interface to LLVM backend technologies -------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "clang/Frontend/ASTConsumers.h"
#include "clang/CodeGen/ModuleBuilder.h"
#include "clang/Frontend/CompileOptions.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/DeclGroup.h"
#include "clang/Basic/TargetInfo.h"
#include "llvm/Module.h"
#include "llvm/ModuleProvider.h"
#include "llvm/PassManager.h"
#include "llvm/ADT/OwningPtr.h"
#include "llvm/Assembly/PrintModulePass.h"
#include "llvm/Analysis/CallGraph.h"
#include "llvm/Analysis/Verifier.h"
#include "llvm/Bitcode/ReaderWriter.h"
#include "llvm/CodeGen/RegAllocRegistry.h"
#include "llvm/CodeGen/SchedulerRegistry.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/FormattedStream.h"
#include "llvm/Support/StandardPasses.h"
#include "llvm/Support/Timer.h"
#include "llvm/System/Path.h"
#include "llvm/System/Program.h"
#include "llvm/Target/SubtargetFeature.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetRegistry.h"
using namespace clang;
using namespace llvm;

namespace {
  class VISIBILITY_HIDDEN BackendConsumer : public ASTConsumer {
    BackendAction Action;
    CompileOptions CompileOpts;
    llvm::raw_ostream *AsmOutStream;
    llvm::formatted_raw_ostream FormattedOutStream;
    ASTContext *Context;

    Timer LLVMIRGeneration;
    Timer CodeGenerationTime;

    llvm::OwningPtr<CodeGenerator> Gen;

    llvm::Module *TheModule;
    llvm::TargetData *TheTargetData;

    mutable llvm::ModuleProvider *ModuleProvider;
    mutable FunctionPassManager *CodeGenPasses;
    mutable PassManager *PerModulePasses;
    mutable FunctionPassManager *PerFunctionPasses;

    FunctionPassManager *getCodeGenPasses() const;
    PassManager *getPerModulePasses() const;
    FunctionPassManager *getPerFunctionPasses() const;

    void CreatePasses();

    /// AddEmitPasses - Add passes necessary to emit assembly or LLVM
    /// IR.
    ///
    /// \return True on success. On failure \arg Error will be set to
    /// a user readable error message.
    bool AddEmitPasses(std::string &Error);

    void EmitAssembly();

  public:
    BackendConsumer(BackendAction action, Diagnostic &Diags,
                    const LangOptions &langopts, const CompileOptions &compopts,
                    const std::string &infile, llvm::raw_ostream* OS,
                    LLVMContext& C) :
      Action(action),
      CompileOpts(compopts),
      AsmOutStream(OS),
      LLVMIRGeneration("LLVM IR Generation Time"),
      CodeGenerationTime("Code Generation Time"),
      Gen(CreateLLVMCodeGen(Diags, infile, compopts, C)),
      TheModule(0), TheTargetData(0), ModuleProvider(0),
      CodeGenPasses(0), PerModulePasses(0), PerFunctionPasses(0) {

      if (AsmOutStream)
        FormattedOutStream.setStream(*AsmOutStream,
                                     formatted_raw_ostream::PRESERVE_STREAM);

      // Enable -time-passes if -ftime-report is enabled.
      llvm::TimePassesIsEnabled = CompileOpts.TimePasses;
    }

    ~BackendConsumer() {
      delete TheTargetData;
      delete ModuleProvider;
      delete CodeGenPasses;
      delete PerModulePasses;
      delete PerFunctionPasses;
    }

    virtual void Initialize(ASTContext &Ctx) {
      Context = &Ctx;

      if (CompileOpts.TimePasses)
        LLVMIRGeneration.startTimer();

      Gen->Initialize(Ctx);

      TheModule = Gen->GetModule();
      ModuleProvider = new ExistingModuleProvider(TheModule);
      TheTargetData = new llvm::TargetData(Ctx.Target.getTargetDescription());

      if (CompileOpts.TimePasses)
        LLVMIRGeneration.stopTimer();
    }

    virtual void HandleTopLevelDecl(DeclGroupRef D) {
      PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
                                     Context->getSourceManager(),
                                     "LLVM IR generation of declaration");

      if (CompileOpts.TimePasses)
        LLVMIRGeneration.startTimer();

      Gen->HandleTopLevelDecl(D);

      if (CompileOpts.TimePasses)
        LLVMIRGeneration.stopTimer();
    }

    virtual void HandleTranslationUnit(ASTContext &C) {
      {
        PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
        if (CompileOpts.TimePasses)
          LLVMIRGeneration.startTimer();

        Gen->HandleTranslationUnit(C);

        if (CompileOpts.TimePasses)
          LLVMIRGeneration.stopTimer();
      }

      // EmitAssembly times and registers crash info itself.
      EmitAssembly();

      // Force a flush here in case we never get released.
      if (AsmOutStream)
        FormattedOutStream.flush();
    }

    virtual void HandleTagDeclDefinition(TagDecl *D) {
      PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
                                     Context->getSourceManager(),
                                     "LLVM IR generation of declaration");
      Gen->HandleTagDeclDefinition(D);
    }

    virtual void CompleteTentativeDefinition(VarDecl *D) {
      Gen->CompleteTentativeDefinition(D);
    }
  };
}

FunctionPassManager *BackendConsumer::getCodeGenPasses() const {
  if (!CodeGenPasses) {
    CodeGenPasses = new FunctionPassManager(ModuleProvider);
    CodeGenPasses->add(new TargetData(*TheTargetData));
  }

  return CodeGenPasses;
}

PassManager *BackendConsumer::getPerModulePasses() const {
  if (!PerModulePasses) {
    PerModulePasses = new PassManager();
    PerModulePasses->add(new TargetData(*TheTargetData));
  }

  return PerModulePasses;
}

FunctionPassManager *BackendConsumer::getPerFunctionPasses() const {
  if (!PerFunctionPasses) {
    PerFunctionPasses = new FunctionPassManager(ModuleProvider);
    PerFunctionPasses->add(new TargetData(*TheTargetData));
  }

  return PerFunctionPasses;
}

bool BackendConsumer::AddEmitPasses(std::string &Error) {
  if (Action == Backend_EmitNothing)
    return true;

  if (Action == Backend_EmitBC) {
    getPerModulePasses()->add(createBitcodeWriterPass(*AsmOutStream));
  } else if (Action == Backend_EmitLL) {
    getPerModulePasses()->add(createPrintModulePass(AsmOutStream));
  } else {
    bool Fast = CompileOpts.OptimizationLevel == 0;

    // Create the TargetMachine for generating code.
    std::string Triple = TheModule->getTargetTriple();
    const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
    if (!TheTarget) {
      Error = std::string("Unable to get target machine: ") + Error;
      return false;
    }

    std::string FeaturesStr;
    if (CompileOpts.CPU.size() || CompileOpts.Features.size()) {
      SubtargetFeatures Features;
      Features.setCPU(CompileOpts.CPU);
      for (std::vector<std::string>::iterator
             it = CompileOpts.Features.begin(),
             ie = CompileOpts.Features.end(); it != ie; ++it)
        Features.AddFeature(*it);
      FeaturesStr = Features.getString();
    }
    TargetMachine *TM = TheTarget->createTargetMachine(*TheModule, Triple,
                                                       FeaturesStr);

    // Set register scheduler & allocation policy.
    RegisterScheduler::setDefault(createDefaultScheduler);
    RegisterRegAlloc::setDefault(Fast ? createLocalRegisterAllocator :
                                 createLinearScanRegisterAllocator);

    // From llvm-gcc:
    // If there are passes we have to run on the entire module, we do codegen
    // as a separate "pass" after that happens.
    // FIXME: This is disabled right now until bugs can be worked out.  Reenable
    // this for fast -O0 compiles!
    FunctionPassManager *PM = getCodeGenPasses();
    CodeGenOpt::Level OptLevel = CodeGenOpt::Default;

    switch (CompileOpts.OptimizationLevel) {
    default: break;
    case 0: OptLevel = CodeGenOpt::None; break;
    case 3: OptLevel = CodeGenOpt::Aggressive; break;
    }

    // Normal mode, emit a .s file by running the code generator.
    // Note, this also adds codegenerator level optimization passes.
    switch (TM->addPassesToEmitFile(*PM, FormattedOutStream,
                                    TargetMachine::AssemblyFile, OptLevel)) {
    default:
    case FileModel::Error:
      Error = "Unable to interface with target machine!\n";
      return false;
    case FileModel::AsmFile:
      break;
    }

    if (TM->addPassesToEmitFileFinish(*CodeGenPasses, (MachineCodeEmitter *)0,
                                      OptLevel)) {
      Error = "Unable to interface with target machine!\n";
      return false;
    }
  }

  return true;
}

void BackendConsumer::CreatePasses() {
  // In -O0 if checking is disabled, we don't even have per-function passes.
  if (CompileOpts.VerifyModule)
    getPerFunctionPasses()->add(createVerifierPass());

  // Assume that standard function passes aren't run for -O0.
  if (CompileOpts.OptimizationLevel > 0)
    llvm::createStandardFunctionPasses(getPerFunctionPasses(),
                                       CompileOpts.OptimizationLevel);

  llvm::Pass *InliningPass = 0;
  switch (CompileOpts.Inlining) {
  case CompileOptions::NoInlining: break;
  case CompileOptions::NormalInlining: {
    // Inline small functions
    unsigned Threshold = (CompileOpts.OptimizeSize ||
                          CompileOpts.OptimizationLevel < 3) ? 50 : 200;
    InliningPass = createFunctionInliningPass(Threshold);
    break;
  }
  case CompileOptions::OnlyAlwaysInlining:
    InliningPass = createAlwaysInlinerPass();         // Respect always_inline
    break;
  }

  // For now we always create per module passes.
  PassManager *PM = getPerModulePasses();
  llvm::createStandardModulePasses(PM, CompileOpts.OptimizationLevel,
                                   CompileOpts.OptimizeSize,
                                   CompileOpts.UnitAtATime,
                                   CompileOpts.UnrollLoops,
                                   CompileOpts.SimplifyLibCalls,
                                   /*HaveExceptions=*/true,
                                   InliningPass);
}

/// EmitAssembly - Handle interaction with LLVM backend to generate
/// actual machine code.
void BackendConsumer::EmitAssembly() {
  // Silently ignore if we weren't initialized for some reason.
  if (!TheModule || !TheTargetData)
    return;

  TimeRegion Region(CompileOpts.TimePasses ? &CodeGenerationTime : 0);

  // Make sure IR generation is happy with the module. This is
  // released by the module provider.
  Module *M = Gen->ReleaseModule();
  if (!M) {
    // The module has been released by IR gen on failures, do not
    // double free.
    ModuleProvider->releaseModule();
    TheModule = 0;
    return;
  }

  assert(TheModule == M && "Unexpected module change during IR generation");

  CreatePasses();

  std::string Error;
  if (!AddEmitPasses(Error)) {
    // FIXME: Don't fail this way.
    llvm::cerr << "ERROR: " << Error << "\n";
    ::exit(1);
  }

  // Run passes. For now we do all passes at once, but eventually we
  // would like to have the option of streaming code generation.

  if (PerFunctionPasses) {
    PrettyStackTraceString CrashInfo("Per-function optimization");

    PerFunctionPasses->doInitialization();
    for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
      if (!I->isDeclaration())
        PerFunctionPasses->run(*I);
    PerFunctionPasses->doFinalization();
  }

  if (PerModulePasses) {
    PrettyStackTraceString CrashInfo("Per-module optimization passes");
    PerModulePasses->run(*M);
  }

  if (CodeGenPasses) {
    PrettyStackTraceString CrashInfo("Code generation");
    CodeGenPasses->doInitialization();
    for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
      if (!I->isDeclaration())
        CodeGenPasses->run(*I);
    CodeGenPasses->doFinalization();
  }
}

ASTConsumer *clang::CreateBackendConsumer(BackendAction Action,
                                          Diagnostic &Diags,
                                          const LangOptions &LangOpts,
                                          const CompileOptions &CompileOpts,
                                          const std::string& InFile,
                                          llvm::raw_ostream* OS,
                                          LLVMContext& C) {
  return new BackendConsumer(Action, Diags, LangOpts, CompileOpts,
                             InFile, OS, C);
}
<commit_msg>Update for LLVM API change<commit_after>//===--- Backend.cpp - Interface to LLVM backend technologies -------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "clang/Frontend/ASTConsumers.h"
#include "clang/CodeGen/ModuleBuilder.h"
#include "clang/Frontend/CompileOptions.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/DeclGroup.h"
#include "clang/Basic/TargetInfo.h"
#include "llvm/Module.h"
#include "llvm/ModuleProvider.h"
#include "llvm/PassManager.h"
#include "llvm/ADT/OwningPtr.h"
#include "llvm/Assembly/PrintModulePass.h"
#include "llvm/Analysis/CallGraph.h"
#include "llvm/Analysis/Verifier.h"
#include "llvm/Bitcode/ReaderWriter.h"
#include "llvm/CodeGen/RegAllocRegistry.h"
#include "llvm/CodeGen/SchedulerRegistry.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/FormattedStream.h"
#include "llvm/Support/StandardPasses.h"
#include "llvm/Support/Timer.h"
#include "llvm/System/Path.h"
#include "llvm/System/Program.h"
#include "llvm/Target/SubtargetFeature.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetRegistry.h"
using namespace clang;
using namespace llvm;

namespace {
  class VISIBILITY_HIDDEN BackendConsumer : public ASTConsumer {
    BackendAction Action;
    CompileOptions CompileOpts;
    llvm::raw_ostream *AsmOutStream;
    llvm::formatted_raw_ostream FormattedOutStream;
    ASTContext *Context;

    Timer LLVMIRGeneration;
    Timer CodeGenerationTime;

    llvm::OwningPtr<CodeGenerator> Gen;

    llvm::Module *TheModule;
    llvm::TargetData *TheTargetData;

    mutable llvm::ModuleProvider *ModuleProvider;
    mutable FunctionPassManager *CodeGenPasses;
    mutable PassManager *PerModulePasses;
    mutable FunctionPassManager *PerFunctionPasses;

    FunctionPassManager *getCodeGenPasses() const;
    PassManager *getPerModulePasses() const;
    FunctionPassManager *getPerFunctionPasses() const;

    void CreatePasses();

    /// AddEmitPasses - Add passes necessary to emit assembly or LLVM
    /// IR.
    ///
    /// \return True on success. On failure \arg Error will be set to
    /// a user readable error message.
    bool AddEmitPasses(std::string &Error);

    void EmitAssembly();

  public:
    BackendConsumer(BackendAction action, Diagnostic &Diags,
                    const LangOptions &langopts, const CompileOptions &compopts,
                    const std::string &infile, llvm::raw_ostream* OS,
                    LLVMContext& C) :
      Action(action),
      CompileOpts(compopts),
      AsmOutStream(OS),
      LLVMIRGeneration("LLVM IR Generation Time"),
      CodeGenerationTime("Code Generation Time"),
      Gen(CreateLLVMCodeGen(Diags, infile, compopts, C)),
      TheModule(0), TheTargetData(0), ModuleProvider(0),
      CodeGenPasses(0), PerModulePasses(0), PerFunctionPasses(0) {

      if (AsmOutStream)
        FormattedOutStream.setStream(*AsmOutStream,
                                     formatted_raw_ostream::PRESERVE_STREAM);

      // Enable -time-passes if -ftime-report is enabled.
      llvm::TimePassesIsEnabled = CompileOpts.TimePasses;
    }

    ~BackendConsumer() {
      delete TheTargetData;
      delete ModuleProvider;
      delete CodeGenPasses;
      delete PerModulePasses;
      delete PerFunctionPasses;
    }

    virtual void Initialize(ASTContext &Ctx) {
      Context = &Ctx;

      if (CompileOpts.TimePasses)
        LLVMIRGeneration.startTimer();

      Gen->Initialize(Ctx);

      TheModule = Gen->GetModule();
      ModuleProvider = new ExistingModuleProvider(TheModule);
      TheTargetData = new llvm::TargetData(Ctx.Target.getTargetDescription());

      if (CompileOpts.TimePasses)
        LLVMIRGeneration.stopTimer();
    }

    virtual void HandleTopLevelDecl(DeclGroupRef D) {
      PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
                                     Context->getSourceManager(),
                                     "LLVM IR generation of declaration");

      if (CompileOpts.TimePasses)
        LLVMIRGeneration.startTimer();

      Gen->HandleTopLevelDecl(D);

      if (CompileOpts.TimePasses)
        LLVMIRGeneration.stopTimer();
    }

    virtual void HandleTranslationUnit(ASTContext &C) {
      {
        PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
        if (CompileOpts.TimePasses)
          LLVMIRGeneration.startTimer();

        Gen->HandleTranslationUnit(C);

        if (CompileOpts.TimePasses)
          LLVMIRGeneration.stopTimer();
      }

      // EmitAssembly times and registers crash info itself.
      EmitAssembly();

      // Force a flush here in case we never get released.
      if (AsmOutStream)
        FormattedOutStream.flush();
    }

    virtual void HandleTagDeclDefinition(TagDecl *D) {
      PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
                                     Context->getSourceManager(),
                                     "LLVM IR generation of declaration");
      Gen->HandleTagDeclDefinition(D);
    }

    virtual void CompleteTentativeDefinition(VarDecl *D) {
      Gen->CompleteTentativeDefinition(D);
    }
  };
}

FunctionPassManager *BackendConsumer::getCodeGenPasses() const {
  if (!CodeGenPasses) {
    CodeGenPasses = new FunctionPassManager(ModuleProvider);
    CodeGenPasses->add(new TargetData(*TheTargetData));
  }

  return CodeGenPasses;
}

PassManager *BackendConsumer::getPerModulePasses() const {
  if (!PerModulePasses) {
    PerModulePasses = new PassManager();
    PerModulePasses->add(new TargetData(*TheTargetData));
  }

  return PerModulePasses;
}

FunctionPassManager *BackendConsumer::getPerFunctionPasses() const {
  if (!PerFunctionPasses) {
    PerFunctionPasses = new FunctionPassManager(ModuleProvider);
    PerFunctionPasses->add(new TargetData(*TheTargetData));
  }

  return PerFunctionPasses;
}

bool BackendConsumer::AddEmitPasses(std::string &Error) {
  if (Action == Backend_EmitNothing)
    return true;

  if (Action == Backend_EmitBC) {
    getPerModulePasses()->add(createBitcodeWriterPass(*AsmOutStream));
  } else if (Action == Backend_EmitLL) {
    getPerModulePasses()->add(createPrintModulePass(AsmOutStream));
  } else {
    bool Fast = CompileOpts.OptimizationLevel == 0;

    // Create the TargetMachine for generating code.
    std::string Triple = TheModule->getTargetTriple();
    const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
    if (!TheTarget) {
      Error = std::string("Unable to get target machine: ") + Error;
      return false;
    }

    std::string FeaturesStr;
    if (CompileOpts.CPU.size() || CompileOpts.Features.size()) {
      SubtargetFeatures Features;
      Features.setCPU(CompileOpts.CPU);
      for (std::vector<std::string>::iterator
             it = CompileOpts.Features.begin(),
             ie = CompileOpts.Features.end(); it != ie; ++it)
        Features.AddFeature(*it);
      FeaturesStr = Features.getString();
    }
    TargetMachine *TM = TheTarget->createTargetMachine(Triple, FeaturesStr);

    // Set register scheduler & allocation policy.
    RegisterScheduler::setDefault(createDefaultScheduler);
    RegisterRegAlloc::setDefault(Fast ? createLocalRegisterAllocator :
                                 createLinearScanRegisterAllocator);

    // From llvm-gcc:
    // If there are passes we have to run on the entire module, we do codegen
    // as a separate "pass" after that happens.
    // FIXME: This is disabled right now until bugs can be worked out.  Reenable
    // this for fast -O0 compiles!
    FunctionPassManager *PM = getCodeGenPasses();
    CodeGenOpt::Level OptLevel = CodeGenOpt::Default;

    switch (CompileOpts.OptimizationLevel) {
    default: break;
    case 0: OptLevel = CodeGenOpt::None; break;
    case 3: OptLevel = CodeGenOpt::Aggressive; break;
    }

    // Normal mode, emit a .s file by running the code generator.
    // Note, this also adds codegenerator level optimization passes.
    switch (TM->addPassesToEmitFile(*PM, FormattedOutStream,
                                    TargetMachine::AssemblyFile, OptLevel)) {
    default:
    case FileModel::Error:
      Error = "Unable to interface with target machine!\n";
      return false;
    case FileModel::AsmFile:
      break;
    }

    if (TM->addPassesToEmitFileFinish(*CodeGenPasses, (MachineCodeEmitter *)0,
                                      OptLevel)) {
      Error = "Unable to interface with target machine!\n";
      return false;
    }
  }

  return true;
}

void BackendConsumer::CreatePasses() {
  // In -O0 if checking is disabled, we don't even have per-function passes.
  if (CompileOpts.VerifyModule)
    getPerFunctionPasses()->add(createVerifierPass());

  // Assume that standard function passes aren't run for -O0.
  if (CompileOpts.OptimizationLevel > 0)
    llvm::createStandardFunctionPasses(getPerFunctionPasses(),
                                       CompileOpts.OptimizationLevel);

  llvm::Pass *InliningPass = 0;
  switch (CompileOpts.Inlining) {
  case CompileOptions::NoInlining: break;
  case CompileOptions::NormalInlining: {
    // Inline small functions
    unsigned Threshold = (CompileOpts.OptimizeSize ||
                          CompileOpts.OptimizationLevel < 3) ? 50 : 200;
    InliningPass = createFunctionInliningPass(Threshold);
    break;
  }
  case CompileOptions::OnlyAlwaysInlining:
    InliningPass = createAlwaysInlinerPass();         // Respect always_inline
    break;
  }

  // For now we always create per module passes.
  PassManager *PM = getPerModulePasses();
  llvm::createStandardModulePasses(PM, CompileOpts.OptimizationLevel,
                                   CompileOpts.OptimizeSize,
                                   CompileOpts.UnitAtATime,
                                   CompileOpts.UnrollLoops,
                                   CompileOpts.SimplifyLibCalls,
                                   /*HaveExceptions=*/true,
                                   InliningPass);
}

/// EmitAssembly - Handle interaction with LLVM backend to generate
/// actual machine code.
void BackendConsumer::EmitAssembly() {
  // Silently ignore if we weren't initialized for some reason.
  if (!TheModule || !TheTargetData)
    return;

  TimeRegion Region(CompileOpts.TimePasses ? &CodeGenerationTime : 0);

  // Make sure IR generation is happy with the module. This is
  // released by the module provider.
  Module *M = Gen->ReleaseModule();
  if (!M) {
    // The module has been released by IR gen on failures, do not
    // double free.
    ModuleProvider->releaseModule();
    TheModule = 0;
    return;
  }

  assert(TheModule == M && "Unexpected module change during IR generation");

  CreatePasses();

  std::string Error;
  if (!AddEmitPasses(Error)) {
    // FIXME: Don't fail this way.
    llvm::cerr << "ERROR: " << Error << "\n";
    ::exit(1);
  }

  // Run passes. For now we do all passes at once, but eventually we
  // would like to have the option of streaming code generation.

  if (PerFunctionPasses) {
    PrettyStackTraceString CrashInfo("Per-function optimization");

    PerFunctionPasses->doInitialization();
    for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
      if (!I->isDeclaration())
        PerFunctionPasses->run(*I);
    PerFunctionPasses->doFinalization();
  }

  if (PerModulePasses) {
    PrettyStackTraceString CrashInfo("Per-module optimization passes");
    PerModulePasses->run(*M);
  }

  if (CodeGenPasses) {
    PrettyStackTraceString CrashInfo("Code generation");
    CodeGenPasses->doInitialization();
    for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
      if (!I->isDeclaration())
        CodeGenPasses->run(*I);
    CodeGenPasses->doFinalization();
  }
}

ASTConsumer *clang::CreateBackendConsumer(BackendAction Action,
                                          Diagnostic &Diags,
                                          const LangOptions &LangOpts,
                                          const CompileOptions &CompileOpts,
                                          const std::string& InFile,
                                          llvm::raw_ostream* OS,
                                          LLVMContext& C) {
  return new BackendConsumer(Action, Diags, LangOpts, CompileOpts,
                             InFile, OS, C);
}
<|endoftext|>


<commit_before>#include <avalon/physics/loadercallbacks.h>
#include "Box2D/Box2D.h"
#include <avalon/physics/Box2dContainer.h>
#include <boost/any.hpp>

namespace avalon {
namespace physics {
namespace loadercallbacks {

avalon::io::TiledMapLoader::Callback createShapes(int filterCategory, bool isSensor)
{
    return [filterCategory](const avalon::io::TiledMapLoader::Configuration& config) {

        float x = boost::any_cast<float>(config.settings.at("x"));
        float y = boost::any_cast<float>(config.settings.at("y"));
        float w = boost::any_cast<float>(config.settings.at("width"));
        float h = boost::any_cast<float>(config.settings.at("height"));

        float density = 0.0;
        float friction = 1.0;
        float restitution = 0.0;
        std::string bodytype = "static";

        if (config.settings.count("friction")) {
            friction = boost::any_cast<float>(config.settings.at("friction"));
        }
        if (config.settings.count("density")) {
            density = boost::any_cast<float>(config.settings.at("density"));
        }
        if (config.settings.count("restitution")) {
            restitution = boost::any_cast<float>(config.settings.at("restitution"));
        }
        if (config.settings.count("bodytype")) {
            bodytype = boost::any_cast<std::string>(config.settings.at("bodytype"));
        }

        std::string type = "static";

        // create the body
        b2BodyDef bodyDef;

        if (type == "static") {
            bodyDef.type = b2_staticBody;
        } else if (type == "dynamic") {
            bodyDef.type = b2_dynamicBody;
        } else if (type == "kinematic") {
            bodyDef.type = b2_kinematicBody;
        } else {
            throw new std::invalid_argument("Unknown box2d type");
        }

        bodyDef.position.Set((x + (w / 2.0f)) / config.box2dContainer->pixelsInMeter,
                             (y + (h / 2.0f)) / config.box2dContainer->pixelsInMeter);
        b2Body* body = config.box2dContainer->world->CreateBody(&bodyDef);

        std::string shapeType = "rectangle";

        if (config.settings.count("polylinePoints") > 0)
            shapeType = "polylinePoints";

        if (config.settings.count("points") > 0)
            shapeType = "points";

        std::shared_ptr<b2Shape> shape;

        if (shapeType == "rectangle") {
            shape = initRectangleShape(w, h, config.box2dContainer->pixelsInMeter);
        } else if (shapeType == "polylinePoints") {
            auto pointList = boost::any_cast<std::list<cocos2d::Point>>(config.settings.at("polylinePoints"));
            if (pointList.size() == 2) {
                int c = 0;
                cocos2d::Point points[2];
                for (auto& p : pointList) {
                    points[c] = p;
                    ++c;
                }
                shape = initEdgeShape(points[0], points[1], config.box2dContainer->pixelsInMeter);
            } else {
                shape = initChainShape(pointList, config.box2dContainer->pixelsInMeter);
            }
        } else if (shapeType == "points") {
            auto pointList = boost::any_cast<std::list<cocos2d::Point>>(config.settings.at("points"));
            if (pointList.size() == 2) {
                int c = 0;
                cocos2d::Point points[2];
                for (auto& p : pointList) {
                    points[c] = p;
                    ++c;
                }
                shape = initEdgeShape(points[0], points[1], config.box2dContainer->pixelsInMeter);
            } else {
                shape = initChainShape(pointList, config.box2dContainer->pixelsInMeter, true);
            }
        }

        // create the fixture
        b2FixtureDef fixtureDef;
        fixtureDef.shape = shape.get();
        body->CreateFixture(&fixtureDef);
    };
}

std::shared_ptr<b2PolygonShape> initRectangleShape(float width, float height, float pixelsInMeter)
{
    auto shape = make_shared<b2PolygonShape>();
    shape->SetAsBox((width / pixelsInMeter) * 0.5f, (height / pixelsInMeter) * 0.5f);
    return shape;
}

std::shared_ptr<b2PolygonShape> initPolygonShape(int width, int height, float pixelsInMeter)
{
    auto shape = initRectangleShape(width, height, pixelsInMeter);
    return shape;
}

std::shared_ptr<b2CircleShape> initCircleShape()
{
    auto shape = make_shared<b2CircleShape>();
    return shape;
}

std::shared_ptr<b2ChainShape> initChainShape(std::list<cocos2d::Point> points, float pixelsInMeter, bool loop)
{

    std::vector<b2Vec2> vecs;
    vecs.reserve(points.size());

    for (auto& p : points) {
        p = p / pixelsInMeter;
        vecs.push_back({p.x, -p.y});
    }

    auto shape = make_shared<b2ChainShape>();

    if (loop) {
        shape->CreateLoop(&vecs[0], points.size());
    } else {
        shape->CreateChain(&vecs[0], points.size());
    }

    return shape;
}

std::shared_ptr<b2EdgeShape> initEdgeShape(cocos2d::Point p1, cocos2d::Point p2, float pixelsInMeter)
{
    p1 = p1 / pixelsInMeter;
    p2 = p2 / pixelsInMeter;
    auto shape = make_shared<b2EdgeShape>();
    shape->Set({p1.x, p1.y}, {p2.x, p2.y});
    return shape;
}

} // namesapce loadercallbacks
} // namespace physics
} // namespace avalon
<commit_msg>removed unused functions<commit_after>#include <avalon/physics/loadercallbacks.h>
#include "Box2D/Box2D.h"
#include <avalon/physics/Box2dContainer.h>
#include <boost/any.hpp>

namespace avalon {
namespace physics {
namespace loadercallbacks {

avalon::io::TiledMapLoader::Callback createShapes(int filterCategory, bool isSensor)
{
    return [filterCategory](const avalon::io::TiledMapLoader::Configuration& config) {

        float x = boost::any_cast<float>(config.settings.at("x"));
        float y = boost::any_cast<float>(config.settings.at("y"));
        float w = boost::any_cast<float>(config.settings.at("width"));
        float h = boost::any_cast<float>(config.settings.at("height"));

        float density = 0.0;
        float friction = 1.0;
        float restitution = 0.0;
        std::string bodytype = "static";

        if (config.settings.count("friction")) {
            friction = boost::any_cast<float>(config.settings.at("friction"));
        }
        if (config.settings.count("density")) {
            density = boost::any_cast<float>(config.settings.at("density"));
        }
        if (config.settings.count("restitution")) {
            restitution = boost::any_cast<float>(config.settings.at("restitution"));
        }
        if (config.settings.count("bodytype")) {
            bodytype = boost::any_cast<std::string>(config.settings.at("bodytype"));
        }

        std::string type = "static";

        // create the body
        b2BodyDef bodyDef;

        if (type == "static") {
            bodyDef.type = b2_staticBody;
        } else if (type == "dynamic") {
            bodyDef.type = b2_dynamicBody;
        } else if (type == "kinematic") {
            bodyDef.type = b2_kinematicBody;
        } else {
            throw new std::invalid_argument("Unknown box2d type");
        }

        bodyDef.position.Set((x + (w / 2.0f)) / config.box2dContainer->pixelsInMeter,
                             (y + (h / 2.0f)) / config.box2dContainer->pixelsInMeter);
        b2Body* body = config.box2dContainer->world->CreateBody(&bodyDef);

        std::string shapeType = "rectangle";

        if (config.settings.count("polylinePoints") > 0)
            shapeType = "polylinePoints";

        if (config.settings.count("points") > 0)
            shapeType = "points";

        std::shared_ptr<b2Shape> shape;

        if (shapeType == "rectangle") {
            shape = initRectangleShape(w, h, config.box2dContainer->pixelsInMeter);
        } else if (shapeType == "polylinePoints") {
            auto pointList = boost::any_cast<std::list<cocos2d::Point>>(config.settings.at("polylinePoints"));
            if (pointList.size() == 2) {
                int c = 0;
                cocos2d::Point points[2];
                for (auto& p : pointList) {
                    points[c] = p;
                    ++c;
                }
                shape = initEdgeShape(points[0], points[1], config.box2dContainer->pixelsInMeter);
            } else {
                shape = initChainShape(pointList, config.box2dContainer->pixelsInMeter);
            }
        } else if (shapeType == "points") {
            auto pointList = boost::any_cast<std::list<cocos2d::Point>>(config.settings.at("points"));
            if (pointList.size() == 2) {
                int c = 0;
                cocos2d::Point points[2];
                for (auto& p : pointList) {
                    points[c] = p;
                    ++c;
                }
                shape = initEdgeShape(points[0], points[1], config.box2dContainer->pixelsInMeter);
            } else {
                shape = initChainShape(pointList, config.box2dContainer->pixelsInMeter, true);
            }
        }

        // create the fixture
        b2FixtureDef fixtureDef;
        fixtureDef.shape = shape.get();
        body->CreateFixture(&fixtureDef);
    };
}

std::shared_ptr<b2PolygonShape> initRectangleShape(float width, float height, float pixelsInMeter)
{
    auto shape = make_shared<b2PolygonShape>();
    shape->SetAsBox((width / pixelsInMeter) * 0.5f, (height / pixelsInMeter) * 0.5f);
    return shape;
}

std::shared_ptr<b2ChainShape> initChainShape(std::list<cocos2d::Point> points, float pixelsInMeter, bool loop)
{

    std::vector<b2Vec2> vecs;
    vecs.reserve(points.size());

    for (auto& p : points) {
        p = p / pixelsInMeter;
        vecs.push_back({p.x, -p.y});
    }

    auto shape = make_shared<b2ChainShape>();

    if (loop) {
        shape->CreateLoop(&vecs[0], points.size());
    } else {
        shape->CreateChain(&vecs[0], points.size());
    }

    return shape;
}

std::shared_ptr<b2EdgeShape> initEdgeShape(cocos2d::Point p1, cocos2d::Point p2, float pixelsInMeter)
{
    p1 = p1 / pixelsInMeter;
    p2 = p2 / pixelsInMeter;
    auto shape = make_shared<b2EdgeShape>();
    shape->Set({p1.x, p1.y}, {p2.x, p2.y});
    return shape;
}

} // namesapce loadercallbacks
} // namespace physics
} // namespace avalon
<|endoftext|>


<commit_before>//===- lib/Linker/LinkItems.cpp - Link LLVM objects and libraries ---------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by Reid Spencer and is distributed under the
// University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains routines to handle linking together LLVM bytecode files,
// and to handle annoying things like static libraries.
//
//===----------------------------------------------------------------------===//

#include "llvm/Linker.h"
#include "llvm/Module.h"
#include "llvm/ModuleProvider.h"
#include "llvm/PassManager.h"
#include "llvm/ADT/SetOperations.h"
#include "llvm/Bytecode/Reader.h"
#include "llvm/Bytecode/Archive.h"
#include "llvm/Bytecode/WriteBytecodePass.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Transforms/IPO.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Config/config.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FileUtilities.h"
#include "llvm/Support/Timer.h"
#include "llvm/System/Signals.h"
#include "llvm/Support/SystemUtils.h"
#include <algorithm>
#include <fstream>
#include <memory>
#include <set>
using namespace llvm;

static bool
LinkOneLibrary(const char*progname, Module* HeadModule,
               const std::string& Lib,
               const std::vector<std::string>& LibPaths,
               bool Verbose, bool Native) {

  // String in which to receive error messages.
  std::string ErrorMessage;

  // Determine where this library lives.
  std::string Pathname = FindLib(Lib, LibPaths);
  if (Pathname.empty()) {
    // If the pathname does not exist, then simply return if we're doing a
    // native link and give a warning if we're doing a bytecode link.
    if (!Native) {
      std::cerr << progname << ": warning: Cannot find library '"
                << Lib << "'\n";
      return false;
    }
  }

  // A user may specify an ar archive without -l, perhaps because it
  // is not installed as a library. Detect that and link the library.
  if (IsArchive(Pathname)) {
    if (Verbose)
      std::cerr << "Trying to link archive '" << Pathname << "' (-l"
                << Lib << ")\n";

    if (LinkInArchive(HeadModule, Pathname, &ErrorMessage, Verbose)) {
      std::cerr << progname << ": " << ErrorMessage
                << ": Error linking in archive '" << Pathname << "' (-l"
                << Lib << ")\n";
      return true;
    }
  } else {
      std::cerr << progname << ": WARNING: Supposed library -l"
                << Lib << " isn't a library.\n";
  }
  return false;
}

// LinkItems - preserve link order for an arbitrary set of linkage items.
Module*
llvm::LinkItems(const char *progname, const LinkItemList& Items,
                const std::vector<std::string>& LibPaths,
                bool Verbose, bool Native) {

  // Construct the HeadModule to contain the result of the linkage
  std::auto_ptr<Module> HeadModule(new Module(progname));

  // Construct a mutable path list we can add paths to. This list will always
  // have LLVM_LIB_SEARCH_PATH at the end so we place it there now.
  std::vector<std::string> MyLibPaths(LibPaths);
  MyLibPaths.insert(MyLibPaths.begin(),".");
  char* SearchPath = getenv("LLVM_LIB_SEARCH_PATH");
  if (SearchPath)
    MyLibPaths.push_back(SearchPath);

  // For each linkage item ...
  for (LinkItemList::const_iterator I = Items.begin(), E = Items.end();
       I != E; ++I) {
    if (I->second) {
      // Link in the library suggested.
      if (LinkOneLibrary(progname,HeadModule.get(),I->first,MyLibPaths,
                     Verbose,Native))
        return 0;
    } else {
      std::vector<std::string> Files;
      Files.push_back(I->first);
      if (LinkFiles(progname,HeadModule.get(),Files,Verbose))
        return 0;
    }
  }

  // At this point we have processed all the link items provided to us. Since
  // we have an aggregated module at this point, the dependent libraries in
  // that module should also be aggregated with duplicates eliminated. This is
  // now the time to process the dependent libraries to resolve any remaining
  // symbols.
  const Module::LibraryListType& DepLibs = HeadModule->getLibraries();
  for (Module::LibraryListType::const_iterator I = DepLibs.begin(),
      E = DepLibs.end(); I != E; ++I) {
    if(LinkOneLibrary(progname,HeadModule.get(),*I,MyLibPaths,Verbose,Native))
      return 0;
  }

  return HeadModule.release();
}

// BuildLinkItems -- This function
void llvm::BuildLinkItems(
  LinkItemList& Items,
  const cl::list<std::string>& Files,
  const cl::list<std::string>& Libraries) {

  // Build the list of linkage items for LinkItems.

  cl::list<std::string>::const_iterator fileIt = Files.begin();
  cl::list<std::string>::const_iterator libIt  = Libraries.begin();

  int libPos = -1, filePos = -1;
  while ( 1 ) {
    if (libIt != Libraries.end())
      libPos = Libraries.getPosition(libIt - Libraries.begin());
    else
      libPos = -1;
    if (fileIt != Files.end())
      filePos = Files.getPosition(fileIt - Files.begin());
    else
      filePos = -1;

    if (filePos != -1 && (libPos == -1 || filePos < libPos)) {
      // Add a source file
      Items.push_back(std::make_pair(*fileIt++, false));
    } else if (libPos != -1 && (filePos == -1 || libPos < filePos)) {
      // Add a library
      Items.push_back(std::make_pair(*libIt++, true));
    } else {
        break; // we're done with the list
    }
  }
}
<commit_msg>For PR351: \ * Remove redundant static function LinkOneLibrary. \ * Remove unneded #includes \ * Convert FileSupport usage to sys::Path instead<commit_after>//===- lib/Linker/LinkItems.cpp - Link LLVM objects and libraries ---------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by Reid Spencer and is distributed under the
// University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains routines to handle linking together LLVM bytecode files,
// and to handle annoying things like static libraries.
//
//===----------------------------------------------------------------------===//

#include "llvm/Linker.h"
#include "llvm/Module.h"

using namespace llvm;

// LinkItems - preserve link order for an arbitrary set of linkage items.
bool
Linker::LinkInItems(const ItemList& Items) {
  // For each linkage item ...
  for (ItemList::const_iterator I = Items.begin(), E = Items.end();
       I != E; ++I) {
    if (I->second) {
      // Link in the library suggested.
      if (LinkInLibrary(I->first))
        return true;
    } else {
      if (LinkInFile(sys::Path(I->first)))
        return true;
    }
  }

  // At this point we have processed all the link items provided to us. Since
  // we have an aggregated module at this point, the dependent libraries in
  // that module should also be aggregated with duplicates eliminated. This is
  // now the time to process the dependent libraries to resolve any remaining
  // symbols.
  const Module::LibraryListType& DepLibs = Composite->getLibraries();
  for (Module::LibraryListType::const_iterator I = DepLibs.begin(),
      E = DepLibs.end(); I != E; ++I) {
    if(LinkInLibrary(*I))
      return true;
  }

  return false;
}
<|endoftext|>