<commit_before>/*

Copyright (c) 2016, Project OSRM contributors
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

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

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/

#ifndef ENGINE_API_ROUTE_PARAMETERS_HPP
#define ENGINE_API_ROUTE_PARAMETERS_HPP

#include "engine/api/base_parameters.hpp"

#include <vector>

namespace osrm
{
namespace engine
{
namespace api
{

/**
 * Parameters specific to the OSRM Route service.
 *
 * Holds member attributes:
 *  - steps: return route step for each route leg
 *  - alternatives: tries to find alternative routes
 *  - geometries: route geometry encoded in Polyline, Polyline6 or GeoJSON
 *  - overview: adds overview geometry either Full, Simplified (according to highest zoom level) or
 *              False (not at all)
 *  - continue_straight: enable or disable continue_straight (disabled by default)
 *
 * \see OSRM, Coordinate, Hint, Bearing, RouteParame, RouteParameters, TableParameters,
 *      NearestParameters, TripParameters, MatchParameters and TileParameters
 */
struct RouteParameters : public BaseParameters
{
    enum class GeometriesType
    {
        Polyline,
        Polyline6,
        GeoJSON
    };
    enum class OverviewType
    {
        Simplified,
        Full,
        False
    };
    enum class AnnotationsType
    {
        None = 0,
        Duration = 0x01,
        Nodes = 0x02,
        Distance = 0x04,
        Weight = 0x08,
        Datasources = 0x10,
        All = Duration | Nodes | Distance | Weight | Datasources
    };

    RouteParameters() = default;

    template <typename... Args>
    RouteParameters(const bool steps_,
                    const bool alternatives_,
                    const GeometriesType geometries_,
                    const OverviewType overview_,
                    const boost::optional<bool> continue_straight_,
                    Args... args_)
        : BaseParameters{std::forward<Args>(args_)...}, steps{steps_}, alternatives{alternatives_},
          annotations{false}, annotations_type{AnnotationsType::None}, geometries{geometries_},
          overview{overview_}, continue_straight{continue_straight_}
    // Once we perfectly-forward `args` (see #2990) this constructor can delegate to the one below.
    {
    }

    // RouteParameters constructor adding the `annotations` setting in a API-compatible way.
    template <typename... Args>
    RouteParameters(const bool steps_,
                    const bool alternatives_,
                    const bool annotations_,
                    const GeometriesType geometries_,
                    const OverviewType overview_,
                    const boost::optional<bool> continue_straight_,
                    Args... args_)
        : BaseParameters{std::forward<Args>(args_)...}, steps{steps_}, alternatives{alternatives_},
          annotations{annotations_},
          annotations_type{annotations_ ? AnnotationsType::All : AnnotationsType::None},
          geometries{geometries_}, overview{overview_}, continue_straight{continue_straight_}
    {
    }

    // enum based implementation of annotations parameter
    template <typename... Args>
    RouteParameters(const bool steps_,
                    const bool alternatives_,
                    const AnnotationsType annotations_,
                    const GeometriesType geometries_,
                    const OverviewType overview_,
                    const boost::optional<bool> continue_straight_,
                    Args... args_)
        : BaseParameters{std::forward<Args>(args_)...}, steps{steps_}, alternatives{alternatives_},
          annotations_type{annotations_},
          annotations{annotations_ == AnnotationsType::None ? false : true},
          geometries{geometries_}, overview{overview_}, continue_straight{continue_straight_}
    {
    }

    bool steps = false;
    bool alternatives = false;
    bool annotations = false;
    AnnotationsType annotations_type = AnnotationsType::None;
    GeometriesType geometries = GeometriesType::Polyline;
    OverviewType overview = OverviewType::Simplified;
    boost::optional<bool> continue_straight;

    bool IsValid() const { return coordinates.size() >= 2 && BaseParameters::IsValid(); }
};

inline bool operator&(RouteParameters::AnnotationsType lhs, RouteParameters::AnnotationsType rhs)
{
    return static_cast<bool>(
        static_cast<std::underlying_type_t<RouteParameters::AnnotationsType>>(lhs) &
        static_cast<std::underlying_type_t<RouteParameters::AnnotationsType>>(rhs));
}

inline RouteParameters::AnnotationsType operator|(RouteParameters::AnnotationsType lhs,
                                                  RouteParameters::AnnotationsType rhs)
{
    return (RouteParameters::AnnotationsType)(
        static_cast<std::underlying_type_t<RouteParameters::AnnotationsType>>(lhs) |
        static_cast<std::underlying_type_t<RouteParameters::AnnotationsType>>(rhs));
}

inline RouteParameters::AnnotationsType operator|=(RouteParameters::AnnotationsType lhs,
                                                   RouteParameters::AnnotationsType rhs)
{
    return lhs = lhs | rhs;
}
}
}
}

#endif
<commit_msg>fix order of parameter initialisation for route parameters<commit_after>/*

Copyright (c) 2016, Project OSRM contributors
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

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

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/

#ifndef ENGINE_API_ROUTE_PARAMETERS_HPP
#define ENGINE_API_ROUTE_PARAMETERS_HPP

#include "engine/api/base_parameters.hpp"

#include <vector>

namespace osrm
{
namespace engine
{
namespace api
{

/**
 * Parameters specific to the OSRM Route service.
 *
 * Holds member attributes:
 *  - steps: return route step for each route leg
 *  - alternatives: tries to find alternative routes
 *  - geometries: route geometry encoded in Polyline, Polyline6 or GeoJSON
 *  - overview: adds overview geometry either Full, Simplified (according to highest zoom level) or
 *              False (not at all)
 *  - continue_straight: enable or disable continue_straight (disabled by default)
 *
 * \see OSRM, Coordinate, Hint, Bearing, RouteParame, RouteParameters, TableParameters,
 *      NearestParameters, TripParameters, MatchParameters and TileParameters
 */
struct RouteParameters : public BaseParameters
{
    enum class GeometriesType
    {
        Polyline,
        Polyline6,
        GeoJSON
    };
    enum class OverviewType
    {
        Simplified,
        Full,
        False
    };
    enum class AnnotationsType
    {
        None = 0,
        Duration = 0x01,
        Nodes = 0x02,
        Distance = 0x04,
        Weight = 0x08,
        Datasources = 0x10,
        All = Duration | Nodes | Distance | Weight | Datasources
    };

    RouteParameters() = default;

    template <typename... Args>
    RouteParameters(const bool steps_,
                    const bool alternatives_,
                    const GeometriesType geometries_,
                    const OverviewType overview_,
                    const boost::optional<bool> continue_straight_,
                    Args... args_)
        : BaseParameters{std::forward<Args>(args_)...}, steps{steps_}, alternatives{alternatives_},
          annotations{false}, annotations_type{AnnotationsType::None}, geometries{geometries_},
          overview{overview_}, continue_straight{continue_straight_}
    // Once we perfectly-forward `args` (see #2990) this constructor can delegate to the one below.
    {
    }

    // RouteParameters constructor adding the `annotations` setting in a API-compatible way.
    template <typename... Args>
    RouteParameters(const bool steps_,
                    const bool alternatives_,
                    const bool annotations_,
                    const GeometriesType geometries_,
                    const OverviewType overview_,
                    const boost::optional<bool> continue_straight_,
                    Args... args_)
        : BaseParameters{std::forward<Args>(args_)...}, steps{steps_}, alternatives{alternatives_},
          annotations{annotations_},
          annotations_type{annotations_ ? AnnotationsType::All : AnnotationsType::None},
          geometries{geometries_}, overview{overview_}, continue_straight{continue_straight_}
    {
    }

    // enum based implementation of annotations parameter
    template <typename... Args>
    RouteParameters(const bool steps_,
                    const bool alternatives_,
                    const AnnotationsType annotations_,
                    const GeometriesType geometries_,
                    const OverviewType overview_,
                    const boost::optional<bool> continue_straight_,
                    Args... args_)
        : BaseParameters{std::forward<Args>(args_)...}, steps{steps_}, alternatives{alternatives_},
          annotations{annotations_ == AnnotationsType::None ? false : true},
          annotations_type{annotations_}, geometries{geometries_}, overview{overview_},
          continue_straight{continue_straight_}
    {
    }

    bool steps = false;
    bool alternatives = false;
    bool annotations = false;
    AnnotationsType annotations_type = AnnotationsType::None;
    GeometriesType geometries = GeometriesType::Polyline;
    OverviewType overview = OverviewType::Simplified;
    boost::optional<bool> continue_straight;

    bool IsValid() const { return coordinates.size() >= 2 && BaseParameters::IsValid(); }
};

inline bool operator&(RouteParameters::AnnotationsType lhs, RouteParameters::AnnotationsType rhs)
{
    return static_cast<bool>(
        static_cast<std::underlying_type_t<RouteParameters::AnnotationsType>>(lhs) &
        static_cast<std::underlying_type_t<RouteParameters::AnnotationsType>>(rhs));
}

inline RouteParameters::AnnotationsType operator|(RouteParameters::AnnotationsType lhs,
                                                  RouteParameters::AnnotationsType rhs)
{
    return (RouteParameters::AnnotationsType)(
        static_cast<std::underlying_type_t<RouteParameters::AnnotationsType>>(lhs) |
        static_cast<std::underlying_type_t<RouteParameters::AnnotationsType>>(rhs));
}

inline RouteParameters::AnnotationsType operator|=(RouteParameters::AnnotationsType lhs,
                                                   RouteParameters::AnnotationsType rhs)
{
    return lhs = lhs | rhs;
}
}
}
}

#endif
<|endoftext|>


<commit_before>/*

Copyright (c) 2003, Magnus Jonsson, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#ifndef TORRENT_RESOURCE_REQUEST_HPP_INCLUDED
#define TORRENT_RESOURCE_REQUEST_HPP_INCLUDED

#include <boost/integer_traits.hpp>

#ifdef min
#undef min
#endif

#ifdef max
#undef max
#endif

#include "libtorrent/config.hpp"

namespace libtorrent
{
	struct TORRENT_EXPORT resource_request
	{
		resource_request()
			: used(0)
			, min(0)
			, max(0)
			, given(0)
		{}

		int left() const
		{
			assert(given <= max);
			assert(given >= min);
			return given - used;
		}

		static const int inf = boost::integer_traits<int>::const_max;

		// I'm right now actively using:
		int used;

		// given cannot be smaller than min
		// and not greater than max.
		int min;
		int max;

		// Reply: Okay, you're allowed to use this much (a compromise):
		int given;
	};
}

#endif
<commit_msg>fixed bug with the bandwidth throttling<commit_after>/*

Copyright (c) 2003, Magnus Jonsson, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#ifndef TORRENT_RESOURCE_REQUEST_HPP_INCLUDED
#define TORRENT_RESOURCE_REQUEST_HPP_INCLUDED

#include <boost/integer_traits.hpp>

#ifdef min
#undef min
#endif

#ifdef max
#undef max
#endif

#include "libtorrent/config.hpp"

namespace libtorrent
{
	struct TORRENT_EXPORT resource_request
	{
		resource_request()
			: used(0)
			, min(0)
			, max(0)
			, given(0)
		{}

		int left() const
		{
			assert(given <= max);
			assert(given >= min);
			if (used < 0 && (given - used < 0))
				return boost::integer_traits<int>::const_max;
			return given - used;
		}

		static const int inf = boost::integer_traits<int>::const_max;

		// I'm right now actively using:
		int used;

		// given cannot be smaller than min
		// and not greater than max.
		int min;
		int max;

		// Reply: Okay, you're allowed to use this much (a compromise):
		int given;
	};
}

#endif
<|endoftext|>


<commit_before>#include "qtquick1applicationviewer.h"
#include <QApplication>
#include <QDeclarativeComponent>
#include <QDeclarativeEngine>
#include <QDeclarativeContext>

#include "qiscp.h"

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QtQuick1ApplicationViewer viewer;

    qmlRegisterType<qiscp>("org.tal.qiscp", 1, 0, "QISCP");

    viewer.addImportPath(QLatin1String("modules"));
    viewer.setOrientation(QtQuick1ApplicationViewer::ScreenOrientationAuto);
    viewer.setMainQmlFile(QLatin1String("qml/test/main.qml"));
    viewer.showExpanded();

    return app.exec();
}
<commit_msg>Register qiscpInputs with qml<commit_after>#include "qtquick1applicationviewer.h"
#include <QApplication>
#include <QDeclarativeComponent>
#include <QDeclarativeEngine>
#include <QDeclarativeContext>
#include "artworkimageprovider.h"

#include "qiscp.h"

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QtQuick1ApplicationViewer viewer;

    qmlRegisterType<qiscp>("org.tal.qiscp", 1, 0, "QISCP");
    qmlRegisterUncreatableType<qiscpInputs>("org.tal.qiscp", 1, 0, "ISCPInputs", "ISCPInputs can not be created");

    viewer.engine()->addImageProvider(QLatin1String("artwork"), new ArtworkImageProvider());

    viewer.addImportPath(QLatin1String("modules"));
    viewer.setOrientation(QtQuick1ApplicationViewer::ScreenOrientationAuto);
    viewer.setMainQmlFile(QLatin1String("qml/test/main.qml"));
    viewer.showExpanded();

    return app.exec();
}
<|endoftext|>


<commit_before>//
// Copyright (c) 2013-2014 Christoph Malek
// See LICENSE for more information.
//

#ifndef RJ_CORE_GAME_HANDLER_HPP
#define RJ_CORE_GAME_HANDLER_HPP

#include "game.hpp"
#include "game_window.hpp"
#include "render.hpp"
#include <rectojump/game/background/background_manager.hpp>
#include <rectojump/game/editor/editor.hpp>
#include <rectojump/game/main_menu/main_menu.hpp>
#include <rectojump/game/popup_manager.hpp>
#include <rectojump/global/common.hpp>
#include <rectojump/global/config_settings.hpp>
#include <rectojump/shared/data_manager.hpp>
#include <rectojump/shared/level_manager/level_manager.hpp>

#include <mlk/containers/container_utl.h>
#include <mlk/tools/bitset.h>

namespace rj
{
	class game_handler
	{
		game_window& m_game_window;
		data_manager& m_datamgr;
		level_manager& m_lvmgr;

		render<game_handler> m_render;
		background_manager m_backgroundmgr;
		game<game_handler> m_game;
		editor<game_handler, decltype(m_game)> m_editor;
		main_menu<game_handler> m_mainmenu;
		popup_manager<game_handler> m_popupmgr;
		debug_info<game_handler, decltype(m_game)> m_debug_info;

		mlk::ebitset<state, state::num> m_current_states;

	public:
		game_handler(game_window& gw, data_manager& dm, level_manager& lm) :
			m_game_window{gw},
			m_datamgr{dm},
			m_lvmgr{lm},
			m_render{*this},
			m_backgroundmgr{m_render},
			m_game{*this},
			m_editor{*this},
			m_mainmenu{*this},
			m_popupmgr{*this},
			m_debug_info{*this}
		{this->init();}

		void load_level(const level_id& id)
		{
			auto& lv(m_lvmgr.get_level(id));
			if(!lv.is_valid())
			{
				m_popupmgr.create_popup<popup_type::error>("Failed to load level: not a valid level");
				return;
			}

			m_backgroundmgr.clear();

			this->deactivate_state(state::main_menu);
			this->activate_state(state::game);

			m_game.load_level(lv);
		}

		template<typename... Args>
		void render_object(Args&&... args)
		{m_game_window.draw(std::forward<Args>(args)...);}

		template<state active_state, typename On_Input, typename... Input_Type_Args>
		void add_input(On_Input&& func, Input_Type_Args&&... keys_btns)
		{
			static_assert(sizeof...(keys_btns) > 0, "at least one key/button/wheel argument needed");
			add_input_helper<(sizeof...(keys_btns) > 1), typename std::tuple_element<0, std::tuple<Input_Type_Args...>>::type, active_state, On_Input, Input_Type_Args...>
			{*this, std::forward<On_Input>(func), std::forward<Input_Type_Args>(keys_btns)...};
		}

		// getters
		auto get_render() noexcept
		-> decltype(m_render)&
		{return m_render;}

		auto get_gamewindow() noexcept
		-> decltype(m_game_window)&
		{return m_game_window;}

		auto get_game() noexcept
		-> decltype(m_game)&
		{return m_game;}

		auto get_backgroundmgr() noexcept
		-> decltype(m_backgroundmgr)&
		{return m_backgroundmgr;}

		auto get_mainmenu() noexcept
		-> decltype(m_mainmenu)&
		{return m_mainmenu;}

		auto get_datamgr() noexcept
		-> decltype(m_datamgr)&
		{return m_datamgr;}

		auto get_levelmgr() noexcept
		-> decltype(m_lvmgr)&
		{return m_lvmgr;}

		auto get_debuginfo() noexcept
		-> decltype(m_debug_info)&
		{return m_debug_info;}

		auto get_popupmgr() noexcept
		-> decltype(m_popupmgr)&
		{return m_popupmgr;}

	private:
		void init()
		{
			m_current_states |= state::main_menu;

			m_game_window.get_updater().on_update += [this](dur duration){this->update(duration);};
			m_game_window.get_updater().on_render += [this]{this->render();};

			settings::on_changed() +=
			[this]{m_game_window.set_size(settings::get_window_size());};

			m_mainmenu.get_menu_start()->get_items().on_event("editor",
			[this]
			{
				this->deactivate_state(state::main_menu);
				this->activate_state(state::editor);
				m_editor.on_activate();
			});

			this->init_pointers();
			this->init_input();
		}

		void init_pointers() noexcept
		{
			m_game.set_levelmgr(&m_lvmgr);
		}

		void init_input()
		{
			// global input
			on_key_pressed(key::F) +=
			[this]
			{
				m_game_window.toggle_fullscreen();
				rj::settings::set_fullscreen(m_game_window.get_fullscreen());
			};

			on_key_pressed(key::T) +=
			[this]{m_game_window.toggle_titlebar();};

			on_keys_pressed(key::LShift, key::D) +=
			[this]{this->toggle_state(state::debug_info);};

			on_keys_pressed(key::LShift, key::Q) +=
			[this]{m_game_window.stop();};

			// window input
			on_key_pressed(key::Escape) +=
			[this]{if(!this->is_active(state::main_menu)) return; m_game_window.stop();};

			// game input
			on_key_pressed(key::P) +=
			[this]
			{
				if(this->is_active(state::game))
				{
					m_current_states.remove(state::game);
					m_current_states |= state::game_menu;
					return;
				}
				else if(this->is_active(state::game_menu))
				{
					m_current_states.remove(state::game_menu);
					m_current_states |= state::game;
					return;
				}
			};

			on_key_pressed(key::D) +=
			[this]{if(!this->is_active(state::game)) return; m_game.get_world().c_player();};

			on_btn_pressed(btn::Left) +=
			[this](const vec2f& pos)
			{
				if(!this->is_active(state::game))
					return;
				m_game.get_world().c_ent(pos);
			};

			on_btn_pressed(btn::Right) +=
			[this](const vec2f& pos)
			{
				if(!this->is_active(state::game))
					return;
				m_game.get_world().c_ent_death(pos);
			};

			on_key_pressed(key::A) +=
			[this]
			{
				if(!this->is_active(state::game))
					return;
				m_game.get_world().c_world();
			};
		}

		void activate_state(state s)
		{m_current_states |= s;}

		void deactivate_state(state s)
		{m_current_states.remove(s);}

		void toggle_state(state s)
		{m_current_states.toggle(s);}

		bool is_active(state s) const
		{return m_current_states & s;}

		void set_only_state(state s)
		{
			m_current_states.remove_all();
			m_current_states |= s;
		}

		void update(dur duration)
		{
			m_backgroundmgr.update(duration);

			if(this->is_active(state::game))
				m_game.update(duration);

			else if(this->is_active(state::editor))
			{
				m_editor.update(duration);
				m_game.get_world().get_entityhandler().update(duration);
			}

			else if(this->is_active(state::main_menu))
				m_mainmenu.update(duration);

			if(this->is_active(state::debug_info))
				m_debug_info.update(duration);

			m_popupmgr.update(duration);
		}

		void render()
		{
			m_backgroundmgr.render();

			// render game when in game menu
			if(this->is_active(state::game) || this->is_active(state::game_menu))
				m_game.render();

			else if(this->is_active(state::editor))
			{
				m_editor.render();
				m_game.get_world().get_entityhandler().render();
			}

			else if(this->is_active(state::main_menu))
				m_mainmenu.render();

			if(this->is_active(state::debug_info))
				m_debug_info.render();

			m_popupmgr.render();
		}

		// multi_args: true, Input_Type = key
		template<bool multi_args, typename Input_Type, state s, typename On_Input, typename... Input_Type_Args>
		struct add_input_helper
		{
			add_input_helper(const game_handler& gh, On_Input&& func, Input_Type_Args&&... keys)
			{
				on_keys_pressed(std::forward<Input_Type_Args>(keys)...) +=
				[&gh, func]{if(gh.is_active(s)) func();};
			}
		};

		// multi_args: false, Input_Type = key
		template<typename Input_Type, state s, typename On_Input, typename... Input_Type_Args>
		struct add_input_helper<false, Input_Type, s, On_Input, Input_Type_Args...>
		{
			add_input_helper(const game_handler& gh, On_Input&& func, Input_Type_Args&&... k)
			{
				on_key_pressed(std::forward<Input_Type_Args>(k)...) +=
				[&gh, func]{if(gh.is_active(s)) func();};
			}
		};

		// multi_args: false, Input_Type = btn
		template<state s, typename On_Input, typename... Input_Type_Args>
		struct add_input_helper<false, btn, s, On_Input, Input_Type_Args...>
		{
			add_input_helper(const game_handler& gh, On_Input&& func, Input_Type_Args&&... b)
			{
				on_btn_pressed(std::forward<Input_Type_Args>(b)...) +=
				[&gh, func](const vec2f& pos){if(gh.is_active(s)) func(pos);};
			}
		};

		// multi_args: false, Input_Type = wheel
		template<state s, typename On_Input, typename... Input_Type_Args>
		struct add_input_helper<false, wheel, s, On_Input, Input_Type_Args...>
		{
			add_input_helper(const game_handler& gh, On_Input&& func, Input_Type_Args&&... w)
			{
				on_mousewheel(std::forward<Input_Type_Args>(w)...) +=
				[&gh, func](const vec2f& pos){if(gh.is_active(s)) func(pos);};
			}
		};
	};
}

#endif // RJ_CORE_GAME_HANDLER_HPP
<commit_msg>game_handler: added default camera<commit_after>//
// Copyright (c) 2013-2014 Christoph Malek
// See LICENSE for more information.
//

#ifndef RJ_CORE_GAME_HANDLER_HPP
#define RJ_CORE_GAME_HANDLER_HPP

#include "game.hpp"
#include "game_window.hpp"
#include "render.hpp"
#include <rectojump/game/background/background_manager.hpp>
#include <rectojump/game/camera.hpp>
#include <rectojump/game/editor/editor.hpp>
#include <rectojump/game/main_menu/main_menu.hpp>
#include <rectojump/game/popup_manager.hpp>
#include <rectojump/global/common.hpp>
#include <rectojump/global/config_settings.hpp>
#include <rectojump/shared/data_manager.hpp>
#include <rectojump/shared/level_manager/level_manager.hpp>

#include <mlk/containers/container_utl.h>
#include <mlk/tools/bitset.h>

namespace rj
{
	class game_handler
	{
		game_window& m_game_window;
		data_manager& m_datamgr;
		level_manager& m_lvmgr;

		camera m_default_camera;
		render<game_handler> m_render;
		background_manager m_backgroundmgr;
		game<game_handler> m_game;
		editor<game_handler, decltype(m_game)> m_editor;
		main_menu<game_handler> m_mainmenu;
		popup_manager<game_handler> m_popupmgr;
		debug_info<game_handler, decltype(m_game)> m_debug_info;

		mlk::ebitset<state, state::num> m_current_states;

	public:
		game_handler(game_window& gw, data_manager& dm, level_manager& lm) :
			m_game_window{gw},
			m_datamgr{dm},
			m_lvmgr{lm},
			m_default_camera{gw, {settings::get_window_size<vec2f>() / 2.f, settings::get_window_size<vec2f>()}},
			m_render{*this},
			m_backgroundmgr{m_render},
			m_game{*this},
			m_editor{*this},
			m_mainmenu{*this},
			m_popupmgr{*this},
			m_debug_info{*this}
		{this->init();}

		void load_level(const level_id& id)
		{
			auto& lv(m_lvmgr.get_level(id));
			if(!lv.is_valid())
			{
				m_popupmgr.create_popup<popup_type::error>("Failed to load level: not a valid level");
				return;
			}

			m_backgroundmgr.clear();

			this->deactivate_state(state::main_menu);
			this->activate_state(state::game);

			m_game.load_level(lv);
		}

		template<typename... Args>
		void render_object(Args&&... args)
		{m_game_window.draw(std::forward<Args>(args)...);}

		template<state active_state, typename On_Input, typename... Input_Type_Args>
		void add_input(On_Input&& func, Input_Type_Args&&... keys_btns)
		{
			static_assert(sizeof...(keys_btns) > 0, "at least one key/button/wheel argument needed");
			add_input_helper<(sizeof...(keys_btns) > 1), typename std::tuple_element<0, std::tuple<Input_Type_Args...>>::type, active_state, On_Input, Input_Type_Args...>
			{*this, std::forward<On_Input>(func), std::forward<Input_Type_Args>(keys_btns)...};
		}

		// getters
		auto get_render() noexcept
		-> decltype(m_render)&
		{return m_render;}

		auto get_gamewindow() noexcept
		-> decltype(m_game_window)&
		{return m_game_window;}

		auto get_game() noexcept
		-> decltype(m_game)&
		{return m_game;}

		auto get_backgroundmgr() noexcept
		-> decltype(m_backgroundmgr)&
		{return m_backgroundmgr;}

		auto get_mainmenu() noexcept
		-> decltype(m_mainmenu)&
		{return m_mainmenu;}

		auto get_datamgr() noexcept
		-> decltype(m_datamgr)&
		{return m_datamgr;}

		auto get_levelmgr() noexcept
		-> decltype(m_lvmgr)&
		{return m_lvmgr;}

		auto get_debuginfo() noexcept
		-> decltype(m_debug_info)&
		{return m_debug_info;}

		auto get_popupmgr() noexcept
		-> decltype(m_popupmgr)&
		{return m_popupmgr;}

	private:
		void init()
		{
			m_current_states |= state::main_menu;

			m_game_window.get_updater().on_update += [this](dur duration){this->update(duration);};
			m_game_window.get_updater().on_render += [this]{this->render();};

			settings::on_changed() +=
			[this]{m_game_window.set_size(settings::get_window_size());};

			m_mainmenu.get_menu_start()->get_items().on_event("editor",
			[this]
			{
				this->deactivate_state(state::main_menu);
				this->activate_state(state::editor);
				m_editor.on_activate();
			});

			this->init_pointers();
			this->init_input();
		}

		void init_pointers() noexcept
		{
			m_game.set_levelmgr(&m_lvmgr);
		}

		void init_input()
		{
			// global input
			on_key_pressed(key::F) +=
			[this]
			{
				m_game_window.toggle_fullscreen();
				rj::settings::set_fullscreen(m_game_window.get_fullscreen());
			};

			on_key_pressed(key::T) +=
			[this]{m_game_window.toggle_titlebar();};

			on_keys_pressed(key::LShift, key::D) +=
			[this]{this->toggle_state(state::debug_info);};

			on_keys_pressed(key::LShift, key::Q) +=
			[this]{m_game_window.stop();};

			// window input
			on_key_pressed(key::Escape) +=
			[this]{if(!this->is_active(state::main_menu)) return; m_game_window.stop();};

			// game input
			on_key_pressed(key::P) +=
			[this]
			{
				if(this->is_active(state::game))
				{
					m_current_states.remove(state::game);
					m_current_states |= state::game_menu;
					return;
				}
				else if(this->is_active(state::game_menu))
				{
					m_current_states.remove(state::game_menu);
					m_current_states |= state::game;
					return;
				}
			};

			on_key_pressed(key::D) +=
			[this]{if(!this->is_active(state::game)) return; m_game.get_world().c_player();};

			on_btn_pressed(btn::Left) +=
			[this](const vec2f& pos)
			{
				if(!this->is_active(state::game))
					return;
				m_game.get_world().c_ent(pos);
			};

			on_btn_pressed(btn::Right) +=
			[this](const vec2f& pos)
			{
				if(!this->is_active(state::game))
					return;
				m_game.get_world().c_ent_death(pos);
			};

			on_key_pressed(key::A) +=
			[this]
			{
				if(!this->is_active(state::game))
					return;
				m_game.get_world().c_world();
			};
		}

		void activate_state(state s)
		{m_current_states |= s;}

		void deactivate_state(state s)
		{m_current_states.remove(s);}

		void toggle_state(state s)
		{m_current_states.toggle(s);}

		bool is_active(state s) const
		{return m_current_states & s;}

		void set_only_state(state s)
		{
			m_current_states.remove_all();
			m_current_states |= s;
		}

		void update(dur duration)
		{
			m_backgroundmgr.update(duration);

			if(this->is_active(state::game))
				m_game.update(duration);

			else if(this->is_active(state::editor))
			{
				m_editor.update(duration);
				m_game.get_world().get_entityhandler().update(duration);
			}

			else if(this->is_active(state::main_menu))
				m_mainmenu.update(duration);

			if(this->is_active(state::debug_info))
				m_debug_info.update(duration);

			m_popupmgr.update(duration);
		}

		void render()
		{
m_default_camera.set_changes();
			m_backgroundmgr.render();

			// render game when in game menu
			if(this->is_active(state::game) || this->is_active(state::game_menu))
				m_game.render();

			else if(this->is_active(state::editor))
			{
				m_editor.render();
//				m_game.get_world().get_entityhandler().render();
			}

			else if(this->is_active(state::main_menu))
				m_mainmenu.render();
m_default_camera.set_changes();
			if(this->is_active(state::debug_info))
				m_debug_info.render();

			m_popupmgr.render();

		}

		// multi_args: true, Input_Type = key
		template<bool multi_args, typename Input_Type, state s, typename On_Input, typename... Input_Type_Args>
		struct add_input_helper
		{
			add_input_helper(const game_handler& gh, On_Input&& func, Input_Type_Args&&... keys)
			{
				on_keys_pressed(std::forward<Input_Type_Args>(keys)...) +=
				[&gh, func]{if(gh.is_active(s)) func();};
			}
		};

		// multi_args: false, Input_Type = key
		template<typename Input_Type, state s, typename On_Input, typename... Input_Type_Args>
		struct add_input_helper<false, Input_Type, s, On_Input, Input_Type_Args...>
		{
			add_input_helper(const game_handler& gh, On_Input&& func, Input_Type_Args&&... k)
			{
				on_key_pressed(std::forward<Input_Type_Args>(k)...) +=
				[&gh, func]{if(gh.is_active(s)) func();};
			}
		};

		// multi_args: false, Input_Type = btn
		template<state s, typename On_Input, typename... Input_Type_Args>
		struct add_input_helper<false, btn, s, On_Input, Input_Type_Args...>
		{
			add_input_helper(const game_handler& gh, On_Input&& func, Input_Type_Args&&... b)
			{
				on_btn_pressed(std::forward<Input_Type_Args>(b)...) +=
				[&gh, func](const vec2f& pos){if(gh.is_active(s)) func(pos);};
			}
		};

		// multi_args: false, Input_Type = wheel
		template<state s, typename On_Input, typename... Input_Type_Args>
		struct add_input_helper<false, wheel, s, On_Input, Input_Type_Args...>
		{
			add_input_helper(const game_handler& gh, On_Input&& func, Input_Type_Args&&... w)
			{
				on_mousewheel(std::forward<Input_Type_Args>(w)...) +=
				[&gh, func](const vec2f& pos){if(gh.is_active(s)) func(pos);};
			}
		};
	};
}

#endif // RJ_CORE_GAME_HANDLER_HPP
<|endoftext|>


<commit_before>#pragma once

#include <cstdint>

namespace tdc {

    /// \brief Lookup table for the rank operation on 8-bit values.
    ///
    /// At index \c i, this table contains the amount of 1-bits in the binary
    /// representation of the value \c i.
    constexpr uint8_t rank1_8bit[] = {
        0, 1, 1, 2, 1, 2, 2, 3,
        1, 2, 2, 3, 2, 3, 3, 4,
        1, 2, 2, 3, 2, 3, 3, 4,
        2, 3, 3, 4, 3, 4, 4, 5,
        1, 2, 2, 3, 2, 3, 3, 4,
        2, 3, 3, 4, 3, 4, 4, 5,
        2, 3, 3, 4, 3, 4, 4, 5,
        3, 4, 4, 5, 4, 5, 5, 6,
        1, 2, 2, 3, 2, 3, 3, 4,
        2, 3, 3, 4, 3, 4, 4, 5,
        2, 3, 3, 4, 3, 4, 4, 5,
        3, 4, 4, 5, 4, 5, 5, 6,
        2, 3, 3, 4, 3, 4, 4, 5,
        3, 4, 4, 5, 4, 5, 5, 6,
        3, 4, 4, 5, 4, 5, 5, 6,
        4, 5, 5, 6, 5, 6, 6, 7,
        1, 2, 2, 3, 2, 3, 3, 4,
        2, 3, 3, 4, 3, 4, 4, 5,
        2, 3, 3, 4, 3, 4, 4, 5,
        3, 4, 4, 5, 4, 5, 5, 6,
        2, 3, 3, 4, 3, 4, 4, 5,
        3, 4, 4, 5, 4, 5, 5, 6,
        3, 4, 4, 5, 4, 5, 5, 6,
        4, 5, 5, 6, 5, 6, 6, 7,
        2, 3, 3, 4, 3, 4, 4, 5,
        3, 4, 4, 5, 4, 5, 5, 6,
        3, 4, 4, 5, 4, 5, 5, 6,
        4, 5, 5, 6, 5, 6, 6, 7,
        3, 4, 4, 5, 4, 5, 5, 6,
        4, 5, 5, 6, 5, 6, 6, 7,
        4, 5, 5, 6, 5, 6, 6, 7,
        5, 6, 6, 7, 6, 7, 7, 8
    };

    /// \brief Computes the amount of 1-bits in the binary representation of
    ///        the given 8-bit value.
    /// \param v the value in question
    /// \return the amount of 1-bits in the value's binary representation
    inline constexpr uint8_t rank1(uint8_t v) {
        return rank1_8bit[v];
    }

    /// \brief Computes the amount of 1-bits in the binary representation of
    ///        the given 16-bit value.
    /// \param v the value in question
    /// \return the amount of 1-bits in the value's binary representation
    inline constexpr uint8_t rank1(uint16_t v) {
        return rank1_8bit[uint8_t(v >> 8)] + rank1_8bit[uint8_t(v)];
    }

    /// \brief Computes the amount of 1-bits in the binary representation of
    ///        the given 32-bit value.
    /// \param v the value in question
    /// \return the amount of 1-bits in the value's binary representation
    inline constexpr uint8_t rank1(uint32_t v) {
        return rank1_8bit[uint8_t(v >> 24)] + rank1_8bit[uint8_t(v >> 16)] +
               rank1_8bit[uint8_t(v >>  8)] + rank1_8bit[uint8_t(v)];
    }

    /// \brief Computes the amount of 1-bits in the binary representation of
    ///        the given 64-bit value.
    /// \param v the value in question
    /// \return the amount of 1-bits in the value's binary representation
    inline constexpr uint8_t rank1(uint64_t v) {
        return rank1_8bit[uint8_t(v >> 56)] + rank1_8bit[uint8_t(v >> 48)] +
               rank1_8bit[uint8_t(v >> 40)] + rank1_8bit[uint8_t(v >> 32)] +
               rank1_8bit[uint8_t(v >> 24)] + rank1_8bit[uint8_t(v >> 16)] +
               rank1_8bit[uint8_t(v >>  8)] + rank1_8bit[uint8_t(v)];
    }

    /// \brief Computes the amount of 1-bits in an interval of the
    ///        binary representation of the given 8-bit value.
    ///
    /// The exact rank value computed is that of the interval [0,m] in
    /// zero-based LSBF order.
    ///
    /// \param v the value in question
    /// \param m the most significant bit (up until which to count)
    /// \return the amount of 1-bits in the given interval
    inline constexpr uint8_t rank1(uint8_t v, uint8_t m) {
        DCHECK(m < 8) << "m=" << m;
        const uint8_t mask = 0xFFU >> (7-m);
        return rank1(uint8_t(v & mask));
    }

    /// \brief Computes the amount of 1-bits in an interval of the
    ///        binary representation of the given 8-bit value.
    ///
    /// The exact rank value computed is that of the interval [l,m] in
    /// zero-based LSBF order.
    ///
    /// \param v the value in question
    /// \param l the least significant bit (from which the counting starts)
    /// \param m the most significant bit (up until which to count)
    /// \return the amount of 1-bits in the given interval
    inline constexpr uint8_t rank1(uint8_t v, uint8_t l, uint8_t m) {
        DCHECK(l < 8 && m < 8 && l <= m) << "l=" << l << ",m=" << m;
        const uint8_t mask_m = UINT8_MAX >> (7-m);
        const uint8_t mask_l = UINT8_MAX << l;
        return rank1(uint8_t(v & mask_m & mask_l));
    }

    /// \brief Computes the amount of 1-bits in an interval of the
    ///        binary representation of the given 16-bit value.
    ///
    /// The exact rank value computed is that of the interval [0,m] in
    /// zero-based LSBF order.
    ///
    /// \param v the value in question
    /// \param m the most significant bit (up until which to count)
    /// \return the amount of 1-bits in the given interval
    inline constexpr uint8_t rank1(uint16_t v, uint8_t m) {
        DCHECK(m < 16) << "m=" << m;
        const uint16_t mask = UINT16_MAX >> (15-m);
        return rank1(uint16_t(v & mask));
    }

    /// \brief Computes the amount of 1-bits in an interval of the
    ///        binary representation of the given 16-bit value.
    ///
    /// The exact rank value computed is that of the interval [l,m] in
    /// zero-based LSBF order.
    ///
    /// \param v the value in question
    /// \param l the least significant bit (from which the counting starts)
    /// \param m the most significant bit (up until which to count)
    /// \return the amount of 1-bits in the given interval
    inline constexpr uint8_t rank1(uint16_t v, uint8_t l, uint8_t m) {
        DCHECK(l < 16 && m < 16 && l <= m) << "l=" << l << ",m=" << m;
        const uint16_t mask_m = UINT16_MAX >> (15-m);
        const uint16_t mask_l = UINT16_MAX << l;
        return rank1(uint16_t(v & mask_m & mask_l));
    }

    /// \brief Computes the amount of 1-bits in an interval of the
    ///        binary representation of the given 32-bit value.
    ///
    /// The exact rank value computed is that of the interval [0,m] in
    /// zero-based LSBF order.
    ///
    /// \param v the value in question
    /// \param m the most significant bit (up until which to count)
    /// \return the amount of 1-bits in the given interval
    inline constexpr uint8_t rank1(uint32_t v, uint8_t m) {
        DCHECK(m < 32) << "m=" << m;
        const uint32_t mask = UINT32_MAX >> (31-m);
        return rank1(uint32_t(v & mask));
    }

    /// \brief Computes the amount of 1-bits in an interval of the
    ///        binary representation of the given 32-bit value.
    ///
    /// The exact rank value computed is that of the interval [l,m] in
    /// zero-based LSBF order.
    ///
    /// \param v the value in question
    /// \param l the least significant bit (from which the counting starts)
    /// \param m the most significant bit (up until which to count)
    /// \return the amount of 1-bits in the given interval
    inline constexpr uint8_t rank1(uint32_t v, uint8_t l, uint8_t m) {
        DCHECK(l < 32 && m < 32 && l <= m) << "l=" << l << ",m=" << m;
        const uint32_t mask_m = UINT32_MAX >> (31-m);
        const uint32_t mask_l = UINT32_MAX << l;
        return rank1(uint32_t(v & mask_m & mask_l));
    }

    /// \brief Computes the amount of 1-bits in an interval of the
    ///        binary representation of the given 64-bit value.
    ///
    /// The exact rank value computed is that of the interval [0,m] in
    /// zero-based LSBF order.
    ///
    /// \param v the value in question
    /// \param m the most significant bit (up until which to count)
    /// \return the amount of 1-bits in the given interval
    inline constexpr uint8_t rank1(uint64_t v, uint8_t m) {
        DCHECK(m < 64) << "m=" << m;
        const uint64_t mask = UINT64_MAX >> (63-m);
        return rank1(uint64_t(v & mask));
    }

    /// \brief Computes the amount of 1-bits in an interval of the
    ///        binary representation of the given 64-bit value.
    ///
    /// The exact rank value computed is that of the interval [l,m] in
    /// zero-based LSBF order.
    ///
    /// \param v the value in question
    /// \param l the least significant bit (from which the counting starts)
    /// \param m the most significant bit (up until which to count)
    /// \return the amount of 1-bits in the given interval
    inline constexpr uint8_t rank1(uint64_t v, uint8_t l, uint8_t m) {
        DCHECK(l < 64 && m < 64 && l <= m) << "l=" << l << ",m=" << m;
        const uint64_t mask_m = UINT64_MAX >> (63-m);
        const uint64_t mask_l = UINT64_MAX << l;
        return rank1(uint64_t(v & mask_m & mask_l));
    }

    inline constexpr uint8_t rank0(uint8_t v) {
        return uint8_t(8) - rank1(v);
    }

    inline constexpr uint8_t rank0(uint16_t v) {
        return uint8_t(16) - rank1(v);
    }

    inline constexpr uint8_t rank0(uint32_t v) {
        return uint8_t(32) - rank1(v);
    }

    inline constexpr uint8_t rank0(uint64_t v) {
        return uint8_t(64) - rank1(v);
    }

    template<typename T>
    inline constexpr uint8_t rank0(T v, uint8_t m) {
        return (m + 1) - rank1(v, m);
    }

    template<typename T>
    inline constexpr uint8_t rank0(T v, uint8_t l, uint8_t m) {
        return (m - l + 1) - rank1(v, l, m);
    }

} //ns
<commit_msg>Improve performance of rank for values > 8-bit using popcount<commit_after>#pragma once

#include <cstdint>

namespace tdc {

    /// \brief Lookup table for the rank operation on 8-bit values.
    ///
    /// At index \c i, this table contains the amount of 1-bits in the binary
    /// representation of the value \c i.
    constexpr uint8_t rank1_8bit[] = {
        0, 1, 1, 2, 1, 2, 2, 3,
        1, 2, 2, 3, 2, 3, 3, 4,
        1, 2, 2, 3, 2, 3, 3, 4,
        2, 3, 3, 4, 3, 4, 4, 5,
        1, 2, 2, 3, 2, 3, 3, 4,
        2, 3, 3, 4, 3, 4, 4, 5,
        2, 3, 3, 4, 3, 4, 4, 5,
        3, 4, 4, 5, 4, 5, 5, 6,
        1, 2, 2, 3, 2, 3, 3, 4,
        2, 3, 3, 4, 3, 4, 4, 5,
        2, 3, 3, 4, 3, 4, 4, 5,
        3, 4, 4, 5, 4, 5, 5, 6,
        2, 3, 3, 4, 3, 4, 4, 5,
        3, 4, 4, 5, 4, 5, 5, 6,
        3, 4, 4, 5, 4, 5, 5, 6,
        4, 5, 5, 6, 5, 6, 6, 7,
        1, 2, 2, 3, 2, 3, 3, 4,
        2, 3, 3, 4, 3, 4, 4, 5,
        2, 3, 3, 4, 3, 4, 4, 5,
        3, 4, 4, 5, 4, 5, 5, 6,
        2, 3, 3, 4, 3, 4, 4, 5,
        3, 4, 4, 5, 4, 5, 5, 6,
        3, 4, 4, 5, 4, 5, 5, 6,
        4, 5, 5, 6, 5, 6, 6, 7,
        2, 3, 3, 4, 3, 4, 4, 5,
        3, 4, 4, 5, 4, 5, 5, 6,
        3, 4, 4, 5, 4, 5, 5, 6,
        4, 5, 5, 6, 5, 6, 6, 7,
        3, 4, 4, 5, 4, 5, 5, 6,
        4, 5, 5, 6, 5, 6, 6, 7,
        4, 5, 5, 6, 5, 6, 6, 7,
        5, 6, 6, 7, 6, 7, 7, 8
    };

    /// \brief Computes the amount of 1-bits in the binary representation of
    ///        the given 8-bit value.
    /// \param v the value in question
    /// \return the amount of 1-bits in the value's binary representation
    inline constexpr uint8_t rank1(uint8_t v) {
        return rank1_8bit[v];
    }

    /// \brief Computes the amount of 1-bits in the binary representation of
    ///        the given 16-bit value.
    /// \param v the value in question
    /// \return the amount of 1-bits in the value's binary representation
    inline constexpr uint8_t rank1(uint16_t v) {
        return __builtin_popcount(v);
    }

    /// \brief Computes the amount of 1-bits in the binary representation of
    ///        the given 32-bit value.
    /// \param v the value in question
    /// \return the amount of 1-bits in the value's binary representation
    inline constexpr uint8_t rank1(uint32_t v) {
        return __builtin_popcount(v);
    }

    /// \brief Computes the amount of 1-bits in the binary representation of
    ///        the given 64-bit value.
    /// \param v the value in question
    /// \return the amount of 1-bits in the value's binary representation
    inline constexpr uint8_t rank1(uint64_t v) {
        return __builtin_popcountll(v);
    }

    /// \brief Computes the amount of 1-bits in an interval of the
    ///        binary representation of the given 8-bit value.
    ///
    /// The exact rank value computed is that of the interval [0,m] in
    /// zero-based LSBF order.
    ///
    /// \param v the value in question
    /// \param m the most significant bit (up until which to count)
    /// \return the amount of 1-bits in the given interval
    inline constexpr uint8_t rank1(uint8_t v, uint8_t m) {
        DCHECK(m < 8) << "m=" << m;
        const uint8_t mask = 0xFFU >> (7-m);
        return rank1_8bit[v & mask];
    }

    /// \brief Computes the amount of 1-bits in an interval of the
    ///        binary representation of the given 8-bit value.
    ///
    /// The exact rank value computed is that of the interval [l,m] in
    /// zero-based LSBF order.
    ///
    /// \param v the value in question
    /// \param l the least significant bit (from which the counting starts)
    /// \param m the most significant bit (up until which to count)
    /// \return the amount of 1-bits in the given interval
    inline constexpr uint8_t rank1(uint8_t v, uint8_t l, uint8_t m) {
        DCHECK(l < 8 && m < 8 && l <= m) << "l=" << l << ",m=" << m;
        const uint8_t mask_m = UINT8_MAX >> (7-m);
        const uint8_t mask_l = UINT8_MAX << l;
        return rank1_8bit[v & mask_m & mask_l];
    }

    /// \brief Computes the amount of 1-bits in an interval of the
    ///        binary representation of the given 16-bit value.
    ///
    /// The exact rank value computed is that of the interval [0,m] in
    /// zero-based LSBF order.
    ///
    /// \param v the value in question
    /// \param m the most significant bit (up until which to count)
    /// \return the amount of 1-bits in the given interval
    inline constexpr uint8_t rank1(uint16_t v, uint8_t m) {
        DCHECK(m < 16) << "m=" << m;
        const uint16_t mask = UINT16_MAX >> (15-m);
        return __builtin_popcount(v & mask);
    }

    /// \brief Computes the amount of 1-bits in an interval of the
    ///        binary representation of the given 16-bit value.
    ///
    /// The exact rank value computed is that of the interval [l,m] in
    /// zero-based LSBF order.
    ///
    /// \param v the value in question
    /// \param l the least significant bit (from which the counting starts)
    /// \param m the most significant bit (up until which to count)
    /// \return the amount of 1-bits in the given interval
    inline constexpr uint8_t rank1(uint16_t v, uint8_t l, uint8_t m) {
        DCHECK(l < 16 && m < 16 && l <= m) << "l=" << l << ",m=" << m;
        const uint16_t mask_m = UINT16_MAX >> (15-m);
        const uint16_t mask_l = UINT16_MAX << l;
        return __builtin_popcount(v & mask_m & mask_l);
    }

    /// \brief Computes the amount of 1-bits in an interval of the
    ///        binary representation of the given 32-bit value.
    ///
    /// The exact rank value computed is that of the interval [0,m] in
    /// zero-based LSBF order.
    ///
    /// \param v the value in question
    /// \param m the most significant bit (up until which to count)
    /// \return the amount of 1-bits in the given interval
    inline constexpr uint8_t rank1(uint32_t v, uint8_t m) {
        DCHECK(m < 32) << "m=" << m;
        const uint32_t mask = UINT32_MAX >> (31-m);
        return __builtin_popcount(v & mask);
    }

    /// \brief Computes the amount of 1-bits in an interval of the
    ///        binary representation of the given 32-bit value.
    ///
    /// The exact rank value computed is that of the interval [l,m] in
    /// zero-based LSBF order.
    ///
    /// \param v the value in question
    /// \param l the least significant bit (from which the counting starts)
    /// \param m the most significant bit (up until which to count)
    /// \return the amount of 1-bits in the given interval
    inline constexpr uint8_t rank1(uint32_t v, uint8_t l, uint8_t m) {
        DCHECK(l < 32 && m < 32 && l <= m) << "l=" << l << ",m=" << m;
        const uint32_t mask_m = UINT32_MAX >> (31-m);
        const uint32_t mask_l = UINT32_MAX << l;
        return __builtin_popcount(v & mask_m & mask_l);
    }

    /// \brief Computes the amount of 1-bits in an interval of the
    ///        binary representation of the given 64-bit value.
    ///
    /// The exact rank value computed is that of the interval [0,m] in
    /// zero-based LSBF order.
    ///
    /// \param v the value in question
    /// \param m the most significant bit (up until which to count)
    /// \return the amount of 1-bits in the given interval
    inline constexpr uint8_t rank1(uint64_t v, uint8_t m) {
        DCHECK(m < 64) << "m=" << m;
        const uint64_t mask = UINT64_MAX >> (63-m);
        return __builtin_popcountll(v & mask);
    }

    /// \brief Computes the amount of 1-bits in an interval of the
    ///        binary representation of the given 64-bit value.
    ///
    /// The exact rank value computed is that of the interval [l,m] in
    /// zero-based LSBF order.
    ///
    /// \param v the value in question
    /// \param l the least significant bit (from which the counting starts)
    /// \param m the most significant bit (up until which to count)
    /// \return the amount of 1-bits in the given interval
    inline constexpr uint8_t rank1(uint64_t v, uint8_t l, uint8_t m) {
        DCHECK(l < 64 && m < 64 && l <= m) << "l=" << l << ",m=" << m;
        const uint64_t mask_m = UINT64_MAX >> (63-m);
        const uint64_t mask_l = UINT64_MAX << l;
        return __builtin_popcountll(v & mask_m & mask_l);
    }

    inline constexpr uint8_t rank0(uint8_t v) {
        return uint8_t(8) - rank1(v);
    }

    inline constexpr uint8_t rank0(uint16_t v) {
        return uint8_t(16) - rank1(v);
    }

    inline constexpr uint8_t rank0(uint32_t v) {
        return uint8_t(32) - rank1(v);
    }

    inline constexpr uint8_t rank0(uint64_t v) {
        return uint8_t(64) - rank1(v);
    }

    template<typename T>
    inline constexpr uint8_t rank0(T v, uint8_t m) {
        return (m + 1) - rank1(v, m);
    }

    template<typename T>
    inline constexpr uint8_t rank0(T v, uint8_t l, uint8_t m) {
        return (m - l + 1) - rank1(v, l, m);
    }

} //ns
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES)
 *
 * This file is part of Orfeo Toolbox
 *
 *     https://www.orfeo-toolbox.org/
 *
 * 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 "otbShaderRegistry.h"
#include <GL/glew.h>

namespace otb
{

ShaderRegistry::Pointer ShaderRegistry::m_Instance;

ShaderRegistry::ShaderRegistry()
  : m_ShaderMap()
{}

ShaderRegistry::~ShaderRegistry()
{
  this->ClearShaders();
}

ShaderRegistry::Pointer  ShaderRegistry::Instance()
{
  if(m_Instance.IsNull())
    {
    m_Instance = ShaderRegistry::New();
    GLenum err = glewInit();
    if (err != GLEW_OK)
      {
      itkGenericExceptionMacro(<< "Failed to initialize GLEW: "<< glewGetErrorString(err));
      }
    }

  return m_Instance;
}

void ShaderRegistry::RegisterShader(const std::string& name, const std::string& vSource, const std::string& fSource)
{
  if(m_ShaderMap.count(name) != 0)
    {
    itkExceptionMacro(<<"A shader with name "<<name<<" has already been registered!");
    }

  if(vSource.empty() && fSource.empty())
    {
    itkExceptionMacro(<<"No shader sources supplied!");
    }

  GLuint vShader = 0;
  if(!vSource.empty())
    {
    vShader = CompileShader(GL_VERTEX_SHADER, name, vSource);
    }

  GLuint fShader = 0;
  if(!fSource.empty())
    {
    fShader = CompileShader(GL_FRAGMENT_SHADER, name, fSource);
    }

  // create a new program for these shader objects
  GLuint program = glCreateProgram();

  // attach the shader objects to the current program, and flag them for
  // deletion, they will be actually destroyed when the program is deleted.
  if(vShader)
    {
    glAttachShader(program,vShader);
    glDeleteShader(vShader);
    }
  if(fShader)
    {
    glAttachShader(program,fShader);
    glDeleteShader(fShader);
    }
  glLinkProgram(program);

  m_ShaderMap[name] = program;
}

bool ShaderRegistry::UnregisterShader(const std::string& name)
{
  if(m_ShaderMap.count(name) != 0)
    {
    glDeleteProgram(m_ShaderMap[name]);
    m_ShaderMap.erase(name);
    return true;
    }
  return false;
}

bool ShaderRegistry::IsShaderRegistered(const std::string& name) const
{
  return (m_ShaderMap.count(name) != 0);
}

bool ShaderRegistry::LoadShader(const std::string& name)
{
  if(!IsShaderRegistered(name))
    {
    return false;
    }
  glUseProgram(m_ShaderMap[name]);
  return true;
}

void ShaderRegistry::UnloadShader()
{
  glUseProgram(0);
}

void ShaderRegistry::ClearShaders()
{
  std::vector<std::string> keys;

  for(ShaderMapType::iterator it = m_ShaderMap.begin();
      it!=m_ShaderMap.end();++it)
    {
    keys.push_back(it->first);
    }

  for(std::vector<std::string>::iterator it = keys.begin();
      it!=keys.end();++it)
    {
    UnregisterShader(*it);
    }

  m_ShaderMap.clear();
}

unsigned int ShaderRegistry::GetShaderProgram(const std::string& name)
{
  if(m_ShaderMap.count(name) == 0)
    {
    itkExceptionMacro(<<"No shader with name "<<name<<" has been registered.");
    }
  return m_ShaderMap[name];
}

unsigned int ShaderRegistry::CompileShader(int stype, const std::string& name, const std::string& src)
{
  GLuint shader = glCreateShader(stype);

  // compile the sources
  const char * source_cstr = src.c_str();
  glShaderSource(shader, 1, &source_cstr,nullptr);
  glCompileShader(shader);

  GLint compiled;
  glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled);
  if(!compiled)
    {
    // get the logs
    int length;
    glGetShaderiv(shader, GL_INFO_LOG_LENGTH , &length);
    char * logs = new char[length];
    glGetShaderInfoLog(shader,1000,&length,logs);
    std::string slogs = logs;
    delete [] logs;
    logs = nullptr;

    // Shader must be destroyed here!
    glDeleteShader( shader );
    shader = 0;

    itkExceptionMacro(<<"Shader "<<name<<" with sources "<<src<<" failed to compile: "<<slogs);
    }
  return shader;
}

}
<commit_msg>REFAC: #1930: force GLEW to use modern OpenGL during glewInit()<commit_after>/*
 * Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES)
 *
 * This file is part of Orfeo Toolbox
 *
 *     https://www.orfeo-toolbox.org/
 *
 * 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 "otbShaderRegistry.h"
#include <GL/glew.h>

namespace otb
{

ShaderRegistry::Pointer ShaderRegistry::m_Instance;

ShaderRegistry::ShaderRegistry()
  : m_ShaderMap()
{}

ShaderRegistry::~ShaderRegistry()
{
  this->ClearShaders();
}

ShaderRegistry::Pointer  ShaderRegistry::Instance()
{
  if(m_Instance.IsNull())
    {
    m_Instance = ShaderRegistry::New();
    glewExperimental = GL_TRUE;
    GLenum err = glewInit();
    if (err != GLEW_OK)
      {
      itkGenericExceptionMacro(<< "Failed to initialize GLEW: "<< glewGetErrorString(err));
      }
    }

  return m_Instance;
}

void ShaderRegistry::RegisterShader(const std::string& name, const std::string& vSource, const std::string& fSource)
{
  if(m_ShaderMap.count(name) != 0)
    {
    itkExceptionMacro(<<"A shader with name "<<name<<" has already been registered!");
    }

  if(vSource.empty() && fSource.empty())
    {
    itkExceptionMacro(<<"No shader sources supplied!");
    }

  GLuint vShader = 0;
  if(!vSource.empty())
    {
    vShader = CompileShader(GL_VERTEX_SHADER, name, vSource);
    }

  GLuint fShader = 0;
  if(!fSource.empty())
    {
    fShader = CompileShader(GL_FRAGMENT_SHADER, name, fSource);
    }

  // create a new program for these shader objects
  GLuint program = glCreateProgram();

  // attach the shader objects to the current program, and flag them for
  // deletion, they will be actually destroyed when the program is deleted.
  if(vShader)
    {
    glAttachShader(program,vShader);
    glDeleteShader(vShader);
    }
  if(fShader)
    {
    glAttachShader(program,fShader);
    glDeleteShader(fShader);
    }
  glLinkProgram(program);

  m_ShaderMap[name] = program;
}

bool ShaderRegistry::UnregisterShader(const std::string& name)
{
  if(m_ShaderMap.count(name) != 0)
    {
    glDeleteProgram(m_ShaderMap[name]);
    m_ShaderMap.erase(name);
    return true;
    }
  return false;
}

bool ShaderRegistry::IsShaderRegistered(const std::string& name) const
{
  return (m_ShaderMap.count(name) != 0);
}

bool ShaderRegistry::LoadShader(const std::string& name)
{
  if(!IsShaderRegistered(name))
    {
    return false;
    }
  glUseProgram(m_ShaderMap[name]);
  return true;
}

void ShaderRegistry::UnloadShader()
{
  glUseProgram(0);
}

void ShaderRegistry::ClearShaders()
{
  std::vector<std::string> keys;

  for(ShaderMapType::iterator it = m_ShaderMap.begin();
      it!=m_ShaderMap.end();++it)
    {
    keys.push_back(it->first);
    }

  for(std::vector<std::string>::iterator it = keys.begin();
      it!=keys.end();++it)
    {
    UnregisterShader(*it);
    }

  m_ShaderMap.clear();
}

unsigned int ShaderRegistry::GetShaderProgram(const std::string& name)
{
  if(m_ShaderMap.count(name) == 0)
    {
    itkExceptionMacro(<<"No shader with name "<<name<<" has been registered.");
    }
  return m_ShaderMap[name];
}

unsigned int ShaderRegistry::CompileShader(int stype, const std::string& name, const std::string& src)
{
  GLuint shader = glCreateShader(stype);

  // compile the sources
  const char * source_cstr = src.c_str();
  glShaderSource(shader, 1, &source_cstr,nullptr);
  glCompileShader(shader);

  GLint compiled;
  glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled);
  if(!compiled)
    {
    // get the logs
    int length;
    glGetShaderiv(shader, GL_INFO_LOG_LENGTH , &length);
    char * logs = new char[length];
    glGetShaderInfoLog(shader,1000,&length,logs);
    std::string slogs = logs;
    delete [] logs;
    logs = nullptr;

    // Shader must be destroyed here!
    glDeleteShader( shader );
    shader = 0;

    itkExceptionMacro(<<"Shader "<<name<<" with sources "<<src<<" failed to compile: "<<slogs);
    }
  return shader;
}

}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: svdibrow.hxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 14:43:34 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _SVDIBROW_HXX
#define _SVDIBROW_HXX

#ifndef _SVX_BRWBOX_HXX //autogen
#include <svtools/brwbox.hxx>
#endif

#ifndef _SV_EDIT_HXX //autogen
#include <vcl/edit.hxx>
#endif

#ifndef _SV_FLOATWIN_HXX //autogen
#include <vcl/floatwin.hxx>
#endif

class SfxItemSet;
class ImpItemListRow;
class BrowserMouseEvent;

class _SdrItemBrowserControl: public BrowseBox
{
friend class ImpItemEdit;
    Container aList;
    long nAktPaintRow;
    Edit* pEditControl;
    XubString aWNamMerk;
    Link aEntryChangedHdl;
    Link aSetDirtyHdl;
    ImpItemListRow* pAktChangeEntry;
    long   nLastWhichOfs;
    USHORT nLastWhich;
    USHORT nLastWhichOben;
    USHORT nLastWhichUnten;
    FASTBOOL bWhichesButNames;
    FASTBOOL bDontHideIneffectiveItems;
    FASTBOOL bDontSortItems;
    FASTBOOL bShowWhichIds;
    FASTBOOL bShowRealValues;
private:
#if _SOLAR__PRIVATE
    void ImpCtor();
    void ImpSetEntry(const ImpItemListRow& rEntry, ULONG nEntryNum);
    ImpItemListRow* ImpGetEntry(ULONG nPos) const { return (ImpItemListRow*)aList.GetObject(nPos); }
    void ImpSaveWhich();
    void ImpRestoreWhich();
#endif // __PRIVATE
protected:
    virtual long GetRowCount() const;
    virtual BOOL SeekRow(long nRow);
    virtual void PaintField(OutputDevice& rDev, const Rectangle& rRect, USHORT nColumnId) const;
#if SUPD >= 345
    virtual void DoubleClick(const BrowserMouseEvent&);
#else
    virtual void DoubleClick();
#endif
    virtual void KeyInput(const KeyEvent& rEvt);
    virtual void Select();
    virtual void SetDirty(); // wird z.B. bei Modusumschaltungen gerufen
    virtual Rectangle GetFieldCharacterBounds(sal_Int32 _nRow,sal_Int32 _nColumnPos,sal_Int32 nIndex);
    virtual sal_Int32 GetFieldIndexAtPoint(sal_Int32 _nRow,sal_Int32 _nColumnPos,const Point& _rPoint);
public:
    _SdrItemBrowserControl(Window* pParent, WinBits nBits=WB_3DLOOK|WB_BORDER|WB_TABSTOP);
    virtual ~_SdrItemBrowserControl();
    void Clear();
    void SetAttributes(const SfxItemSet* pAttr, const SfxItemSet* p2ndSet=NULL);
    ULONG GetCurrentPos() const;
    USHORT GetCurrentWhich() const;
    virtual FASTBOOL BegChangeEntry(ULONG nPos);
    virtual FASTBOOL EndChangeEntry();
    virtual void     BrkChangeEntry();

    /** GetCellText returns the text at the given position
        @param  _nRow
            the number of the row
        @param  _nColId
            the ID of the column
        @return
            the text out of the cell
    */
    virtual String  GetCellText(long _nRow, USHORT _nColId) const;

    const ImpItemListRow* GetAktChangeEntry() const { return pAktChangeEntry; }
    XubString GetNewEntryValue() const                 { return pEditControl->GetText(); }
    void SetEntryChangedHdl(const Link& rLink)      { aEntryChangedHdl=rLink; }
    const Link& GetEntryChangedHdl() const          { return aEntryChangedHdl; }
    void SetSetDirtyHdl(const Link& rLink)          { aSetDirtyHdl=rLink; }
    const Link& GetSetDirtyHdl() const              { return aSetDirtyHdl; }
};

#define WB_STDSIZEABLEDOCKWIN  (WB_STDDOCKWIN|WB_3DLOOK|WB_CLOSEABLE|WB_SIZEMOVE)
#define WB_STDSIZEABLEFLOATWIN (WB_STDFLOATWIN|WB_3DLOOK|WB_CLOSEABLE|WB_SIZEMOVE)

class _SdrItemBrowserWindow: public FloatingWindow {
    _SdrItemBrowserControl aBrowse;
public:
    _SdrItemBrowserWindow(Window* pParent, WinBits nBits=WB_STDSIZEABLEDOCKWIN);
    virtual ~_SdrItemBrowserWindow();
    virtual void Resize();
    virtual void GetFocus();
    void Clear()                                            { aBrowse.Clear(); }
    void SetAttributes(const SfxItemSet* pAttr, const SfxItemSet* p2ndSet=NULL) { aBrowse.SetAttributes(pAttr,p2ndSet); }
    void SetFloatingMode(FASTBOOL /*bOn*/) {}
    const _SdrItemBrowserControl& GetBrowserControl() const { return aBrowse; }
    _SdrItemBrowserControl& GetBrowserControl()             { return aBrowse; }
};

class SdrView;

class SdrItemBrowser: public _SdrItemBrowserWindow {
    Timer aIdleTimer;
    SdrView* pView;
    FASTBOOL bDirty;
private:
    static Window* ImpGetViewWin(SdrView& rView);
    DECL_LINK(IdleHdl,Timer*);
    DECL_LINK(ChangedHdl,_SdrItemBrowserControl*);
    DECL_LINK(SetDirtyHdl,_SdrItemBrowserControl*);
public:
    SdrItemBrowser(SdrView& rView);
    void ForceParent();
    void SetView(SdrView& rView) { pView=&rView; ForceParent(); SetDirty(); }
    void SetDirty();
    void Undirty();
    void ForceUndirty() { if (bDirty) Undirty(); }
};

#endif //_SVDIBROW_HXX

<commit_msg>INTEGRATION: CWS supdremove (1.7.678); FILE MERGED 2007/11/16 10:23:10 vg 1.7.678.1: #i83674# cleanup: remove obsolete SUPD macro use<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: svdibrow.hxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: obo $ $Date: 2008-01-07 08:35:51 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _SVDIBROW_HXX
#define _SVDIBROW_HXX

#ifndef _SVX_BRWBOX_HXX //autogen
#include <svtools/brwbox.hxx>
#endif

#ifndef _SV_EDIT_HXX //autogen
#include <vcl/edit.hxx>
#endif

#ifndef _SV_FLOATWIN_HXX //autogen
#include <vcl/floatwin.hxx>
#endif

class SfxItemSet;
class ImpItemListRow;
class BrowserMouseEvent;

class _SdrItemBrowserControl: public BrowseBox
{
friend class ImpItemEdit;
    Container aList;
    long nAktPaintRow;
    Edit* pEditControl;
    XubString aWNamMerk;
    Link aEntryChangedHdl;
    Link aSetDirtyHdl;
    ImpItemListRow* pAktChangeEntry;
    long   nLastWhichOfs;
    USHORT nLastWhich;
    USHORT nLastWhichOben;
    USHORT nLastWhichUnten;
    FASTBOOL bWhichesButNames;
    FASTBOOL bDontHideIneffectiveItems;
    FASTBOOL bDontSortItems;
    FASTBOOL bShowWhichIds;
    FASTBOOL bShowRealValues;
private:
#if _SOLAR__PRIVATE
    void ImpCtor();
    void ImpSetEntry(const ImpItemListRow& rEntry, ULONG nEntryNum);
    ImpItemListRow* ImpGetEntry(ULONG nPos) const { return (ImpItemListRow*)aList.GetObject(nPos); }
    void ImpSaveWhich();
    void ImpRestoreWhich();
#endif // __PRIVATE
protected:
    virtual long GetRowCount() const;
    virtual BOOL SeekRow(long nRow);
    virtual void PaintField(OutputDevice& rDev, const Rectangle& rRect, USHORT nColumnId) const;
    virtual void DoubleClick(const BrowserMouseEvent&);
    virtual void KeyInput(const KeyEvent& rEvt);
    virtual void Select();
    virtual void SetDirty(); // wird z.B. bei Modusumschaltungen gerufen
    virtual Rectangle GetFieldCharacterBounds(sal_Int32 _nRow,sal_Int32 _nColumnPos,sal_Int32 nIndex);
    virtual sal_Int32 GetFieldIndexAtPoint(sal_Int32 _nRow,sal_Int32 _nColumnPos,const Point& _rPoint);
public:
    _SdrItemBrowserControl(Window* pParent, WinBits nBits=WB_3DLOOK|WB_BORDER|WB_TABSTOP);
    virtual ~_SdrItemBrowserControl();
    void Clear();
    void SetAttributes(const SfxItemSet* pAttr, const SfxItemSet* p2ndSet=NULL);
    ULONG GetCurrentPos() const;
    USHORT GetCurrentWhich() const;
    virtual FASTBOOL BegChangeEntry(ULONG nPos);
    virtual FASTBOOL EndChangeEntry();
    virtual void     BrkChangeEntry();

    /** GetCellText returns the text at the given position
        @param  _nRow
            the number of the row
        @param  _nColId
            the ID of the column
        @return
            the text out of the cell
    */
    virtual String  GetCellText(long _nRow, USHORT _nColId) const;

    const ImpItemListRow* GetAktChangeEntry() const { return pAktChangeEntry; }
    XubString GetNewEntryValue() const                 { return pEditControl->GetText(); }
    void SetEntryChangedHdl(const Link& rLink)      { aEntryChangedHdl=rLink; }
    const Link& GetEntryChangedHdl() const          { return aEntryChangedHdl; }
    void SetSetDirtyHdl(const Link& rLink)          { aSetDirtyHdl=rLink; }
    const Link& GetSetDirtyHdl() const              { return aSetDirtyHdl; }
};

#define WB_STDSIZEABLEDOCKWIN  (WB_STDDOCKWIN|WB_3DLOOK|WB_CLOSEABLE|WB_SIZEMOVE)
#define WB_STDSIZEABLEFLOATWIN (WB_STDFLOATWIN|WB_3DLOOK|WB_CLOSEABLE|WB_SIZEMOVE)

class _SdrItemBrowserWindow: public FloatingWindow {
    _SdrItemBrowserControl aBrowse;
public:
    _SdrItemBrowserWindow(Window* pParent, WinBits nBits=WB_STDSIZEABLEDOCKWIN);
    virtual ~_SdrItemBrowserWindow();
    virtual void Resize();
    virtual void GetFocus();
    void Clear()                                            { aBrowse.Clear(); }
    void SetAttributes(const SfxItemSet* pAttr, const SfxItemSet* p2ndSet=NULL) { aBrowse.SetAttributes(pAttr,p2ndSet); }
    void SetFloatingMode(FASTBOOL /*bOn*/) {}
    const _SdrItemBrowserControl& GetBrowserControl() const { return aBrowse; }
    _SdrItemBrowserControl& GetBrowserControl()             { return aBrowse; }
};

class SdrView;

class SdrItemBrowser: public _SdrItemBrowserWindow {
    Timer aIdleTimer;
    SdrView* pView;
    FASTBOOL bDirty;
private:
    static Window* ImpGetViewWin(SdrView& rView);
    DECL_LINK(IdleHdl,Timer*);
    DECL_LINK(ChangedHdl,_SdrItemBrowserControl*);
    DECL_LINK(SetDirtyHdl,_SdrItemBrowserControl*);
public:
    SdrItemBrowser(SdrView& rView);
    void ForceParent();
    void SetView(SdrView& rView) { pView=&rView; ForceParent(); SetDirty(); }
    void SetDirty();
    void Undirty();
    void ForceUndirty() { if (bDirty) Undirty(); }
};

#endif //_SVDIBROW_HXX

<|endoftext|>


<commit_before>/*
 NUI3 - C++ cross-platform GUI framework for OpenGL based applications
 Copyright (C) 2002-2003 Sebastien Metrot

 licence: see nui3/LICENCE.TXT
 */

#include "nuiAudioDevice.h"
#include "nglThread.h"
#include "nuiAudioDevice_AudioUnit.h"

//class nuiAudioDevice_AudioUnit : public nuiAudioDevice
nuiAudioDevice_AudioUnit::nuiAudioDevice_AudioUnit()
{
  EnumSampleRates();
  EnumBufferSizes();
}

nuiAudioDevice_AudioUnit::~nuiAudioDevice_AudioUnit()
{
	AudioOutputUnitStop(mAudioUnit);
	AudioComponentInstanceDispose(mAudioUnit);
}

/*
 * The main audio i/o callback.  This number of frames is currently fixed at 1024, but Bill Stewart
 * tells me they're working on a way to let us specify smaller buffer sizes.
 *
 * I should point out that there's something wrong with my dsp somewhere.  This code works on
 * my iPhone, but there are discontinuities in the generated sine that I haven't figure out yet
 * Could be my fixed-point sine table, or maybe I'm doing something wrong with my 16.16
 * phase accumulator.
 */

OSStatus AudioUnitCallback(void* inRefCon,
                    AudioUnitRenderActionFlags* ioActionFlags,
                    const AudioTimeStamp* inTimeStamp,
                    UInt32 inBusNumber,
                    UInt32 inNumberFrames_,
                    AudioBufferList* ioData)
{
  // Return if not pre-render
	if(!(*ioActionFlags & kAudioUnitRenderAction_PreRender))
  {
    return noErr;
  }

	// Get a pointer to the audio device
	nuiAudioDevice_AudioUnit* pAudioDevice = (nuiAudioDevice_AudioUnit*)inRefCon;

	// Process
	pAudioDevice->Process(inNumberFrames_, ioData);

	return noErr;
}

void nuiAudioDevice_AudioUnit::Process(uint uNumFrames, AudioBufferList* ioData)
{
  NGL_OUT(_T("nuiAudioDevice_AudioUnit::Process uNumFrames %d    %d %d\n"),uNumFrames, ioData->mBuffers[0].mNumberChannels, ioData->mBuffers[1].mNumberChannels );

//  for (uint32 s = 0; s < uNumFrames; s++)
//  memcpy(mOutputBuffers[0], ioData->mBuffers[0].mData, uNumFrames * sizeof(float));
//  memcpy(mOutputBuffers[1], ioData->mBuffers[1].mData, uNumFrames * sizeof(float));

  mOutputBuffers[0] = (float*)ioData->mBuffers[0].mData;
  mOutputBuffers[1] = (float*)ioData->mBuffers[1].mData;
  mAudioProcessFn(mInputBuffers, mOutputBuffers, uNumFrames);
}

void interruptionListener( void* inClientData, UInt32 inInterruptionState)
{

}

bool nuiAudioDevice_AudioUnit::Open(std::vector<uint32>& rInputChannels, std::vector<uint32>& rOutputChannels, double SampleRate, uint32 BufferSize, nuiAudioProcessFn pProcessFunction)
{
  OSStatus err;

  mAudioProcessFn = pProcessFunction;
  mSampleRate = SampleRate;
  mBufferSize = BufferSize;

  mOutputBuffers.resize(2);
//  for (uint32 i = 0; i < 2; i++)
//    mOutputBuffers[i].

  UInt32 size = sizeof (UInt32);
  UInt32 value = kAudioSessionOverrideAudioRoute_None;
  AudioSessionSetProperty(kAudioSessionProperty_OverrideAudioRoute, size, &value);

	// Initialize our session
	err = AudioSessionInitialize(NULL, NULL, interruptionListener, NULL);

	// Set the category
	UInt32 uCategory = kAudioSessionCategory_LiveAudio;
	err = AudioSessionSetProperty(kAudioSessionProperty_AudioCategory, sizeof(UInt32), &uCategory);
//	if (err != noErr)
//  {
//    NGL_ASSERT(0);
//    return false;
//  }

	// Set the buffer size
	Float32 fBufferSize = mBufferSize / mSampleRate;	//256frames @ 44.1khz
	err = AudioSessionSetProperty(kAudioSessionProperty_PreferredHardwareIOBufferDuration, sizeof(Float32), &fBufferSize);
//	if (err != noErr)
//  {
//    NGL_ASSERT(0);
//    return false;
//  }

	// Set active
	err = AudioSessionSetActive(true);
//	if (err != noErr)
//  {
//    NGL_ASSERT(0);
//    return false;
//  }

	// Initialize the audio unit
	mAudioUnit = 0;

	AudioComponentDescription desc;
	desc.componentManufacturer = kAudioUnitManufacturer_Apple;
	desc.componentType = kAudioUnitType_Output;

	//RemoteIO is equivalent to AUHAL on OS X
	desc.componentSubType = kAudioUnitSubType_RemoteIO;
	desc.componentFlags = 0;
	desc.componentFlagsMask = 0;

	//@see 'Audio Component Services Reference'
	UInt32 count = AudioComponentCount(&desc);
	// Make sure we got RemoteIO
	if (1 != count)
  {
    NGL_ASSERT(0);
    return false;
  }

	AudioComponent comp = 0;
	comp = AudioComponentFindNext(comp, &desc);

	// Make sure we found RemoteIO
	if (!comp)
  {
    NGL_ASSERT(0);
    return false;
  }

	err = AudioComponentInstanceNew(comp, &mAudioUnit);
	// Make sure we instantiated
	if (noErr != err)
  {
    NGL_ASSERT(0);
    return false;
  }

	//find out about the device's format (but I can save you the suspense:
	//integer | non-interleaved | packed | little endian | 32 bits (8.24 fixed)
	AudioStreamBasicDescription fmt_desc;
	size = sizeof(fmt_desc);

	err = AudioUnitGetProperty(mAudioUnit,
                             kAudioUnitProperty_StreamFormat,
                             kAudioUnitScope_Output,
                             0, &fmt_desc, &size);
	if( err != noErr )
  {
    NGL_ASSERT(0);
    return false;
  }

	//NSAssert (noErr == err, @"Retrieving ASBD failed");

	//
	// These new flags in CoreAudioTypes.h tell us how many fractional bits the fixed-point format
	// uses.  In the current iPhone OS devices, it's always 24

	//int number_fractional_bits = (fmt_desc.mFormatFlags & kLinearPCMFormatFlagsSampleFractionMask) >> kLinearPCMFormatFlagsSampleFractionShift;
	err = AudioUnitInitialize(mAudioUnit);
	if (err != noErr)
  {
    NGL_ASSERT(0);
    return false;
  }

	//NSAssert (noErr == err, @"AU Init Failed");
	err = AudioUnitAddRenderNotify(mAudioUnit, AudioUnitCallback, this);
	if (err != noErr)
  {
    NGL_ASSERT(0);
    return false;
  }
	//NSAssert (noErr == err, @"Add Render Callback failed");

	err = AudioOutputUnitStart(mAudioUnit);
	if (err != noErr)
  {
    NGL_ASSERT(0);
    return false;
  }
	//NSAssert (noErr == err, @"AU Start failed");

	return true;
}

bool nuiAudioDevice_AudioUnit::Close()
{

	AudioUnitUninitialize(mAudioUnit);
  return true;
}

void nuiAudioDevice_AudioUnit::EnumSampleRates()
{
}

void nuiAudioDevice_AudioUnit::EnumBufferSizes()
{
}

nglString nuiAudioDevice_AudioUnit::GetChannelName(bool IsInput, uint32 index) const
{
  if (IsInput || index > 0)
    return nglString::Null;

  return _T("Output");
}

//class nuiAudioDeviceAPI_AudioUnit : public nuiAudioDeviceAPI
nuiAudioDeviceAPI_AudioUnit::nuiAudioDeviceAPI_AudioUnit()
{
  mName = _T("AudioUnit");
  RegisterWithManager();
}

nuiAudioDeviceAPI_AudioUnit::~nuiAudioDeviceAPI_AudioUnit()
{
}

uint32 nuiAudioDeviceAPI_AudioUnit::GetDeviceCount() const
{
  return 1;
}

nuiAudioDevice* nuiAudioDeviceAPI_AudioUnit::GetDevice(uint32 index)
{
  if (index == 0)
    return new nuiAudioDevice_AudioUnit();
  return NULL;
}

nuiAudioDevice* nuiAudioDeviceAPI_AudioUnit::GetDevice(const nglString& rDeviceName)
{
  if (index == 0)
    return new nuiAudioDevice_AudioUnit();
  return NULL;
}

nglString nuiAudioDeviceAPI_AudioUnit::GetDeviceName(uint32 index) const
{
  if (index == 0)
    return nglString(_T("Output"));
  return nglString::Null;
}

nuiAudioDevice* nuiAudioDeviceAPI_AudioUnit::GetDefaultOutputDevice()
{
  return GetDevice(0);
}

nuiAudioDevice* nuiAudioDeviceAPI_AudioUnit::GetDefaultInputDevice()
{
  return GetDevice(0);
}

nuiAudioDeviceAPI_AudioUnit AudioUnitAPI;
<commit_msg>nuiAudioDevice_AudioUnit work in progress<commit_after>/*
 NUI3 - C++ cross-platform GUI framework for OpenGL based applications
 Copyright (C) 2002-2003 Sebastien Metrot

 licence: see nui3/LICENCE.TXT
 */

#include "nuiAudioDevice.h"
#include "nglThread.h"
#include "nuiAudioDevice_AudioUnit.h"
#include "nuiAudioConvert.h"

//class nuiAudioDevice_AudioUnit : public nuiAudioDevice
nuiAudioDevice_AudioUnit::nuiAudioDevice_AudioUnit()
{
  EnumSampleRates();
  EnumBufferSizes();
}

nuiAudioDevice_AudioUnit::~nuiAudioDevice_AudioUnit()
{
	AudioOutputUnitStop(mAudioUnit);
	AudioComponentInstanceDispose(mAudioUnit);
}

/*
 * The main audio i/o callback.  This number of frames is currently fixed at 1024, but Bill Stewart
 * tells me they're working on a way to let us specify smaller buffer sizes.
 *
 * I should point out that there's something wrong with my dsp somewhere.  This code works on
 * my iPhone, but there are discontinuities in the generated sine that I haven't figure out yet
 * Could be my fixed-point sine table, or maybe I'm doing something wrong with my 16.16
 * phase accumulator.
 */

OSStatus AudioUnitCallback(void* inRefCon,
                    AudioUnitRenderActionFlags* ioActionFlags,
                    const AudioTimeStamp* inTimeStamp,
                    UInt32 inBusNumber,
                    UInt32 inNumberFrames_,
                    AudioBufferList* ioData)
{
  // Return if not pre-render
	if(!(*ioActionFlags & kAudioUnitRenderAction_PreRender))
  {
    return noErr;
  }

	// Get a pointer to the audio device
	nuiAudioDevice_AudioUnit* pAudioDevice = (nuiAudioDevice_AudioUnit*)inRefCon;

	// Process
	pAudioDevice->Process(inNumberFrames_, ioData);

	return noErr;
}

void nuiAudioDevice_AudioUnit::Process(uint uNumFrames, AudioBufferList* ioData)
{
//  NGL_OUT(_T("nuiAudioDevice_AudioUnit::Process uNumFrames %d    %d %d\n"),uNumFrames, ioData->mBuffers[0].mNumberChannels, ioData->mBuffers[1].mNumberChannels );

  mAudioProcessFn(mInputBuffers, mOutputBuffers, uNumFrames);

  // copy buffers (int -> float)
  float* ptr0 = mOutputBuffers[0];
  float* ptr1 = mOutputBuffers[1];

  uint32* dst0 = (uint32*)ioData->mBuffers[0].mData;
  uint32* dst1 = (uint32*)ioData->mBuffers[1].mData;

  for (uint32 s = 0; s < uNumFrames; s++)
  {
    *dst0 = *ptr0 * (1 << 24);
    *dst1 = *ptr1 * (1 << 24);
    ptr0++; ptr1++;
    dst0++; dst1++;
  }
}

void interruptionListener( void* inClientData, UInt32 inInterruptionState)
{

}

bool nuiAudioDevice_AudioUnit::Open(std::vector<uint32>& rInputChannels, std::vector<uint32>& rOutputChannels, double SampleRate, uint32 BufferSize, nuiAudioProcessFn pProcessFunction)
{
  OSStatus err;

  mAudioProcessFn = pProcessFunction;
  mSampleRate = SampleRate;
  mBufferSize = BufferSize;

  mActiveInputChannels.resize(rInputChannels.size());
  mActiveOutputChannels.resize(rOutputChannels.size());

  mOutputBuffers.resize(mActiveOutputChannels.size(), NULL);
  // init buffers
  for (uint32 i = 0; i < mOutputBuffers.size(); i++)
    mOutputBuffers[i] = (float*)malloc(mBufferSize * sizeof(float));

  UInt32 size = sizeof (UInt32);
  UInt32 value = kAudioSessionOverrideAudioRoute_None;
  AudioSessionSetProperty(kAudioSessionProperty_OverrideAudioRoute, size, &value);

	// Initialize our session
	err = AudioSessionInitialize(NULL, NULL, interruptionListener, NULL);

	// Set the category
	UInt32 uCategory = kAudioSessionCategory_LiveAudio;
	err = AudioSessionSetProperty(kAudioSessionProperty_AudioCategory, sizeof(UInt32), &uCategory);
//	if (err != noErr)
//  {
//    NGL_ASSERT(0);
//    return false;
//  }

	// Set the buffer size
	Float32 fBufferSize = (float)mBufferSize / mSampleRate;	//256frames @ 44.1khz
	err = AudioSessionSetProperty(kAudioSessionProperty_PreferredHardwareIOBufferDuration, sizeof(Float32), &fBufferSize);
//	if (err != noErr)
//  {
//    NGL_ASSERT(0);
//    return false;
//  }

	// Set active
	err = AudioSessionSetActive(true);
//	if (err != noErr)
//  {
//    NGL_ASSERT(0);
//    return false;
//  }

	// Initialize the audio unit
	mAudioUnit = 0;

	AudioComponentDescription desc;
	desc.componentManufacturer = kAudioUnitManufacturer_Apple;
	desc.componentType = kAudioUnitType_Output;

	//RemoteIO is equivalent to AUHAL on OS X
	desc.componentSubType = kAudioUnitSubType_RemoteIO;
	desc.componentFlags = 0;
	desc.componentFlagsMask = 0;

	//@see 'Audio Component Services Reference'
	UInt32 count = AudioComponentCount(&desc);
	// Make sure we got RemoteIO
	if (1 != count)
  {
    NGL_ASSERT(0);
    return false;
  }

	AudioComponent comp = 0;
	comp = AudioComponentFindNext(comp, &desc);

	// Make sure we found RemoteIO
	if (!comp)
  {
    NGL_ASSERT(0);
    return false;
  }

	err = AudioComponentInstanceNew(comp, &mAudioUnit);
	// Make sure we instantiated
	if (noErr != err)
  {
    NGL_ASSERT(0);
    return false;
  }

	//find out about the device's format (but I can save you the suspense:
	//integer | non-interleaved | packed | little endian | 32 bits (8.24 fixed)
	AudioStreamBasicDescription fmt_desc;
	size = sizeof(fmt_desc);

	err = AudioUnitGetProperty(mAudioUnit,
                             kAudioUnitProperty_StreamFormat,
                             kAudioUnitScope_Output,
                             0, &fmt_desc, &size);
	if( err != noErr )
  {
    NGL_ASSERT(0);
    return false;
  }

	//NSAssert (noErr == err, @"Retrieving ASBD failed");

	//
	// These new flags in CoreAudioTypes.h tell us how many fractional bits the fixed-point format
	// uses.  In the current iPhone OS devices, it's always 24

	//int number_fractional_bits = (fmt_desc.mFormatFlags & kLinearPCMFormatFlagsSampleFractionMask) >> kLinearPCMFormatFlagsSampleFractionShift;
	err = AudioUnitInitialize(mAudioUnit);
	if (err != noErr)
  {
    NGL_ASSERT(0);
    return false;
  }

	//NSAssert (noErr == err, @"AU Init Failed");
	err = AudioUnitAddRenderNotify(mAudioUnit, AudioUnitCallback, this);
	if (err != noErr)
  {
    NGL_ASSERT(0);
    return false;
  }
	//NSAssert (noErr == err, @"Add Render Callback failed");

	err = AudioOutputUnitStart(mAudioUnit);
	if (err != noErr)
  {
    NGL_ASSERT(0);
    return false;
  }
	//NSAssert (noErr == err, @"AU Start failed");

	return true;
}

bool nuiAudioDevice_AudioUnit::Close()
{

	AudioUnitUninitialize(mAudioUnit);
  return true;
}

void nuiAudioDevice_AudioUnit::EnumSampleRates()
{
}

void nuiAudioDevice_AudioUnit::EnumBufferSizes()
{
}

nglString nuiAudioDevice_AudioUnit::GetChannelName(bool IsInput, uint32 index) const
{
  if (IsInput || index > 0)
    return nglString::Null;

  return _T("Output");
}

//class nuiAudioDeviceAPI_AudioUnit : public nuiAudioDeviceAPI
nuiAudioDeviceAPI_AudioUnit::nuiAudioDeviceAPI_AudioUnit()
{
  mName = _T("AudioUnit");
  RegisterWithManager();
}

nuiAudioDeviceAPI_AudioUnit::~nuiAudioDeviceAPI_AudioUnit()
{
}

uint32 nuiAudioDeviceAPI_AudioUnit::GetDeviceCount() const
{
  return 1;
}

nuiAudioDevice* nuiAudioDeviceAPI_AudioUnit::GetDevice(uint32 index)
{
  if (index == 0)
    return new nuiAudioDevice_AudioUnit();
  return NULL;
}

nuiAudioDevice* nuiAudioDeviceAPI_AudioUnit::GetDevice(const nglString& rDeviceName)
{
  if (index == 0)
    return new nuiAudioDevice_AudioUnit();
  return NULL;
}

nglString nuiAudioDeviceAPI_AudioUnit::GetDeviceName(uint32 index) const
{
  if (index == 0)
    return nglString(_T("Output"));
  return nglString::Null;
}

nuiAudioDevice* nuiAudioDeviceAPI_AudioUnit::GetDefaultOutputDevice()
{
  return GetDevice(0);
}

nuiAudioDevice* nuiAudioDeviceAPI_AudioUnit::GetDefaultInputDevice()
{
  return GetDevice(0);
}

nuiAudioDeviceAPI_AudioUnit AudioUnitAPI;
<|endoftext|>