<commit_before>#ifndef _SDD_MEM_HASH_TABLE_HH_
#define _SDD_MEM_HASH_TABLE_HH_

#include <algorithm>  // fill
#include <functional> // hash
#include <utility>    // make_pair, pair

#include "sdd/util/next_power.hh"
#include "sdd/util/packed.hh"

namespace sdd { namespace mem {

/*------------------------------------------------------------------------------------------------*/

/// @internal
/// @brief It must be stored by the hash table's data as a member named 'hook'.
template <typename Data>
struct intrusive_member_hook
{
  /// @brief Store the next data in a bucket.
  mutable Data* next;

  /// @brief Default constructor.
  intrusive_member_hook()
    : next(nullptr)
  {}
};

/*------------------------------------------------------------------------------------------------*/

/// @internal
/// @brief An intrusive hash table.
///
/// It's modeled after boost::intrusive. Only the interfaces needed by the libsdd are implemented.
/// It uses chaining to handle collisions.
template <typename Data>
class hash_table
{
public:

  /// @brief Used by insert_check
  struct insert_commit_data
  {
    std::size_t hash;
  };

private:

  /// @brief
  std::size_t nb_buckets_;

  /// @brief
  std::size_t size_;

  /// @brief
  Data** buckets_;

  /// @brief The maximal allowed load factor.
  const double max_load_factor_;

  /// @brief The number of times this hash table has been rehashed.
  std::size_t rehash_;

  /// @brief
  const bool no_rehash_;

public:

  /// @brief Constructor
  hash_table(std::size_t size, double max_load_factor = 0.75, bool no_rehash = false)
    : nb_buckets_(util::next_power_of_2(size))
    , size_(0)
    , buckets_(new Data*[nb_buckets_])
    , max_load_factor_(max_load_factor)
    , rehash_(0)
    , no_rehash_(no_rehash)
  {
    std::fill(buckets_, buckets_ + nb_buckets_, nullptr);
  }

  /// @brief Destructor
  ~hash_table()
  {
    delete[] buckets_;
  }

  /// @brief
  template <typename T, typename HashT, typename EqT>
//  std::pair<iterator, bool>
  std::pair<Data*, bool>
  insert_check(const T& x, HashT hash, EqT eq, insert_commit_data& commit_data)
  const noexcept(noexcept(hash(x)))
  {
    commit_data.hash = hash(x);
    // same as commit_data.h % nb_buckets_, but much more efficient (works only with powers of 2)
    const std::size_t pos = commit_data.hash & (nb_buckets_ - 1);

    Data* current = buckets_[pos];
    bool insertion = true;
    while (current != nullptr)
    {
      if (eq(x, *current))
      {
        insertion = false;
        break;
      }
      current = current->hook.next;
    }

//    return std::make_pair(iterator(this, pos, current), insertion);
    return std::make_pair(current, insertion);
  }

  /// @brief
  void
  insert_commit(Data& x, const insert_commit_data& commit_data)
  noexcept
  {
    const std::size_t pos = commit_data.hash & (nb_buckets_ - 1);

    Data* previous = nullptr;
    Data* current = buckets_[pos];

    while (current != nullptr)
    {
      if (x == *current)
      {
        return;
      }
      previous = current;
      current = current->hook.next;
    }

    if (previous != nullptr)
    {
      previous->hook.next = &x;
    }
    else
    {
      buckets_[pos] = &x;
    }

    ++size_;
    rehash();
  }

  /// @brief Insert an element.
//  std::pair<iterator, bool>
  std::pair<Data*, bool>
  insert(Data& x)
  noexcept(noexcept(std::hash<Data>()(x)))
  {
    auto res = insert_impl(&x, buckets_, nb_buckets_);
    rehash();
    return res;
  }

  /// @brief Return the number of elements.
  std::size_t
  size()
  const noexcept
  {
    return size_;
  }

  /// @brief Return the number of buckets.
  std::size_t
  bucket_count()
  const noexcept
  {
    return nb_buckets_;
  }

  /// @brief Remove an element given its value.
  void
  erase(const Data& x)
  noexcept
  {
    const std::size_t pos = std::hash<Data>()(x) & (nb_buckets_ - 1);
    Data* previous = nullptr;
    Data* current = buckets_[pos];
    while (current != nullptr)
    {
      if (x == *current)
      {
        if (previous == nullptr) // first element in bucket
        {
          buckets_[pos] = current->hook.next;
        }
        else
        {
          previous->hook.next = current->hook.next;
        }
        --size_;
        return;
      }
      previous = current;
      current = current->hook.next;
    }
  }

  /// @brief Clear the whole table.
  template <typename Disposer>
  void
  clear_and_dispose(Disposer disposer)
  {
    for (std::size_t i = 0; i < nb_buckets_; ++i)
    {
//      Data* previous = nullptr;
      Data* current = buckets_[i];
      while (current != nullptr)
      {
        const auto to_erase = current;
        current = current->hook.next;
        disposer(to_erase);
      }
      buckets_[i] = nullptr;
    }
    size_ = 0;
  }

  /// @brief Get the load factor of the internal hash table.
  double
  load_factor()
  const noexcept
  {
    return static_cast<double>(size()) / static_cast<double>(bucket_count());
  }

  /// @brief The number of times this hash table has been rehashed.
  std::size_t
  nb_rehash()
  const noexcept
  {
    return rehash_;
  }

  /// @brief The number of collisions.
  std::size_t
  collisions()
  const noexcept
  {
    std::size_t c = 0;
    for (std::size_t i = 0; i < nb_buckets_; ++i)
    {
      std::size_t nb = 0;
      auto current = buckets_[i];
      while (current != nullptr)
      {
        ++nb;
        current = current->hook.next;
      }
      if (nb > 1) ++c;
    }
    return c;
  }

private:

  void
  rehash()
  {
    if (no_rehash_ or (load_factor() < max_load_factor_))
    {
      return;
    }
    ++rehash_;
    auto new_nb_buckets = nb_buckets_ * 2;
    auto new_buckets = new Data*[new_nb_buckets];
    std::fill(new_buckets, new_buckets + new_nb_buckets, nullptr);
    size_ = 0;
    for (std::size_t i = 0; i < nb_buckets_; ++i)
    {
      Data* data_ptr = buckets_[i];
      while (data_ptr)
      {
        Data* next = data_ptr->hook.next;
        data_ptr->hook.next = nullptr;
        insert_impl(data_ptr, new_buckets, new_nb_buckets);
        data_ptr = next;
      }
      // else empty bucket
    }
    std::swap(new_buckets, buckets_);
    std::swap(new_nb_buckets, nb_buckets_);
    delete[] new_buckets;
  }

  /// @brief Insert an element.
  std::pair<Data*, bool>
  insert_impl(Data* x, Data** buckets, std::size_t nb_buckets)
  noexcept(noexcept(std::hash<Data>()(*x)))
  {
    const std::size_t pos = std::hash<Data>()(*x) & (nb_buckets - 1);

    Data* current = buckets[pos];

    while (current != nullptr)
    {
      if (*x == *current)
      {
//        return std::make_pair(iterator(this, pos, current), false /* no insertion */);
        return std::make_pair(current, false /* no insertion */);
      }
      current = current->hook.next;
    }

    // Push in front of the list.
    x->hook.next = buckets[pos];
    buckets[pos] = x;

    current = x;
    ++size_;
//    return std::make_pair(iterator(this, pos, current), true /* insertion */);
    return std::make_pair(current, true /* insertion */);
  }
};

/*------------------------------------------------------------------------------------------------*/

}} // namespace sdd::mem

#endif // _SDD_MEM_HASH_TABLE_HH_
<commit_msg>Remove commented code.<commit_after>#ifndef _SDD_MEM_HASH_TABLE_HH_
#define _SDD_MEM_HASH_TABLE_HH_

#include <algorithm>  // fill
#include <functional> // hash
#include <utility>    // make_pair, pair

#include "sdd/util/next_power.hh"
#include "sdd/util/packed.hh"

namespace sdd { namespace mem {

/*------------------------------------------------------------------------------------------------*/

/// @internal
/// @brief It must be stored by the hash table's data as a member named 'hook'.
template <typename Data>
struct intrusive_member_hook
{
  /// @brief Store the next data in a bucket.
  mutable Data* next;

  /// @brief Default constructor.
  intrusive_member_hook()
    : next(nullptr)
  {}
};

/*------------------------------------------------------------------------------------------------*/

/// @internal
/// @brief An intrusive hash table.
///
/// It's modeled after boost::intrusive. Only the interfaces needed by the libsdd are implemented.
/// It uses chaining to handle collisions.
template <typename Data>
class hash_table
{
public:

  /// @brief Used by insert_check
  struct insert_commit_data
  {
    std::size_t hash;
  };

private:

  /// @brief
  std::size_t nb_buckets_;

  /// @brief
  std::size_t size_;

  /// @brief
  Data** buckets_;

  /// @brief The maximal allowed load factor.
  const double max_load_factor_;

  /// @brief The number of times this hash table has been rehashed.
  std::size_t rehash_;

  /// @brief
  const bool no_rehash_;

public:

  /// @brief Constructor
  hash_table(std::size_t size, double max_load_factor = 0.75, bool no_rehash = false)
    : nb_buckets_(util::next_power_of_2(size))
    , size_(0)
    , buckets_(new Data*[nb_buckets_])
    , max_load_factor_(max_load_factor)
    , rehash_(0)
    , no_rehash_(no_rehash)
  {
    std::fill(buckets_, buckets_ + nb_buckets_, nullptr);
  }

  /// @brief Destructor
  ~hash_table()
  {
    delete[] buckets_;
  }

  /// @brief
  template <typename T, typename HashT, typename EqT>
//  std::pair<iterator, bool>
  std::pair<Data*, bool>
  insert_check(const T& x, HashT hash, EqT eq, insert_commit_data& commit_data)
  const noexcept(noexcept(hash(x)))
  {
    commit_data.hash = hash(x);
    // same as commit_data.h % nb_buckets_, but much more efficient (works only with powers of 2)
    const std::size_t pos = commit_data.hash & (nb_buckets_ - 1);

    Data* current = buckets_[pos];
    bool insertion = true;
    while (current != nullptr)
    {
      if (eq(x, *current))
      {
        insertion = false;
        break;
      }
      current = current->hook.next;
    }

    return std::make_pair(current, insertion);
  }

  /// @brief
  void
  insert_commit(Data& x, const insert_commit_data& commit_data)
  noexcept
  {
    const std::size_t pos = commit_data.hash & (nb_buckets_ - 1);

    Data* previous = nullptr;
    Data* current = buckets_[pos];

    while (current != nullptr)
    {
      if (x == *current)
      {
        return;
      }
      previous = current;
      current = current->hook.next;
    }

    if (previous != nullptr)
    {
      previous->hook.next = &x;
    }
    else
    {
      buckets_[pos] = &x;
    }

    ++size_;
    rehash();
  }

  /// @brief Insert an element.
  std::pair<Data*, bool>
  insert(Data& x)
  noexcept(noexcept(std::hash<Data>()(x)))
  {
    auto res = insert_impl(&x, buckets_, nb_buckets_);
    rehash();
    return res;
  }

  /// @brief Return the number of elements.
  std::size_t
  size()
  const noexcept
  {
    return size_;
  }

  /// @brief Return the number of buckets.
  std::size_t
  bucket_count()
  const noexcept
  {
    return nb_buckets_;
  }

  /// @brief Remove an element given its value.
  void
  erase(const Data& x)
  noexcept
  {
    const std::size_t pos = std::hash<Data>()(x) & (nb_buckets_ - 1);
    Data* previous = nullptr;
    Data* current = buckets_[pos];
    while (current != nullptr)
    {
      if (x == *current)
      {
        if (previous == nullptr) // first element in bucket
        {
          buckets_[pos] = current->hook.next;
        }
        else
        {
          previous->hook.next = current->hook.next;
        }
        --size_;
        return;
      }
      previous = current;
      current = current->hook.next;
    }
  }

  /// @brief Clear the whole table.
  template <typename Disposer>
  void
  clear_and_dispose(Disposer disposer)
  {
    for (std::size_t i = 0; i < nb_buckets_; ++i)
    {
      Data* current = buckets_[i];
      while (current != nullptr)
      {
        const auto to_erase = current;
        current = current->hook.next;
        disposer(to_erase);
      }
      buckets_[i] = nullptr;
    }
    size_ = 0;
  }

  /// @brief Get the load factor of the internal hash table.
  double
  load_factor()
  const noexcept
  {
    return static_cast<double>(size()) / static_cast<double>(bucket_count());
  }

  /// @brief The number of times this hash table has been rehashed.
  std::size_t
  nb_rehash()
  const noexcept
  {
    return rehash_;
  }

  /// @brief The number of collisions.
  std::size_t
  collisions()
  const noexcept
  {
    std::size_t c = 0;
    for (std::size_t i = 0; i < nb_buckets_; ++i)
    {
      std::size_t nb = 0;
      auto current = buckets_[i];
      while (current != nullptr)
      {
        ++nb;
        current = current->hook.next;
      }
      if (nb > 1) ++c;
    }
    return c;
  }

private:

  void
  rehash()
  {
    if (no_rehash_ or (load_factor() < max_load_factor_))
    {
      return;
    }
    ++rehash_;
    auto new_nb_buckets = nb_buckets_ * 2;
    auto new_buckets = new Data*[new_nb_buckets];
    std::fill(new_buckets, new_buckets + new_nb_buckets, nullptr);
    size_ = 0;
    for (std::size_t i = 0; i < nb_buckets_; ++i)
    {
      Data* data_ptr = buckets_[i];
      while (data_ptr)
      {
        Data* next = data_ptr->hook.next;
        data_ptr->hook.next = nullptr;
        insert_impl(data_ptr, new_buckets, new_nb_buckets);
        data_ptr = next;
      }
      // else empty bucket
    }
    std::swap(new_buckets, buckets_);
    std::swap(new_nb_buckets, nb_buckets_);
    delete[] new_buckets;
  }

  /// @brief Insert an element.
  std::pair<Data*, bool>
  insert_impl(Data* x, Data** buckets, std::size_t nb_buckets)
  noexcept(noexcept(std::hash<Data>()(*x)))
  {
    const std::size_t pos = std::hash<Data>()(*x) & (nb_buckets - 1);

    Data* current = buckets[pos];

    while (current != nullptr)
    {
      if (*x == *current)
      {
        return std::make_pair(current, false /* no insertion */);
      }
      current = current->hook.next;
    }

    // Push in front of the list.
    x->hook.next = buckets[pos];
    buckets[pos] = x;

    current = x;
    ++size_;
    return std::make_pair(current, true /* insertion */);
  }
};

/*------------------------------------------------------------------------------------------------*/

}} // namespace sdd::mem

#endif // _SDD_MEM_HASH_TABLE_HH_
<|endoftext|>


<commit_before>/*
    main.cpp:
    Copyright (C) 2006 Istvan Varga

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

    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
*/

#include "CsoundGUI.hpp"

int main(int argc, char **argv)
{
    CsoundGUIMain   *mainWin;
    bool            enablePython = false;

    if (csoundGetSizeOfMYFLT() == (int) sizeof(double))
      enablePython = true;
    for (int i = 1; i < argc; i++) {
      if (std::strcmp(argv[i], "-python") == 0)
        enablePython = true;
      else if (std::strcmp(argv[i], "-nopython") == 0)
        enablePython = false;
    }
    Fl::lock();
    mainWin = new CsoundGUIMain;
    mainWin->run(enablePython);
    delete mainWin;
    Fl::wait(0.0);

    return 0;
}

<commit_msg>Call csoundInitialize()<commit_after>/*
    main.cpp:
    Copyright (C) 2006 Istvan Varga

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

    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
*/

#include "CsoundGUI.hpp"

int main(int argc, char **argv)
{
    CsoundGUIMain   *mainWin;
    bool            enablePython = false;

    if (csoundInitialize(&argc, &argv, 0) < 0)
      return -1;
    if (csoundGetSizeOfMYFLT() == (int) sizeof(double))
      enablePython = true;
    for (int i = 1; i < argc; i++) {
      if (std::strcmp(argv[i], "-python") == 0)
        enablePython = true;
      else if (std::strcmp(argv[i], "-nopython") == 0)
        enablePython = false;
    }
    Fl::lock();
    mainWin = new CsoundGUIMain;
    mainWin->run(enablePython);
    delete mainWin;
    Fl::wait(0.0);

    return 0;
}

<|endoftext|>


<commit_before>#include "world.h"

#include <cassert>
#include <foundation/array.h>
#include <foundation/quad.h>
#include "drawable.h"
#include "material.h"
#include "render_interface.h"
#include "resource_manager.h"
#include "rectangle_geometry.h"
#include "sprite_geometry.h"
#include "text_geometry.h"

namespace bowtie
{

World::World(Allocator& allocator, RenderInterface& render_interface, ResourceManager& resource_manager) :
	_allocator(allocator), _drawables(array::create<Drawable*>(allocator)), _render_interface(render_interface), _resource_manager(resource_manager)
{
	rectangle_renderer_component::init(_rectangle_renderer_component, allocator);
	transform_component::init(_transform_component, allocator);
}

World::~World()
{
	for (unsigned i = 0; i < array::size(_drawables); ++i)
		_allocator.destroy(_drawables[i]);

	array::deinit(_drawables);
	rectangle_renderer_component::deinit(_rectangle_renderer_component, _allocator);
	transform_component::deinit(_transform_component, _allocator);
}

void World::set_render_handle(RenderResourceHandle render_handle)
{
	_render_handle = render_handle;
}

Drawable* World::spawn_rectangle(const Rect& rect, const Color& color, int depth)
{
	auto geometry = _allocator.construct<RectangleGeometry>(color, rect);
	auto material = _resource_manager.load(ResourceType::Material, "shared/default_resources/rect.material");
	auto rectangle = _allocator.construct<Drawable>(_allocator, *geometry, (Material*)material.object, depth);
	rectangle->set_position(rect.position);
	array::push_back(_drawables, rectangle);
	_render_interface.spawn(*this, *rectangle, _resource_manager);
	return rectangle;
}

Drawable* World::spawn_sprite(const char* sprite_name, int depth)
{
	auto sprite_prototype = _resource_manager.get<Drawable>(ResourceType::Drawable, sprite_name);
	auto sprite = _allocator.construct<Drawable>(*sprite_prototype);
	sprite->set_depth(depth);
	array::push_back(_drawables, sprite);
	_render_interface.spawn(*this, *sprite, _resource_manager);

	return sprite;
}

void World::unspawn(Drawable& drawable)
{
	array::remove(_drawables, &drawable);
	_render_interface.unspawn(*this, drawable);
	_allocator.destroy(&drawable);
}

RenderResourceHandle World::render_handle()
{
	return _render_handle;
}

RectangleRendererComponent& World::rectangle_renderer_component()
{
	return _rectangle_renderer_component;
}

TransformComponent& World::transform_component()
{
	return _transform_component;
}

const Array<Drawable*>& World::drawables() const
{
	return _drawables;
}

void update_drawable_state(Allocator& allocator, RenderInterface& render_interface, Drawable& drawable)
{
	auto state_changed_command = render_interface.create_command(RendererCommand::DrawableStateReflection);

	auto& scd = *(DrawableStateReflectionData*)allocator.allocate(sizeof(DrawableStateReflectionData));
	scd.model = drawable.model_matrix();
	scd.material = drawable.material()->render_handle;
	scd.drawble = drawable.render_handle();
	scd.depth = drawable.depth();
	state_changed_command.data = &scd;

	drawable.reset_state_changed();

	render_interface.dispatch(state_changed_command);
}

void update_drawable_geometry(Allocator& allocator, RenderInterface& render_interface, Drawable& drawable)
{
	auto geometry_changed_command = render_interface.create_command(RendererCommand::DrawableGeometryReflection);

	auto& sgr = *(DrawableGeometryReflectionData*)allocator.allocate(sizeof(DrawableGeometryReflectionData));
	sgr.drawable = drawable.render_handle();
	sgr.size = drawable.geometry().data_size();

	geometry_changed_command.data = &sgr;
	geometry_changed_command.dynamic_data_size = sgr.size;
	geometry_changed_command.dynamic_data = allocator.allocate(sgr.size);
	memcpy(geometry_changed_command.dynamic_data, drawable.geometry().data(), sgr.size);

	drawable.reset_geometry_changed();

	render_interface.dispatch(geometry_changed_command);
}

Matrix4 world_matrix(const TransformComponentData& c, unsigned i)
{
	auto m = Matrix4();
	m[3][0] = c.position[i].x - c.pivot[i].x;
	m[3][1] = c.position[i].y - c.pivot[i].y;
	m[0][0] = cos(c.rotation[i]);
	m[1][0] = -sin(c.rotation[i]);
	m[0][1] = sin(c.rotation[i]);
	m[1][1] = cos(c.rotation[i]);

	if (c.parent[i] == transform_component::not_assigned)
		return m;
	else
		return m * c.world_transform[c.parent[i]];
}

void update_transforms(TransformComponentData& c, unsigned start, unsigned end, RectangleRendererComponent& rectangle_renderer)
{
	for (unsigned i = start; i < end; ++i)
	{
		auto entity = c.entity[i];
		auto world_transform = world_matrix(c, i);
		c.world_transform[i] = world_transform;

		if (!component::has_entity(rectangle_renderer.header, entity))
			continue;

		auto rectangle_index = hash::get(rectangle_renderer.header.map, c.entity[i]);
		auto rect = rectangle_renderer.data.rect[rectangle_index];
		auto v1 = world_transform * Vector4(rect.position.x, rect.position.y, 0, 1);
		auto v2 = world_transform * Vector4(rect.position.x + rect.size.x, rect.position.y, 0, 1);
		auto v3 = world_transform * Vector4(rect.position.x, rect.position.y + rect.size.y, 0, 1);
		auto v4 = world_transform * Vector4(rect.position.x + rect.size.x, rect.position.y + rect.size.y, 0, 1);

		Quad geometry = {
			Vector2(v1.x, v1.y),
			Vector2(v2.x, v2.y),
			Vector2(v3.x, v3.y),
			Vector2(v4.x, v4.y)
		};

		rectangle_renderer_component::set_geometry(rectangle_renderer, entity, geometry);
	}
}

void create_rectangles(Allocator& allocator, RenderInterface& ri, RenderResourceHandle default_material, RenderResourceHandle render_world, RectangleRendererComponent& c, unsigned num)
{
	auto rrd = ri.create_render_resource_data(RenderResourceData::RectangleRenderer);

	for (unsigned i = c.header.first_new; i < c.header.num; ++i)
	{
		c.data.render_handle[i] = ri.create_handle();
		c.data.material[i] = default_material;
	}

	CreateRectangleRendererData data;
	data.num = num;
	data.world = render_world;
	rrd.data = &data;
	ri.create_resource(rrd, rectangle_renderer_component::copy_new_data(c, allocator), rectangle_renderer_component::component_size * data.num);
}

void update_rectangles(Allocator& allocator, RenderInterface& ri, RectangleRendererComponent& c, unsigned num)
{
	auto rrd = ri.create_render_resource_data(RenderResourceData::RectangleRenderer);
	UpdateRectangleRendererData data;
	data.num = num;
	rrd.data = &data;
	ri.update_resource(rrd, rectangle_renderer_component::copy_dirty_data(c, allocator), rectangle_renderer_component::component_size * data.num);
}

void World::update()
{
	for (unsigned i = 0; i < array::size(_drawables); ++i)
	{
		auto drawable = _drawables[i];

		if (drawable->state_changed())
			update_drawable_state(_allocator, _render_interface, *drawable);

		if (drawable->geometry_changed())
			update_drawable_geometry(_allocator, _render_interface, *drawable);
	}

	if (component::num_new(_transform_component.header) > 0)
		update_transforms(_transform_component.data, _transform_component.header.first_new, _transform_component.header.num, _rectangle_renderer_component);

	component::reset_new(_transform_component.header);
	const auto num_dirty_transforms = component::num_dirty(_transform_component.header);

	if (num_dirty_transforms > 0)
		update_transforms(_transform_component.data, 0, num_dirty_transforms, _rectangle_renderer_component);

	component::reset_dirty(_transform_component.header);
	const auto num_new_rectangles = component::num_new(_rectangle_renderer_component.header);

	if (num_new_rectangles > 0)
	{
		auto default_material = ((Material*)_resource_manager.load(ResourceType::Material, "shared/default_resources/rect.material").object)->render_handle;
		create_rectangles(_allocator, _render_interface, default_material, _render_handle, _rectangle_renderer_component, num_new_rectangles);
	}

	component::reset_new(_rectangle_renderer_component.header);
	const auto num_dirty_rectangles = component::num_dirty(_rectangle_renderer_component.header);

	if (num_dirty_rectangles > 0)
		update_rectangles(_allocator, _render_interface, _rectangle_renderer_component, num_dirty_rectangles);

	component::reset_dirty(_rectangle_renderer_component.header);
}

void World::draw(const Rect& view)
{
	auto render_world_command = _render_interface.create_command(RendererCommand::RenderWorld);

	auto& rwd = *(RenderWorldData*)_allocator.allocate(sizeof(RenderWorldData));
	rwd.view = view;
	rwd.render_world = _render_handle;
	render_world_command.data = &rwd;

	_render_interface.dispatch(render_world_command);
}

Drawable* World::spawn_text(const Font& font, const char* text_str, int depth)
{
	auto text_geometry = _allocator.construct<TextGeometry>(font, _allocator);
	text_geometry->set_text(text_str);
	auto text = _allocator.construct<Drawable>(_allocator, *text_geometry, (Material*)_resource_manager.get_default(ResourceType::Material).object, depth);
	array::push_back(_drawables, text);
	_render_interface.spawn(*this, *text, _resource_manager);
	return text;
}

} // namespace bowtie
<commit_msg>Removed silly names.<commit_after>#include "world.h"

#include <cassert>
#include <foundation/array.h>
#include <foundation/quad.h>
#include "drawable.h"
#include "material.h"
#include "render_interface.h"
#include "resource_manager.h"
#include "rectangle_geometry.h"
#include "sprite_geometry.h"
#include "text_geometry.h"

namespace bowtie
{

World::World(Allocator& allocator, RenderInterface& render_interface, ResourceManager& resource_manager) :
	_allocator(allocator), _drawables(array::create<Drawable*>(allocator)), _render_interface(render_interface), _resource_manager(resource_manager)
{
	rectangle_renderer_component::init(_rectangle_renderer_component, allocator);
	transform_component::init(_transform_component, allocator);
}

World::~World()
{
	for (unsigned i = 0; i < array::size(_drawables); ++i)
		_allocator.destroy(_drawables[i]);

	array::deinit(_drawables);
	rectangle_renderer_component::deinit(_rectangle_renderer_component, _allocator);
	transform_component::deinit(_transform_component, _allocator);
}

void World::set_render_handle(RenderResourceHandle render_handle)
{
	_render_handle = render_handle;
}

Drawable* World::spawn_rectangle(const Rect& rect, const Color& color, int depth)
{
	auto geometry = _allocator.construct<RectangleGeometry>(color, rect);
	auto material = _resource_manager.load(ResourceType::Material, "shared/default_resources/rect.material");
	auto rectangle = _allocator.construct<Drawable>(_allocator, *geometry, (Material*)material.object, depth);
	rectangle->set_position(rect.position);
	array::push_back(_drawables, rectangle);
	_render_interface.spawn(*this, *rectangle, _resource_manager);
	return rectangle;
}

Drawable* World::spawn_sprite(const char* sprite_name, int depth)
{
	auto sprite_prototype = _resource_manager.get<Drawable>(ResourceType::Drawable, sprite_name);
	auto sprite = _allocator.construct<Drawable>(*sprite_prototype);
	sprite->set_depth(depth);
	array::push_back(_drawables, sprite);
	_render_interface.spawn(*this, *sprite, _resource_manager);

	return sprite;
}

void World::unspawn(Drawable& drawable)
{
	array::remove(_drawables, &drawable);
	_render_interface.unspawn(*this, drawable);
	_allocator.destroy(&drawable);
}

RenderResourceHandle World::render_handle()
{
	return _render_handle;
}

RectangleRendererComponent& World::rectangle_renderer_component()
{
	return _rectangle_renderer_component;
}

TransformComponent& World::transform_component()
{
	return _transform_component;
}

const Array<Drawable*>& World::drawables() const
{
	return _drawables;
}

void update_drawable_state(Allocator& allocator, RenderInterface& render_interface, Drawable& drawable)
{
	auto state_changed_command = render_interface.create_command(RendererCommand::DrawableStateReflection);

	auto& scd = *(DrawableStateReflectionData*)allocator.allocate(sizeof(DrawableStateReflectionData));
	scd.model = drawable.model_matrix();
	scd.material = drawable.material()->render_handle;
	scd.drawble = drawable.render_handle();
	scd.depth = drawable.depth();
	state_changed_command.data = &scd;

	drawable.reset_state_changed();

	render_interface.dispatch(state_changed_command);
}

void update_drawable_geometry(Allocator& allocator, RenderInterface& render_interface, Drawable& drawable)
{
	auto geometry_changed_command = render_interface.create_command(RendererCommand::DrawableGeometryReflection);

	auto& sgr = *(DrawableGeometryReflectionData*)allocator.allocate(sizeof(DrawableGeometryReflectionData));
	sgr.drawable = drawable.render_handle();
	sgr.size = drawable.geometry().data_size();

	geometry_changed_command.data = &sgr;
	geometry_changed_command.dynamic_data_size = sgr.size;
	geometry_changed_command.dynamic_data = allocator.allocate(sgr.size);
	memcpy(geometry_changed_command.dynamic_data, drawable.geometry().data(), sgr.size);

	drawable.reset_geometry_changed();

	render_interface.dispatch(geometry_changed_command);
}

Matrix4 world_matrix(const TransformComponentData& c, unsigned i)
{
	auto m = Matrix4();
	m[3][0] = c.position[i].x - c.pivot[i].x;
	m[3][1] = c.position[i].y - c.pivot[i].y;
	m[0][0] = cos(c.rotation[i]);
	m[1][0] = -sin(c.rotation[i]);
	m[0][1] = sin(c.rotation[i]);
	m[1][1] = cos(c.rotation[i]);

	if (c.parent[i] == transform_component::not_assigned)
		return m;
	else
		return m * c.world_transform[c.parent[i]];
}

void update_transforms(TransformComponentData& transform, unsigned start, unsigned end, RectangleRendererComponent& rectangle_renderer)
{
	for (unsigned i = start; i < end; ++i)
	{
		auto entity = transform.entity[i];
		auto world_transform = world_matrix(transform, i);
		transform.world_transform[i] = world_transform;

		if (!component::has_entity(rectangle_renderer.header, entity))
			continue;

		auto rectangle_index = hash::get(rectangle_renderer.header.map, transform.entity[i]);
		auto rect = rectangle_renderer.data.rect[rectangle_index];
		auto v1 = world_transform * Vector4(rect.position.x, rect.position.y, 0, 1);
		auto v2 = world_transform * Vector4(rect.position.x + rect.size.x, rect.position.y, 0, 1);
		auto v3 = world_transform * Vector4(rect.position.x, rect.position.y + rect.size.y, 0, 1);
		auto v4 = world_transform * Vector4(rect.position.x + rect.size.x, rect.position.y + rect.size.y, 0, 1);

		Quad geometry = {
			Vector2(v1.x, v1.y),
			Vector2(v2.x, v2.y),
			Vector2(v3.x, v3.y),
			Vector2(v4.x, v4.y)
		};

		rectangle_renderer_component::set_geometry(rectangle_renderer, entity, geometry);
	}
}

void create_rectangles(Allocator& allocator, RenderInterface& ri, RenderResourceHandle default_material, RenderResourceHandle render_world, RectangleRendererComponent& rectangle_renderer, unsigned num)
{
	auto rrd = ri.create_render_resource_data(RenderResourceData::RectangleRenderer);

	for (unsigned i = rectangle_renderer.header.first_new; i < rectangle_renderer.header.num; ++i)
	{
		rectangle_renderer.data.render_handle[i] = ri.create_handle();
		rectangle_renderer.data.material[i] = default_material;
	}

	CreateRectangleRendererData data;
	data.num = num;
	data.world = render_world;
	rrd.data = &data;
	ri.create_resource(rrd, rectangle_renderer_component::copy_new_data(rectangle_renderer, allocator), rectangle_renderer_component::component_size * data.num);
}

void update_rectangles(Allocator& allocator, RenderInterface& ri, RectangleRendererComponent& rectangle_renderer, unsigned num)
{
	auto rrd = ri.create_render_resource_data(RenderResourceData::RectangleRenderer);
	UpdateRectangleRendererData data;
	data.num = num;
	rrd.data = &data;
	ri.update_resource(rrd, rectangle_renderer_component::copy_dirty_data(rectangle_renderer, allocator), rectangle_renderer_component::component_size * data.num);
}

void World::update()
{
	for (unsigned i = 0; i < array::size(_drawables); ++i)
	{
		auto drawable = _drawables[i];

		if (drawable->state_changed())
			update_drawable_state(_allocator, _render_interface, *drawable);

		if (drawable->geometry_changed())
			update_drawable_geometry(_allocator, _render_interface, *drawable);
	}

	if (component::num_new(_transform_component.header) > 0)
		update_transforms(_transform_component.data, _transform_component.header.first_new, _transform_component.header.num, _rectangle_renderer_component);

	component::reset_new(_transform_component.header);
	const auto num_dirty_transforms = component::num_dirty(_transform_component.header);

	if (num_dirty_transforms > 0)
		update_transforms(_transform_component.data, 0, num_dirty_transforms, _rectangle_renderer_component);

	component::reset_dirty(_transform_component.header);
	const auto num_new_rectangles = component::num_new(_rectangle_renderer_component.header);

	if (num_new_rectangles > 0)
	{
		auto default_material = ((Material*)_resource_manager.load(ResourceType::Material, "shared/default_resources/rect.material").object)->render_handle;
		create_rectangles(_allocator, _render_interface, default_material, _render_handle, _rectangle_renderer_component, num_new_rectangles);
	}

	component::reset_new(_rectangle_renderer_component.header);
	const auto num_dirty_rectangles = component::num_dirty(_rectangle_renderer_component.header);

	if (num_dirty_rectangles > 0)
		update_rectangles(_allocator, _render_interface, _rectangle_renderer_component, num_dirty_rectangles);

	component::reset_dirty(_rectangle_renderer_component.header);
}

void World::draw(const Rect& view)
{
	auto render_world_command = _render_interface.create_command(RendererCommand::RenderWorld);

	auto& rwd = *(RenderWorldData*)_allocator.allocate(sizeof(RenderWorldData));
	rwd.view = view;
	rwd.render_world = _render_handle;
	render_world_command.data = &rwd;

	_render_interface.dispatch(render_world_command);
}

Drawable* World::spawn_text(const Font& font, const char* text_str, int depth)
{
	auto text_geometry = _allocator.construct<TextGeometry>(font, _allocator);
	text_geometry->set_text(text_str);
	auto text = _allocator.construct<Drawable>(_allocator, *text_geometry, (Material*)_resource_manager.get_default(ResourceType::Material).object, depth);
	array::push_back(_drawables, text);
	_render_interface.spawn(*this, *text, _resource_manager);
	return text;
}

} // namespace bowtie
<|endoftext|>


<commit_before>/////////////////////////////////////////////////////////////////////////
// $Id$
/////////////////////////////////////////////////////////////////////////
//
//   Copyright (c) 2007 Stanislav Shwartsman
//          Written by Stanislav Shwartsman [sshwarts at sourceforge net]
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  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
//
/////////////////////////////////////////////////////////////////////////

#define NEED_CPU_REG_SHORTCUTS 1
#include "bochs.h"
#include "cpu.h"
#define LOG_THIS BX_CPU_THIS_PTR

bx_bool BX_CPU_C::fetchInstruction(bxInstruction_c *iStorage, Bit32u eipBiased)
{
  unsigned remainingInPage = BX_CPU_THIS_PTR eipPageWindowSize - eipBiased;
  const Bit8u *fetchPtr = BX_CPU_THIS_PTR eipFetchPtr + eipBiased;
  unsigned ret;

#if BX_SUPPORT_X86_64
  if (BX_CPU_THIS_PTR cpu_mode == BX_MODE_LONG_64)
    ret = fetchDecode64(fetchPtr, iStorage, remainingInPage);
  else
#endif
    ret = fetchDecode32(fetchPtr, iStorage, remainingInPage);

  if (ret==0) {
    // handle instrumentation callback inside boundaryFetch
    boundaryFetch(fetchPtr, remainingInPage, iStorage);
    return 0;
  }

#if BX_INSTRUMENTATION
  BX_INSTR_OPCODE(BX_CPU_ID, fetchPtr, iStorage->ilen(),
       BX_CPU_THIS_PTR sregs[BX_SEG_REG_CS].cache.u.segment.d_b, Is64BitMode());
#endif

  return 1;
}

#if BX_SUPPORT_ICACHE

bxPageWriteStampTable pageWriteStampTable;

void flushICaches(void)
{
  for (unsigned i=0; i<BX_SMP_PROCESSORS; i++) {
    BX_CPU(i)->iCache.flushICacheEntries();
    BX_CPU(i)->invalidate_prefetch_q();
  }

  pageWriteStampTable.resetWriteStamps();
}

void purgeICaches(void)
{
  flushICaches();
}

#if BX_SUPPORT_TRACE_CACHE

void handleSMC(void)
{
  for (unsigned i=0; i<BX_SMP_PROCESSORS; i++)
    BX_CPU(i)->async_event |= BX_ASYNC_EVENT_STOP_TRACE;
}

void BX_CPU_C::serveICacheMiss(bxICacheEntry_c *cache_entry, Bit32u eipBiased, bx_phy_address pAddr)
{
  BX_CPU_THIS_PTR iCache.alloc_trace(cache_entry);

  // Cache miss. We weren't so lucky, but let's be optimistic - try to build
  // trace from incoming instruction bytes stream !
  cache_entry->pAddr = pAddr;
  cache_entry->writeStamp = *(BX_CPU_THIS_PTR currPageWriteStampPtr);

  unsigned remainingInPage = BX_CPU_THIS_PTR eipPageWindowSize - eipBiased;
  const Bit8u *fetchPtr = BX_CPU_THIS_PTR eipFetchPtr + eipBiased;
  unsigned ret;

  bxInstruction_c *i = cache_entry->i;

  for (unsigned n=0;n<BX_MAX_TRACE_LENGTH;n++)
  {
#if BX_SUPPORT_X86_64
    if (BX_CPU_THIS_PTR cpu_mode == BX_MODE_LONG_64)
      ret = fetchDecode64(fetchPtr, i, remainingInPage);
    else
#endif
      ret = fetchDecode32(fetchPtr, i, remainingInPage);

    if (ret==0) {
      // Fetching instruction on segment/page boundary
      if (n > 0) {
         // The trace is already valid, it has several instructions inside,
         // in this case just drop the boundary instruction and stop
         // tracing.
         break;
      }
      // First instruction is boundary fetch, leave the trace cache entry
      // invalid and do not cache the instruction.
      cache_entry->writeStamp = ICacheWriteStampInvalid;
      cache_entry->ilen = 1;
      boundaryFetch(fetchPtr, remainingInPage, i);
      return;
    }

    // add instruction to the trace
    unsigned iLen = i->ilen();
    cache_entry->ilen++;

    // continue to the next instruction
    remainingInPage -= iLen;
    if (i->getStopTraceAttr() || remainingInPage == 0) break;
    pAddr += iLen;
    fetchPtr += iLen;
    i++;

    // try to find a trace starting from current pAddr and merge
    if (mergeTraces(cache_entry, i, pAddr)) break;
  }

  BX_CPU_THIS_PTR iCache.commit_trace(cache_entry->ilen);
}

bx_bool BX_CPU_C::mergeTraces(bxICacheEntry_c *entry, bxInstruction_c *i, bx_phy_address pAddr)
{
  bxICacheEntry_c *e = BX_CPU_THIS_PTR iCache.get_entry(pAddr);

  if ((e->pAddr == pAddr) && (e->writeStamp == entry->writeStamp))
  {
    // determine max amount of instruction to take from another entry
    unsigned max_length = e->ilen;
    if (max_length + entry->ilen > BX_MAX_TRACE_LENGTH)
        max_length = BX_MAX_TRACE_LENGTH - entry->ilen;
    if(max_length == 0) return 0;

    memcpy(i, e->i, sizeof(bxInstruction_c)*max_length);
    entry->ilen += max_length;
    BX_ASSERT(entry->ilen <= BX_MAX_TRACE_LENGTH);

    return 1;
  }

  return 0;
}

#else // BX_SUPPORT_TRACE_CACHE == 0

void BX_CPU_C::serveICacheMiss(bxICacheEntry_c *cache_entry, Bit32u eipBiased, bx_phy_address pAddr)
{
  // The entry will be marked valid if fetchdecode will succeed
  cache_entry->writeStamp = ICacheWriteStampInvalid;

  if (fetchInstruction(cache_entry->i, eipBiased)) {
    cache_entry->pAddr = pAddr;
    cache_entry->writeStamp = *(BX_CPU_THIS_PTR currPageWriteStampPtr);
  }
}

#endif

#endif // BX_SUPPORT_ICACHE
<commit_msg>Fixed CPU runway after pressing reset button<commit_after>/////////////////////////////////////////////////////////////////////////
// $Id$
/////////////////////////////////////////////////////////////////////////
//
//   Copyright (c) 2007 Stanislav Shwartsman
//          Written by Stanislav Shwartsman [sshwarts at sourceforge net]
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  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
//
/////////////////////////////////////////////////////////////////////////

#define NEED_CPU_REG_SHORTCUTS 1
#include "bochs.h"
#include "cpu.h"
#define LOG_THIS BX_CPU_THIS_PTR

bx_bool BX_CPU_C::fetchInstruction(bxInstruction_c *iStorage, Bit32u eipBiased)
{
  unsigned remainingInPage = BX_CPU_THIS_PTR eipPageWindowSize - eipBiased;
  const Bit8u *fetchPtr = BX_CPU_THIS_PTR eipFetchPtr + eipBiased;
  unsigned ret;

#if BX_SUPPORT_X86_64
  if (BX_CPU_THIS_PTR cpu_mode == BX_MODE_LONG_64)
    ret = fetchDecode64(fetchPtr, iStorage, remainingInPage);
  else
#endif
    ret = fetchDecode32(fetchPtr, iStorage, remainingInPage);

  if (ret==0) {
    // handle instrumentation callback inside boundaryFetch
    boundaryFetch(fetchPtr, remainingInPage, iStorage);
    return 0;
  }

#if BX_INSTRUMENTATION
  BX_INSTR_OPCODE(BX_CPU_ID, fetchPtr, iStorage->ilen(),
       BX_CPU_THIS_PTR sregs[BX_SEG_REG_CS].cache.u.segment.d_b, Is64BitMode());
#endif

  return 1;
}

#if BX_SUPPORT_ICACHE

bxPageWriteStampTable pageWriteStampTable;

void flushICaches(void)
{
  for (unsigned i=0; i<BX_SMP_PROCESSORS; i++) {
    BX_CPU(i)->iCache.flushICacheEntries();
    BX_CPU(i)->invalidate_prefetch_q();
    BX_CPU(i)->async_event |= BX_ASYNC_EVENT_STOP_TRACE;
  }

  pageWriteStampTable.resetWriteStamps();
}

void purgeICaches(void)
{
  flushICaches();
}

#if BX_SUPPORT_TRACE_CACHE

void handleSMC(void)
{
  for (unsigned i=0; i<BX_SMP_PROCESSORS; i++)
    BX_CPU(i)->async_event |= BX_ASYNC_EVENT_STOP_TRACE;
}

void BX_CPU_C::serveICacheMiss(bxICacheEntry_c *cache_entry, Bit32u eipBiased, bx_phy_address pAddr)
{
  BX_CPU_THIS_PTR iCache.alloc_trace(cache_entry);

  // Cache miss. We weren't so lucky, but let's be optimistic - try to build
  // trace from incoming instruction bytes stream !
  cache_entry->pAddr = pAddr;
  cache_entry->writeStamp = *(BX_CPU_THIS_PTR currPageWriteStampPtr);

  unsigned remainingInPage = BX_CPU_THIS_PTR eipPageWindowSize - eipBiased;
  const Bit8u *fetchPtr = BX_CPU_THIS_PTR eipFetchPtr + eipBiased;
  unsigned ret;

  bxInstruction_c *i = cache_entry->i;

  for (unsigned n=0;n<BX_MAX_TRACE_LENGTH;n++)
  {
#if BX_SUPPORT_X86_64
    if (BX_CPU_THIS_PTR cpu_mode == BX_MODE_LONG_64)
      ret = fetchDecode64(fetchPtr, i, remainingInPage);
    else
#endif
      ret = fetchDecode32(fetchPtr, i, remainingInPage);

    if (ret==0) {
      // Fetching instruction on segment/page boundary
      if (n > 0) {
         // The trace is already valid, it has several instructions inside,
         // in this case just drop the boundary instruction and stop
         // tracing.
         break;
      }
      // First instruction is boundary fetch, leave the trace cache entry
      // invalid and do not cache the instruction.
      cache_entry->writeStamp = ICacheWriteStampInvalid;
      cache_entry->ilen = 1;
      boundaryFetch(fetchPtr, remainingInPage, i);
      return;
    }

    // add instruction to the trace
    unsigned iLen = i->ilen();
    cache_entry->ilen++;

    // continue to the next instruction
    remainingInPage -= iLen;
    if (i->getStopTraceAttr() || remainingInPage == 0) break;
    pAddr += iLen;
    fetchPtr += iLen;
    i++;

    // try to find a trace starting from current pAddr and merge
    if (mergeTraces(cache_entry, i, pAddr)) break;
  }

  BX_CPU_THIS_PTR iCache.commit_trace(cache_entry->ilen);
}

bx_bool BX_CPU_C::mergeTraces(bxICacheEntry_c *entry, bxInstruction_c *i, bx_phy_address pAddr)
{
  bxICacheEntry_c *e = BX_CPU_THIS_PTR iCache.get_entry(pAddr);

  if ((e->pAddr == pAddr) && (e->writeStamp == entry->writeStamp))
  {
    // determine max amount of instruction to take from another entry
    unsigned max_length = e->ilen;
    if (max_length + entry->ilen > BX_MAX_TRACE_LENGTH)
        max_length = BX_MAX_TRACE_LENGTH - entry->ilen;
    if(max_length == 0) return 0;

    memcpy(i, e->i, sizeof(bxInstruction_c)*max_length);
    entry->ilen += max_length;
    BX_ASSERT(entry->ilen <= BX_MAX_TRACE_LENGTH);

    return 1;
  }

  return 0;
}

#else // BX_SUPPORT_TRACE_CACHE == 0

void BX_CPU_C::serveICacheMiss(bxICacheEntry_c *cache_entry, Bit32u eipBiased, bx_phy_address pAddr)
{
  // The entry will be marked valid if fetchdecode will succeed
  cache_entry->writeStamp = ICacheWriteStampInvalid;

  if (fetchInstruction(cache_entry->i, eipBiased)) {
    cache_entry->pAddr = pAddr;
    cache_entry->writeStamp = *(BX_CPU_THIS_PTR currPageWriteStampPtr);
  }
}

#endif

#endif // BX_SUPPORT_ICACHE
<|endoftext|>


<commit_before>// Copyright (c) 2009-2021 The Regents of the University of Michigan
// This file is part of the HOOMD-blue project, released under the BSD 3-Clause License.

// Maintainer: jglaser

/*! \file SnapshotSystemData.cc
    \brief Implements SnapshotSystemData related functions
 */

#include "SnapshotSystemData.h"
#include <pybind11/pybind11.h>
namespace py = pybind11;

template<class Real>
void SnapshotSystemData<Real>::replicate(unsigned int nx, unsigned int ny, unsigned int nz)
    {
    assert(nx > 0);
    assert(ny > 0);
    assert(nz > 0);

    // Update global box
    BoxDim old_box = global_box;
    Scalar3 L = global_box.getL();
    L.x *= (Scalar)nx;
    L.y *= (Scalar)ny;
    L.z *= (Scalar)nz;
    global_box.setL(L);

    unsigned int old_n = particle_data.size;
    unsigned int n = nx * ny * nz;

    // replicate snapshots
    particle_data.replicate(nx, ny, nz, old_box, global_box);
    bond_data.replicate(n, old_n);
    angle_data.replicate(n, old_n);
    dihedral_data.replicate(n, old_n);
    improper_data.replicate(n, old_n);
    constraint_data.replicate(n, old_n);
    pair_data.replicate(n, old_n);
    }

template<class Real> void SnapshotSystemData<Real>::wrap()
    {
    for (unsigned int i = 0; i < particle_data.size; i++)
        {
        auto const frac = global_box.makeFraction(particle_data.pos[i]);
        auto modulus_positive
            = [](Real x) { return std::fmod(std::fmod(x, Real(1.0)) + Real(1.0), Real(1.0)); };
        auto const wrapped = vec3<Real>(modulus_positive(static_cast<Real>(frac.x)),
                                        modulus_positive(static_cast<Real>(frac.y)),
                                        modulus_positive(static_cast<Real>(frac.z)));
        particle_data.pos[i] = global_box.makeCoordinates(wrapped);
        auto const img = make_int3(static_cast<int>(std::floor(frac.x)),
                                   static_cast<int>(std::floor(frac.y)),
                                   static_cast<int>(std::floor(frac.z)));
        particle_data.image[i] = img;
        }
    }

template<class Real>
void SnapshotSystemData<Real>::broadcast_box(std::shared_ptr<MPIConfiguration> mpi_conf)
    {
#ifdef ENABLE_MPI
    if (mpi_conf->getNRanks() > 1)
        {
        bcast(global_box, 0, mpi_conf->getCommunicator());
        bcast(dimensions, 0, mpi_conf->getCommunicator());
        }
#endif
    }

template<class Real>
void SnapshotSystemData<Real>::broadcast(unsigned int root,
                                         std::shared_ptr<ExecutionConfiguration> exec_conf)
    {
#ifdef ENABLE_MPI
    if (exec_conf->getNRanks() > 1)
        {
        bcast(global_box, root, exec_conf->getMPICommunicator());
        bcast(dimensions, root, exec_conf->getMPICommunicator());

        particle_data.bcast(root, exec_conf->getMPICommunicator());
        bcast(map, root, exec_conf->getMPICommunicator());
        bond_data.bcast(root, exec_conf->getMPICommunicator());
        angle_data.bcast(root, exec_conf->getMPICommunicator());
        dihedral_data.bcast(root, exec_conf->getMPICommunicator());
        improper_data.bcast(root, exec_conf->getMPICommunicator());
        constraint_data.bcast(root, exec_conf->getMPICommunicator());
        pair_data.bcast(root, exec_conf->getMPICommunicator());
        }
#endif
    }

template<class Real>
void SnapshotSystemData<Real>::broadcast_all(unsigned int root,
                                             std::shared_ptr<ExecutionConfiguration> exec_conf)
    {
#ifdef ENABLE_MPI
    MPI_Comm hoomd_world = exec_conf->getHOOMDWorldMPICommunicator();
    int n_ranks;
    MPI_Comm_size(hoomd_world, &n_ranks);
    if (n_ranks > 0)
        {
        bcast(global_box, root, hoomd_world);
        bcast(dimensions, root, hoomd_world);

        particle_data.bcast(root, hoomd_world);
        bcast(map, root, hoomd_world);

        bond_data.bcast(root, hoomd_world);
        angle_data.bcast(root, hoomd_world);
        dihedral_data.bcast(root, hoomd_world);
        improper_data.bcast(root, hoomd_world);
        constraint_data.bcast(root, hoomd_world);
        pair_data.bcast(root, hoomd_world);
        }
#endif
    }

// instantiate both float and double snapshots
template struct PYBIND11_EXPORT SnapshotSystemData<float>;
template struct PYBIND11_EXPORT SnapshotSystemData<double>;

void export_SnapshotSystemData(py::module& m)
    {
    py::class_<SnapshotSystemData<float>, std::shared_ptr<SnapshotSystemData<float>>>(
        m,
        "SnapshotSystemData_float")
        .def(py::init<>())
        .def_readwrite("_dimensions", &SnapshotSystemData<float>::dimensions)
        .def_readwrite("_global_box", &SnapshotSystemData<float>::global_box)
        .def_readonly("particles", &SnapshotSystemData<float>::particle_data)
        .def_readonly("bonds", &SnapshotSystemData<float>::bond_data)
        .def_readonly("angles", &SnapshotSystemData<float>::angle_data)
        .def_readonly("dihedrals", &SnapshotSystemData<float>::dihedral_data)
        .def_readonly("impropers", &SnapshotSystemData<float>::improper_data)
        .def_readonly("constraints", &SnapshotSystemData<float>::constraint_data)
        .def_readonly("pairs", &SnapshotSystemData<float>::pair_data)
        .def("replicate", &SnapshotSystemData<float>::replicate)
        .def("wrap", &SnapshotSystemData<float>::wrap)
        .def("_broadcast_box", &SnapshotSystemData<float>::broadcast_box)
        .def("_broadcast", &SnapshotSystemData<float>::broadcast)
        .def("_broadcast_all", &SnapshotSystemData<float>::broadcast_all);

    py::class_<SnapshotSystemData<double>, std::shared_ptr<SnapshotSystemData<double>>>(
        m,
        "SnapshotSystemData_double")
        .def(py::init<>())
        .def_readwrite("_dimensions", &SnapshotSystemData<double>::dimensions)
        .def_readwrite("_global_box", &SnapshotSystemData<double>::global_box)
        .def_readonly("particles", &SnapshotSystemData<double>::particle_data)
        .def_readonly("bonds", &SnapshotSystemData<double>::bond_data)
        .def_readonly("angles", &SnapshotSystemData<double>::angle_data)
        .def_readonly("dihedrals", &SnapshotSystemData<double>::dihedral_data)
        .def_readonly("impropers", &SnapshotSystemData<double>::improper_data)
        .def_readonly("constraints", &SnapshotSystemData<double>::constraint_data)
        .def_readonly("pairs", &SnapshotSystemData<double>::pair_data)
        .def("replicate", &SnapshotSystemData<double>::replicate)
        .def("wrap", &SnapshotSystemData<double>::wrap)
        .def("_broadcast_box", &SnapshotSystemData<double>::broadcast_box)
        .def("_broadcast", &SnapshotSystemData<double>::broadcast)
        .def("_broadcast_all", &SnapshotSystemData<double>::broadcast_all);
    }
<commit_msg>account for current particle image<commit_after>// Copyright (c) 2009-2021 The Regents of the University of Michigan
// This file is part of the HOOMD-blue project, released under the BSD 3-Clause License.

// Maintainer: jglaser

/*! \file SnapshotSystemData.cc
    \brief Implements SnapshotSystemData related functions
 */

#include "SnapshotSystemData.h"
#include <pybind11/pybind11.h>
namespace py = pybind11;

template<class Real>
void SnapshotSystemData<Real>::replicate(unsigned int nx, unsigned int ny, unsigned int nz)
    {
    assert(nx > 0);
    assert(ny > 0);
    assert(nz > 0);

    // Update global box
    BoxDim old_box = global_box;
    Scalar3 L = global_box.getL();
    L.x *= (Scalar)nx;
    L.y *= (Scalar)ny;
    L.z *= (Scalar)nz;
    global_box.setL(L);

    unsigned int old_n = particle_data.size;
    unsigned int n = nx * ny * nz;

    // replicate snapshots
    particle_data.replicate(nx, ny, nz, old_box, global_box);
    bond_data.replicate(n, old_n);
    angle_data.replicate(n, old_n);
    dihedral_data.replicate(n, old_n);
    improper_data.replicate(n, old_n);
    constraint_data.replicate(n, old_n);
    pair_data.replicate(n, old_n);
    }

template<class Real> void SnapshotSystemData<Real>::wrap()
    {
    for (unsigned int i = 0; i < particle_data.size; i++)
        {
        auto const frac = global_box.makeFraction(particle_data.pos[i]);
        auto modulus_positive
            = [](Real x) { return std::fmod(std::fmod(x, Real(1.0)) + Real(1.0), Real(1.0)); };
        auto const wrapped = vec3<Real>(modulus_positive(static_cast<Real>(frac.x)),
                                        modulus_positive(static_cast<Real>(frac.y)),
                                        modulus_positive(static_cast<Real>(frac.z)));
        particle_data.pos[i] = global_box.makeCoordinates(wrapped);
        auto const img = make_int3(static_cast<int>(std::floor(frac.x)),
                                   static_cast<int>(std::floor(frac.y)),
                                   static_cast<int>(std::floor(frac.z)));
        particle_data.image[i] += img;
        }
    }

template<class Real>
void SnapshotSystemData<Real>::broadcast_box(std::shared_ptr<MPIConfiguration> mpi_conf)
    {
#ifdef ENABLE_MPI
    if (mpi_conf->getNRanks() > 1)
        {
        bcast(global_box, 0, mpi_conf->getCommunicator());
        bcast(dimensions, 0, mpi_conf->getCommunicator());
        }
#endif
    }

template<class Real>
void SnapshotSystemData<Real>::broadcast(unsigned int root,
                                         std::shared_ptr<ExecutionConfiguration> exec_conf)
    {
#ifdef ENABLE_MPI
    if (exec_conf->getNRanks() > 1)
        {
        bcast(global_box, root, exec_conf->getMPICommunicator());
        bcast(dimensions, root, exec_conf->getMPICommunicator());

        particle_data.bcast(root, exec_conf->getMPICommunicator());
        bcast(map, root, exec_conf->getMPICommunicator());
        bond_data.bcast(root, exec_conf->getMPICommunicator());
        angle_data.bcast(root, exec_conf->getMPICommunicator());
        dihedral_data.bcast(root, exec_conf->getMPICommunicator());
        improper_data.bcast(root, exec_conf->getMPICommunicator());
        constraint_data.bcast(root, exec_conf->getMPICommunicator());
        pair_data.bcast(root, exec_conf->getMPICommunicator());
        }
#endif
    }

template<class Real>
void SnapshotSystemData<Real>::broadcast_all(unsigned int root,
                                             std::shared_ptr<ExecutionConfiguration> exec_conf)
    {
#ifdef ENABLE_MPI
    MPI_Comm hoomd_world = exec_conf->getHOOMDWorldMPICommunicator();
    int n_ranks;
    MPI_Comm_size(hoomd_world, &n_ranks);
    if (n_ranks > 0)
        {
        bcast(global_box, root, hoomd_world);
        bcast(dimensions, root, hoomd_world);

        particle_data.bcast(root, hoomd_world);
        bcast(map, root, hoomd_world);

        bond_data.bcast(root, hoomd_world);
        angle_data.bcast(root, hoomd_world);
        dihedral_data.bcast(root, hoomd_world);
        improper_data.bcast(root, hoomd_world);
        constraint_data.bcast(root, hoomd_world);
        pair_data.bcast(root, hoomd_world);
        }
#endif
    }

// instantiate both float and double snapshots
template struct PYBIND11_EXPORT SnapshotSystemData<float>;
template struct PYBIND11_EXPORT SnapshotSystemData<double>;

void export_SnapshotSystemData(py::module& m)
    {
    py::class_<SnapshotSystemData<float>, std::shared_ptr<SnapshotSystemData<float>>>(
        m,
        "SnapshotSystemData_float")
        .def(py::init<>())
        .def_readwrite("_dimensions", &SnapshotSystemData<float>::dimensions)
        .def_readwrite("_global_box", &SnapshotSystemData<float>::global_box)
        .def_readonly("particles", &SnapshotSystemData<float>::particle_data)
        .def_readonly("bonds", &SnapshotSystemData<float>::bond_data)
        .def_readonly("angles", &SnapshotSystemData<float>::angle_data)
        .def_readonly("dihedrals", &SnapshotSystemData<float>::dihedral_data)
        .def_readonly("impropers", &SnapshotSystemData<float>::improper_data)
        .def_readonly("constraints", &SnapshotSystemData<float>::constraint_data)
        .def_readonly("pairs", &SnapshotSystemData<float>::pair_data)
        .def("replicate", &SnapshotSystemData<float>::replicate)
        .def("wrap", &SnapshotSystemData<float>::wrap)
        .def("_broadcast_box", &SnapshotSystemData<float>::broadcast_box)
        .def("_broadcast", &SnapshotSystemData<float>::broadcast)
        .def("_broadcast_all", &SnapshotSystemData<float>::broadcast_all);

    py::class_<SnapshotSystemData<double>, std::shared_ptr<SnapshotSystemData<double>>>(
        m,
        "SnapshotSystemData_double")
        .def(py::init<>())
        .def_readwrite("_dimensions", &SnapshotSystemData<double>::dimensions)
        .def_readwrite("_global_box", &SnapshotSystemData<double>::global_box)
        .def_readonly("particles", &SnapshotSystemData<double>::particle_data)
        .def_readonly("bonds", &SnapshotSystemData<double>::bond_data)
        .def_readonly("angles", &SnapshotSystemData<double>::angle_data)
        .def_readonly("dihedrals", &SnapshotSystemData<double>::dihedral_data)
        .def_readonly("impropers", &SnapshotSystemData<double>::improper_data)
        .def_readonly("constraints", &SnapshotSystemData<double>::constraint_data)
        .def_readonly("pairs", &SnapshotSystemData<double>::pair_data)
        .def("replicate", &SnapshotSystemData<double>::replicate)
        .def("wrap", &SnapshotSystemData<double>::wrap)
        .def("_broadcast_box", &SnapshotSystemData<double>::broadcast_box)
        .def("_broadcast", &SnapshotSystemData<double>::broadcast)
        .def("_broadcast_all", &SnapshotSystemData<double>::broadcast_all);
    }
<|endoftext|>


<commit_before>#include <iostream>
#include <string>

using namespace std;

string readFile(string name) {
	FILE* f;
	char* str;
	int size;
	int c;

	f = fopen(name.c_str(), "r");
	if (!f) return NULL;

	fseek(f, 0, SEEK_END);
	size = ftell(f);
	//rewind(f);
	fseek(f, 0, SEEK_SET);

	str = new char[size + 1];
	//fgets(str, size, f);
	//fread(str, 1, size, f);
	//str[size] = '\0';
	int i = 0;
	while((c = fgetc(f)) != EOF)
		*(str + i++) = (char)c;
	*(str + i) = '\0';
	fclose(f);
	string ret(str);
	free(str);
	return ret;
}

bool writeFile(string name, string data) {
	cout << name << "\n";
	FILE* f;

	f = fopen(name.c_str(), "w");
	if (!f) return false;

	fwrite(data.c_str(), 1, data.length(), f);
	fclose(f);

	return true;
}
<commit_msg>removed some comments<commit_after>#include <iostream>
#include <string>

using namespace std;

string readFile(string name) {
	FILE* f;
	char* str;
	int size;
	int i = 0;

	f = fopen(name.c_str(), "r");
	if (!f) return NULL;

	fseek(f, 0, SEEK_END);
	size = ftell(f);
	fseek(f, 0, SEEK_SET);

	str = new char[size + 1];

	while((c = fgetc(f)) != EOF)
		*(str + i++) = (char)c;

	*(str + i) = '\0';

	fclose(f);

	string ret(str);
	free(str);
	return ret;
}

bool writeFile(string name, string data) {
	cout << name << "\n";
	FILE* f;

	f = fopen(name.c_str(), "w");
	if (!f) return false;

	fwrite(data.c_str(), 1, data.length(), f);
	fclose(f);

	return true;
}
<|endoftext|>


<commit_before><commit_msg>qt, tests: Replace accidentally commited assert<commit_after><|endoftext|>


<commit_before>/******************************************************************************
 *                       ____    _    _____                                   *
 *                      / ___|  / \  |  ___|    C++                           *
 *                     | |     / _ \ | |_       Actor                         *
 *                     | |___ / ___ \|  _|      Framework                     *
 *                      \____/_/   \_|_|                                      *
 *                                                                            *
 * Copyright (C) 2011 - 2015                                                  *
 * Dominik Charousset <dominik.charousset (at) haw-hamburg.de>                *
 *                                                                            *
 * Distributed under the terms and conditions of the BSD 3-Clause License or  *
 * (at your option) under the terms and conditions of the Boost Software      *
 * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE.       *
 *                                                                            *
 * If you did not receive a copy of the license files, see                    *
 * http://opensource.org/licenses/BSD-3-Clause and                            *
 * http://www.boost.org/LICENSE_1_0.txt.                                      *
 ******************************************************************************/

#ifndef CAF_IO_BROKER_HPP
#define CAF_IO_BROKER_HPP

#include <map>
#include <vector>

#include "caf/spawn.hpp"
#include "caf/extend.hpp"
#include "caf/local_actor.hpp"

#include "caf/io/abstract_broker.hpp"

namespace caf {
namespace io {

/// Describes a dynamically typed broker.
/// @extends abstract_broker
/// @ingroup Broker
class broker : public abstract_event_based_actor<behavior, false,
                                                 abstract_broker> {
public:
  using super = abstract_event_based_actor<behavior, false, abstract_broker>;

  template <class F, class... Ts>
  actor fork(F fun, connection_handle hdl, Ts&&... xs) {
    // provoke compile-time errors early
    using fun_res = decltype(fun(this, hdl, std::forward<Ts>(xs)...));
    // prevent warning about unused local type
    static_assert(std::is_same<fun_res, fun_res>::value,
                  "your compiler is lying to you");
    auto sptr = take(hdl);
    CAF_ASSERT(sptr->hdl() == hdl);
    return spawn_functor(nullptr,
                         [sptr](broker* forked) {
                           sptr->set_parent(forked);
                           forked->add_scribe(sptr);
                         },
                         fun, hdl, std::forward<Ts>(xs)...);
  }

  void initialize() override;

  broker();

  broker(middleman& parent_ref);

protected:
  virtual behavior make_behavior();
};

using broker_ptr = intrusive_ptr<broker>;

} // namespace io
} // namespace caf

#endif // CAF_IO_BROKER_HPP
<commit_msg>Remove check that collides with stateful brokers<commit_after>/******************************************************************************
 *                       ____    _    _____                                   *
 *                      / ___|  / \  |  ___|    C++                           *
 *                     | |     / _ \ | |_       Actor                         *
 *                     | |___ / ___ \|  _|      Framework                     *
 *                      \____/_/   \_|_|                                      *
 *                                                                            *
 * Copyright (C) 2011 - 2015                                                  *
 * Dominik Charousset <dominik.charousset (at) haw-hamburg.de>                *
 *                                                                            *
 * Distributed under the terms and conditions of the BSD 3-Clause License or  *
 * (at your option) under the terms and conditions of the Boost Software      *
 * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE.       *
 *                                                                            *
 * If you did not receive a copy of the license files, see                    *
 * http://opensource.org/licenses/BSD-3-Clause and                            *
 * http://www.boost.org/LICENSE_1_0.txt.                                      *
 ******************************************************************************/

#ifndef CAF_IO_BROKER_HPP
#define CAF_IO_BROKER_HPP

#include <map>
#include <vector>

#include "caf/spawn.hpp"
#include "caf/extend.hpp"
#include "caf/local_actor.hpp"

#include "caf/io/abstract_broker.hpp"

namespace caf {
namespace io {

/// Describes a dynamically typed broker.
/// @extends abstract_broker
/// @ingroup Broker
class broker : public abstract_event_based_actor<behavior, false,
                                                 abstract_broker> {
public:
  using super = abstract_event_based_actor<behavior, false, abstract_broker>;

  template <class F, class... Ts>
  actor fork(F fun, connection_handle hdl, Ts&&... xs) {
    auto sptr = take(hdl);
    CAF_ASSERT(sptr->hdl() == hdl);
    return spawn_functor(nullptr,
                         [sptr](broker* forked) {
                           sptr->set_parent(forked);
                           forked->add_scribe(sptr);
                         },
                         fun, hdl, std::forward<Ts>(xs)...);
  }

  void initialize() override;

  broker();

  broker(middleman& parent_ref);

protected:
  virtual behavior make_behavior();
};

using broker_ptr = intrusive_ptr<broker>;

} // namespace io
} // namespace caf

#endif // CAF_IO_BROKER_HPP
<|endoftext|>


<commit_before><commit_msg>There is no limitation that 'more' messages in the response should be of the same type, hence the debug message is not needed.<commit_after><|endoftext|>


<commit_before><commit_msg>feat: add util/format_nth to format index<commit_after><|endoftext|>


<commit_before><commit_msg>TextView kerning / spacing fix<commit_after><|endoftext|>


<commit_before><commit_msg>fix wrong Geom initialisierung in mapper constructor<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: regspeed.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 01:55:40 $
 *
 *  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
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_registry.hxx"

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/timeb.h>
#include <sys/types.h>

#include "registry/registry.h"

#ifndef _RTL_USTRING_HXX_
#include    <rtl/ustring.hxx>
#endif

#ifndef _RTL_ALLOC_H_
#include    <rtl/alloc.h>
#endif

using namespace std;

/*****************************************************************
    MyTimer
*****************************************************************/
#ifndef UNX
class MyTimer
{
public:
    void start() { _ftime( &m_start ); };
    void stop()
    {
        _ftime( &m_stop );
        m_diff = difftime(m_stop.time, m_start.time);
        if (m_stop.millitm > m_start.millitm)
        {
            m_diff += ((double)(m_stop.millitm - m_start.millitm)) / 1000;
        }
        else
        {
            m_diff -= 1;
            m_diff += ((double)(1000 - (m_start.millitm - m_stop.millitm))) / 1000;
        }
        printf(" %.4f Sekunden\n", m_diff);
    };

protected:
#ifdef OS2
    struct timeb m_start, m_stop;
#else
    struct _timeb m_start, m_stop;
#endif
    double m_diff;
};
#else
extern "C" int ftime(struct timeb *pt);

class MyTimer
{
public:
    void start() { ftime( &m_start ); };
    void stop()
    {
        ftime( &m_stop );
        m_diff = difftime(m_stop.time, m_start.time);
        if (m_stop.millitm > m_start.millitm)
        {
            m_diff += ((double)(m_stop.millitm - m_start.millitm)) / 1000;
        }
        else
        {
            m_diff -= 1;
            m_diff += ((double)(1000 - (m_start.millitm - m_stop.millitm))) / 1000;
        }
        printf(" %.4f Sekunden\n", m_diff);
    };

protected:
    struct timeb m_start, m_stop;
    double m_diff;
};
#endif

using namespace rtl;

#if (defined UNX) || (defined OS2)
int main( int argc, char * argv[] )
#else
int _cdecl main( int argc, char * argv[] )
#endif
{
    RegHandle       hReg;
    RegKeyHandle    hRootKey, hKey, hSubKey, hSubSubKey;
    OUString        sName1(RTL_CONSTASCII_USTRINGPARAM("regkey"));
    OUString        sName2(RTL_CONSTASCII_USTRINGPARAM("regSubkey"));
    OUString        sName3(RTL_CONSTASCII_USTRINGPARAM("regSubSubkey"));
    OUString        keyName1;
    OUString        keyName2;
    OUString        keyName3;
    int             S1 = 10;
    int             S2 = 10;
    int             S3 = 10;
    MyTimer         aTimer;

    if (argc < 4)
    {
        cerr << "using regspeed count1 count2 count3\n";
        exit(1);
    }

    S1 = atoi(argv[1]);
    S2 = atoi(argv[2]);
    S3 = atoi(argv[3]);

    OUString speedReg( RTL_CONSTASCII_USTRINGPARAM("speed.reg"));
    if (reg_createRegistry(speedReg.pData, &hReg))
    {
        cout << "creating registry \"test.reg\" failed\n";
    } else
    {
        if (reg_openRootKey(hReg, &hRootKey))
        {
            cout << "open root key \"test.reg\" failed\n";
        } else
        {
            printf("\n %d keys anlegen, oeffnen und schliessen dauert ... ", (S1 * S2 * S3));
            aTimer.start();

            for (sal_Int32 i=0; i < S1; i++)
            {
                keyName1 = sName1;
                keyName1 += OUString().valueOf(i);
                if (reg_createKey(hRootKey, keyName1.pData, &hKey))
                    cout << "creating key \"" << OUStringToOString(keyName1, RTL_TEXTENCODING_ASCII_US).getStr()
                         << "\" failed\n";

                for (sal_Int32 j=0; j < S2; j++)
                {
                    keyName2 = sName2;
                    keyName2 += OUString().valueOf(j);
                    if (reg_createKey(hKey, keyName2.pData, &hSubKey))
                        cout << "creating key \"" << OUStringToOString(keyName2, RTL_TEXTENCODING_ASCII_US).getStr()
                             << "\" failed\n";

                        for (sal_Int32 n=0; n < S3; n++)
                        {
                            keyName3 = sName3;
                            keyName3 += OUString().valueOf(n);
                            if (reg_createKey(hSubKey, keyName3.pData, &hSubSubKey))
                                cout << "creating key \"" << OUStringToOString(keyName3, RTL_TEXTENCODING_ASCII_US).getStr()
                                     << "\" failed\n";

                            if (reg_closeKey(hSubSubKey))
                                cout << "closing key \"" << OUStringToOString(keyName3, RTL_TEXTENCODING_ASCII_US).getStr()
                                     << "\" failed\n";
                        }

                    if (reg_closeKey(hSubKey))
                        cout << "closing key \"" << OUStringToOString(keyName2, RTL_TEXTENCODING_ASCII_US).getStr()
                             << "\" failed\n";
                }

                if (reg_closeKey(hKey))
                    cout << "closing key \"" << OUStringToOString(keyName1, RTL_TEXTENCODING_ASCII_US).getStr()
                         << "\" failed\n";
            }

            aTimer.stop();

            printf("\n %d keys oeffnen und schliessen dauert ... ", (S1 * S2 * S3));
            aTimer.start();

            for (sal_Int32 i=0; i < S1; i++)
            {
                keyName1 = OUString::createFromAscii("/");
                keyName1 += sName1;
                keyName1 += OUString().valueOf(i);
                if (reg_openKey(hRootKey, keyName1.pData, &hKey))
                    cout << "open key \"" << OUStringToOString(keyName1, RTL_TEXTENCODING_ASCII_US).getStr()
                         << "\" failed\n";

                for (sal_Int32 j=0; j < S2; j++)
                {
                    keyName2 = OUString::createFromAscii("/");
                    keyName2 += sName1;
                    keyName2 += OUString().valueOf(i);
                    keyName2 += OUString::createFromAscii("/");
                    keyName2 += sName2;
                    keyName2 += OUString().valueOf(j);
                    if (reg_openKey(hRootKey, keyName2.pData, &hSubKey))
                        cout << "open key \"" << OUStringToOString(keyName2, RTL_TEXTENCODING_ASCII_US).getStr()
                             << "\" failed\n";

                        for (sal_Int32 n=0; n < S3; n++)
                        {
                            keyName3 = OUString::createFromAscii("/");
                            keyName3 += sName1;
                            keyName3 += OUString().valueOf(i);
                            keyName3 += OUString::createFromAscii("/");
                            keyName3 += sName2;
                            keyName3 += OUString().valueOf(j);
                            keyName3 += OUString::createFromAscii("/");
                            keyName3 += sName3;
                            keyName3 += OUString().valueOf(n);
                            if (reg_openKey(hRootKey, keyName3.pData, &hSubSubKey))
                                cout << "open key \"" << OUStringToOString(keyName3, RTL_TEXTENCODING_ASCII_US).getStr()
                                     << "\" failed\n";

                            if (reg_closeKey(hSubSubKey))
                                cout << "open key \"" << OUStringToOString(keyName3, RTL_TEXTENCODING_ASCII_US).getStr()
                                     << "\" failed\n";
                        }

                    if (reg_closeKey(hSubKey))
                        cout << "closing key \"" << OUStringToOString(keyName2, RTL_TEXTENCODING_ASCII_US).getStr()
                             << "\" failed\n";
                }

                if (reg_closeKey(hKey))
                    cout << "closing key \"" << OUStringToOString(keyName1, RTL_TEXTENCODING_ASCII_US).getStr()
                         << "\" failed\n";
            }

            aTimer.stop();

            printf("\n 1 key oeffnen und schliessen dauert ... ");
            aTimer.start();

            if (reg_openKey(hRootKey, keyName3.pData, &hSubSubKey))
                cout << "open key \"" << OUStringToOString(keyName3, RTL_TEXTENCODING_ASCII_US).getStr()
                     << "\" failed\n";

            if (reg_closeKey(hSubSubKey))
                cout << "open key \"" << OUStringToOString(keyName3, RTL_TEXTENCODING_ASCII_US).getStr()
                     << "\" failed\n";

            aTimer.stop();

        }

        if (reg_closeKey(hRootKey))
            cout << "closing root key failed\n";
        if (reg_closeRegistry(hReg))
            cout << "\t41. closing registry \"test.reg\" failed\n";
    }

    return(0);
}

<commit_msg>INTEGRATION: CWS changefileheader (1.5.42); FILE MERGED 2008/04/01 15:23:09 thb 1.5.42.2: #i85898# Stripping all external header guards 2008/03/31 07:25:19 rt 1.5.42.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: regspeed.cxx,v $
 * $Revision: 1.6 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_registry.hxx"

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/timeb.h>
#include <sys/types.h>

#include "registry/registry.h"
#include    <rtl/ustring.hxx>
#include    <rtl/alloc.h>

using namespace std;

/*****************************************************************
    MyTimer
*****************************************************************/
#ifndef UNX
class MyTimer
{
public:
    void start() { _ftime( &m_start ); };
    void stop()
    {
        _ftime( &m_stop );
        m_diff = difftime(m_stop.time, m_start.time);
        if (m_stop.millitm > m_start.millitm)
        {
            m_diff += ((double)(m_stop.millitm - m_start.millitm)) / 1000;
        }
        else
        {
            m_diff -= 1;
            m_diff += ((double)(1000 - (m_start.millitm - m_stop.millitm))) / 1000;
        }
        printf(" %.4f Sekunden\n", m_diff);
    };

protected:
#ifdef OS2
    struct timeb m_start, m_stop;
#else
    struct _timeb m_start, m_stop;
#endif
    double m_diff;
};
#else
extern "C" int ftime(struct timeb *pt);

class MyTimer
{
public:
    void start() { ftime( &m_start ); };
    void stop()
    {
        ftime( &m_stop );
        m_diff = difftime(m_stop.time, m_start.time);
        if (m_stop.millitm > m_start.millitm)
        {
            m_diff += ((double)(m_stop.millitm - m_start.millitm)) / 1000;
        }
        else
        {
            m_diff -= 1;
            m_diff += ((double)(1000 - (m_start.millitm - m_stop.millitm))) / 1000;
        }
        printf(" %.4f Sekunden\n", m_diff);
    };

protected:
    struct timeb m_start, m_stop;
    double m_diff;
};
#endif

using namespace rtl;

#if (defined UNX) || (defined OS2)
int main( int argc, char * argv[] )
#else
int _cdecl main( int argc, char * argv[] )
#endif
{
    RegHandle       hReg;
    RegKeyHandle    hRootKey, hKey, hSubKey, hSubSubKey;
    OUString        sName1(RTL_CONSTASCII_USTRINGPARAM("regkey"));
    OUString        sName2(RTL_CONSTASCII_USTRINGPARAM("regSubkey"));
    OUString        sName3(RTL_CONSTASCII_USTRINGPARAM("regSubSubkey"));
    OUString        keyName1;
    OUString        keyName2;
    OUString        keyName3;
    int             S1 = 10;
    int             S2 = 10;
    int             S3 = 10;
    MyTimer         aTimer;

    if (argc < 4)
    {
        cerr << "using regspeed count1 count2 count3\n";
        exit(1);
    }

    S1 = atoi(argv[1]);
    S2 = atoi(argv[2]);
    S3 = atoi(argv[3]);

    OUString speedReg( RTL_CONSTASCII_USTRINGPARAM("speed.reg"));
    if (reg_createRegistry(speedReg.pData, &hReg))
    {
        cout << "creating registry \"test.reg\" failed\n";
    } else
    {
        if (reg_openRootKey(hReg, &hRootKey))
        {
            cout << "open root key \"test.reg\" failed\n";
        } else
        {
            printf("\n %d keys anlegen, oeffnen und schliessen dauert ... ", (S1 * S2 * S3));
            aTimer.start();

            for (sal_Int32 i=0; i < S1; i++)
            {
                keyName1 = sName1;
                keyName1 += OUString().valueOf(i);
                if (reg_createKey(hRootKey, keyName1.pData, &hKey))
                    cout << "creating key \"" << OUStringToOString(keyName1, RTL_TEXTENCODING_ASCII_US).getStr()
                         << "\" failed\n";

                for (sal_Int32 j=0; j < S2; j++)
                {
                    keyName2 = sName2;
                    keyName2 += OUString().valueOf(j);
                    if (reg_createKey(hKey, keyName2.pData, &hSubKey))
                        cout << "creating key \"" << OUStringToOString(keyName2, RTL_TEXTENCODING_ASCII_US).getStr()
                             << "\" failed\n";

                        for (sal_Int32 n=0; n < S3; n++)
                        {
                            keyName3 = sName3;
                            keyName3 += OUString().valueOf(n);
                            if (reg_createKey(hSubKey, keyName3.pData, &hSubSubKey))
                                cout << "creating key \"" << OUStringToOString(keyName3, RTL_TEXTENCODING_ASCII_US).getStr()
                                     << "\" failed\n";

                            if (reg_closeKey(hSubSubKey))
                                cout << "closing key \"" << OUStringToOString(keyName3, RTL_TEXTENCODING_ASCII_US).getStr()
                                     << "\" failed\n";
                        }

                    if (reg_closeKey(hSubKey))
                        cout << "closing key \"" << OUStringToOString(keyName2, RTL_TEXTENCODING_ASCII_US).getStr()
                             << "\" failed\n";
                }

                if (reg_closeKey(hKey))
                    cout << "closing key \"" << OUStringToOString(keyName1, RTL_TEXTENCODING_ASCII_US).getStr()
                         << "\" failed\n";
            }

            aTimer.stop();

            printf("\n %d keys oeffnen und schliessen dauert ... ", (S1 * S2 * S3));
            aTimer.start();

            for (sal_Int32 i=0; i < S1; i++)
            {
                keyName1 = OUString::createFromAscii("/");
                keyName1 += sName1;
                keyName1 += OUString().valueOf(i);
                if (reg_openKey(hRootKey, keyName1.pData, &hKey))
                    cout << "open key \"" << OUStringToOString(keyName1, RTL_TEXTENCODING_ASCII_US).getStr()
                         << "\" failed\n";

                for (sal_Int32 j=0; j < S2; j++)
                {
                    keyName2 = OUString::createFromAscii("/");
                    keyName2 += sName1;
                    keyName2 += OUString().valueOf(i);
                    keyName2 += OUString::createFromAscii("/");
                    keyName2 += sName2;
                    keyName2 += OUString().valueOf(j);
                    if (reg_openKey(hRootKey, keyName2.pData, &hSubKey))
                        cout << "open key \"" << OUStringToOString(keyName2, RTL_TEXTENCODING_ASCII_US).getStr()
                             << "\" failed\n";

                        for (sal_Int32 n=0; n < S3; n++)
                        {
                            keyName3 = OUString::createFromAscii("/");
                            keyName3 += sName1;
                            keyName3 += OUString().valueOf(i);
                            keyName3 += OUString::createFromAscii("/");
                            keyName3 += sName2;
                            keyName3 += OUString().valueOf(j);
                            keyName3 += OUString::createFromAscii("/");
                            keyName3 += sName3;
                            keyName3 += OUString().valueOf(n);
                            if (reg_openKey(hRootKey, keyName3.pData, &hSubSubKey))
                                cout << "open key \"" << OUStringToOString(keyName3, RTL_TEXTENCODING_ASCII_US).getStr()
                                     << "\" failed\n";

                            if (reg_closeKey(hSubSubKey))
                                cout << "open key \"" << OUStringToOString(keyName3, RTL_TEXTENCODING_ASCII_US).getStr()
                                     << "\" failed\n";
                        }

                    if (reg_closeKey(hSubKey))
                        cout << "closing key \"" << OUStringToOString(keyName2, RTL_TEXTENCODING_ASCII_US).getStr()
                             << "\" failed\n";
                }

                if (reg_closeKey(hKey))
                    cout << "closing key \"" << OUStringToOString(keyName1, RTL_TEXTENCODING_ASCII_US).getStr()
                         << "\" failed\n";
            }

            aTimer.stop();

            printf("\n 1 key oeffnen und schliessen dauert ... ");
            aTimer.start();

            if (reg_openKey(hRootKey, keyName3.pData, &hSubSubKey))
                cout << "open key \"" << OUStringToOString(keyName3, RTL_TEXTENCODING_ASCII_US).getStr()
                     << "\" failed\n";

            if (reg_closeKey(hSubSubKey))
                cout << "open key \"" << OUStringToOString(keyName3, RTL_TEXTENCODING_ASCII_US).getStr()
                     << "\" failed\n";

            aTimer.stop();

        }

        if (reg_closeKey(hRootKey))
            cout << "closing root key failed\n";
        if (reg_closeRegistry(hReg))
            cout << "\t41. closing registry \"test.reg\" failed\n";
    }

    return(0);
}

<|endoftext|>