<commit_before>/*!
 * \file painter_image_brush_shader.cpp
 * \brief file painter_image_brush_shader.cpp
 *
 * Copyright 2019 by Intel.
 *
 * Contact: kevin.rogovin@intel.com
 *
 * This Source Code Form is subject to the
 * terms of the Mozilla Public License, v. 2.0.
 * If a copy of the MPL was not distributed with
 * this file, You can obtain one at
 * http://mozilla.org/MPL/2.0/.
 *
 * \author Kevin Rogovin <kevin.rogovin@intel.com>
 *
 */

#include <iostream>
#include <fastuidraw/util/vecN.hpp>
#include <fastuidraw/painter/shader/painter_image_brush_shader.hpp>
#include <fastuidraw/painter/painter_packed_value_pool.hpp>
#include <private/util_private_ostream.hpp>

namespace
{
  class PainterImageBrushShaderPrivate
  {
  public:
    typedef fastuidraw::reference_counted_ptr<fastuidraw::PainterBrushShader> shader_ref;

    shader_ref m_parent_shader;
    fastuidraw::vecN<shader_ref, fastuidraw::PainterImageBrushShader::number_sub_shaders> m_sub_shaders;
  };
}

/////////////////////////////////////////////
// fastuidraw::PainterImageBrushShader methods
fastuidraw::PainterImageBrushShader::
PainterImageBrushShader(const reference_counted_ptr<PainterBrushShader> &parent_shader)
{
  PainterImageBrushShaderPrivate *d;

  m_d = d = FASTUIDRAWnew PainterImageBrushShaderPrivate();
  d->m_parent_shader = parent_shader;

  for (unsigned int i = 0; i < number_sub_shaders; ++i)
    {
      d->m_sub_shaders[i] = FASTUIDRAWnew PainterBrushShader(parent_shader, i);
    }
}

fastuidraw::PainterImageBrushShader::
~PainterImageBrushShader()
{
  PainterImageBrushShaderPrivate *d;
  d = static_cast<PainterImageBrushShaderPrivate*>(m_d);
  FASTUIDRAWdelete(d);
}

uint32_t
fastuidraw::PainterImageBrushShader::
sub_shader_id(const Image *image,
              enum filter_t image_filter,
              enum mipmap_t mip_mapping)
{
  uint32_t return_value(0u);
  if (image)
    {
      uint32_t filter_bits, type_bits, mip_bits, format_bits;

      filter_bits = pack_bits(filter_bit0, filter_num_bits, image_filter);
      mip_bits = pack_bits(mipmap_bit0, mipmap_num_bits,
                           (mip_mapping == apply_mipmapping) ?
                           image->number_mipmap_levels() - 1u: 0u);
      type_bits = pack_bits(type_bit0, type_num_bits, image->type());
      format_bits =  pack_bits(format_bit0, format_num_bits, image->format());
      return_value = filter_bits | mip_bits | type_bits | format_bits;
    }
  return return_value;
}

const fastuidraw::reference_counted_ptr<fastuidraw::PainterBrushShader>&
fastuidraw::PainterImageBrushShader::
sub_shader(const Image *image,
           enum filter_t image_filter,
           enum mipmap_t mip_mapping) const
{
  PainterImageBrushShaderPrivate *d;
  d = static_cast<PainterImageBrushShaderPrivate*>(m_d);
  return d->m_sub_shaders[sub_shader_id(image, image_filter, mip_mapping)];
}

fastuidraw::c_array<const fastuidraw::reference_counted_ptr<fastuidraw::PainterBrushShader> >
fastuidraw::PainterImageBrushShader::
sub_shaders(void) const
{
  PainterImageBrushShaderPrivate *d;
  d = static_cast<PainterImageBrushShaderPrivate*>(m_d);
  return d->m_sub_shaders;
}

fastuidraw::PainterCustomBrush
fastuidraw::PainterImageBrushShader::
create_brush(PainterPackedValuePool &pool,
             const reference_counted_ptr<const Image> &image,
             uvec2 xy, uvec2 wh,
             enum filter_t image_filter,
             enum mipmap_t mip_mapping) const
{
  PainterDataValue<PainterBrushShaderData> packed_data;
  PainterImageBrushShaderData data;

  data.sub_image(image, xy, wh);
  packed_data = pool.create_packed_value(data);
  return PainterCustomBrush(packed_data, sub_shader(image.get(), image_filter, mip_mapping).get());
}

fastuidraw::PainterCustomBrush
fastuidraw::PainterImageBrushShader::
create_brush(PainterPackedValuePool &pool,
             const reference_counted_ptr<const Image> &image,
             enum filter_t image_filter,
             enum mipmap_t mip_mapping) const
{
  PainterDataValue<PainterBrushShaderData> packed_data;
  PainterImageBrushShaderData data;

  data.image(image);
  packed_data = pool.create_packed_value(data);
  return PainterCustomBrush(packed_data, sub_shader(image.get(), image_filter, mip_mapping).get());
}

////////////////////////////////////////////////
// fastuidraw::PainterImageBrushShaderData methods
fastuidraw::PainterImageBrushShaderData::
PainterImageBrushShaderData(void)
{
  reference_counted_ptr<const Image> null_image;
  image(null_image);
}

unsigned int
fastuidraw::PainterImageBrushShaderData::
data_size(void) const
{
  return FASTUIDRAW_NUMBER_BLOCK4_NEEDED(shader_data_size);
}

void
fastuidraw::PainterImageBrushShaderData::
save_resources(c_array<reference_counted_ptr<const resource_base> > dst) const
{
  if (m_image)
    {
      dst[0] = m_image;
    }
}

unsigned int
fastuidraw::PainterImageBrushShaderData::
number_resources(void) const
{
  return (m_image) ? 1 : 0;
}

fastuidraw::c_array<const fastuidraw::reference_counted_ptr<const fastuidraw::Image> >
fastuidraw::PainterImageBrushShaderData::
bind_images(void) const
{
  unsigned int sz;
  const reference_counted_ptr<const Image> *im;
  sz = (m_image && m_image->type() == Image::context_texture2d) ? 1 : 0;
  im = (sz != 0) ? &m_image : nullptr;
  return c_array<const reference_counted_ptr<const Image> >(im, sz);
}

void
fastuidraw::PainterImageBrushShaderData::
image(const reference_counted_ptr<const Image> &im)
{
  sub_image(im, uvec2(0, 0),
            (im) ? uvec2(im->dimensions()) : uvec2(0, 0));
}

void
fastuidraw::PainterImageBrushShaderData::
sub_image(const reference_counted_ptr<const Image> &im,
          uvec2 xy, uvec2 wh)
{
  m_image = im;
  m_image_xy = xy;
  m_image_wh = wh;
}

void
fastuidraw::PainterImageBrushShaderData::
pack_data(c_array<vecN<generic_data, 4> > pdst) const
{
  c_array<generic_data> dst;

  dst = pdst.flatten_array();
  if (m_image)
    {
      dst[start_xy_offset].u = pack_bits(uvec2_x_bit0, uvec2_x_num_bits, m_image_xy.x())
        | pack_bits(uvec2_y_bit0, uvec2_y_num_bits, m_image_xy.y());

      dst[size_xy_offset].u = pack_bits(uvec2_x_bit0, uvec2_x_num_bits, m_image_wh.x())
        | pack_bits(uvec2_y_bit0, uvec2_y_num_bits, m_image_wh.y());

      switch (m_image->type())
        {
        case Image::on_atlas:
          {
            uvec3 loc(m_image->master_index_tile());
            uint32_t lookups(m_image->number_index_lookups());

            dst[atlas_location_xyz_offset].u = pack_bits(atlas_location_x_bit0, atlas_location_x_num_bits, loc.x())
              | pack_bits(atlas_location_y_bit0, atlas_location_y_num_bits, loc.y())
              | pack_bits(atlas_location_z_bit0, atlas_location_z_num_bits, loc.z());

            dst[number_lookups_offset].u = lookups;
          }
          break;

        case Image::bindless_texture2d:
          {
            uint64_t v, hi, low;

            v = m_image->bindless_handle();
            hi = uint64_unpack_bits(32, 32, v);
            low = uint64_unpack_bits(0, 32, v);
            dst[bindless_handle_hi_offset].u = hi;
            dst[bindless_handle_low_offset].u = low;
          }
          break;

        default:
          break;
        }
    }
  else
    {
      generic_data zero;

      zero.u = 0u;
      std::fill(dst.begin(), dst.end(), zero);
    }
}
<commit_msg>fastuidraw/painter/shader/painter_image_brush_shader: remove unneeded includes<commit_after>/*!
 * \file painter_image_brush_shader.cpp
 * \brief file painter_image_brush_shader.cpp
 *
 * Copyright 2019 by Intel.
 *
 * Contact: kevin.rogovin@intel.com
 *
 * This Source Code Form is subject to the
 * terms of the Mozilla Public License, v. 2.0.
 * If a copy of the MPL was not distributed with
 * this file, You can obtain one at
 * http://mozilla.org/MPL/2.0/.
 *
 * \author Kevin Rogovin <kevin.rogovin@intel.com>
 *
 */

#include <fastuidraw/util/vecN.hpp>
#include <fastuidraw/painter/shader/painter_image_brush_shader.hpp>
#include <fastuidraw/painter/painter_packed_value_pool.hpp>

namespace
{
  class PainterImageBrushShaderPrivate
  {
  public:
    typedef fastuidraw::reference_counted_ptr<fastuidraw::PainterBrushShader> shader_ref;

    shader_ref m_parent_shader;
    fastuidraw::vecN<shader_ref, fastuidraw::PainterImageBrushShader::number_sub_shaders> m_sub_shaders;
  };
}

/////////////////////////////////////////////
// fastuidraw::PainterImageBrushShader methods
fastuidraw::PainterImageBrushShader::
PainterImageBrushShader(const reference_counted_ptr<PainterBrushShader> &parent_shader)
{
  PainterImageBrushShaderPrivate *d;

  m_d = d = FASTUIDRAWnew PainterImageBrushShaderPrivate();
  d->m_parent_shader = parent_shader;

  for (unsigned int i = 0; i < number_sub_shaders; ++i)
    {
      d->m_sub_shaders[i] = FASTUIDRAWnew PainterBrushShader(parent_shader, i);
    }
}

fastuidraw::PainterImageBrushShader::
~PainterImageBrushShader()
{
  PainterImageBrushShaderPrivate *d;
  d = static_cast<PainterImageBrushShaderPrivate*>(m_d);
  FASTUIDRAWdelete(d);
}

uint32_t
fastuidraw::PainterImageBrushShader::
sub_shader_id(const Image *image,
              enum filter_t image_filter,
              enum mipmap_t mip_mapping)
{
  uint32_t return_value(0u);
  if (image)
    {
      uint32_t filter_bits, type_bits, mip_bits, format_bits;

      filter_bits = pack_bits(filter_bit0, filter_num_bits, image_filter);
      mip_bits = pack_bits(mipmap_bit0, mipmap_num_bits,
                           (mip_mapping == apply_mipmapping) ?
                           image->number_mipmap_levels() - 1u: 0u);
      type_bits = pack_bits(type_bit0, type_num_bits, image->type());
      format_bits =  pack_bits(format_bit0, format_num_bits, image->format());
      return_value = filter_bits | mip_bits | type_bits | format_bits;
    }
  return return_value;
}

const fastuidraw::reference_counted_ptr<fastuidraw::PainterBrushShader>&
fastuidraw::PainterImageBrushShader::
sub_shader(const Image *image,
           enum filter_t image_filter,
           enum mipmap_t mip_mapping) const
{
  PainterImageBrushShaderPrivate *d;
  d = static_cast<PainterImageBrushShaderPrivate*>(m_d);
  return d->m_sub_shaders[sub_shader_id(image, image_filter, mip_mapping)];
}

fastuidraw::c_array<const fastuidraw::reference_counted_ptr<fastuidraw::PainterBrushShader> >
fastuidraw::PainterImageBrushShader::
sub_shaders(void) const
{
  PainterImageBrushShaderPrivate *d;
  d = static_cast<PainterImageBrushShaderPrivate*>(m_d);
  return d->m_sub_shaders;
}

fastuidraw::PainterCustomBrush
fastuidraw::PainterImageBrushShader::
create_brush(PainterPackedValuePool &pool,
             const reference_counted_ptr<const Image> &image,
             uvec2 xy, uvec2 wh,
             enum filter_t image_filter,
             enum mipmap_t mip_mapping) const
{
  PainterDataValue<PainterBrushShaderData> packed_data;
  PainterImageBrushShaderData data;

  data.sub_image(image, xy, wh);
  packed_data = pool.create_packed_value(data);
  return PainterCustomBrush(packed_data, sub_shader(image.get(), image_filter, mip_mapping).get());
}

fastuidraw::PainterCustomBrush
fastuidraw::PainterImageBrushShader::
create_brush(PainterPackedValuePool &pool,
             const reference_counted_ptr<const Image> &image,
             enum filter_t image_filter,
             enum mipmap_t mip_mapping) const
{
  PainterDataValue<PainterBrushShaderData> packed_data;
  PainterImageBrushShaderData data;

  data.image(image);
  packed_data = pool.create_packed_value(data);
  return PainterCustomBrush(packed_data, sub_shader(image.get(), image_filter, mip_mapping).get());
}

////////////////////////////////////////////////
// fastuidraw::PainterImageBrushShaderData methods
fastuidraw::PainterImageBrushShaderData::
PainterImageBrushShaderData(void)
{
  reference_counted_ptr<const Image> null_image;
  image(null_image);
}

unsigned int
fastuidraw::PainterImageBrushShaderData::
data_size(void) const
{
  return FASTUIDRAW_NUMBER_BLOCK4_NEEDED(shader_data_size);
}

void
fastuidraw::PainterImageBrushShaderData::
save_resources(c_array<reference_counted_ptr<const resource_base> > dst) const
{
  if (m_image)
    {
      dst[0] = m_image;
    }
}

unsigned int
fastuidraw::PainterImageBrushShaderData::
number_resources(void) const
{
  return (m_image) ? 1 : 0;
}

fastuidraw::c_array<const fastuidraw::reference_counted_ptr<const fastuidraw::Image> >
fastuidraw::PainterImageBrushShaderData::
bind_images(void) const
{
  unsigned int sz;
  const reference_counted_ptr<const Image> *im;
  sz = (m_image && m_image->type() == Image::context_texture2d) ? 1 : 0;
  im = (sz != 0) ? &m_image : nullptr;
  return c_array<const reference_counted_ptr<const Image> >(im, sz);
}

void
fastuidraw::PainterImageBrushShaderData::
image(const reference_counted_ptr<const Image> &im)
{
  sub_image(im, uvec2(0, 0),
            (im) ? uvec2(im->dimensions()) : uvec2(0, 0));
}

void
fastuidraw::PainterImageBrushShaderData::
sub_image(const reference_counted_ptr<const Image> &im,
          uvec2 xy, uvec2 wh)
{
  m_image = im;
  m_image_xy = xy;
  m_image_wh = wh;
}

void
fastuidraw::PainterImageBrushShaderData::
pack_data(c_array<vecN<generic_data, 4> > pdst) const
{
  c_array<generic_data> dst;

  dst = pdst.flatten_array();
  if (m_image)
    {
      dst[start_xy_offset].u = pack_bits(uvec2_x_bit0, uvec2_x_num_bits, m_image_xy.x())
        | pack_bits(uvec2_y_bit0, uvec2_y_num_bits, m_image_xy.y());

      dst[size_xy_offset].u = pack_bits(uvec2_x_bit0, uvec2_x_num_bits, m_image_wh.x())
        | pack_bits(uvec2_y_bit0, uvec2_y_num_bits, m_image_wh.y());

      switch (m_image->type())
        {
        case Image::on_atlas:
          {
            uvec3 loc(m_image->master_index_tile());
            uint32_t lookups(m_image->number_index_lookups());

            dst[atlas_location_xyz_offset].u = pack_bits(atlas_location_x_bit0, atlas_location_x_num_bits, loc.x())
              | pack_bits(atlas_location_y_bit0, atlas_location_y_num_bits, loc.y())
              | pack_bits(atlas_location_z_bit0, atlas_location_z_num_bits, loc.z());

            dst[number_lookups_offset].u = lookups;
          }
          break;

        case Image::bindless_texture2d:
          {
            uint64_t v, hi, low;

            v = m_image->bindless_handle();
            hi = uint64_unpack_bits(32, 32, v);
            low = uint64_unpack_bits(0, 32, v);
            dst[bindless_handle_hi_offset].u = hi;
            dst[bindless_handle_low_offset].u = low;
          }
          break;

        default:
          break;
        }
    }
  else
    {
      generic_data zero;

      zero.u = 0u;
      std::fill(dst.begin(), dst.end(), zero);
    }
}
<|endoftext|>


<commit_before>//=============================================================================
// ■ tile.cpp
//-----------------------------------------------------------------------------
//   3D模型：Tile
//=============================================================================

#include "tile.hpp"

namespace VM76 {
	Tiles::Tiles(int tid) {
		int x = tid % 16;
		int y = tid / 16;
		float T = 1.0f / 16.0f;
		float S = 0.0f;
		float xs = x * T;
		float ys = y * T;
		vtx[0] = new Vertex[4] {
			{{0.0, 0.0, 0.0},{1.0, 1.0, 1.0, 1.0},{xs + S, ys + T},{0.0, 0.0, -1.0}},
			{{0.0, 1.0, 0.0},{1.0, 1.0, 1.0, 1.0},{xs + S, ys + S},{0.0, 0.0, -1.0}},
			{{1.0, 1.0, 0.0},{1.0, 1.0, 1.0, 1.0},{xs + T, ys + S},{0.0, 0.0, -1.0}},
			{{1.0, 0.0, 0.0},{1.0, 1.0, 1.0, 1.0},{xs + T, ys + T},{0.0, 0.0, -1.0}},
		};
		vtx[1] = new Vertex[4] {
			{{0.0, 0.0, 1.0},{1.0, 1.0, 1.0, 1.0},{xs + S, ys + T},{0.0, 0.0, 1.0}},
			{{0.0, 1.0, 1.0},{1.0, 1.0, 1.0, 1.0},{xs + S, ys + S},{0.0, 0.0, 1.0}},
			{{1.0, 1.0, 1.0},{1.0, 1.0, 1.0, 1.0},{xs + T, ys + S},{0.0, 0.0, 1.0}},
			{{1.0, 0.0, 1.0},{1.0, 1.0, 1.0, 1.0},{xs + T, ys + T},{0.0, 0.0, 1.0}},
		};
		vtx[2] = new Vertex[4] {
			{{0.0, 1.0, 0.0},{1.0, 1.0, 1.0, 1.0},{xs + S, ys + S},{0.0, 1.0, 0.0}},
			{{0.0, 1.0, 1.0},{1.0, 1.0, 1.0, 1.0},{xs + S, ys + T},{0.0, 1.0, 0.0}},
			{{1.0, 1.0, 1.0},{1.0, 1.0, 1.0, 1.0},{xs + T, ys + T},{0.0, 1.0, 0.0}},
			{{1.0, 1.0, 0.0},{1.0, 1.0, 1.0, 1.0},{xs + T, ys + S},{0.0, 1.0, 0.0}},
		};
		vtx[3] = new Vertex[4] {
			{{0.0, 0.0, 0.0},{1.0, 1.0, 1.0, 1.0},{xs + S, ys + T},{0.0, -1.0, 0.0}},
			{{0.0, 0.0, 1.0},{1.0, 1.0, 1.0, 1.0},{xs + T, ys + T},{0.0, -1.0, 0.0}},
			{{1.0, 0.0, 1.0},{1.0, 1.0, 1.0, 1.0},{xs + T, ys + S},{0.0, -1.0, 0.0}},
			{{1.0, 0.0, 0.0},{1.0, 1.0, 1.0, 1.0},{xs + S, ys + S},{0.0, -1.0, 0.0}},
		};
		vtx[4] = new Vertex[4] {
			{{0.0, 0.0, 0.0},{1.0, 1.0, 1.0, 1.0},{xs + S, ys + T},{-1.0, 0.0, 0.0}},
			{{0.0, 0.0, 1.0},{1.0, 1.0, 1.0, 1.0},{xs + T, ys + T},{-1.0, 0.0, 0.0}},
			{{0.0, 1.0, 1.0},{1.0, 1.0, 1.0, 1.0},{xs + T, ys + S},{-1.0, 0.0, 0.0}},
			{{0.0, 1.0, 0.0},{1.0, 1.0, 1.0, 1.0},{xs + S, ys + S},{-1.0, 0.0, 0.0}},
		};
		vtx[5] = new Vertex[4] {
			{{1.0, 0.0, 0.0},{1.0, 1.0, 1.0, 1.0},{xs + S, ys + T},{1.0, 0.0, 0.0}},
			{{1.0, 0.0, 1.0},{1.0, 1.0, 1.0, 1.0},{xs + T, ys + T},{1.0, 0.0, 0.0}},
			{{1.0, 1.0, 1.0},{1.0, 1.0, 1.0, 1.0},{xs + T, ys + S},{1.0, 0.0, 0.0}},
			{{1.0, 1.0, 0.0},{1.0, 1.0, 1.0, 1.0},{xs + S, ys + S},{1.0, 0.0, 0.0}},
		};
		itx[0] = new GLuint[6] {0,1,3,  1,2,3};
		itx[1] = new GLuint[6] {3,1,0,  3,2,1};
		itx[2] = new GLuint[6] {0,1,3,  1,2,3};
		itx[3] = new GLuint[6] {3,1,0,  3,2,1};
		itx[4] = new GLuint[6] {0,1,3,  1,2,3};
		itx[5] = new GLuint[6] {3,1,0,  3,2,1};

		// Prepare an empty space
		for (int i = 0; i < 6; i++) {
			mat[i] = new glm::mat4[4096];
			for (int x = 0; x < 4096; x++) mat[i][x] = glm::mat4(1.0);

			obj[i] = new GDrawable();
			obj[i]->data.vtx_c = 4;
			obj[i]->data.ind_c = 2 * 3;
			obj[i]->data.vertices = vtx[i];
			obj[i]->data.indices = itx[i];
			obj[i]->data.tri_mesh_count = 2;
			// Reserve 512 spaces
			obj[i]->data.mat_c = 4096;
			obj[i]->data.mat = (GLuint*) &mat[0];
			obj[i]->fbind();
			// Draw none for default
			obj[i]->data.mat_c = 0;
		}
	}

	void Tiles::update_instance(int c1, int c2, int c3, int c4, int c5, int c6) {
		obj[0]->data.mat_c = c1;
		obj[0]->data.mat = (GLuint*) mat[0];
		obj[0]->update_instance();

		obj[1]->data.mat_c = c2;
		obj[1]->data.mat = (GLuint*) mat[1];
		obj[1]->update_instance();

		obj[2]->data.mat_c = c3;
		obj[2]->data.mat = (GLuint*) mat[2];
		obj[2]->update_instance();

		obj[3]->data.mat_c = c4;
		obj[3]->data.mat = (GLuint*) mat[3];
		obj[3]->update_instance();

		obj[4]->data.mat_c = c5;
		obj[4]->data.mat = (GLuint*) mat[4];
		obj[4]->update_instance();

		obj[5]->data.mat_c = c6;
		obj[5]->data.mat = (GLuint*) mat[5];
		obj[5]->update_instance();
	}

	void Tiles::render() {
		for (int i = 0; i < 6; i++)
			if (obj[i]->data.mat_c) obj[i]->draw();
	}

	void Tiles::dispose() {
		for (int i = 0; i < 6; i++) {
			VMDE_Dispose(obj[i]);
			xefree(vtx[i]); xefree(itx[i]);
		}
	}
}
<commit_msg>FIX SAD BUG<commit_after>//=============================================================================
// ■ tile.cpp
//-----------------------------------------------------------------------------
//   3D模型：Tile
//=============================================================================

#include "tile.hpp"

namespace VM76 {
	Tiles::Tiles(int tid) {
		int x = tid % 16;
		int y = tid / 16;
		float T = 1.0f / 16.0f;
		float S = 0.0f;
		float xs = x * T;
		float ys = y * T;
		vtx[0] = new Vertex[4] {
			{{0.0, 0.0, 0.0},{1.0, 1.0, 1.0, 1.0},{xs + S, ys + T},{0.0, 0.0, -1.0}},
			{{0.0, 1.0, 0.0},{1.0, 1.0, 1.0, 1.0},{xs + S, ys + S},{0.0, 0.0, -1.0}},
			{{1.0, 1.0, 0.0},{1.0, 1.0, 1.0, 1.0},{xs + T, ys + S},{0.0, 0.0, -1.0}},
			{{1.0, 0.0, 0.0},{1.0, 1.0, 1.0, 1.0},{xs + T, ys + T},{0.0, 0.0, -1.0}},
		};
		vtx[1] = new Vertex[4] {
			{{0.0, 0.0, 1.0},{1.0, 1.0, 1.0, 1.0},{xs + S, ys + T},{0.0, 0.0, 1.0}},
			{{0.0, 1.0, 1.0},{1.0, 1.0, 1.0, 1.0},{xs + S, ys + S},{0.0, 0.0, 1.0}},
			{{1.0, 1.0, 1.0},{1.0, 1.0, 1.0, 1.0},{xs + T, ys + S},{0.0, 0.0, 1.0}},
			{{1.0, 0.0, 1.0},{1.0, 1.0, 1.0, 1.0},{xs + T, ys + T},{0.0, 0.0, 1.0}},
		};
		vtx[2] = new Vertex[4] {
			{{0.0, 1.0, 0.0},{1.0, 1.0, 1.0, 1.0},{xs + S, ys + S},{0.0, 1.0, 0.0}},
			{{0.0, 1.0, 1.0},{1.0, 1.0, 1.0, 1.0},{xs + S, ys + T},{0.0, 1.0, 0.0}},
			{{1.0, 1.0, 1.0},{1.0, 1.0, 1.0, 1.0},{xs + T, ys + T},{0.0, 1.0, 0.0}},
			{{1.0, 1.0, 0.0},{1.0, 1.0, 1.0, 1.0},{xs + T, ys + S},{0.0, 1.0, 0.0}},
		};
		vtx[3] = new Vertex[4] {
			{{0.0, 0.0, 0.0},{1.0, 1.0, 1.0, 1.0},{xs + S, ys + T},{0.0, -1.0, 0.0}},
			{{0.0, 0.0, 1.0},{1.0, 1.0, 1.0, 1.0},{xs + T, ys + T},{0.0, -1.0, 0.0}},
			{{1.0, 0.0, 1.0},{1.0, 1.0, 1.0, 1.0},{xs + T, ys + S},{0.0, -1.0, 0.0}},
			{{1.0, 0.0, 0.0},{1.0, 1.0, 1.0, 1.0},{xs + S, ys + S},{0.0, -1.0, 0.0}},
		};
		vtx[4] = new Vertex[4] {
			{{0.0, 0.0, 0.0},{1.0, 1.0, 1.0, 1.0},{xs + S, ys + T},{-1.0, 0.0, 0.0}},
			{{0.0, 0.0, 1.0},{1.0, 1.0, 1.0, 1.0},{xs + T, ys + T},{-1.0, 0.0, 0.0}},
			{{0.0, 1.0, 1.0},{1.0, 1.0, 1.0, 1.0},{xs + T, ys + S},{-1.0, 0.0, 0.0}},
			{{0.0, 1.0, 0.0},{1.0, 1.0, 1.0, 1.0},{xs + S, ys + S},{-1.0, 0.0, 0.0}},
		};
		vtx[5] = new Vertex[4] {
			{{1.0, 0.0, 0.0},{1.0, 1.0, 1.0, 1.0},{xs + S, ys + T},{1.0, 0.0, 0.0}},
			{{1.0, 0.0, 1.0},{1.0, 1.0, 1.0, 1.0},{xs + T, ys + T},{1.0, 0.0, 0.0}},
			{{1.0, 1.0, 1.0},{1.0, 1.0, 1.0, 1.0},{xs + T, ys + S},{1.0, 0.0, 0.0}},
			{{1.0, 1.0, 0.0},{1.0, 1.0, 1.0, 1.0},{xs + S, ys + S},{1.0, 0.0, 0.0}},
		};
		itx[0] = new GLuint[6] {0,1,3,  1,2,3};
		itx[1] = new GLuint[6] {3,1,0,  3,2,1};
		itx[2] = new GLuint[6] {0,1,3,  1,2,3};
		itx[3] = new GLuint[6] {3,1,0,  3,2,1};
		itx[4] = new GLuint[6] {0,1,3,  1,2,3};
		itx[5] = new GLuint[6] {3,1,0,  3,2,1};

		// Prepare an empty space
		for (int i = 0; i < 6; i++) {
			mat[i] = new glm::mat4[4096];
			for (int x = 0; x < 4096; x++) mat[i][x] = glm::mat4(1.0);

			obj[i] = new GDrawable();
			obj[i]->data.vtx_c = 4;
			obj[i]->data.ind_c = 2 * 3;
			obj[i]->data.vertices = vtx[i];
			obj[i]->data.indices = itx[i];
			// Reserve 512 spaces
			obj[i]->data.mat_c = 4096;
			obj[i]->data.mat = (GLuint*) &mat[i][0];
			obj[i]->fbind();
			// Draw none for default
			obj[i]->data.mat_c = 0;
		}
	}

	void Tiles::update_instance(int c1, int c2, int c3, int c4, int c5, int c6) {
		obj[0]->data.mat_c = c1;
		obj[0]->data.mat = (GLuint*) mat[0];
		obj[0]->update_instance();

		obj[1]->data.mat_c = c2;
		obj[1]->data.mat = (GLuint*) mat[1];
		obj[1]->update_instance();

		obj[2]->data.mat_c = c3;
		obj[2]->data.mat = (GLuint*) mat[2];
		obj[2]->update_instance();

		obj[3]->data.mat_c = c4;
		obj[3]->data.mat = (GLuint*) mat[3];
		obj[3]->update_instance();

		obj[4]->data.mat_c = c5;
		obj[4]->data.mat = (GLuint*) mat[4];
		obj[4]->update_instance();

		obj[5]->data.mat_c = c6;
		obj[5]->data.mat = (GLuint*) mat[5];
		obj[5]->update_instance();
	}

	void Tiles::render() {
		for (int i = 0; i < 6; i++)
			if (obj[i]->data.mat_c) obj[i]->draw();
	}

	void Tiles::dispose() {
		for (int i = 0; i < 6; i++) {
			VMDE_Dispose(obj[i]);
			xefree(vtx[i]); xefree(itx[i]);
		}
	}
}
<|endoftext|>


<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "config.h"

#include "base/compiler_specific.h"

#include "GenericWorkerTask.h"
#include "KURL.h"
#include "ScriptExecutionContext.h"
#include "SecurityOrigin.h"
#include "WorkerContext.h"
#include "WorkerThread.h"
#include <wtf/Threading.h>

#undef LOG

#include "base/logging.h"
#include "webkit/glue/glue_util.h"
#include "webkit/glue/webworkerclient.h"
#include "webkit/glue/webworker_impl.h"

#if ENABLE(WORKERS)

WebWorker* WebWorker::Create(WebWorkerClient* client) {
  return new WebWorkerImpl(client);
}

// This function is called on the main thread to force to initialize some static
// values used in WebKit before any worker thread is started. This is because in
// our worker processs, we do not run any WebKit code in main thread and thus
// when multiple workers try to start at the same time, we might hit crash due
// to contention for initializing static values.
void InitializeWebKitStaticValues() {
  static bool initialized = false;
  if (!initialized) {
    initialized= true;
    WTF::RefPtr<WebCore::SecurityOrigin> origin =
        WebCore::SecurityOrigin::create(WebCore::KURL());
    origin.release();
  }
}

WebWorkerImpl::WebWorkerImpl(WebWorkerClient* client) : client_(client) {
  InitializeWebKitStaticValues();
}

WebWorkerImpl::~WebWorkerImpl() {
}

void WebWorkerImpl::PostMessageToWorkerContextTask(
    WebCore::ScriptExecutionContext* context,
    WebWorkerImpl* this_ptr,
    const WebCore::String& message) {
  DCHECK(context->isWorkerContext());
  WebCore::WorkerContext* worker_context =
      static_cast<WebCore::WorkerContext*>(context);
  worker_context->dispatchMessage(message);

  this_ptr->client_->ConfirmMessageFromWorkerObject(
      worker_context->hasPendingActivity());
}

void WebWorkerImpl::StartWorkerContext(const GURL& script_url,
                                       const string16& user_agent,
                                       const string16& source_code) {
  worker_thread_ = WebCore::WorkerThread::create(
      webkit_glue::GURLToKURL(script_url),
      webkit_glue::String16ToString(user_agent),
      webkit_glue::String16ToString(source_code),
      this);

  // Worker initialization means a pending activity.
  reportPendingActivity(true);

  worker_thread_->start();
}

void WebWorkerImpl::TerminateWorkerContext() {
  worker_thread_->stop();
}

void WebWorkerImpl::PostMessageToWorkerContext(const string16& message) {
  worker_thread_->runLoop().postTask(WebCore::createCallbackTask(
      &PostMessageToWorkerContextTask,
      this,
      webkit_glue::String16ToString(message)));
}

void WebWorkerImpl::WorkerObjectDestroyed() {
}

void WebWorkerImpl::postMessageToWorkerObject(const WebCore::String& message) {
  client_->PostMessageToWorkerObject(webkit_glue::StringToString16(message));
}

void WebWorkerImpl::postExceptionToWorkerObject(
    const WebCore::String& errorMessage,
    int lineNumber,
    const WebCore::String& sourceURL) {
  client_->PostExceptionToWorkerObject(
      webkit_glue::StringToString16(errorMessage),
      lineNumber,
      webkit_glue::StringToString16(sourceURL));
}

void WebWorkerImpl::postConsoleMessageToWorkerObject(
    WebCore::MessageDestination destination,
    WebCore::MessageSource source,
    WebCore::MessageLevel level,
    const WebCore::String& message,
    int lineNumber,
    const WebCore::String& sourceURL) {
  client_->PostConsoleMessageToWorkerObject(
      destination,
      source,
      level,
      webkit_glue::StringToString16(message),
      lineNumber,
      webkit_glue::StringToString16(sourceURL));
}

void WebWorkerImpl::confirmMessageFromWorkerObject(bool hasPendingActivity) {
  client_->ConfirmMessageFromWorkerObject(hasPendingActivity);
}

void WebWorkerImpl::reportPendingActivity(bool hasPendingActivity) {
  client_->ReportPendingActivity(hasPendingActivity);
}

void WebWorkerImpl::workerContextDestroyed() {
  client_->WorkerContextDestroyed();

  // The lifetime of this proxy is controlled by the worker context.
  delete this;
}

#else

WebWorker* WebWorker::Create(WebWorkerClient* client) {
  return NULL;
}

#endif
<commit_msg>Pass a URL with valid protocol to SecurityOrigin::create in order to follow the code path to do static value initializations for worker process. Review URL: http://codereview.chromium.org/66063<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "config.h"

#include "base/compiler_specific.h"

#include "GenericWorkerTask.h"
#include "KURL.h"
#include "ScriptExecutionContext.h"
#include "SecurityOrigin.h"
#include "WorkerContext.h"
#include "WorkerThread.h"
#include <wtf/Threading.h>

#undef LOG

#include "base/logging.h"
#include "webkit/glue/glue_util.h"
#include "webkit/glue/webworkerclient.h"
#include "webkit/glue/webworker_impl.h"

#if ENABLE(WORKERS)

WebWorker* WebWorker::Create(WebWorkerClient* client) {
  return new WebWorkerImpl(client);
}

// This function is called on the main thread to force to initialize some static
// values used in WebKit before any worker thread is started. This is because in
// our worker processs, we do not run any WebKit code in main thread and thus
// when multiple workers try to start at the same time, we might hit crash due
// to contention for initializing static values.
void InitializeWebKitStaticValues() {
  static bool initialized = false;
  if (!initialized) {
    initialized= true;
    // Note that we have to pass a URL with valid protocol in order to follow
    // the path to do static value initializations.
    WTF::RefPtr<WebCore::SecurityOrigin> origin =
        WebCore::SecurityOrigin::create(WebCore::KURL("http://localhost"));
    origin.release();
  }
}

WebWorkerImpl::WebWorkerImpl(WebWorkerClient* client) : client_(client) {
  InitializeWebKitStaticValues();
}

WebWorkerImpl::~WebWorkerImpl() {
}

void WebWorkerImpl::PostMessageToWorkerContextTask(
    WebCore::ScriptExecutionContext* context,
    WebWorkerImpl* this_ptr,
    const WebCore::String& message) {
  DCHECK(context->isWorkerContext());
  WebCore::WorkerContext* worker_context =
      static_cast<WebCore::WorkerContext*>(context);
  worker_context->dispatchMessage(message);

  this_ptr->client_->ConfirmMessageFromWorkerObject(
      worker_context->hasPendingActivity());
}

void WebWorkerImpl::StartWorkerContext(const GURL& script_url,
                                       const string16& user_agent,
                                       const string16& source_code) {
  worker_thread_ = WebCore::WorkerThread::create(
      webkit_glue::GURLToKURL(script_url),
      webkit_glue::String16ToString(user_agent),
      webkit_glue::String16ToString(source_code),
      this);

  // Worker initialization means a pending activity.
  reportPendingActivity(true);

  worker_thread_->start();
}

void WebWorkerImpl::TerminateWorkerContext() {
  worker_thread_->stop();
}

void WebWorkerImpl::PostMessageToWorkerContext(const string16& message) {
  worker_thread_->runLoop().postTask(WebCore::createCallbackTask(
      &PostMessageToWorkerContextTask,
      this,
      webkit_glue::String16ToString(message)));
}

void WebWorkerImpl::WorkerObjectDestroyed() {
}

void WebWorkerImpl::postMessageToWorkerObject(const WebCore::String& message) {
  client_->PostMessageToWorkerObject(webkit_glue::StringToString16(message));
}

void WebWorkerImpl::postExceptionToWorkerObject(
    const WebCore::String& errorMessage,
    int lineNumber,
    const WebCore::String& sourceURL) {
  client_->PostExceptionToWorkerObject(
      webkit_glue::StringToString16(errorMessage),
      lineNumber,
      webkit_glue::StringToString16(sourceURL));
}

void WebWorkerImpl::postConsoleMessageToWorkerObject(
    WebCore::MessageDestination destination,
    WebCore::MessageSource source,
    WebCore::MessageLevel level,
    const WebCore::String& message,
    int lineNumber,
    const WebCore::String& sourceURL) {
  client_->PostConsoleMessageToWorkerObject(
      destination,
      source,
      level,
      webkit_glue::StringToString16(message),
      lineNumber,
      webkit_glue::StringToString16(sourceURL));
}

void WebWorkerImpl::confirmMessageFromWorkerObject(bool hasPendingActivity) {
  client_->ConfirmMessageFromWorkerObject(hasPendingActivity);
}

void WebWorkerImpl::reportPendingActivity(bool hasPendingActivity) {
  client_->ReportPendingActivity(hasPendingActivity);
}

void WebWorkerImpl::workerContextDestroyed() {
  client_->WorkerContextDestroyed();

  // The lifetime of this proxy is controlled by the worker context.
  delete this;
}

#else

WebWorker* WebWorker::Create(WebWorkerClient* client) {
  return NULL;
}

#endif
<|endoftext|>


<commit_before>#include <math.h>
#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <time.h>

#include <fj_tool/fapp.h>
#include <fjcoll.h>

#include "pearson-3d.h"

int T_MAX;
int T_MONITOR;
int mpi_my_rank;
const double PI=3.14159265358979323846;

float frand() {
  return rand() / float(RAND_MAX);
}

double wctime() {
  struct timeval tv;
  gettimeofday(&tv,NULL);
  return (double)tv.tv_sec + (double)tv.tv_usec*1e-6;
}

void init() {
  double wx = frand() * 2 * PI;
  double wy = frand() * 2 * PI;
  double wz = frand() * 2 * PI;
  for(int ix = navi.lower_x; ix < navi.upper_x; ++ix) {
    for(int iy = navi.lower_y; iy < navi.upper_y; ++iy) {
      for(int iz = navi.lower_z; iz < navi.upper_z; ++iz) {
        double k = (2*PI) / 128;
        double x = k * (navi.offset_x + ix);
        double y = k * (navi.offset_y + iy);
        double z = k * (navi.offset_z + iz);
        U[ix][iy][iz] = 1.0;
        V[ix][iy][iz] = 0.0;
        if (abs(cos(x+0.1*y+wx) * cos(y+0.1*z+wy) * cos(z+0.1*x+wz)) > 0.1) {
          U[ix][iy][iz] = 0.5;
          V[ix][iy][iz] = 0.25;
        }
      }
    }
  }
}

void write_monitor() {
  printf("#%d: t = %d\n", mpi_my_rank, navi.time_step);
  char fn[256];
  sprintf(fn, "out/monitor-%06d-%d.txt", navi.time_step, mpi_my_rank);
  FILE *fp = fopen(fn,"wb");
  int global_position[6];
  global_position[0] = navi.offset_x + navi.lower_x;
  global_position[1] = navi.offset_y + navi.lower_y;
  global_position[2] = navi.offset_z + navi.lower_z;
  global_position[3] = navi.upper_x - navi.lower_x;
  global_position[4] = navi.upper_y - navi.lower_y;
  global_position[5] = navi.upper_z - navi.lower_z;
  fwrite(global_position, sizeof(int), 6, fp);

  int x_size = navi.upper_x - navi.lower_x;
  int y_size = navi.upper_y - navi.lower_y;
  int z_size = navi.upper_z - navi.lower_z;
  {
    const int y=navi.lower_y + y_size/2;
    for(int x = navi.lower_x; x < navi.upper_x; ++x) fwrite(U[x][y]+navi.lower_z, sizeof(double),z_size, fp);
    for(int x = navi.lower_x; x < navi.upper_x; ++x) fwrite(V[x][y]+navi.lower_z, sizeof(double),z_size, fp);
  }
  {
    const int x=navi.lower_x + x_size/2;
    for(int y = navi.lower_y; y < navi.upper_y; ++y) fwrite(U[x][y]+navi.lower_z, sizeof(double),z_size, fp);
    for(int y = navi.lower_y; y < navi.upper_y; ++y) fwrite(V[x][y]+navi.lower_z, sizeof(double),z_size, fp);
  }
  fclose(fp);
}

int main (int argc, char **argv) {
  MPI_Init(&argc, &argv);
  Formura_Init(&navi, MPI_COMM_WORLD);
  MPI_Comm_rank(MPI_COMM_WORLD, &mpi_my_rank);
  srand(time(NULL)+mpi_my_rank*65537);

  if (argc <= 1) {
    T_MAX=8192;
  }else{
    sscanf(argv[1], "%d",  &T_MAX);
  }
  if (argc <= 2) {
    T_MONITOR=8192;
  }else{
    sscanf(argv[2], "%d",  &T_MONITOR);
  }

  init();

  double t_begin = wctime(), t_end;

  int last_monitor_t = -T_MONITOR;
  for(;;){
    double t = wctime();
    bool monitor_flag = navi.time_step >= last_monitor_t + T_MONITOR;
    if(monitor_flag || navi.time_step <= 3 * T_MONITOR ) {
      printf("%d step @ %lf sec\n", navi.time_step, t-t_begin);
    }
    if(monitor_flag) {
      write_monitor();
    }
    if(monitor_flag) {
      last_monitor_t += T_MONITOR;
    }

    if (navi.time_step >= T_MAX) break;
    if (navi.time_step == 0) {
      t_begin = wctime();
      start_collection("main");
    }

    Formura_Forward(&navi); // navi.time_step increases
    MPI_Barrier(MPI_COMM_WORLD); // TODO: test the effect of synchronization

    if (navi.time_step >= T_MAX) {
      t_end = wctime();
      stop_collection("main");
    }
  }
  printf("wct = %lf sec\n",t_end - t_begin);

  MPI_Barrier(MPI_COMM_WORLD);
  MPI_Finalize();
}
<commit_msg>Rewrite seeding for pearson-3d<commit_after>#include <algorithm>
#include <map>
#include <math.h>
#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <time.h>

#include <fj_tool/fapp.h>
#include <fjcoll.h>

#include "pearson-3d.h"

int T_MAX;
int T_MONITOR;
int mpi_my_rank;
const double PI=3.14159265358979323846;

float frand() {
  return rand() / float(RAND_MAX);
}

double wctime() {
  struct timeval tv;
  gettimeofday(&tv,NULL);
  return (double)tv.tv_sec + (double)tv.tv_usec*1e-6;
}

/*
void init() {
  for(int ix = navi.lower_x; ix < navi.upper_x; ++ix) {
    for(int iy = navi.lower_y; iy < navi.upper_y; ++iy) {
      for(int iz = navi.lower_z; iz < navi.upper_z; ++iz) {
        double k = (2*PI) / 128;
        double x = k * (navi.offset_x + ix);
        double y = k * (navi.offset_y + iy);
        double z = k * (navi.offset_z + iz);
        U[ix][iy][iz] = 1.0;
        V[ix][iy][iz] = 0.0;
        if (abs(cos(x+0.1*y+wx) * cos(y+0.1*z+wy) * cos(z+0.1*x+wz)) > 0.1) {
        if (frand() < 0.5) {
          U[ix][iy][iz] = 0.5;
          V[ix][iy][iz] = 0.25;
        }
      }
    }
  }
  }*/

typedef pair<int,<int,int> > Key;
void init() {
  map<Key ,double> seeds;
  for(int ix = navi.lower_x; ix < navi.upper_x; ++ix) {
    for(int iy = navi.lower_y; iy < navi.upper_y; ++iy) {
      for(int iz = navi.lower_z; iz < navi.upper_z; ++iz) {
        Key k (ix%16, pair<int,int>(iy%16, iz%16));
        U[ix][iy][iz] = 1.0;
        V[ix][iy][iz] = 0.0;
        double s = seeds[k];
        if (s==0) {
          s = frand();
          seeds[k]=s;
        }
        if (s < 0.25) {
          U[ix][iy][iz] = 0.5;
          V[ix][iy][iz] = 0.25;
        }
      }
    }
  }
}

void write_monitor() {
  printf("#%d: t = %d\n", mpi_my_rank, navi.time_step);
  char fn[256];
  sprintf(fn, "out/monitor-%06d-%d.txt", navi.time_step, mpi_my_rank);
  FILE *fp = fopen(fn,"wb");
  int global_position[6];
  global_position[0] = navi.offset_x + navi.lower_x;
  global_position[1] = navi.offset_y + navi.lower_y;
  global_position[2] = navi.offset_z + navi.lower_z;
  global_position[3] = navi.upper_x - navi.lower_x;
  global_position[4] = navi.upper_y - navi.lower_y;
  global_position[5] = navi.upper_z - navi.lower_z;
  fwrite(global_position, sizeof(int), 6, fp);

  int x_size = navi.upper_x - navi.lower_x;
  int y_size = navi.upper_y - navi.lower_y;
  int z_size = navi.upper_z - navi.lower_z;
  {
    const int y=navi.lower_y + y_size/2;
    for(int x = navi.lower_x; x < navi.upper_x; ++x) fwrite(U[x][y]+navi.lower_z, sizeof(double),z_size, fp);
    for(int x = navi.lower_x; x < navi.upper_x; ++x) fwrite(V[x][y]+navi.lower_z, sizeof(double),z_size, fp);
  }
  {
    const int x=navi.lower_x + x_size/2;
    for(int y = navi.lower_y; y < navi.upper_y; ++y) fwrite(U[x][y]+navi.lower_z, sizeof(double),z_size, fp);
    for(int y = navi.lower_y; y < navi.upper_y; ++y) fwrite(V[x][y]+navi.lower_z, sizeof(double),z_size, fp);
  }
  fclose(fp);
}

int main (int argc, char **argv) {
  MPI_Init(&argc, &argv);
  Formura_Init(&navi, MPI_COMM_WORLD);
  MPI_Comm_rank(MPI_COMM_WORLD, &mpi_my_rank);
  srand(time(NULL)+mpi_my_rank*65537);

  if (argc <= 1) {
    T_MAX=8192;
  }else{
    sscanf(argv[1], "%d",  &T_MAX);
  }
  if (argc <= 2) {
    T_MONITOR=8192;
  }else{
    sscanf(argv[2], "%d",  &T_MONITOR);
  }

  init();

  double t_begin = wctime(), t_end;

  int last_monitor_t = -T_MONITOR;
  for(;;){
    double t = wctime();
    bool monitor_flag = navi.time_step >= last_monitor_t + T_MONITOR;
    if(monitor_flag || navi.time_step <= 3 * T_MONITOR ) {
      printf("%d step @ %lf sec\n", navi.time_step, t-t_begin);
    }
    if(monitor_flag) {
      write_monitor();
    }
    if(monitor_flag) {
      last_monitor_t += T_MONITOR;
    }

    if (navi.time_step >= T_MAX) break;
    if (navi.time_step == 0) {
      t_begin = wctime();
      start_collection("main");
    }

    Formura_Forward(&navi); // navi.time_step increases
    MPI_Barrier(MPI_COMM_WORLD); // TODO: test the effect of synchronization

    if (navi.time_step >= T_MAX) {
      t_end = wctime();
      stop_collection("main");
    }
  }
  printf("wct = %lf sec\n",t_end - t_begin);

  MPI_Barrier(MPI_COMM_WORLD);
  MPI_Finalize();
}
<|endoftext|>


<commit_before>/*
 Copyright (C) 2003 Justin Karneges
 Copyright (C) 2005 Brad Hards

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
 AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
 AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

#include <QtCrypto>

#include <iostream>

int main(int argc, char **argv)
{
    // The Initializer object sets things up, and also
    // does cleanup when it goes out of scope
    QCA::Initializer init;

    QCoreApplication app(argc, argv);

    // we use the first argument if provided, or
    // use "hello" if no arguments
    QSecureArray arg = (argc >= 2) ? argv[1] : "hello";

    // We demonstrate PEM usage here, so we need to test for
    // supportedIOTypes, not just supportedTypes
    if(!QCA::isSupported("pkey") ||
       !QCA::PKey::supportedIOTypes().contains(QCA::PKey::RSA))
	printf("RSA not supported!\n");
    else {
	// When creating a public / private key pair, you make the
	// private key, and then extract the public key component from it
	// Using RSA is very common, however DSA can provide equivalent
	// signature/verification. This example applies to DSA to the
	// extent that the operations work on that key type.

	// QCA provides KeyGenerator as a convenient source of new keys,
	// however you could also import an existing key instead.
	QCA::PrivateKey seckey = QCA::KeyGenerator().createRSA(1024);
	if(seckey.isNull()) {
	    std::cout << "Failed to make private RSA key" << std::endl;
	    return 1;
	}

	QCA::PublicKey pubkey = seckey.toPublicKey();

	// check if the key can encrypt
	if(!pubkey.canEncrypt()) {
	    std::cout << "Error: this kind of key cannot encrypt" << std::endl;
	    return 1;
	}

	// encrypt some data - note that only the public key is required
	// you must also choose the algorithm to be used
	QSecureArray result = pubkey.encrypt(arg, QCA::EME_PKCS1_OAEP);
	if(result.isEmpty()) {
	    std::cout << "Error encrypting" << std::endl;
	    return 1;
	}

	// output the encrypted data
	QString rstr = QCA::arrayToHex(result);
	std::cout << "\"" << arg.data() << "\" encrypted with RSA is \"";
	std::cout << qPrintable(rstr) << "\"" << std::endl;

	// save the private key - in a real example, make sure this goes
	// somewhere secure and has a good pass phrase
	// You can use the same technique with the public key too.
	QSecureArray passPhrase = "pass phrase";
	seckey.toPEMFile("keyprivate.pem", passPhrase);

	// Read that key back in, checking if the read succeeded
	QCA::ConvertResult conversionResult;
	QCA::PrivateKey privateKey = QCA::PrivateKey::fromPEMFile( "keyprivate.pem",
								   passPhrase,
								   &conversionResult);
	if (! QCA::ConvertGood == conversionResult) {
	    std::cout << "Private key read failed" << std::endl;
	}

	// now decrypt that encrypted data using the private key that
	// we read in. The algorithm is the same.
	QSecureArray decrypt;
	if(0 == privateKey.decrypt(result, &decrypt, QCA::EME_PKCS1_OAEP)) {
	    printf("Error decrypting.\n");
	    return 1;
	}

	// output the resulting decrypted string
	std::cout << "\"" << qPrintable(rstr) << "\" decrypted with RSA is \"";
	std::cout << decrypt.data() << "\"" << std::endl;

	// Some private keys can also be used for producing signatures
	if(!privateKey.canSign()) {
	    std::cout << "Error: this kind of key cannot sign" << std::endl;
	    return 1;
	}
	privateKey.startSign( QCA::EMSA3_MD5 );
	privateKey.update( arg ); // just reuse the same message
	QSecureArray argSig = privateKey.signature();

	// instead of using the startSign(), update(), signature() calls,
	// you may be better doing the whole thing in one go, using the
	// signMessage call. Of course you need the whole message in one
	// hit, which may or may not be a problem

	// output the resulting signature
	rstr = QCA::arrayToHex(argSig);
	std::cout << "Signature for \"" << arg.data() << "\" using RSA, is ";
	std::cout << "\"" << qPrintable( rstr ) << "\"" << std::endl;

	// to check a signature, we can
	if(pubkey.canVerify()) {
	    pubkey.startVerify( QCA::EMSA3_MD5 );
	    pubkey.update( arg );
	    if ( pubkey.validSignature( argSig ) ) {
		std::cout << "Signature is valid" << std::endl;
	    } else {
		std::cout << "Bad signature" << std::endl;
	    }
	}

	// We can also do the verification in a single step if we
	// have all the message
	if ( pubkey.canVerify() &&
	     pubkey.verifyMessage( arg, argSig, QCA::EMSA3_MD5 ) ) {
	    std::cout << "Signature is valid" << std::endl;
	} else {
	    std::cout << "Signature could not be verified" << std::endl;
	}

    }

    return 0;
}

<commit_msg>Finish off the comment. Not sure what I was going to say...<commit_after>/*
 Copyright (C) 2003 Justin Karneges
 Copyright (C) 2005 Brad Hards

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
 AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
 AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

#include <QtCrypto>

#include <iostream>

int main(int argc, char **argv)
{
    // The Initializer object sets things up, and also
    // does cleanup when it goes out of scope
    QCA::Initializer init;

    QCoreApplication app(argc, argv);

    // we use the first argument if provided, or
    // use "hello" if no arguments
    QSecureArray arg = (argc >= 2) ? argv[1] : "hello";

    // We demonstrate PEM usage here, so we need to test for
    // supportedIOTypes, not just supportedTypes
    if(!QCA::isSupported("pkey") ||
       !QCA::PKey::supportedIOTypes().contains(QCA::PKey::RSA))
	printf("RSA not supported!\n");
    else {
	// When creating a public / private key pair, you make the
	// private key, and then extract the public key component from it
	// Using RSA is very common, however DSA can provide equivalent
	// signature/verification. This example applies to DSA to the
	// extent that the operations work on that key type.

	// QCA provides KeyGenerator as a convenient source of new keys,
	// however you could also import an existing key instead.
	QCA::PrivateKey seckey = QCA::KeyGenerator().createRSA(1024);
	if(seckey.isNull()) {
	    std::cout << "Failed to make private RSA key" << std::endl;
	    return 1;
	}

	QCA::PublicKey pubkey = seckey.toPublicKey();

	// check if the key can encrypt
	if(!pubkey.canEncrypt()) {
	    std::cout << "Error: this kind of key cannot encrypt" << std::endl;
	    return 1;
	}

	// encrypt some data - note that only the public key is required
	// you must also choose the algorithm to be used
	QSecureArray result = pubkey.encrypt(arg, QCA::EME_PKCS1_OAEP);
	if(result.isEmpty()) {
	    std::cout << "Error encrypting" << std::endl;
	    return 1;
	}

	// output the encrypted data
	QString rstr = QCA::arrayToHex(result);
	std::cout << "\"" << arg.data() << "\" encrypted with RSA is \"";
	std::cout << qPrintable(rstr) << "\"" << std::endl;

	// save the private key - in a real example, make sure this goes
	// somewhere secure and has a good pass phrase
	// You can use the same technique with the public key too.
	QSecureArray passPhrase = "pass phrase";
	seckey.toPEMFile("keyprivate.pem", passPhrase);

	// Read that key back in, checking if the read succeeded
	QCA::ConvertResult conversionResult;
	QCA::PrivateKey privateKey = QCA::PrivateKey::fromPEMFile( "keyprivate.pem",
								   passPhrase,
								   &conversionResult);
	if (! QCA::ConvertGood == conversionResult) {
	    std::cout << "Private key read failed" << std::endl;
	}

	// now decrypt that encrypted data using the private key that
	// we read in. The algorithm is the same.
	QSecureArray decrypt;
	if(0 == privateKey.decrypt(result, &decrypt, QCA::EME_PKCS1_OAEP)) {
	    printf("Error decrypting.\n");
	    return 1;
	}

	// output the resulting decrypted string
	std::cout << "\"" << qPrintable(rstr) << "\" decrypted with RSA is \"";
	std::cout << decrypt.data() << "\"" << std::endl;

	// Some private keys can also be used for producing signatures
	if(!privateKey.canSign()) {
	    std::cout << "Error: this kind of key cannot sign" << std::endl;
	    return 1;
	}
	privateKey.startSign( QCA::EMSA3_MD5 );
	privateKey.update( arg ); // just reuse the same message
	QSecureArray argSig = privateKey.signature();

	// instead of using the startSign(), update(), signature() calls,
	// you may be better doing the whole thing in one go, using the
	// signMessage call. Of course you need the whole message in one
	// hit, which may or may not be a problem

	// output the resulting signature
	rstr = QCA::arrayToHex(argSig);
	std::cout << "Signature for \"" << arg.data() << "\" using RSA, is ";
	std::cout << "\"" << qPrintable( rstr ) << "\"" << std::endl;

	// to check a signature, we must check that the key is
	// appropriate
	if(pubkey.canVerify()) {
	    pubkey.startVerify( QCA::EMSA3_MD5 );
	    pubkey.update( arg );
	    if ( pubkey.validSignature( argSig ) ) {
		std::cout << "Signature is valid" << std::endl;
	    } else {
		std::cout << "Bad signature" << std::endl;
	    }
	}

	// We can also do the verification in a single step if we
	// have all the message
	if ( pubkey.canVerify() &&
	     pubkey.verifyMessage( arg, argSig, QCA::EMSA3_MD5 ) ) {
	    std::cout << "Signature is valid" << std::endl;
	} else {
	    std::cout << "Signature could not be verified" << std::endl;
	}

    }

    return 0;
}

<|endoftext|>


<commit_before>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * 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 "modules/perception/obstacle/onboard/fusion_subnode.h"

#include <unordered_map>

#include "modules/common/adapters/adapter_manager.h"
#include "modules/common/configs/config_gflags.h"
#include "modules/common/log.h"
#include "modules/perception/common/perception_gflags.h"
#include "modules/perception/onboard/event_manager.h"
#include "modules/perception/onboard/shared_data_manager.h"
#include "modules/perception/onboard/subnode_helper.h"

namespace apollo {
namespace perception {

using apollo::canbus::Chassis;
using apollo::common::ErrorCode;
using apollo::common::Status;
using apollo::common::adapter::AdapterManager;

bool FusionSubnode::InitInternal() {
  RegistAllAlgorithm();

  AdapterManager::Init(FLAGS_perception_adapter_config_filename);

  CHECK(AdapterManager::GetChassis()) << "Chassis is not initialized.";
  AdapterManager::AddChassisCallback(&FusionSubnode::OnChassis, this);

  CHECK(shared_data_manager_ != nullptr);
  fusion_.reset(BaseFusionRegisterer::GetInstanceByName(FLAGS_onboard_fusion));
  if (fusion_ == nullptr) {
    AERROR << "Failed to get fusion instance: " << FLAGS_onboard_fusion;
    return false;
  }
  if (!fusion_->Init()) {
    AERROR << "Failed to init fusion:" << FLAGS_onboard_fusion;
    return false;
  }
  radar_object_data_ = dynamic_cast<RadarObjectData *>(
      shared_data_manager_->GetSharedData("RadarObjectData"));
  if (radar_object_data_ == nullptr) {
    AWARN << "Failed to get RadarObjectData.";
  }
  lidar_object_data_ = dynamic_cast<LidarObjectData *>(
      shared_data_manager_->GetSharedData("LidarObjectData"));
  if (lidar_object_data_ == nullptr) {
    AWARN << "Failed to get LidarObjectData.";
  }
  camera_object_data_ = dynamic_cast<CameraObjectData *>(
      shared_data_manager_->GetSharedData("CameraObjectData"));
  if (camera_object_data_ == nullptr) {
    AWARN << "Failed to get CameraObjectData.";
  }

  fusion_data_ = dynamic_cast<FusionSharedData *>(
      shared_data_manager_->GetSharedData("FusionSharedData"));
  if (fusion_data_ == nullptr) {
    AWARN << "Failed to get FusionSharedData.";
  }

  lane_shared_data_ = dynamic_cast<LaneSharedData *>(
      shared_data_manager_->GetSharedData("LaneSharedData"));
  if (lane_shared_data_ == nullptr) {
    AERROR << "failed to get shared data instance: LaneSharedData ";
    return false;
  }

  lane_objects_.reset(new LaneObjects());

  if (!InitOutputStream()) {
    AERROR << "Failed to init output stream.";
    return false;
  }

  AINFO << "Init FusionSubnode succ. Using fusion:" << fusion_->name();
  return true;
}

bool FusionSubnode::InitOutputStream() {
  // expect reserve_ format:
  //       pub_driven_event_id:n
  //       lidar_output_stream : event_id=n&sink_type=m&sink_name=x
  //       radar_output_stream : event_id=n&sink_type=m&sink_name=x
  std::unordered_map<std::string, std::string> reserve_field_map;
  if (!SubnodeHelper::ParseReserveField(reserve_, &reserve_field_map)) {
    AERROR << "Failed to parse reserve string: " << reserve_;
    return false;
  }
  auto iter = reserve_field_map.find("pub_driven_event_id");
  if (iter == reserve_field_map.end()) {
    AERROR << "Failed to find pub_driven_event_id:" << reserve_;
    return false;
  }
  pub_driven_event_id_ = static_cast<EventID>(atoi((iter->second).c_str()));

  auto lidar_iter = reserve_field_map.find("lidar_event_id");
  if (lidar_iter == reserve_field_map.end()) {
    AWARN << "Failed to find lidar_event_id:" << reserve_;
    AINFO << "lidar_event_id will be set -1";
    lidar_event_id_ = -1;
  } else {
    lidar_event_id_ = static_cast<EventID>(atoi((lidar_iter->second).c_str()));
  }

  auto radar_iter = reserve_field_map.find("radar_event_id");
  if (radar_iter == reserve_field_map.end()) {
    AWARN << "Failed to find radar_event_id:" << reserve_;
    AINFO << "radar_event_id will be set -1";
    radar_event_id_ = -1;
  } else {
    radar_event_id_ = static_cast<EventID>(atoi((radar_iter->second).c_str()));
  }

  auto camera_iter = reserve_field_map.find("camera_event_id");
  if (camera_iter == reserve_field_map.end()) {
    AWARN << "Failed to find camera_event_id:" << reserve_;
    AINFO << "camera_event_id will be set -1";
    camera_event_id_ = -1;
  } else {
    camera_event_id_ =
        static_cast<EventID>(atoi((camera_iter->second).c_str()));
  }

  auto lane_iter = reserve_field_map.find("lane_event_id");
  if (lane_iter == reserve_field_map.end()) {
    AWARN << "Failed to find camera_event_id:" << reserve_;
    AINFO << "camera_event_id will be set -1";
    lane_event_id_ = -1;
  } else {
    lane_event_id_ = static_cast<EventID>(atoi((lane_iter->second).c_str()));
  }

  return true;
}

Status FusionSubnode::ProcEvents() {
  for (auto event_meta : sub_meta_events_) {
    // ignore lane event from polling
    if (event_meta.event_id == lane_event_id_) continue;

    std::vector<Event> events;
    if (!SubscribeEvents(event_meta, &events)) {
      AERROR << "event meta id:" << event_meta.event_id << " "
             << event_meta.from_node << " " << event_meta.to_node;
      return Status(ErrorCode::PERCEPTION_ERROR, "Subscribe event fail.");
    }
    if (events.empty()) {
      usleep(500);
      continue;
    }
    Process(event_meta, events);

    if (event_meta.event_id != pub_driven_event_id_) {
      ADEBUG << "Not pub_driven_event_id, skip to publish."
             << " event_id:" << event_meta.event_id
             << " fused_obj_cnt:" << objects_.size();
      continue;
    }

    // public obstacle message
    PerceptionObstacles obstacles;
    if (GeneratePbMsg(&obstacles)) {
      common::adapter::AdapterManager::PublishPerceptionObstacles(obstacles);
    }
    AINFO << "Publish 3d perception fused msg. timestamp:"
          << GLOG_TIMESTAMP(timestamp_) << " obj_cnt:" << objects_.size();
  }
  return Status::OK();
}

Status FusionSubnode::Process(const EventMeta &event_meta,
                              const std::vector<Event> &events) {
  std::vector<SensorObjects> sensor_objs;
  if (!BuildSensorObjs(events, &sensor_objs)) {
    AERROR << "Failed to build_sensor_objs";
    error_code_ = common::PERCEPTION_ERROR_PROCESS;
    return Status(ErrorCode::PERCEPTION_ERROR, "Failed to build_sensor_objs.");
  }
  PERF_BLOCK_START();
  objects_.clear();
  if (!fusion_->Fuse(sensor_objs, &objects_)) {
    AWARN << "Failed to call fusion plugin."
          << " event_meta: [" << event_meta.to_string()
          << "] event_cnt:" << events.size() << " event_0: ["
          << events[0].to_string() << "]";
    error_code_ = common::PERCEPTION_ERROR_PROCESS;
    return Status(ErrorCode::PERCEPTION_ERROR, "Failed to call fusion plugin.");
  }
  if (event_meta.event_id == lidar_event_id_) {
    PERF_BLOCK_END("fusion_lidar");
  } else if (event_meta.event_id == radar_event_id_) {
    PERF_BLOCK_END("fusion_radar");
  } else if (event_meta.event_id == camera_event_id_) {
    PERF_BLOCK_END("fusion_camera");
  }

  if (objects_.size() > 0 && FLAGS_publish_fusion_event) {
    SharedDataPtr<FusionItem> fusion_item_ptr(new FusionItem);
    fusion_item_ptr->timestamp = objects_[0]->latest_tracked_time;
    const std::string &device_id = events[0].reserve;
    for (auto obj : objects_) {
      ObjectPtr objclone(new Object());
      objclone->clone(*obj);
      fusion_item_ptr->obstacles.push_back(objclone);
    }
    AINFO << "publishing event for timestamp deviceid and size of fusion object"
          << fusion_item_ptr->timestamp << " " << device_id << " "
          << fusion_item_ptr->obstacles.size();
    PublishDataAndEvent(fusion_item_ptr->timestamp, device_id, fusion_item_ptr);
  }

  timestamp_ = sensor_objs[0].timestamp;
  error_code_ = common::OK;
  return Status::OK();
}

void FusionSubnode::PublishDataAndEvent(const double &timestamp,
                                        const std::string &device_id,
                                        const SharedDataPtr<FusionItem> &data) {
  CommonSharedDataKey key(timestamp, device_id);
  bool fusion_succ = fusion_data_->Add(key, data);
  if (!fusion_succ) {
    AERROR << "fusion shared data addkey failure";
  }
  AINFO << "adding key in fusion shared data " << key.ToString();

  for (size_t idx = 0; idx < pub_meta_events_.size(); ++idx) {
    const EventMeta &event_meta = pub_meta_events_[idx];
    Event event;
    event.event_id = event_meta.event_id;
    event.timestamp = timestamp;
    event.reserve = device_id;
    event_manager_->Publish(event);
  }
}

bool FusionSubnode::SubscribeEvents(const EventMeta &event_meta,
                                    std::vector<Event> *events) const {
  Event event;
  // no blocking
  while (event_manager_->Subscribe(event_meta.event_id, &event, true)) {
    events->push_back(event);
  }
  return true;
}
bool FusionSubnode::BuildSensorObjs(
    const std::vector<Event> &events,
    std::vector<SensorObjects> *multi_sensor_objs) {
  PERF_FUNCTION();
  for (auto event : events) {
    std::shared_ptr<SensorObjects> sensor_objects;
    if (!GetSharedData(event, &sensor_objects)) {
      return false;
    }
    // Make sure timestamp and type are filled.
    sensor_objects->timestamp = event.timestamp;
    if (event.event_id == lidar_event_id_) {
      sensor_objects->sensor_type = SensorType::VELODYNE_64;
    } else if (event.event_id == radar_event_id_) {
      sensor_objects->sensor_type = SensorType::RADAR;
    } else if (event.event_id == camera_event_id_) {
      sensor_objects->sensor_type = SensorType::CAMERA;
    } else {
      AERROR << "Event id is not supported. event:" << event.to_string();
      return false;
    }
    sensor_objects->sensor_id = GetSensorType(sensor_objects->sensor_type);
    multi_sensor_objs->push_back(*sensor_objects);
    ADEBUG << "get sensor objs:" << sensor_objects->ToString();
  }
  return true;
}

bool FusionSubnode::GetSharedData(const Event &event,
                                  std::shared_ptr<SensorObjects> *objs) {
  double timestamp = event.timestamp;
  const std::string &device_id = event.reserve;
  std::string data_key;
  if (!SubnodeHelper::ProduceSharedDataKey(timestamp, device_id, &data_key)) {
    AERROR << "Failed to produce shared data key. EventID:" << event.event_id
           << " timestamp:" << timestamp << " device_id:" << device_id;
    return false;
  }
  bool get_data_succ = false;
  if (event.event_id == lidar_event_id_ && lidar_object_data_ != nullptr) {
    get_data_succ = lidar_object_data_->Get(data_key, objs);
  } else if (event.event_id == radar_event_id_ &&
             radar_object_data_ != nullptr) {
    get_data_succ = radar_object_data_->Get(data_key, objs);
  } else if (event.event_id == camera_event_id_ &&
             camera_object_data_ != nullptr) {
    get_data_succ = camera_object_data_->Get(data_key, objs);
    // trying to get lane shared data as well
    Event lane_event;
    if (event_manager_->Subscribe(lane_event_id_, &lane_event, false)) {
      get_data_succ = lane_shared_data_->Get(data_key, &lane_objects_);
      ADEBUG << "getting lane data successfully for data key " << data_key;
    }
  } else {
    AERROR << "Event id is not supported. event:" << event.to_string();
    return false;
  }
  if (!get_data_succ) {
    AERROR << "Failed to get shared data. event:" << event.to_string();
    return false;
  }
  return true;
}

bool FusionSubnode::GeneratePbMsg(PerceptionObstacles *obstacles) {
  common::adapter::AdapterManager::FillPerceptionObstaclesHeader(
      FLAGS_obstacle_module_name, obstacles);
  common::Header *header = obstacles->mutable_header();
  if (pub_driven_event_id_ == lidar_event_id_) {
    header->set_lidar_timestamp(timestamp_ * 1e9);  // in ns
    header->set_camera_timestamp(0);
    header->set_radar_timestamp(0);
  } else if (pub_driven_event_id_ == camera_event_id_) {
    header->set_lidar_timestamp(0);  // in ns
    header->set_camera_timestamp(timestamp_ * 1e9);
    header->set_radar_timestamp(0);
  }

  obstacles->set_error_code(error_code_);

  for (const auto &obj : objects_) {
    PerceptionObstacle *obstacle = obstacles->add_perception_obstacle();
    obj->Serialize(obstacle);
  }

  if (FLAGS_use_navigation_mode) {
    // generate lane marker protobuf messages
    LaneMarkers *lane_markers = obstacles->mutable_lane_marker();
    LaneObjectsToLaneMarkerProto(*(lane_objects_), lane_markers);

    // Relative speed of objects + latest ego car speed in X
    for (auto obstacle : obstacles->perception_obstacle()) {
      obstacle.mutable_velocity()->set_x(obstacle.velocity().x() +
                                         chassis_speed_mps_);
    }
  }

  ADEBUG << "PerceptionObstacles: " << obstacles->ShortDebugString();
  return true;
}

void FusionSubnode::RegistAllAlgorithm() {
  RegisterFactoryProbabilisticFusion();
  RegisterFactoryAsyncFusion();
}

void FusionSubnode::OnChassis(const Chassis &chassis) {
  ADEBUG << "Received chassis data: run chassis callback.";
  chassis_.CopyFrom(chassis);
  chassis_speed_mps_ = chassis_.speed_mps();
}

}  // namespace perception
}  // namespace apollo
<commit_msg>fix fusion_subnode init failure (#3656)<commit_after>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * 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 "modules/perception/obstacle/onboard/fusion_subnode.h"

#include <unordered_map>

#include "modules/common/adapters/adapter_manager.h"
#include "modules/common/configs/config_gflags.h"
#include "modules/common/log.h"
#include "modules/perception/common/perception_gflags.h"
#include "modules/perception/onboard/event_manager.h"
#include "modules/perception/onboard/shared_data_manager.h"
#include "modules/perception/onboard/subnode_helper.h"

namespace apollo {
namespace perception {

using apollo::canbus::Chassis;
using apollo::common::ErrorCode;
using apollo::common::Status;
using apollo::common::adapter::AdapterManager;

bool FusionSubnode::InitInternal() {
  RegistAllAlgorithm();

  AdapterManager::Init(FLAGS_perception_adapter_config_filename);

  CHECK(AdapterManager::GetChassis()) << "Chassis is not initialized.";
  AdapterManager::AddChassisCallback(&FusionSubnode::OnChassis, this);

  CHECK(shared_data_manager_ != nullptr);
  fusion_.reset(BaseFusionRegisterer::GetInstanceByName(FLAGS_onboard_fusion));
  if (fusion_ == nullptr) {
    AERROR << "Failed to get fusion instance: " << FLAGS_onboard_fusion;
    return false;
  }
  if (!fusion_->Init()) {
    AERROR << "Failed to init fusion:" << FLAGS_onboard_fusion;
    return false;
  }
  radar_object_data_ = dynamic_cast<RadarObjectData *>(
      shared_data_manager_->GetSharedData("RadarObjectData"));
  if (radar_object_data_ == nullptr) {
    AWARN << "Failed to get RadarObjectData.";
  }
  lidar_object_data_ = dynamic_cast<LidarObjectData *>(
      shared_data_manager_->GetSharedData("LidarObjectData"));
  if (lidar_object_data_ == nullptr) {
    AWARN << "Failed to get LidarObjectData.";
  }
  camera_object_data_ = dynamic_cast<CameraObjectData *>(
      shared_data_manager_->GetSharedData("CameraObjectData"));
  if (camera_object_data_ == nullptr) {
    AWARN << "Failed to get CameraObjectData.";
  }

  fusion_data_ = dynamic_cast<FusionSharedData *>(
      shared_data_manager_->GetSharedData("FusionSharedData"));
  if (fusion_data_ == nullptr) {
    AWARN << "Failed to get FusionSharedData.";
  }

  lane_shared_data_ = dynamic_cast<LaneSharedData *>(
      shared_data_manager_->GetSharedData("LaneSharedData"));
  if (lane_shared_data_ == nullptr) {
    AWARN << "failed to get shared data instance: LaneSharedData ";
  }

  lane_objects_.reset(new LaneObjects());

  if (!InitOutputStream()) {
    AERROR << "Failed to init output stream.";
    return false;
  }

  AINFO << "Init FusionSubnode succ. Using fusion:" << fusion_->name();
  return true;
}

bool FusionSubnode::InitOutputStream() {
  // expect reserve_ format:
  //       pub_driven_event_id:n
  //       lidar_output_stream : event_id=n&sink_type=m&sink_name=x
  //       radar_output_stream : event_id=n&sink_type=m&sink_name=x
  std::unordered_map<std::string, std::string> reserve_field_map;
  if (!SubnodeHelper::ParseReserveField(reserve_, &reserve_field_map)) {
    AERROR << "Failed to parse reserve string: " << reserve_;
    return false;
  }
  auto iter = reserve_field_map.find("pub_driven_event_id");
  if (iter == reserve_field_map.end()) {
    AERROR << "Failed to find pub_driven_event_id:" << reserve_;
    return false;
  }
  pub_driven_event_id_ = static_cast<EventID>(atoi((iter->second).c_str()));

  auto lidar_iter = reserve_field_map.find("lidar_event_id");
  if (lidar_iter == reserve_field_map.end()) {
    AWARN << "Failed to find lidar_event_id:" << reserve_;
    AINFO << "lidar_event_id will be set -1";
    lidar_event_id_ = -1;
  } else {
    lidar_event_id_ = static_cast<EventID>(atoi((lidar_iter->second).c_str()));
  }

  auto radar_iter = reserve_field_map.find("radar_event_id");
  if (radar_iter == reserve_field_map.end()) {
    AWARN << "Failed to find radar_event_id:" << reserve_;
    AINFO << "radar_event_id will be set -1";
    radar_event_id_ = -1;
  } else {
    radar_event_id_ = static_cast<EventID>(atoi((radar_iter->second).c_str()));
  }

  auto camera_iter = reserve_field_map.find("camera_event_id");
  if (camera_iter == reserve_field_map.end()) {
    AWARN << "Failed to find camera_event_id:" << reserve_;
    AINFO << "camera_event_id will be set -1";
    camera_event_id_ = -1;
  } else {
    camera_event_id_ =
        static_cast<EventID>(atoi((camera_iter->second).c_str()));
  }

  auto lane_iter = reserve_field_map.find("lane_event_id");
  if (lane_iter == reserve_field_map.end()) {
    AWARN << "Failed to find camera_event_id:" << reserve_;
    AINFO << "camera_event_id will be set -1";
    lane_event_id_ = -1;
  } else {
    lane_event_id_ = static_cast<EventID>(atoi((lane_iter->second).c_str()));
  }

  return true;
}

Status FusionSubnode::ProcEvents() {
  for (auto event_meta : sub_meta_events_) {
    // ignore lane event from polling
    if (event_meta.event_id == lane_event_id_) continue;

    std::vector<Event> events;
    if (!SubscribeEvents(event_meta, &events)) {
      AERROR << "event meta id:" << event_meta.event_id << " "
             << event_meta.from_node << " " << event_meta.to_node;
      return Status(ErrorCode::PERCEPTION_ERROR, "Subscribe event fail.");
    }
    if (events.empty()) {
      usleep(500);
      continue;
    }
    Process(event_meta, events);

    if (event_meta.event_id != pub_driven_event_id_) {
      ADEBUG << "Not pub_driven_event_id, skip to publish."
             << " event_id:" << event_meta.event_id
             << " fused_obj_cnt:" << objects_.size();
      continue;
    }

    // public obstacle message
    PerceptionObstacles obstacles;
    if (GeneratePbMsg(&obstacles)) {
      common::adapter::AdapterManager::PublishPerceptionObstacles(obstacles);
    }
    AINFO << "Publish 3d perception fused msg. timestamp:"
          << GLOG_TIMESTAMP(timestamp_) << " obj_cnt:" << objects_.size();
  }
  return Status::OK();
}

Status FusionSubnode::Process(const EventMeta &event_meta,
                              const std::vector<Event> &events) {
  std::vector<SensorObjects> sensor_objs;
  if (!BuildSensorObjs(events, &sensor_objs)) {
    AERROR << "Failed to build_sensor_objs";
    error_code_ = common::PERCEPTION_ERROR_PROCESS;
    return Status(ErrorCode::PERCEPTION_ERROR, "Failed to build_sensor_objs.");
  }
  PERF_BLOCK_START();
  objects_.clear();
  if (!fusion_->Fuse(sensor_objs, &objects_)) {
    AWARN << "Failed to call fusion plugin."
          << " event_meta: [" << event_meta.to_string()
          << "] event_cnt:" << events.size() << " event_0: ["
          << events[0].to_string() << "]";
    error_code_ = common::PERCEPTION_ERROR_PROCESS;
    return Status(ErrorCode::PERCEPTION_ERROR, "Failed to call fusion plugin.");
  }
  if (event_meta.event_id == lidar_event_id_) {
    PERF_BLOCK_END("fusion_lidar");
  } else if (event_meta.event_id == radar_event_id_) {
    PERF_BLOCK_END("fusion_radar");
  } else if (event_meta.event_id == camera_event_id_) {
    PERF_BLOCK_END("fusion_camera");
  }

  if (objects_.size() > 0 && FLAGS_publish_fusion_event) {
    SharedDataPtr<FusionItem> fusion_item_ptr(new FusionItem);
    fusion_item_ptr->timestamp = objects_[0]->latest_tracked_time;
    const std::string &device_id = events[0].reserve;
    for (auto obj : objects_) {
      ObjectPtr objclone(new Object());
      objclone->clone(*obj);
      fusion_item_ptr->obstacles.push_back(objclone);
    }
    AINFO << "publishing event for timestamp deviceid and size of fusion object"
          << fusion_item_ptr->timestamp << " " << device_id << " "
          << fusion_item_ptr->obstacles.size();
    PublishDataAndEvent(fusion_item_ptr->timestamp, device_id, fusion_item_ptr);
  }

  timestamp_ = sensor_objs[0].timestamp;
  error_code_ = common::OK;
  return Status::OK();
}

void FusionSubnode::PublishDataAndEvent(const double &timestamp,
                                        const std::string &device_id,
                                        const SharedDataPtr<FusionItem> &data) {
  CommonSharedDataKey key(timestamp, device_id);
  bool fusion_succ = fusion_data_->Add(key, data);
  if (!fusion_succ) {
    AERROR << "fusion shared data addkey failure";
  }
  AINFO << "adding key in fusion shared data " << key.ToString();

  for (size_t idx = 0; idx < pub_meta_events_.size(); ++idx) {
    const EventMeta &event_meta = pub_meta_events_[idx];
    Event event;
    event.event_id = event_meta.event_id;
    event.timestamp = timestamp;
    event.reserve = device_id;
    event_manager_->Publish(event);
  }
}

bool FusionSubnode::SubscribeEvents(const EventMeta &event_meta,
                                    std::vector<Event> *events) const {
  Event event;
  // no blocking
  while (event_manager_->Subscribe(event_meta.event_id, &event, true)) {
    events->push_back(event);
  }
  return true;
}
bool FusionSubnode::BuildSensorObjs(
    const std::vector<Event> &events,
    std::vector<SensorObjects> *multi_sensor_objs) {
  PERF_FUNCTION();
  for (auto event : events) {
    std::shared_ptr<SensorObjects> sensor_objects;
    if (!GetSharedData(event, &sensor_objects)) {
      return false;
    }
    // Make sure timestamp and type are filled.
    sensor_objects->timestamp = event.timestamp;
    if (event.event_id == lidar_event_id_) {
      sensor_objects->sensor_type = SensorType::VELODYNE_64;
    } else if (event.event_id == radar_event_id_) {
      sensor_objects->sensor_type = SensorType::RADAR;
    } else if (event.event_id == camera_event_id_) {
      sensor_objects->sensor_type = SensorType::CAMERA;
    } else {
      AERROR << "Event id is not supported. event:" << event.to_string();
      return false;
    }
    sensor_objects->sensor_id = GetSensorType(sensor_objects->sensor_type);
    multi_sensor_objs->push_back(*sensor_objects);
    ADEBUG << "get sensor objs:" << sensor_objects->ToString();
  }
  return true;
}

bool FusionSubnode::GetSharedData(const Event &event,
                                  std::shared_ptr<SensorObjects> *objs) {
  double timestamp = event.timestamp;
  const std::string &device_id = event.reserve;
  std::string data_key;
  if (!SubnodeHelper::ProduceSharedDataKey(timestamp, device_id, &data_key)) {
    AERROR << "Failed to produce shared data key. EventID:" << event.event_id
           << " timestamp:" << timestamp << " device_id:" << device_id;
    return false;
  }
  bool get_data_succ = false;
  if (event.event_id == lidar_event_id_ && lidar_object_data_ != nullptr) {
    get_data_succ = lidar_object_data_->Get(data_key, objs);
  } else if (event.event_id == radar_event_id_ &&
             radar_object_data_ != nullptr) {
    get_data_succ = radar_object_data_->Get(data_key, objs);
  } else if (event.event_id == camera_event_id_ &&
             camera_object_data_ != nullptr) {
    get_data_succ = camera_object_data_->Get(data_key, objs);
    // trying to get lane shared data as well
    Event lane_event;
    if (event_manager_->Subscribe(lane_event_id_, &lane_event, false)) {
      get_data_succ = lane_shared_data_->Get(data_key, &lane_objects_);
      ADEBUG << "getting lane data successfully for data key " << data_key;
    }
  } else {
    AERROR << "Event id is not supported. event:" << event.to_string();
    return false;
  }
  if (!get_data_succ) {
    AERROR << "Failed to get shared data. event:" << event.to_string();
    return false;
  }
  return true;
}

bool FusionSubnode::GeneratePbMsg(PerceptionObstacles *obstacles) {
  common::adapter::AdapterManager::FillPerceptionObstaclesHeader(
      FLAGS_obstacle_module_name, obstacles);
  common::Header *header = obstacles->mutable_header();
  if (pub_driven_event_id_ == lidar_event_id_) {
    header->set_lidar_timestamp(timestamp_ * 1e9);  // in ns
    header->set_camera_timestamp(0);
    header->set_radar_timestamp(0);
  } else if (pub_driven_event_id_ == camera_event_id_) {
    header->set_lidar_timestamp(0);  // in ns
    header->set_camera_timestamp(timestamp_ * 1e9);
    header->set_radar_timestamp(0);
  }

  obstacles->set_error_code(error_code_);

  for (const auto &obj : objects_) {
    PerceptionObstacle *obstacle = obstacles->add_perception_obstacle();
    obj->Serialize(obstacle);
  }

  if (FLAGS_use_navigation_mode) {
    // generate lane marker protobuf messages
    LaneMarkers *lane_markers = obstacles->mutable_lane_marker();
    LaneObjectsToLaneMarkerProto(*(lane_objects_), lane_markers);

    // Relative speed of objects + latest ego car speed in X
    for (auto obstacle : obstacles->perception_obstacle()) {
      obstacle.mutable_velocity()->set_x(obstacle.velocity().x() +
                                         chassis_speed_mps_);
    }
  }

  ADEBUG << "PerceptionObstacles: " << obstacles->ShortDebugString();
  return true;
}

void FusionSubnode::RegistAllAlgorithm() {
  RegisterFactoryProbabilisticFusion();
  RegisterFactoryAsyncFusion();
}

void FusionSubnode::OnChassis(const Chassis &chassis) {
  ADEBUG << "Received chassis data: run chassis callback.";
  chassis_.CopyFrom(chassis);
  chassis_speed_mps_ = chassis_.speed_mps();
}

}  // namespace perception
}  // namespace apollo
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * 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: stylematrixreferencecontext.hxx,v $
 *
 * $Revision: 1.2 $
 *
 * 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.
 *
 ************************************************************************/

#ifndef OOX_DRAWINGML_STYLEMATRIXREFERENCECONTEXT_HXX
#define OOX_DRAWINGML_STYLEMATRIXREFERENCECONTEXT_HXX

#include "oox/core/contexthandler.hxx"
#include "oox/drawingml/color.hxx"

namespace oox { namespace drawingml {

class StyleMatrixReferenceContext : public oox::core::ContextHandler
{
public:

    StyleMatrixReferenceContext( ::oox::core::ContextHandler& rParent,
        const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastAttributeList >& Attribs,
            rtl::OUString& rIdentifier, oox::drawingml::Color& rColor );
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastContextHandler > SAL_CALL createFastChildContext( ::sal_Int32 Element, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastAttributeList >& Attribs ) throw (::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException);

protected:

    ::oox::drawingml::Color& mrColor;
};

} }

#endif  //  OOX_DRAWINGML_STYLEMATRIXREFERENCECONTEXT_HXX
<commit_msg>INTEGRATION: CWS xmlfilter06 (1.2.8); FILE MERGED 2008/06/30 14:50:17 dr 1.2.8.1: #i10000# resync additions<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: stylematrixreferencecontext.hxx,v $
 *
 * $Revision: 1.3 $
 *
 * 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.
 *
 ************************************************************************/

#ifndef OOX_DRAWINGML_STYLEMATRIXREFERENCECONTEXT_HXX
#define OOX_DRAWINGML_STYLEMATRIXREFERENCECONTEXT_HXX

#include "oox/core/contexthandler.hxx"
#include "oox/drawingml/color.hxx"

namespace oox { namespace drawingml {

class StyleMatrixReferenceContext : public oox::core::ContextHandler
{
public:
    StyleMatrixReferenceContext( ::oox::core::ContextHandler& rParent, Color& rColor );
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastContextHandler > SAL_CALL createFastChildContext( ::sal_Int32 Element, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastAttributeList >& Attribs ) throw (::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException);

private:
    Color& mrColor;
};

} }

#endif  //  OOX_DRAWINGML_STYLEMATRIXREFERENCECONTEXT_HXX
<|endoftext|>


<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** No Commercial Usage
**
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/

#include "resizetool.h"

#include "formeditorscene.h"
#include "formeditorview.h"
#include "formeditorwidget.h"

#include "resizehandleitem.h"

#include <QApplication>
#include <QGraphicsSceneMouseEvent>
#include <QAction>
#include <QtDebug>

namespace QmlDesigner {

ResizeTool::ResizeTool(FormEditorView *editorView)
    : AbstractFormEditorTool(editorView),
    m_selectionIndicator(editorView->scene()->manipulatorLayerItem()),
    m_resizeIndicator(editorView->scene()->manipulatorLayerItem()),
    m_resizeManipulator(editorView->scene()->manipulatorLayerItem(), editorView)
{
}

ResizeTool::~ResizeTool()
{
}

void ResizeTool::mousePressEvent(const QList<QGraphicsItem*> &itemList,
                                            QGraphicsSceneMouseEvent *event)
{
    if (itemList.isEmpty())
        return;

    ResizeHandleItem *resizeHandle = ResizeHandleItem::fromGraphicsItem(itemList.first());
    if (resizeHandle && resizeHandle->resizeController().isValid()) {
        m_resizeManipulator.setHandle(resizeHandle);
        m_resizeManipulator.begin(event->scenePos());
        m_resizeIndicator.hide();
    }
}

void ResizeTool::mouseMoveEvent(const QList<QGraphicsItem*> &,
                                           QGraphicsSceneMouseEvent *event)
{
    bool shouldSnapping = view()->widget()->snappingAction()->isChecked();
    bool shouldSnappingAndAnchoring = view()->widget()->snappingAndAnchoringAction()->isChecked();

    ResizeManipulator::Snapping useSnapping = ResizeManipulator::NoSnapping;
    if (event->modifiers().testFlag(Qt::ControlModifier) != (shouldSnapping || shouldSnappingAndAnchoring)) {
        if (shouldSnappingAndAnchoring)
            useSnapping = ResizeManipulator::UseSnappingAndAnchoring;
        else
            useSnapping = ResizeManipulator::UseSnapping;
    }

    m_resizeManipulator.update(event->scenePos(), useSnapping);
}

void ResizeTool::hoverMoveEvent(const QList<QGraphicsItem*> &itemList,
                        QGraphicsSceneMouseEvent * /*event*/)
{
    if (itemList.isEmpty())
        return;
    ResizeHandleItem* resizeHandle = ResizeHandleItem::fromGraphicsItem(itemList.first());
    if (resizeHandle && resizeHandle->resizeController().isValid()) {
        m_resizeManipulator.setHandle(resizeHandle);
    } else {
        view()->changeToSelectionTool();
        return;
    }
}

void ResizeTool::mouseReleaseEvent(const QList<QGraphicsItem*> &itemList,
                                              QGraphicsSceneMouseEvent * /*event*/)
{
    if (itemList.isEmpty())
        return;

    m_selectionIndicator.show();
    m_resizeIndicator.show();
    m_resizeManipulator.end();
}

void ResizeTool::mouseDoubleClickEvent(const QList<QGraphicsItem*> & /*itemList*/,
                                              QGraphicsSceneMouseEvent * /*event*/)
{
}

void ResizeTool::keyPressEvent(QKeyEvent * event)
{
    switch(event->key()) {
        case Qt::Key_Shift:
        case Qt::Key_Alt:
        case Qt::Key_Control:
        case Qt::Key_AltGr:
            event->setAccepted(false);
            return;
    }

    double moveStep = 1.0;

    if (event->modifiers().testFlag(Qt::ShiftModifier))
        moveStep = 10.0;

    switch(event->key()) {
        case Qt::Key_Left: m_resizeManipulator.moveBy(-moveStep, 0.0); break;
        case Qt::Key_Right: m_resizeManipulator.moveBy(moveStep, 0.0); break;
        case Qt::Key_Up: m_resizeManipulator.moveBy(0.0, -moveStep); break;
        case Qt::Key_Down: m_resizeManipulator.moveBy(0.0, moveStep); break;
    }

}

void ResizeTool::keyReleaseEvent(QKeyEvent * keyEvent)
{
     switch(keyEvent->key()) {
        case Qt::Key_Shift:
        case Qt::Key_Alt:
        case Qt::Key_Control:
        case Qt::Key_AltGr:
            keyEvent->setAccepted(false);
            return;
    }

//     if (!keyEvent->isAutoRepeat())
//         m_resizeManipulator.clear();
}

void ResizeTool::itemsAboutToRemoved(const QList<FormEditorItem*> & /*itemList*/)
{

}

void ResizeTool::selectedItemsChanged(const QList<FormEditorItem*> & /*itemList*/)
{
    m_selectionIndicator.setItems(items());
    m_resizeIndicator.setItems(items());
}

void ResizeTool::clear()
{
    m_selectionIndicator.clear();
    m_resizeIndicator.clear();
    m_resizeManipulator.clear();
}

void ResizeTool::formEditorItemsChanged(const QList<FormEditorItem*> &itemList)
{
    m_selectionIndicator.updateItems(itemList);
    m_resizeIndicator.updateItems(itemList);
}

 void ResizeTool::instancesCompleted(const QList<FormEditorItem*> &/*itemList*/)
 {
 }

}
<commit_msg>QmlDesigner.FormEditor: Resize only for hovering<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** No Commercial Usage
**
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/

#include "resizetool.h"

#include "formeditorscene.h"
#include "formeditorview.h"
#include "formeditorwidget.h"

#include "resizehandleitem.h"

#include <QApplication>
#include <QGraphicsSceneMouseEvent>
#include <QAction>
#include <QtDebug>

namespace QmlDesigner {

ResizeTool::ResizeTool(FormEditorView *editorView)
    : AbstractFormEditorTool(editorView),
    m_selectionIndicator(editorView->scene()->manipulatorLayerItem()),
    m_resizeIndicator(editorView->scene()->manipulatorLayerItem()),
    m_resizeManipulator(editorView->scene()->manipulatorLayerItem(), editorView)
{
}

ResizeTool::~ResizeTool()
{
}

void ResizeTool::mousePressEvent(const QList<QGraphicsItem*> &itemList,
                                            QGraphicsSceneMouseEvent *event)
{
    if (itemList.isEmpty())
        return;

    ResizeHandleItem *resizeHandle = ResizeHandleItem::fromGraphicsItem(itemList.first());
    if (resizeHandle && resizeHandle->resizeController().isValid()) {
        m_resizeManipulator.setHandle(resizeHandle);
        m_resizeManipulator.begin(event->scenePos());
        m_resizeIndicator.hide();
    }
}

void ResizeTool::mouseMoveEvent(const QList<QGraphicsItem*> &,
                                           QGraphicsSceneMouseEvent *event)
{
    bool shouldSnapping = view()->widget()->snappingAction()->isChecked();
    bool shouldSnappingAndAnchoring = view()->widget()->snappingAndAnchoringAction()->isChecked();

    ResizeManipulator::Snapping useSnapping = ResizeManipulator::NoSnapping;
    if (event->modifiers().testFlag(Qt::ControlModifier) != (shouldSnapping || shouldSnappingAndAnchoring)) {
        if (shouldSnappingAndAnchoring)
            useSnapping = ResizeManipulator::UseSnappingAndAnchoring;
        else
            useSnapping = ResizeManipulator::UseSnapping;
    }

    m_resizeManipulator.update(event->scenePos(), useSnapping);
}

void ResizeTool::hoverMoveEvent(const QList<QGraphicsItem*> &itemList,
                        QGraphicsSceneMouseEvent * /*event*/)
{
    if (itemList.isEmpty()) {
       view()->changeToSelectionTool();
       return;
    }

    ResizeHandleItem* resizeHandle = ResizeHandleItem::fromGraphicsItem(itemList.first());
    if (resizeHandle && resizeHandle->resizeController().isValid()) {
        m_resizeManipulator.setHandle(resizeHandle);
    } else {
        view()->changeToSelectionTool();
        return;
    }
}

void ResizeTool::mouseReleaseEvent(const QList<QGraphicsItem*> &itemList,
                                              QGraphicsSceneMouseEvent * /*event*/)
{
    if (itemList.isEmpty())
        return;

    m_selectionIndicator.show();
    m_resizeIndicator.show();
    m_resizeManipulator.end();
}

void ResizeTool::mouseDoubleClickEvent(const QList<QGraphicsItem*> & /*itemList*/,
                                              QGraphicsSceneMouseEvent * /*event*/)
{
}

void ResizeTool::keyPressEvent(QKeyEvent * event)
{
    switch(event->key()) {
        case Qt::Key_Shift:
        case Qt::Key_Alt:
        case Qt::Key_Control:
        case Qt::Key_AltGr:
            event->setAccepted(false);
            return;
    }

    double moveStep = 1.0;

    if (event->modifiers().testFlag(Qt::ShiftModifier))
        moveStep = 10.0;

    switch(event->key()) {
        case Qt::Key_Left: m_resizeManipulator.moveBy(-moveStep, 0.0); break;
        case Qt::Key_Right: m_resizeManipulator.moveBy(moveStep, 0.0); break;
        case Qt::Key_Up: m_resizeManipulator.moveBy(0.0, -moveStep); break;
        case Qt::Key_Down: m_resizeManipulator.moveBy(0.0, moveStep); break;
    }

}

void ResizeTool::keyReleaseEvent(QKeyEvent * keyEvent)
{
     switch(keyEvent->key()) {
        case Qt::Key_Shift:
        case Qt::Key_Alt:
        case Qt::Key_Control:
        case Qt::Key_AltGr:
            keyEvent->setAccepted(false);
            return;
    }

//     if (!keyEvent->isAutoRepeat())
//         m_resizeManipulator.clear();
}

void ResizeTool::itemsAboutToRemoved(const QList<FormEditorItem*> & /*itemList*/)
{

}

void ResizeTool::selectedItemsChanged(const QList<FormEditorItem*> & /*itemList*/)
{
    m_selectionIndicator.setItems(items());
    m_resizeIndicator.setItems(items());
}

void ResizeTool::clear()
{
    m_selectionIndicator.clear();
    m_resizeIndicator.clear();
    m_resizeManipulator.clear();
}

void ResizeTool::formEditorItemsChanged(const QList<FormEditorItem*> &itemList)
{
    m_selectionIndicator.updateItems(itemList);
    m_resizeIndicator.updateItems(itemList);
}

 void ResizeTool::instancesCompleted(const QList<FormEditorItem*> &/*itemList*/)
 {
 }

}
<|endoftext|>