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

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include "mitkLookupTablePropertySerializer.h"
#include <mitkLookupTableProperty.h>

TiXmlElement* mitk::LookupTablePropertySerializer::Serialize()
{
  if (const LookupTableProperty* prop = dynamic_cast<const LookupTableProperty*>(m_Property.GetPointer()))
  {
    LookupTable::Pointer mitkLut = const_cast<LookupTableProperty*>(prop)->GetLookupTable();
    if (mitkLut.IsNull()) return nullptr; // really?

    vtkLookupTable* lut = mitkLut->GetVtkLookupTable();
    if (!lut) return nullptr;

    auto  element = new TiXmlElement("LookupTable");

    double*  range;
    double*  rgba;

    element->SetAttribute("NumberOfColors", lut->GetNumberOfTableValues());
    element->SetAttribute("Scale", lut->GetScale());
    element->SetAttribute("Ramp", lut->GetRamp());

    range = lut->GetHueRange();
    auto  child = new TiXmlElement("HueRange");
    element->LinkEndChild( child );
      child->SetDoubleAttribute("min", range[0]);
      child->SetDoubleAttribute("max", range[1]);

    range = lut->GetValueRange();
      child = new TiXmlElement("ValueRange");
    element->LinkEndChild( child );
      child->SetDoubleAttribute("min", range[0]);
      child->SetDoubleAttribute("max", range[1]);

    range = lut->GetSaturationRange();
	  child = new TiXmlElement("SaturationRange");
	element->LinkEndChild( child );
	  child->SetDoubleAttribute("min", range[0]);
	  child->SetDoubleAttribute("max", range[1]);

	range = lut->GetAlphaRange();
				  child = new TiXmlElement("AlphaRange");
	element->LinkEndChild( child );
	  child->SetDoubleAttribute("min", range[0]);
	  child->SetDoubleAttribute("max", range[1]);

	range = lut->GetTableRange();
				  child = new TiXmlElement("TableRange");
	element->LinkEndChild( child );
	  child->SetDoubleAttribute("min", range[0]);
	  child->SetDoubleAttribute("max", range[1]);

	child = new TiXmlElement("Table");
	element->LinkEndChild( child );
	for ( int index = 0; index < lut->GetNumberOfTableValues(); ++index)
	{
	  auto  grandChildNinife = new TiXmlElement("RgbaColor");
	  rgba = lut->GetTableValue(index);
	  grandChildNinife->SetDoubleAttribute("R", rgba[0]);
	  grandChildNinife->SetDoubleAttribute("G", rgba[1]);
	  grandChildNinife->SetDoubleAttribute("B", rgba[2]);
	  grandChildNinife->SetDoubleAttribute("A", rgba[3]);
	  child->LinkEndChild( grandChildNinife );
	}
    return element;
  }
  else return nullptr;
}

mitk::BaseProperty::Pointer mitk::LookupTablePropertySerializer::Deserialize(TiXmlElement* element)
{
  if (!element) return nullptr;

  typedef double OUR_VTK_FLOAT_TYPE;
  double range[2];
  double  rgba[4];

  double d;  // bec. of tinyXML's interface that takes a pointer to float or double...

  vtkSmartPointer<vtkLookupTable> lut = vtkSmartPointer<vtkLookupTable>::New();

  int numberOfColors;
  int scale;
  int ramp; // hope the int values don't change betw. vtk versions...
  if ( element->QueryIntAttribute( "NumberOfColors", &numberOfColors ) == TIXML_SUCCESS )
  {
	lut->SetNumberOfTableValues( numberOfColors );
  }
  else
	return nullptr;
  if ( element->QueryIntAttribute( "Scale", &scale ) == TIXML_SUCCESS )
  {
	lut->SetScale( scale );
  }
  else
	return nullptr;
  if ( element->QueryIntAttribute( "Ramp", &ramp ) == TIXML_SUCCESS )
  {
	lut->SetRamp( ramp );
  }
  else
	return nullptr;

  TiXmlElement* child = element->FirstChildElement("HueRange");
  if (child)
  {
	if ( child->QueryDoubleAttribute( "min", &d ) != TIXML_SUCCESS )
	  return nullptr;
	range[0] = static_cast<OUR_VTK_FLOAT_TYPE>(d);
	if ( child->QueryDoubleAttribute( "max", &d ) != TIXML_SUCCESS )
	  return nullptr;
	range[1] = static_cast<OUR_VTK_FLOAT_TYPE>(d);
	lut->SetHueRange( range );
  }

				child = element->FirstChildElement("ValueRange");
  if (child)
  {
	if ( child->QueryDoubleAttribute( "min", &d ) != TIXML_SUCCESS ) return nullptr; range[0] = static_cast<OUR_VTK_FLOAT_TYPE>(d);
	if ( child->QueryDoubleAttribute( "max", &d ) != TIXML_SUCCESS ) return nullptr; range[1] = static_cast<OUR_VTK_FLOAT_TYPE>(d);
	lut->SetValueRange( range );
  }

				child = element->FirstChildElement("SaturationRange");
  if (child)
  {
	if ( child->QueryDoubleAttribute( "min", &d ) != TIXML_SUCCESS ) return nullptr; range[0] = static_cast<OUR_VTK_FLOAT_TYPE>(d);
	if ( child->QueryDoubleAttribute( "max", &d ) != TIXML_SUCCESS ) return nullptr; range[1] = static_cast<OUR_VTK_FLOAT_TYPE>(d);
	lut->SetSaturationRange( range );
  }

				child = element->FirstChildElement("AlphaRange");
  if (child)
  {
	if ( child->QueryDoubleAttribute( "min", &d ) != TIXML_SUCCESS ) return nullptr; range[0] = static_cast<OUR_VTK_FLOAT_TYPE>(d);
	if ( child->QueryDoubleAttribute( "max", &d ) != TIXML_SUCCESS ) return nullptr; range[1] = static_cast<OUR_VTK_FLOAT_TYPE>(d);
	lut->SetAlphaRange( range );
  }

				child = element->FirstChildElement("TableRange");
  if (child)
  {
	if ( child->QueryDoubleAttribute( "min", &d ) != TIXML_SUCCESS ) return nullptr; range[0] = static_cast<OUR_VTK_FLOAT_TYPE>(d);
	if ( child->QueryDoubleAttribute( "max", &d ) != TIXML_SUCCESS ) return nullptr; range[1] = static_cast<OUR_VTK_FLOAT_TYPE>(d);
	lut->SetTableRange( range );
  }

  child = element->FirstChildElement("Table");
  if (child)
  {
	unsigned int index(0);
	for( TiXmlElement* grandChild = child->FirstChildElement("RgbaColor"); grandChild; grandChild = grandChild->NextSiblingElement("RgbaColor"))
	{
	  if ( grandChild->QueryDoubleAttribute("R", &d) != TIXML_SUCCESS ) return nullptr; rgba[0] = static_cast<OUR_VTK_FLOAT_TYPE>(d);
	  if ( grandChild->QueryDoubleAttribute("G", &d) != TIXML_SUCCESS ) return nullptr; rgba[1] = static_cast<OUR_VTK_FLOAT_TYPE>(d);
	  if ( grandChild->QueryDoubleAttribute("B", &d) != TIXML_SUCCESS ) return nullptr; rgba[2] = static_cast<OUR_VTK_FLOAT_TYPE>(d);
	  if ( grandChild->QueryDoubleAttribute("A", &d) != TIXML_SUCCESS ) return nullptr; rgba[3] = static_cast<OUR_VTK_FLOAT_TYPE>(d);

	  lut->SetTableValue( index, rgba );
	  ++index;
	}
  }

  LookupTable::Pointer mitkLut = LookupTable::New();
  mitkLut->SetVtkLookupTable( lut );

  return LookupTableProperty::New(mitkLut).GetPointer();
}<commit_msg>Revert "Separating mitkLookupTablePropertySerliazer into header and source"<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#ifndef mitkLookupTablePropertySerializer_h_included
#define mitkLookupTablePropertySerializer_h_included

#include "mitkBasePropertySerializer.h"

#include "mitkLookupTableProperty.h"

namespace mitk
{

class LookupTablePropertySerializer : public BasePropertySerializer
{
  public:

    mitkClassMacro( LookupTablePropertySerializer, BasePropertySerializer );
    itkFactorylessNewMacro(Self)
    itkCloneMacro(Self)

    virtual TiXmlElement* Serialize() override
    {
      if (const LookupTableProperty* prop = dynamic_cast<const LookupTableProperty*>(m_Property.GetPointer()))
      {
        LookupTable::Pointer mitkLut = const_cast<LookupTableProperty*>(prop)->GetLookupTable();
        if (mitkLut.IsNull()) return nullptr; // really?

        vtkLookupTable* lut = mitkLut->GetVtkLookupTable();
        if (!lut) return nullptr;

        auto  element = new TiXmlElement("LookupTable");

        double*  range;
        double*  rgba;

        element->SetAttribute("NumberOfColors", lut->GetNumberOfTableValues());
        element->SetAttribute("Scale", lut->GetScale());
        element->SetAttribute("Ramp", lut->GetRamp());

        range = lut->GetHueRange();
        auto  child = new TiXmlElement("HueRange");
        element->LinkEndChild( child );
          child->SetDoubleAttribute("min", range[0]);
          child->SetDoubleAttribute("max", range[1]);

        range = lut->GetValueRange();
                      child = new TiXmlElement("ValueRange");
        element->LinkEndChild( child );
          child->SetDoubleAttribute("min", range[0]);
          child->SetDoubleAttribute("max", range[1]);

        range = lut->GetSaturationRange();
                      child = new TiXmlElement("SaturationRange");
        element->LinkEndChild( child );
          child->SetDoubleAttribute("min", range[0]);
          child->SetDoubleAttribute("max", range[1]);

        range = lut->GetAlphaRange();
                      child = new TiXmlElement("AlphaRange");
        element->LinkEndChild( child );
          child->SetDoubleAttribute("min", range[0]);
          child->SetDoubleAttribute("max", range[1]);

        range = lut->GetTableRange();
                      child = new TiXmlElement("TableRange");
        element->LinkEndChild( child );
          child->SetDoubleAttribute("min", range[0]);
          child->SetDoubleAttribute("max", range[1]);

        child = new TiXmlElement("Table");
        element->LinkEndChild( child );
        for ( int index = 0; index < lut->GetNumberOfTableValues(); ++index)
        {
          auto  grandChildNinife = new TiXmlElement("RgbaColor");
          rgba = lut->GetTableValue(index);
          grandChildNinife->SetDoubleAttribute("R", rgba[0]);
          grandChildNinife->SetDoubleAttribute("G", rgba[1]);
          grandChildNinife->SetDoubleAttribute("B", rgba[2]);
          grandChildNinife->SetDoubleAttribute("A", rgba[3]);
          child->LinkEndChild( grandChildNinife );
        }
        return element;
      }
      else return nullptr;
    }

    virtual BaseProperty::Pointer Deserialize(TiXmlElement* element) override
    {
      if (!element) return nullptr;

      typedef double OUR_VTK_FLOAT_TYPE;
      double range[2];
      double  rgba[4];

      double d;  // bec. of tinyXML's interface that takes a pointer to float or double...

      vtkSmartPointer<vtkLookupTable> lut = vtkSmartPointer<vtkLookupTable>::New();

      int numberOfColors;
      int scale;
      int ramp; // hope the int values don't change betw. vtk versions...
      if ( element->QueryIntAttribute( "NumberOfColors", &numberOfColors ) == TIXML_SUCCESS )
      {
        lut->SetNumberOfTableValues( numberOfColors );
      }
      else
        return nullptr;
      if ( element->QueryIntAttribute( "Scale", &scale ) == TIXML_SUCCESS )
      {
        lut->SetScale( scale );
      }
      else
        return nullptr;
      if ( element->QueryIntAttribute( "Ramp", &ramp ) == TIXML_SUCCESS )
      {
        lut->SetRamp( ramp );
      }
      else
        return nullptr;

      TiXmlElement* child = element->FirstChildElement("HueRange");
      if (child)
      {
        if ( child->QueryDoubleAttribute( "min", &d ) != TIXML_SUCCESS )
          return nullptr;
        range[0] = static_cast<OUR_VTK_FLOAT_TYPE>(d);
        if ( child->QueryDoubleAttribute( "max", &d ) != TIXML_SUCCESS )
          return nullptr;
        range[1] = static_cast<OUR_VTK_FLOAT_TYPE>(d);
        lut->SetHueRange( range );
      }

                    child = element->FirstChildElement("ValueRange");
      if (child)
      {
        if ( child->QueryDoubleAttribute( "min", &d ) != TIXML_SUCCESS ) return nullptr; range[0] = static_cast<OUR_VTK_FLOAT_TYPE>(d);
        if ( child->QueryDoubleAttribute( "max", &d ) != TIXML_SUCCESS ) return nullptr; range[1] = static_cast<OUR_VTK_FLOAT_TYPE>(d);
        lut->SetValueRange( range );
      }

                    child = element->FirstChildElement("SaturationRange");
      if (child)
      {
        if ( child->QueryDoubleAttribute( "min", &d ) != TIXML_SUCCESS ) return nullptr; range[0] = static_cast<OUR_VTK_FLOAT_TYPE>(d);
        if ( child->QueryDoubleAttribute( "max", &d ) != TIXML_SUCCESS ) return nullptr; range[1] = static_cast<OUR_VTK_FLOAT_TYPE>(d);
        lut->SetSaturationRange( range );
      }

                    child = element->FirstChildElement("AlphaRange");
      if (child)
      {
        if ( child->QueryDoubleAttribute( "min", &d ) != TIXML_SUCCESS ) return nullptr; range[0] = static_cast<OUR_VTK_FLOAT_TYPE>(d);
        if ( child->QueryDoubleAttribute( "max", &d ) != TIXML_SUCCESS ) return nullptr; range[1] = static_cast<OUR_VTK_FLOAT_TYPE>(d);
        lut->SetAlphaRange( range );
      }

                    child = element->FirstChildElement("TableRange");
      if (child)
      {
        if ( child->QueryDoubleAttribute( "min", &d ) != TIXML_SUCCESS ) return nullptr; range[0] = static_cast<OUR_VTK_FLOAT_TYPE>(d);
        if ( child->QueryDoubleAttribute( "max", &d ) != TIXML_SUCCESS ) return nullptr; range[1] = static_cast<OUR_VTK_FLOAT_TYPE>(d);
        lut->SetTableRange( range );
      }

      child = element->FirstChildElement("Table");
      if (child)
      {
        unsigned int index(0);
        for( TiXmlElement* grandChild = child->FirstChildElement("RgbaColor"); grandChild; grandChild = grandChild->NextSiblingElement("RgbaColor"))
        {
          if ( grandChild->QueryDoubleAttribute("R", &d) != TIXML_SUCCESS ) return nullptr; rgba[0] = static_cast<OUR_VTK_FLOAT_TYPE>(d);
          if ( grandChild->QueryDoubleAttribute("G", &d) != TIXML_SUCCESS ) return nullptr; rgba[1] = static_cast<OUR_VTK_FLOAT_TYPE>(d);
          if ( grandChild->QueryDoubleAttribute("B", &d) != TIXML_SUCCESS ) return nullptr; rgba[2] = static_cast<OUR_VTK_FLOAT_TYPE>(d);
          if ( grandChild->QueryDoubleAttribute("A", &d) != TIXML_SUCCESS ) return nullptr; rgba[3] = static_cast<OUR_VTK_FLOAT_TYPE>(d);

          lut->SetTableValue( index, rgba );
          ++index;
        }
      }

      LookupTable::Pointer mitkLut = LookupTable::New();
      mitkLut->SetVtkLookupTable( lut );

      return LookupTableProperty::New(mitkLut).GetPointer();
    }

  protected:

    LookupTablePropertySerializer() {}
    virtual ~LookupTablePropertySerializer() {}
};

} // namespace

// important to put this into the GLOBAL namespace (because it starts with 'namespace mitk')
MITK_REGISTER_SERIALIZER(LookupTablePropertySerializer);

#endif

<|endoftext|>


<commit_before>// $Id$

// The libMesh Finite Element Library.
// Copyright (C) 2002-2008 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner

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

// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.

// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

// library configuration
#include "libmesh_config.h"

// C++ includes
#include <algorithm> // for std::min
#include <map>       // for std::multimap
#include <sstream>   // for std::ostringstream

// Local includes
#include "boundary_info.h"
#include "elem.h"
#include "mesh_base.h"
#include "parallel.h"
#include "partitioner.h"
#include "point_locator_base.h"

namespace libMesh
{

// ------------------------------------------------------------
// MeshBase class member functions
MeshBase::MeshBase (unsigned int d) :
  boundary_info  (new BoundaryInfo(*this)),
  _n_parts       (1),
  _dim           (d),
  _is_prepared   (false),
  _point_locator (NULL),
  _partitioner   (NULL)
{
  libmesh_assert (LIBMESH_DIM <= 3);
  libmesh_assert (LIBMESH_DIM >= _dim);
  libmesh_assert (libMesh::initialized());
}

MeshBase::MeshBase (const MeshBase& other_mesh) :
  boundary_info  (new BoundaryInfo(*this)), // no copy constructor defined for BoundaryInfo?
  _n_parts       (other_mesh._n_parts),
  _dim           (other_mesh._dim),
  _is_prepared   (other_mesh._is_prepared),
  _point_locator (NULL),
  _partitioner   (other_mesh._partitioner->clone())
{
}

MeshBase::~MeshBase()
{
  this->clear();

  libmesh_assert (!libMesh::closed());
}

void MeshBase::prepare_for_use (const bool skip_renumber_nodes_and_elements)
{
  // Renumber the nodes and elements so that they in contiguous
  // blocks.  By default, skip_renumber_nodes_and_elements is false,
  // however we may skip this step by passing
  // skip_renumber_nodes_and_elements==true to this function.
  //
  // Instances where you if prepare_for_use() should not renumber the nodes
  // and elements include reading in e.g. an xda/r or gmv file. In
  // this case, the ordering of the nodes may depend on an accompanying
  // solution, and the node ordering cannot be changed.
  if(!skip_renumber_nodes_and_elements)
    this->renumber_nodes_and_elements();

  // Let all the elements find their neighbors
  this->find_neighbors();

  // Partition the mesh.
  this->partition();

  // If we're using ParallelMesh, we'll want it parallelized.
  this->delete_remote_elements();

  if(!skip_renumber_nodes_and_elements)
    this->renumber_nodes_and_elements();

  // Reset our PointLocator.  This needs to happen any time the elements
  // in the underlying elements in the mesh have changed, so we do it here.
  this->clear_point_locator();

  // The mesh is now prepared for use.
  _is_prepared = true;
}

void MeshBase::clear ()
{
  // Reset the number of partitions
  _n_parts = 1;

  // Reset the _is_prepared flag
  _is_prepared = false;

  // Clear boundary information
  this->boundary_info->clear();

  // Clear our point locator.
  this->clear_point_locator();
}

unsigned int MeshBase::n_subdomains() const
{
  // This requires an inspection on every processor
  parallel_only();

  const_element_iterator       el  = this->active_elements_begin();
  const const_element_iterator end = this->active_elements_end();

  std::set<unsigned int> subdomain_ids;

  for (; el!=end; ++el)
    subdomain_ids.insert((*el)->subdomain_id());

  // Some subdomains may only live on other processors
  Parallel::set_union(subdomain_ids, 0);

  unsigned int n_sbd_ids = subdomain_ids.size();
  Parallel::broadcast(n_sbd_ids);

  return n_sbd_ids;
}

unsigned int MeshBase::n_nodes_on_proc (const unsigned int proc_id) const
{
  // We're either counting a processor's nodes or unpartitioned
  // nodes
  libmesh_assert (proc_id < libMesh::n_processors() ||
	  proc_id == DofObject::invalid_processor_id);

  return static_cast<unsigned int>(std::distance (this->pid_nodes_begin(proc_id),
						  this->pid_nodes_end  (proc_id)));
}

unsigned int MeshBase::n_elem_on_proc (const unsigned int proc_id) const
{
  // We're either counting a processor's elements or unpartitioned
  // elements
  libmesh_assert (proc_id < libMesh::n_processors() ||
	  proc_id == DofObject::invalid_processor_id);

  return static_cast<unsigned int>(std::distance (this->pid_elements_begin(proc_id),
						  this->pid_elements_end  (proc_id)));
}

unsigned int MeshBase::n_active_elem_on_proc (const unsigned int proc_id) const
{
  libmesh_assert (proc_id < libMesh::n_processors());
  return static_cast<unsigned int>(std::distance (this->active_pid_elements_begin(proc_id),
						  this->active_pid_elements_end  (proc_id)));
}

unsigned int MeshBase::n_sub_elem () const
{
  unsigned int ne=0;

  const_element_iterator       el  = this->elements_begin();
  const const_element_iterator end = this->elements_end();

  for (; el!=end; ++el)
    ne += (*el)->n_sub_elem();

  return ne;
}

unsigned int MeshBase::n_active_sub_elem () const
{
  unsigned int ne=0;

  const_element_iterator       el  = this->active_elements_begin();
  const const_element_iterator end = this->active_elements_end();

  for (; el!=end; ++el)
    ne += (*el)->n_sub_elem();

  return ne;
}

std::string MeshBase::get_info() const
{
  std::ostringstream out;

  out << " Mesh Information:"                                  << '\n'
      << "  mesh_dimension()="    << this->mesh_dimension()    << '\n'
      << "  spatial_dimension()=" << this->spatial_dimension() << '\n'
      << "  n_nodes()="           << this->n_nodes()           << '\n'
      << "    n_local_nodes()="   << this->n_local_nodes()     << '\n'
      << "  n_elem()="            << this->n_elem()            << '\n'
      << "    n_local_elem()="    << this->n_local_elem()      << '\n'
#ifdef LIBMESH_ENABLE_AMR
      << "    n_active_elem()="   << this->n_active_elem()     << '\n'
#endif
      << "  n_subdomains()="      << this->n_subdomains()      << '\n'
      << "  n_processors()="      << this->n_processors()      << '\n'
      << "  processor_id()="      << this->processor_id()      << '\n';

  return out.str();
}

void MeshBase::print_info(std::ostream& os) const
{
  os << this->get_info()
     << std::endl;
}

std::ostream& operator << (std::ostream& os, const MeshBase& m)
{
  m.print_info(os);
  return os;
}

void MeshBase::partition (const unsigned int n_parts)
{
  if (partitioner().get()) // "NULL" means don't partition
    partitioner()->partition (*this, n_parts);
}

unsigned int MeshBase::recalculate_n_partitions()
{
  const_element_iterator       el  = this->active_elements_begin();
  const const_element_iterator end = this->active_elements_end();

  unsigned int max_proc_id=0;

  for (; el!=end; ++el)
    max_proc_id = std::max(max_proc_id, static_cast<unsigned int>((*el)->processor_id()));

  // The number of partitions is one more than the max processor ID.
  _n_parts = max_proc_id+1;

  return _n_parts;
}

const PointLocatorBase & MeshBase::point_locator () const
{
  // Double checked lock pattern for efficiency
  if (_point_locator.get() == NULL)
  {
    Threads::spin_mutex::scoped_lock lock(Threads::spin_mtx);

    if (_point_locator.get() == NULL)
      _point_locator.reset (PointLocatorBase::build(TREE, *this).release());
  }

  return *_point_locator;
}

void MeshBase::clear_point_locator ()
{
  _point_locator.reset(NULL);
}

} // namespace libMesh

<commit_msg>Remove unnecessary/buggy mutex acquisition from point_locator()<commit_after>// $Id$

// The libMesh Finite Element Library.
// Copyright (C) 2002-2008 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner

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

// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.

// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

// library configuration
#include "libmesh_config.h"

// C++ includes
#include <algorithm> // for std::min
#include <map>       // for std::multimap
#include <sstream>   // for std::ostringstream

// Local includes
#include "boundary_info.h"
#include "elem.h"
#include "mesh_base.h"
#include "parallel.h"
#include "partitioner.h"
#include "point_locator_base.h"
#include "threads.h"

namespace libMesh
{

// ------------------------------------------------------------
// MeshBase class member functions
MeshBase::MeshBase (unsigned int d) :
  boundary_info  (new BoundaryInfo(*this)),
  _n_parts       (1),
  _dim           (d),
  _is_prepared   (false),
  _point_locator (NULL),
  _partitioner   (NULL)
{
  libmesh_assert (LIBMESH_DIM <= 3);
  libmesh_assert (LIBMESH_DIM >= _dim);
  libmesh_assert (libMesh::initialized());
}

MeshBase::MeshBase (const MeshBase& other_mesh) :
  boundary_info  (new BoundaryInfo(*this)), // no copy constructor defined for BoundaryInfo?
  _n_parts       (other_mesh._n_parts),
  _dim           (other_mesh._dim),
  _is_prepared   (other_mesh._is_prepared),
  _point_locator (NULL),
  _partitioner   (other_mesh._partitioner->clone())
{
}

MeshBase::~MeshBase()
{
  this->clear();

  libmesh_assert (!libMesh::closed());
}

void MeshBase::prepare_for_use (const bool skip_renumber_nodes_and_elements)
{
  // Renumber the nodes and elements so that they in contiguous
  // blocks.  By default, skip_renumber_nodes_and_elements is false,
  // however we may skip this step by passing
  // skip_renumber_nodes_and_elements==true to this function.
  //
  // Instances where you if prepare_for_use() should not renumber the nodes
  // and elements include reading in e.g. an xda/r or gmv file. In
  // this case, the ordering of the nodes may depend on an accompanying
  // solution, and the node ordering cannot be changed.
  if(!skip_renumber_nodes_and_elements)
    this->renumber_nodes_and_elements();

  // Let all the elements find their neighbors
  this->find_neighbors();

  // Partition the mesh.
  this->partition();

  // If we're using ParallelMesh, we'll want it parallelized.
  this->delete_remote_elements();

  if(!skip_renumber_nodes_and_elements)
    this->renumber_nodes_and_elements();

  // Reset our PointLocator.  This needs to happen any time the elements
  // in the underlying elements in the mesh have changed, so we do it here.
  this->clear_point_locator();

  // The mesh is now prepared for use.
  _is_prepared = true;
}

void MeshBase::clear ()
{
  // Reset the number of partitions
  _n_parts = 1;

  // Reset the _is_prepared flag
  _is_prepared = false;

  // Clear boundary information
  this->boundary_info->clear();

  // Clear our point locator.
  this->clear_point_locator();
}

unsigned int MeshBase::n_subdomains() const
{
  // This requires an inspection on every processor
  parallel_only();

  const_element_iterator       el  = this->active_elements_begin();
  const const_element_iterator end = this->active_elements_end();

  std::set<unsigned int> subdomain_ids;

  for (; el!=end; ++el)
    subdomain_ids.insert((*el)->subdomain_id());

  // Some subdomains may only live on other processors
  Parallel::set_union(subdomain_ids, 0);

  unsigned int n_sbd_ids = subdomain_ids.size();
  Parallel::broadcast(n_sbd_ids);

  return n_sbd_ids;
}

unsigned int MeshBase::n_nodes_on_proc (const unsigned int proc_id) const
{
  // We're either counting a processor's nodes or unpartitioned
  // nodes
  libmesh_assert (proc_id < libMesh::n_processors() ||
	  proc_id == DofObject::invalid_processor_id);

  return static_cast<unsigned int>(std::distance (this->pid_nodes_begin(proc_id),
						  this->pid_nodes_end  (proc_id)));
}

unsigned int MeshBase::n_elem_on_proc (const unsigned int proc_id) const
{
  // We're either counting a processor's elements or unpartitioned
  // elements
  libmesh_assert (proc_id < libMesh::n_processors() ||
	  proc_id == DofObject::invalid_processor_id);

  return static_cast<unsigned int>(std::distance (this->pid_elements_begin(proc_id),
						  this->pid_elements_end  (proc_id)));
}

unsigned int MeshBase::n_active_elem_on_proc (const unsigned int proc_id) const
{
  libmesh_assert (proc_id < libMesh::n_processors());
  return static_cast<unsigned int>(std::distance (this->active_pid_elements_begin(proc_id),
						  this->active_pid_elements_end  (proc_id)));
}

unsigned int MeshBase::n_sub_elem () const
{
  unsigned int ne=0;

  const_element_iterator       el  = this->elements_begin();
  const const_element_iterator end = this->elements_end();

  for (; el!=end; ++el)
    ne += (*el)->n_sub_elem();

  return ne;
}

unsigned int MeshBase::n_active_sub_elem () const
{
  unsigned int ne=0;

  const_element_iterator       el  = this->active_elements_begin();
  const const_element_iterator end = this->active_elements_end();

  for (; el!=end; ++el)
    ne += (*el)->n_sub_elem();

  return ne;
}

std::string MeshBase::get_info() const
{
  std::ostringstream out;

  out << " Mesh Information:"                                  << '\n'
      << "  mesh_dimension()="    << this->mesh_dimension()    << '\n'
      << "  spatial_dimension()=" << this->spatial_dimension() << '\n'
      << "  n_nodes()="           << this->n_nodes()           << '\n'
      << "    n_local_nodes()="   << this->n_local_nodes()     << '\n'
      << "  n_elem()="            << this->n_elem()            << '\n'
      << "    n_local_elem()="    << this->n_local_elem()      << '\n'
#ifdef LIBMESH_ENABLE_AMR
      << "    n_active_elem()="   << this->n_active_elem()     << '\n'
#endif
      << "  n_subdomains()="      << this->n_subdomains()      << '\n'
      << "  n_processors()="      << this->n_processors()      << '\n'
      << "  processor_id()="      << this->processor_id()      << '\n';

  return out.str();
}

void MeshBase::print_info(std::ostream& os) const
{
  os << this->get_info()
     << std::endl;
}

std::ostream& operator << (std::ostream& os, const MeshBase& m)
{
  m.print_info(os);
  return os;
}

void MeshBase::partition (const unsigned int n_parts)
{
  if (partitioner().get()) // "NULL" means don't partition
    partitioner()->partition (*this, n_parts);
}

unsigned int MeshBase::recalculate_n_partitions()
{
  const_element_iterator       el  = this->active_elements_begin();
  const const_element_iterator end = this->active_elements_end();

  unsigned int max_proc_id=0;

  for (; el!=end; ++el)
    max_proc_id = std::max(max_proc_id, static_cast<unsigned int>((*el)->processor_id()));

  // The number of partitions is one more than the max processor ID.
  _n_parts = max_proc_id+1;

  return _n_parts;
}

const PointLocatorBase & MeshBase::point_locator () const
{
  if (_point_locator.get() == NULL)
    {
      // PointLocator construction may not be safe within threads
      libmesh_assert(!Threads::in_threads);

      _point_locator.reset (PointLocatorBase::build(TREE, *this).release());
    }
}

void MeshBase::clear_point_locator ()
{
  _point_locator.reset(NULL);
}

} // namespace libMesh

<|endoftext|>


<commit_before><commit_msg>Rename ImplGetGradientColorValue<commit_after><|endoftext|>


<commit_before><commit_msg>help coverity out wrt coverity#1267682 String not null terminated<commit_after><|endoftext|>


<commit_before>#include <QApplication>
#include <QMainWindow>
#include <QToolBar>
#include <QDebug>
#include "../core/folder.h"
#include "../foldermodel.h"
#include "../folderview.h"
#include "../cachedfoldermodel.h"
#include "../proxyfoldermodel.h"
#include "../pathedit.h"
#include "libfmqt.h"

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

    Fm::LibFmQt contex;
    QMainWindow win;

    Fm::FolderView folder_view;
    win.setCentralWidget(&folder_view);

    auto home = Fm::FilePath::homeDir();
    Fm::CachedFolderModel* model = Fm::CachedFolderModel::modelFromPath(home);
    auto proxy_model = new Fm::ProxyFolderModel();
    proxy_model->sort(Fm::FolderModel::ColumnFileName, Qt::AscendingOrder);
    proxy_model->setSourceModel(model);

    proxy_model->setThumbnailSize(64);
    proxy_model->setShowThumbnails(true);

    folder_view.setModel(proxy_model);

    QToolBar toolbar;
    win.addToolBar(Qt::TopToolBarArea, &toolbar);
    Fm::PathEdit edit;
    edit.setText(home.toString().get());
    toolbar.addWidget(&edit);
    auto action = new QAction(QStringLiteral("Go"), nullptr);
    toolbar.addAction(action);
    QObject::connect(action, &QAction::triggered, [&]() {
        auto path = Fm::FilePath::fromPathStr(edit.text().toLocal8Bit().constData());
        auto new_model = Fm::CachedFolderModel::modelFromPath(path);
        proxy_model->setSourceModel(new_model);
    });

    win.show();
    return app.exec();
}
<commit_msg>Update test-folderview.cpp<commit_after>/*
 * Copyright (C) 2017  Hong Jen Yee (PCMan) <pcman.tw@gmail.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 */
#include <QApplication>
#include <QMainWindow>
#include <QToolBar>
#include <QDebug>
#include "../core/folder.h"
#include "../foldermodel.h"
#include "../folderview.h"
#include "../cachedfoldermodel.h"
#include "../proxyfoldermodel.h"
#include "../pathedit.h"
#include "libfmqt.h"

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

    Fm::LibFmQt contex;
    QMainWindow win;

    Fm::FolderView folder_view;
    win.setCentralWidget(&folder_view);

    auto home = Fm::FilePath::homeDir();
    Fm::CachedFolderModel* model = Fm::CachedFolderModel::modelFromPath(home);
    auto proxy_model = new Fm::ProxyFolderModel();
    proxy_model->sort(Fm::FolderModel::ColumnFileName, Qt::AscendingOrder);
    proxy_model->setSourceModel(model);

    proxy_model->setThumbnailSize(64);
    proxy_model->setShowThumbnails(true);

    folder_view.setModel(proxy_model);

    QToolBar toolbar;
    win.addToolBar(Qt::TopToolBarArea, &toolbar);
    Fm::PathEdit edit;
    edit.setText(home.toString().get());
    toolbar.addWidget(&edit);
    auto action = new QAction(QStringLiteral("Go"), nullptr);
    toolbar.addAction(action);
    QObject::connect(action, &QAction::triggered, [&]() {
        auto path = Fm::FilePath::fromPathStr(edit.text().toLocal8Bit().constData());
        auto new_model = Fm::CachedFolderModel::modelFromPath(path);
        proxy_model->setSourceModel(new_model);
    });

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


<commit_before>#include <taichi/visual/gui.h>
#include "../tlang.h"

TLANG_NAMESPACE_BEGIN

auto volume_renderer = [] {
  CoreState::set_trigger_gdb_when_crash(true);

  int n = 512;
  int grid_resolution = 256;

  auto f = fopen("snow_density_256.bin", "rb");
  TC_ASSERT_INFO(f, "./snow_density_256.bin not found");
  std::vector<float32> density_field(pow<3>(grid_resolution));
  std::fread(density_field.data(), sizeof(float32), density_field.size(), f);
  std::fclose(f);

  Program prog(Arch::gpu);
  prog.config.print_ir = true;

  Vector buffer(DataType::f32, 3);
  Global(density, f32);

  layout([&]() {
    root.dense(Index(0), n * n * 2).place(buffer(0), buffer(1), buffer(2));
    root.dense(Indices(0, 1, 2), grid_resolution).place(density);
  });

  // If p is in the density field return the density, other 0
  auto query_density = [&](Vector p) {
    auto inside_box = Var(0.0f <= p(0) && p(0) < 1.0f && 0.0f <= p(1) &&
                          p(1) < 1.0f && 0.0f <= p(2) && p(2) < 1.0f);
    auto ret = Var(0.0f);
    If(inside_box).Then([&] {
      auto i = floor(p(0) * float32(grid_resolution));
      auto j = floor(p(1) * float32(grid_resolution));
      auto k = floor(p(2) * float32(grid_resolution));
      ret = density[i, j, k];
    });
    return ret;
  };

  auto background = [](Vector dir) {
    return 1.0f * max(dir(1) + dir(0), 0.0f);
  };

  float32 fov = 0.7;

  Kernel(main).def([&]() {
    For(0, n * n * 2, [&](Expr i) {
      auto orig = Var(Vector({0.5f, 0.3f, 1.5f}));

      auto c = Var(Vector({fov * (cast<float32>(i / n) / float32(n / 2) - 2.0f),
                           fov * (cast<float32>(i % n) / float32(n / 2) - 1.0f),
                           -1.0f}));

      c = normalized(c);

      auto color = Var(Vector({1.0f, 1.0f, 1.0f}));

      For(0, 200, [&](Expr k) {
        auto p = Var(orig + c * ((cast<float32>(k) + Rand<float32>()) * 0.01f));
        color *= (1.0_f - query_density(p) * 0.1f);
      });

      buffer[i] += color;
    });
  });

  for (int i = 0; i < grid_resolution; i++) {
    for (int j = 0; j < grid_resolution; j++) {
      for (int k = 0; k < grid_resolution; k++) {
        density.val<float32>(i, j, k) =
            density_field[i * grid_resolution * grid_resolution +
                          j * grid_resolution + k];
      }
    }
  }

  GUI gui("Volume Renderer", Vector2i(n * 2, n));

  auto tone_map = [](real x) { return x; };
  constexpr int N = 10;
  for (int frame = 0;; frame++) {
    for (int i = 0; i < N; i++)
      main();
    real scale = 1.0f / ((frame + 1) * N);
    for (int i = 0; i < n * n * 2; i++) {
      gui.buffer[i / n][i % n] =
          Vector4(tone_map(scale * buffer(0).val<float32>(i)),
                  tone_map(scale * buffer(1).val<float32>(i)),
                  tone_map(scale * buffer(2).val<float32>(i)), 1);
    }
    gui.update();
  }
};
TC_REGISTER_TASK(volume_renderer);

TLANG_NAMESPACE_END
<commit_msg>Volume renderer<commit_after>#include <taichi/visual/gui.h>
#include "../tlang.h"

TLANG_NAMESPACE_BEGIN

auto volume_renderer = [] {
  //CoreState::set_trigger_gdb_when_crash(true);

  int depth_limit = 40;
  int n = 512;
  int grid_resolution = 256;
  Vector3 albedo(0.95, 0.95, 0.95);
  float32 scale = 724.0;
  float32 one_over_four_pi = 0.07957747154;
  float32 pi = 3.14159265359;

  auto f = fopen("snow_density_256.bin", "rb");
  TC_ASSERT_INFO(f, "./snow_density_256.bin not found");
  std::vector<float32> density_field(pow<3>(grid_resolution));
  std::fread(density_field.data(), sizeof(float32), density_field.size(), f);
  std::fclose(f);

  Program prog(Arch::gpu);
  prog.config.print_ir = true;

  Vector buffer(DataType::f32, 3);
  Global(density, f32);

  layout([&]() {
    root.dense(Index(0), n * n * 2).place(buffer(0), buffer(1), buffer(2));
    root.dense(Indices(0, 1, 2), grid_resolution).place(density);
  });

  auto point_inside_box = [&](Vector p) {
    return Var(0.0f <= p(0) && p(0) < 1.0f && 0.0f <= p(1) &&
                          p(1) < 1.0f && 0.0f <= p(2) && p(2) < 1.0f);
  };

  // If p is in the density field, return the density, otherwise return 0
  auto query_density = [&](Vector p) {
    auto inside_box = point_inside_box(p);
    auto ret = Var(0.0f);
    If(inside_box).Then([&] {
      auto i = floor(p(0) * float32(grid_resolution));
      auto j = floor(p(1) * float32(grid_resolution));
      auto k = floor(p(2) * float32(grid_resolution));
      ret = density[i, j, k] * scale;
    });
    return ret;
  };

  // Adapted from Mitsuba: include/mitsuba/core/aabb.h#L308
  auto box_intersect = [&](Vector o, Vector d, Expr& near_t, Expr& far_t) {
    auto result = Var(1);

    /* For each pair of AABB planes */
    for (int i = 0; i < 3; i++) {
      auto origin = o(i);
      auto min_val = Var(0.f);
      auto max_val = Var(1.f);
      auto d_rcp = Var(1.f / d(i));

      If(d(i) == 0.f)
        .Then([&] {
          /* The ray is parallel to the planes */
          If(origin < min_val || origin > max_val, [&] {
            result = 0;
          });
        }).Else([&] {
          /* Calculate intersection distances */
          auto t1 = Var((min_val - origin) * d_rcp);
          auto t2 = Var((max_val - origin) * d_rcp);

          If(t1 > t2, [&] {
            auto tmp = Var(t1);
            t1 = t2;
            t2 = tmp;
          });

          near_t = max(t1, near_t);
          far_t = min(t2, far_t);

          If(near_t > far_t, [&] {
            result = 0;
          });
        });
    }

    return result;
  };

  // Adapted from Mitsuba: src/libcore/warp.cpp#L25
  auto sample_phase_isotropic = [&]() {
    auto z = Var(1.0f - 2.0f * Rand<float32>());
    auto r = Var(sqrt(1.0f - z * z));
    auto phi = Var(2.0f * pi * Rand<float32>());
    auto sin_phi = Var(sin(phi));
    auto cos_phi = Var(cos(phi));
    return Var(Vector({r * cos_phi, r * sin_phi, z}));
  };

  auto pdf_phase_isotropic = [&]() {
    return Var(one_over_four_pi);
  };

  auto eval_phase_isotropic = [&]() {
    return pdf_phase_isotropic();
  };

  // Direct sample light
  auto sample_light = [&](Vector p, float32 inv_max_density) {
    auto Le = Var(Vector({5.0f, 5.0f, 5.0f}));
    auto light_p = Var(Vector({0.5f, 1.5f, 0.5f}));
    auto dir_to_p = Var(p - light_p);
    auto dist_to_p = Var(dir_to_p.norm());
    auto inv_dist_to_p = Var(1.f / dist_to_p);
    dir_to_p = normalized(dir_to_p);

    auto near_t = Var(-std::numeric_limits<float>::max());
    auto far_t = Var(std::numeric_limits<float>::max());
    auto hit = box_intersect(light_p, dir_to_p, near_t, far_t);
    auto interaction = Var(0);
    auto transmittance = Var(1.f);

    If(hit, [&] {
      auto cond = Var(hit);
      auto t = Var(near_t);

      While(cond, [&] {
        t -= log(1.f - Rand<float32>()) * inv_max_density;

        p = Var(light_p + t * dir_to_p);
        If(t >= dist_to_p || !point_inside_box(p))
          .Then([&] {
            cond = 0;
          })
          .Else([&] {
            auto density_at_p = query_density(p);
            If(density_at_p * inv_max_density > Rand<float32>()).Then([&] {
              cond = 0;
              transmittance = Var(0.f);
            });
          });
      });
    });

    return Var(transmittance * Le * inv_dist_to_p * inv_dist_to_p);
  };

  // Woodcock tracking
  auto sample_distance = [&](Vector o, Vector d, float32 inv_max_density, Expr& dist, Vector& sigma_s, Expr& transmittance, Vector& p) {
    auto near_t = Var(-std::numeric_limits<float>::max());
    auto far_t = Var(std::numeric_limits<float>::max());
    auto hit = box_intersect(o, d, near_t, far_t);

    auto cond = Var(hit);
    auto interaction = Var(0);
    auto t = Var(near_t);

    While(cond, [&] {
      t -= log(1.f - Rand<float32>()) * inv_max_density;

      p = Var(o + t * d);
      If(t >= far_t || !point_inside_box(p))
        .Then([&] {
          cond = 0;
        })
        .Else([&] {
          auto density_at_p = query_density(p);
          If(density_at_p * inv_max_density > Rand<float32>()).Then([&] {
            sigma_s(0) = Var(density_at_p * albedo[0]);
            sigma_s(1) = Var(density_at_p * albedo[1]);
            sigma_s(2) = Var(density_at_p * albedo[2]);
            If(density_at_p != 0.f).Then([&] {
              transmittance = 1.f / density_at_p;
            });
            cond = 0;
            interaction = 1;
          });
        });
    });

    dist = t - near_t;

    return hit && interaction;
  };

  auto background = [](Vector dir) {
    return Vector({0.4f, 0.4f, 0.4f});
  };

  float32 fov = 0.7;

  auto max_density = *std::max_element(density_field.begin(), density_field.end()) * scale;
  auto inv_max_density = 0.f;
  if (max_density > 0.f) {
    inv_max_density = 1.f / max_density;
  }

  Kernel(main).def([&]() {
    For(0, n * n * 2, [&](Expr i) {
      auto orig = Var(Vector({0.5f, 0.3f, 1.5f}));

      auto c = Var(Vector({fov * ((Rand<float32>() + cast<float32>(i / n)) / float32(n / 2) - 2.0f),
                           fov * ((Rand<float32>() + cast<float32>(i % n)) / float32(n / 2) - 1.0f),
                           -1.0f}));

      c = normalized(c);

      auto color = Var(Vector({1.0f, 1.0f, 1.0f}));
      auto Li = Var(Vector({0.0f, 0.0f, 0.0f}));
      auto throughput = Var(Vector({1.0f, 1.0f, 1.0f}));
      auto depth = Var(0);

      While(depth < depth_limit, [&] {
        auto dist = Var(0.f);
        auto transmittance = Var(0.f);
        auto sigma_s = Var(Vector({0.f, 0.f, 0.f}));
        auto interaction_p = Var(Vector({0.f, 0.f, 0.f}));
        auto interaction = sample_distance(orig, c, inv_max_density, dist, sigma_s, transmittance, interaction_p);

        depth += 1;
        If(interaction)
          .Then([&] {
            throughput = throughput.element_wise_prod(sigma_s * transmittance);

            auto phase_value = eval_phase_isotropic();
            auto light_value = sample_light(interaction_p, inv_max_density);
            Li += phase_value * throughput.element_wise_prod(light_value);

            orig = interaction_p;
            c = sample_phase_isotropic();
          }).Else([&] {
            Li += throughput.element_wise_prod(background(c));
            depth = depth_limit;
          });
      });

      buffer[i] += Li;

    });
  });

  for (int i = 0; i < grid_resolution; i++) {
    for (int j = 0; j < grid_resolution; j++) {
      for (int k = 0; k < grid_resolution; k++) {
        density.val<float32>(i, j, k) =
            density_field[i * grid_resolution * grid_resolution +
                          j * grid_resolution + k];
      }
    }
  }

  //GUI gui("Volume Renderer", Vector2i(n * 2, n));
  Vector2i render_size(n * 2, n);
  Array2D<Vector4> render_buffer;
  std::unique_ptr<Canvas> canvas;

  auto tone_map = [](real x) { return x; };
  constexpr int N = 1024;
  for (int frame = 0; frame < 1; frame++) {
    for (int i = 0; i < N; i++) {
      main();
    }

    real scale = 1.0f / ((frame + 1) * N);
    render_buffer.initialize(render_size);
    canvas = std::make_unique<Canvas>(render_buffer);
    for (int i = 0; i < n * n * 2; i++) {
      render_buffer[i / n][i % n] =
          Vector4(tone_map(scale * buffer(0).val<float32>(i)),
                  tone_map(scale * buffer(1).val<float32>(i)),
                  tone_map(scale * buffer(2).val<float32>(i)), 1);
    }
    //gui.update();
    canvas->img.write_as_image(fmt::format("{:05d}-{:05d}-{:05d}.png", frame, N, depth_limit));
  }
};
TC_REGISTER_TASK(volume_renderer);

TLANG_NAMESPACE_END
<|endoftext|>


<commit_before>
#include "vtrc-transport-tcp.h"

#include "vtrc-protocol-layer.h"
#include "vtrc-transport-stream-impl.h"

namespace vtrc { namespace common {

    namespace basio = boost::asio;
    namespace bip   = boost::asio::ip;
    namespace bsys  = boost::system;

    namespace {
        typedef transport_tcp::socket_type socket_type;
        typedef transport_impl<socket_type, transport_tcp> impl_type;

    }

    struct transport_tcp::impl: public impl_type {

        impl( vtrc::shared_ptr<socket_type> s, const std::string &n )
            :impl_type(s, n)
        { }

        std::string prepare_for_write(const char *data, size_t len)
        {
            return get_parent( )->prepare_for_write( data, len );
        }

    };

    std::string make_name( socket_type &sock )
    {
        std::ostringstream oss;
        oss << "tcp://" << sock.remote_endpoint( );
    }

    transport_tcp::transport_tcp( vtrc::shared_ptr<socket_type> sock )
        :impl_(new impl(sock, "tcp"))
    {
        impl_->set_parent( this );
    }

    transport_tcp::~transport_tcp(  )
    {
        delete impl_;
    }

    std::string transport_tcp::name( ) const
    {
        return impl_->name( );
    }

    void transport_tcp::close( )
    {
        impl_->close( );
    }

    void transport_tcp::write( const char *data, size_t length )
    {
        return impl_->write( data, length );
    }

    void transport_tcp::write(const char *data, size_t length,
                       const system_closure_type &success, bool on_send_success)
    {
        impl_->write( data, length, success, on_send_success );
    }

    std::string transport_tcp::prepare_for_write(const char *data, size_t len)
    {
        return impl_->prepare_for_write( data, len );
    }

    socket_type &transport_tcp::get_socket( )
    {
        return impl_->get_socket( );
    }

    const socket_type &transport_tcp::get_socket( ) const
    {
        return impl_->get_socket( );
    }

}}
<commit_msg>listener<commit_after>
#include "vtrc-transport-tcp.h"

#include "vtrc-protocol-layer.h"
#include "vtrc-transport-stream-impl.h"

namespace vtrc { namespace common {

    namespace basio = boost::asio;
    namespace bip   = boost::asio::ip;
    namespace bsys  = boost::system;

    namespace {
        typedef transport_tcp::socket_type socket_type;
        typedef transport_impl<socket_type, transport_tcp> impl_type;

    }

    struct transport_tcp::impl: public impl_type {

        impl( vtrc::shared_ptr<socket_type> s, const std::string &n )
            :impl_type(s, n)
        { }

        std::string prepare_for_write(const char *data, size_t len)
        {
            return get_parent( )->prepare_for_write( data, len );
        }

    };

    transport_tcp::transport_tcp( vtrc::shared_ptr<socket_type> sock )
        :impl_(new impl(sock, "tcp"))
    {
        impl_->set_parent( this );
    }

    transport_tcp::~transport_tcp(  )
    {
        delete impl_;
    }

    std::string transport_tcp::name( ) const
    {
        return impl_->name( );
    }

    void transport_tcp::close( )
    {
        impl_->close( );
    }

    void transport_tcp::write( const char *data, size_t length )
    {
        return impl_->write( data, length );
    }

    void transport_tcp::write(const char *data, size_t length,
                       const system_closure_type &success, bool on_send_success)
    {
        impl_->write( data, length, success, on_send_success );
    }

    std::string transport_tcp::prepare_for_write(const char *data, size_t len)
    {
        return impl_->prepare_for_write( data, len );
    }

    socket_type &transport_tcp::get_socket( )
    {
        return impl_->get_socket( );
    }

    const socket_type &transport_tcp::get_socket( ) const
    {
        return impl_->get_socket( );
    }

}}
<|endoftext|>


<commit_before>#ifndef MJOLNIR_UTIL_ALIGNED_STORAGE_HPP
#define MJOLNIR_UTIL_ALIGNED_STORAGE_HPP
#include <type_traits>
#include <array>
#include <cstdint>

namespace mjolnir
{

template<typename T, std::size_t Align = 64>
struct alignas(Align) aligned_storage
{
  public:
    using type = T;
    static_assert(Align != 0, "");

    static constexpr std::size_t alignment_size = Align;
    static constexpr std::size_t value_size     = sizeof(T);
    static constexpr std::size_t padded_size    =
        alignment_size * (value_size / alignment_size + 1);
    static constexpr std::size_t padding_size =
        alignment_size - (value_size % alignment_size);

    static_assert((padding_size + value_size) % padded_size    == 0, "");
    static_assert((padding_size + value_size) % alignment_size == 0, "");

  public:
    aligned_storage() = default;
    ~aligned_storage() = default;
    aligned_storage(aligned_storage const&) = default;
    aligned_storage(aligned_storage &&)     = default;
    aligned_storage& operator=(aligned_storage const&) = default;
    aligned_storage& operator=(aligned_storage &&)     = default;

    aligned_storage(const T& v)
        noexcept(std::is_nothrow_copy_constructible<T>::value)
        : value(v)
    {}
    aligned_storage(T&& v)
        noexcept(std::is_nothrow_move_constructible<T>::value)
        : value(v)
    {}

    T value;

  private:
    std::array<std::uint8_t, padding_size> padding_;
};

static_assert(alignof(aligned_storage<std::int32_t, 64>) == 64, "");
static_assert(sizeof (aligned_storage<std::int32_t, 64>) == 64, "");

} // mjolnir
#endif// MJOLNIR_UTIL_ALIGNED_STORAGE_HPP
<commit_msg>test: add a static_assert for aligned storage<commit_after>#ifndef MJOLNIR_UTIL_ALIGNED_STORAGE_HPP
#define MJOLNIR_UTIL_ALIGNED_STORAGE_HPP
#include <type_traits>
#include <utility>
#include <array>
#include <cstdint>

namespace mjolnir
{

template<typename T, std::size_t Align = 64>
struct alignas(Align) aligned_storage
{
  public:
    using type = T;
    static_assert(Align != 0, "");

    static constexpr std::size_t alignment_size = Align;
    static constexpr std::size_t value_size     = sizeof(T);
    static constexpr std::size_t padded_size    =
        alignment_size * (value_size / alignment_size + 1);
    static constexpr std::size_t padding_size =
        alignment_size - (value_size % alignment_size);

    static_assert((padding_size + value_size) % padded_size    == 0, "");
    static_assert((padding_size + value_size) % alignment_size == 0, "");

  public:
    aligned_storage() = default;
    ~aligned_storage() = default;
    aligned_storage(aligned_storage const&) = default;
    aligned_storage(aligned_storage &&)     = default;
    aligned_storage& operator=(aligned_storage const&) = default;
    aligned_storage& operator=(aligned_storage &&)     = default;

    aligned_storage(const T& v)
        noexcept(std::is_nothrow_copy_constructible<T>::value)
        : value(v)
    {}
    aligned_storage(T&& v)
        noexcept(std::is_nothrow_move_constructible<T>::value)
        : value(v)
    {}

    T value;

  private:
    std::array<std::uint8_t, padding_size> padding_;
};

static_assert(alignof(aligned_storage<std::int32_t, 64>) == 64, "");
static_assert(sizeof (aligned_storage<std::int32_t, 64>) == 64, "");

static_assert(alignof(aligned_storage<std::pair<std::int32_t, std::int64_t>, 64>) == 64, "");
static_assert(sizeof (aligned_storage<std::pair<std::int32_t, std::int64_t>, 64>) == 64, "");

} // mjolnir
#endif// MJOLNIR_UTIL_ALIGNED_STORAGE_HPP
<|endoftext|>


<commit_before>/**************************************************************************************/
/*                                                                                */
/*  Visualization Library                                                             */
/*  http://www.visualizationlibrary.com                                               */
/*                                                                                */
/*  Copyright (c) 2005-2010, Michele Bosi                                             */
/*  All rights reserved.                                                              */
/*                                                                                */
/*  Redistribution and use in source and binary forms, with or without modification,  */
/*  are permitted provided that the following conditions are met:                     */
/*                                                                                */
/*  - Redistributions of source code must retain the above copyright notice, this     */
/*  list of conditions and the following disclaimer.                                  */
/*                                                                                */
/*  - Redistributions in binary form must reproduce the above copyright notice, this  */
/*  list of conditions and the following disclaimer in the documentation and/or       */
/*  other materials provided with the distribution.                                   */
/*                                                                                */
/*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND   */
/*  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED     */
/*  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE            */
/*  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR  */
/*  ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES    */
/*  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;      */
/*  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON    */
/*  ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT           */
/*  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS     */
/*  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.                      */
/*                                                                                */
/**************************************************************************************/

#ifndef DrawArrays_INCLUDE_DEFINE
#define DrawArrays_INCLUDE_DEFINE

#include <vlGraphics/DrawCall.hpp>
#include <vlGraphics/TriangleIterator.hpp>

namespace vl
{
  //------------------------------------------------------------------------------
  // DrawArrays
  //------------------------------------------------------------------------------
  /**
   * Wraps the OpenGL function glDrawArrays(). See also http://www.opengl.org/sdk/docs/man/xhtml/glDrawArrays.xml for more information.
   *
   * DrawElements, MultiDrawElements, DrawRangeElements, DrawArrays are used by Geometry to define a set of primitives to be rendered, see Geometry::drawCalls().
   *
   * \sa DrawCall, DrawElements, MultiDrawElements, DrawRangeElements, Geometry, Actor */
  class DrawArrays: public DrawCall
  {
  public:
    DrawArrays(): mStart(0), mCount(0)
    {
      VL_DEBUG_SET_OBJECT_NAME()
      mType      = PT_TRIANGLES;
      mInstances = 1;
    }
    DrawArrays(EPrimitiveType primitive, int start, int count, int instances=1)
      : mStart(start), mCount(count)
    {
      VL_DEBUG_SET_OBJECT_NAME()
      mInstances = instances;
      mType = primitive;
    }
    virtual const char* className() const { return "vl::DrawArrays"; }

    DrawArrays& operator=(const DrawArrays& other)
    {
      DrawCall::operator=(other);
      mStart     = other.mStart;
      mCount     = other.mCount;
      mInstances = other.mInstances;
      return *this;
    }

    virtual ref<DrawCall> clone() const
    {
      return new DrawArrays( primitiveType(), (int)start(), (int)count(), (int)instances() );
    }

    virtual void deleteVBOs() {}
    virtual void updateVBOs(bool,bool) {}
    virtual unsigned int handle() const { return 0; }

    virtual void render(bool) const
    {
      // apply patch parameters if any and if using PT_PATCHES
      applyPatchParameters();

      if ( instances() > 1 && (Has_GL_ARB_draw_instanced||Has_GL_EXT_draw_instanced) )
        VL_glDrawArraysInstanced( primitiveType(), (int)start(), (int)count(), (int)instances() );
      else
        glDrawArrays( primitiveType(), (int)start(), (int)count() );

      #ifndef NDEBUG
        unsigned int glerr = glGetError();
        if (glerr != GL_NO_ERROR)
        {
          String msg( (char*)gluErrorString(glerr) );
          Log::error( Say("glGetError() [%s:%n]: %s\n") << __FILE__ << __LINE__ << msg );
          Log::print(
            "OpenGL Geometry Instancing (GL_ARB_draw_instanced) does not support display lists."
            "If you are using geometry instancing in conjunction with display lists you will have to disable one of them.\n"
          );
          VL_TRAP()
        }
      #endif
    }

    //! sets the starting vertex for the rendering.
    void setStart(int start) { mStart = start; }

    //! returns the starting vertex for the rendering.
    int start() const { return mStart; }

    //! sets the number of vertices to be rendered.
    void setCount(int count) { mCount = count; }

    //! returns the number of vertices to be rendered.
    int count() const { return mCount; }

    //! Sets the number of instances for this set of primitives.
    void setInstances(int instances) { mInstances = instances; }

    //! Returns the number of instances for this set of primitives.
    int instances() const { return mInstances; }

    TriangleIterator triangleIterator() const
    {
      ref<TriangleIteratorDirect> tid = new TriangleIteratorDirect( primitiveType() );
      tid->initialize(mStart, mStart+mCount);
      return TriangleIterator(tid.get());
    }

    IndexIterator indexIterator() const
    {
      ref<IndexIteratorDrawArrays> iida = new IndexIteratorDrawArrays;
      iida->initialize( mStart, mCount );
      IndexIterator iit;
      iit.initialize( iida.get() );
      return iit;
    }

    protected:
      int mStart;
      int mCount;
      int mInstances;
  };

}

#endif

<commit_msg>Removed glu dependency.<commit_after>/**************************************************************************************/
/*                                                                                */
/*  Visualization Library                                                             */
/*  http://www.visualizationlibrary.com                                               */
/*                                                                                */
/*  Copyright (c) 2005-2010, Michele Bosi                                             */
/*  All rights reserved.                                                              */
/*                                                                                */
/*  Redistribution and use in source and binary forms, with or without modification,  */
/*  are permitted provided that the following conditions are met:                     */
/*                                                                                */
/*  - Redistributions of source code must retain the above copyright notice, this     */
/*  list of conditions and the following disclaimer.                                  */
/*                                                                                */
/*  - Redistributions in binary form must reproduce the above copyright notice, this  */
/*  list of conditions and the following disclaimer in the documentation and/or       */
/*  other materials provided with the distribution.                                   */
/*                                                                                */
/*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND   */
/*  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED     */
/*  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE            */
/*  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR  */
/*  ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES    */
/*  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;      */
/*  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON    */
/*  ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT           */
/*  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS     */
/*  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.                      */
/*                                                                                */
/**************************************************************************************/

#ifndef DrawArrays_INCLUDE_DEFINE
#define DrawArrays_INCLUDE_DEFINE

#include <vlGraphics/DrawCall.hpp>
#include <vlGraphics/TriangleIterator.hpp>

namespace vl
{
  //------------------------------------------------------------------------------
  // DrawArrays
  //------------------------------------------------------------------------------
  /**
   * Wraps the OpenGL function glDrawArrays(). See also http://www.opengl.org/sdk/docs/man/xhtml/glDrawArrays.xml for more information.
   *
   * DrawElements, MultiDrawElements, DrawRangeElements, DrawArrays are used by Geometry to define a set of primitives to be rendered, see Geometry::drawCalls().
   *
   * \sa DrawCall, DrawElements, MultiDrawElements, DrawRangeElements, Geometry, Actor */
  class DrawArrays: public DrawCall
  {
  public:
    DrawArrays(): mStart(0), mCount(0)
    {
      VL_DEBUG_SET_OBJECT_NAME()
      mType      = PT_TRIANGLES;
      mInstances = 1;
    }
    DrawArrays(EPrimitiveType primitive, int start, int count, int instances=1)
      : mStart(start), mCount(count)
    {
      VL_DEBUG_SET_OBJECT_NAME()
      mInstances = instances;
      mType = primitive;
    }
    virtual const char* className() const { return "vl::DrawArrays"; }

    DrawArrays& operator=(const DrawArrays& other)
    {
      DrawCall::operator=(other);
      mStart     = other.mStart;
      mCount     = other.mCount;
      mInstances = other.mInstances;
      return *this;
    }

    virtual ref<DrawCall> clone() const
    {
      return new DrawArrays( primitiveType(), (int)start(), (int)count(), (int)instances() );
    }

    virtual void deleteVBOs() {}
    virtual void updateVBOs(bool,bool) {}
    virtual unsigned int handle() const { return 0; }

    virtual void render(bool) const
    {
      // apply patch parameters if any and if using PT_PATCHES
      applyPatchParameters();

      if ( instances() > 1 && (Has_GL_ARB_draw_instanced||Has_GL_EXT_draw_instanced) )
        VL_glDrawArraysInstanced( primitiveType(), (int)start(), (int)count(), (int)instances() );
      else
        glDrawArrays( primitiveType(), (int)start(), (int)count() );

      #ifndef NDEBUG
        unsigned int glerr = glGetError();
        if (glerr != GL_NO_ERROR)
        {
          String msg( getGLErrorString(glerr) );
          Log::error( Say("glGetError() [%s:%n]: %s\n") << __FILE__ << __LINE__ << msg );
          Log::print(
            "OpenGL Geometry Instancing (GL_ARB_draw_instanced) does not support display lists."
            "If you are using geometry instancing in conjunction with display lists you will have to disable one of them.\n"
          );
          VL_TRAP()
        }
      #endif
    }

    //! sets the starting vertex for the rendering.
    void setStart(int start) { mStart = start; }

    //! returns the starting vertex for the rendering.
    int start() const { return mStart; }

    //! sets the number of vertices to be rendered.
    void setCount(int count) { mCount = count; }

    //! returns the number of vertices to be rendered.
    int count() const { return mCount; }

    //! Sets the number of instances for this set of primitives.
    void setInstances(int instances) { mInstances = instances; }

    //! Returns the number of instances for this set of primitives.
    int instances() const { return mInstances; }

    TriangleIterator triangleIterator() const
    {
      ref<TriangleIteratorDirect> tid = new TriangleIteratorDirect( primitiveType() );
      tid->initialize(mStart, mStart+mCount);
      return TriangleIterator(tid.get());
    }

    IndexIterator indexIterator() const
    {
      ref<IndexIteratorDrawArrays> iida = new IndexIteratorDrawArrays;
      iida->initialize( mStart, mCount );
      IndexIterator iit;
      iit.initialize( iida.get() );
      return iit;
    }

    protected:
      int mStart;
      int mCount;
      int mInstances;
  };

}

#endif

<|endoftext|>


<commit_before>#ifndef STAN_MATH_REV_FUN_SOFTMAX_HPP
#define STAN_MATH_REV_FUN_SOFTMAX_HPP

#include <stan/math/rev/meta.hpp>
#include <stan/math/rev/fun/value_of.hpp>
#include <stan/math/rev/functor/reverse_pass_callback.hpp>
#include <stan/math/rev/functor/arena_matrix.hpp>
#include <stan/math/prim/fun/Eigen.hpp>
#include <stan/math/prim/fun/typedefs.hpp>
#include <stan/math/prim/fun/softmax.hpp>
#include <stan/math/prim/fun/to_ref.hpp>
#include <stan/math/prim/fun/value_of.hpp>
#include <tuple>
#include <vector>

namespace stan {
namespace math {

/**
 * Return the softmax of the specified Eigen vector.  Softmax is
 * guaranteed to return a simplex.
 *
 * @param alpha Unconstrained input vector.
 * @return Softmax of the input.
 * @throw std::domain_error If the input vector is size 0.
 */

inline Eigen::Matrix<var, Eigen::Dynamic, 1> softmax(
    const Eigen::Matrix<var, Eigen::Dynamic, 1>& alpha) {
  if (alpha.size() == 0) {
    return alpha;
  }

  arena_matrix<Eigen::VectorXd> res_val = softmax(value_of(alpha));
  arena_matrix<Eigen::Matrix<var, Eigen::Dynamic, 1>> res = res_val;
  arena_matrix<Eigen::Matrix<var, Eigen::Dynamic, 1>> alpha_arena = alpha;

  reverse_pass_callback([res_val, res, alpha_arena]() mutable {
    const auto& res_adj = to_ref(res.adj());
    alpha_arena.adj()
      += -res_val * res_adj.dot(res_val) + res_val.cwiseProduct(res_adj);
  });

  return res;
}

template <typename Mat, require_var_vt<is_eigen, Mat>* = nullptr>
inline auto softmax(const Mat& alpha) {
  if (alpha.size() == 0) {
    return alpha;
  }
  Mat res(softmax(value_of(alpha)));
  reverse_pass_callback([alpha, res]() mutable {
    alpha.adj() += alpha.adj() -res.val() * res.adj().dot(res.val()) + res.val().cwiseProduct(res.adj());
  });
  return res;
}

}  // namespace math
}  // namespace stan
#endif
<commit_msg>remove double += alpha.adj()<commit_after>#ifndef STAN_MATH_REV_FUN_SOFTMAX_HPP
#define STAN_MATH_REV_FUN_SOFTMAX_HPP

#include <stan/math/rev/meta.hpp>
#include <stan/math/rev/fun/value_of.hpp>
#include <stan/math/rev/functor/reverse_pass_callback.hpp>
#include <stan/math/rev/functor/arena_matrix.hpp>
#include <stan/math/prim/fun/Eigen.hpp>
#include <stan/math/prim/fun/typedefs.hpp>
#include <stan/math/prim/fun/softmax.hpp>
#include <stan/math/prim/fun/to_ref.hpp>
#include <stan/math/prim/fun/value_of.hpp>
#include <tuple>
#include <vector>

namespace stan {
namespace math {

/**
 * Return the softmax of the specified Eigen vector.  Softmax is
 * guaranteed to return a simplex.
 *
 * @param alpha Unconstrained input vector.
 * @return Softmax of the input.
 * @throw std::domain_error If the input vector is size 0.
 */

inline Eigen::Matrix<var, Eigen::Dynamic, 1> softmax(
    const Eigen::Matrix<var, Eigen::Dynamic, 1>& alpha) {
  if (alpha.size() == 0) {
    return alpha;
  }

  arena_matrix<Eigen::VectorXd> res_val = softmax(value_of(alpha));
  arena_matrix<Eigen::Matrix<var, Eigen::Dynamic, 1>> res = res_val;
  arena_matrix<Eigen::Matrix<var, Eigen::Dynamic, 1>> alpha_arena = alpha;

  reverse_pass_callback([res_val, res, alpha_arena]() mutable {
    const auto& res_adj = to_ref(res.adj());
    alpha_arena.adj()
      += -res_val * res_adj.dot(res_val) + res_val.cwiseProduct(res_adj);
  });

  return res;
}

template <typename Mat, require_var_vt<is_eigen, Mat>* = nullptr>
inline auto softmax(const Mat& alpha) {
  if (alpha.size() == 0) {
    return alpha;
  }
  Mat res(softmax(value_of(alpha)));
  reverse_pass_callback([alpha, res]() mutable {
    alpha.adj() += -res.val() * res.adj().dot(res.val()) + res.val().cwiseProduct(res.adj());
  });
  return res;
}

}  // namespace math
}  // namespace stan
#endif
<|endoftext|>


<commit_before>/*
Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto

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

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

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

#include "Camera.h"
#include "Device.h"
#include "Types.h"
#include "Renderer.h"

namespace crown
{

Camera::Camera(const Vec3& position, bool visible, float fov, float aspect, bool active) :
	mPosition(position),
	mLookAt(0, 0, -1),
	mUp(0, 1, 0),
	mFOV(fov),
	mAspect(aspect),
	mNear(0.1f),
	mFar(1000.0f),
	mActive(active),
	mAutoAspect(true)
{
	UpdateProjectionMatrix();
	UpdateViewMatrix();
	UpdateFrustum();
}

Camera::~Camera()
{
}

void Camera::SetPosition(const Vec3& position)
{
	mPosition = position;
	UpdateViewMatrix();
}

const Vec3& Camera::GetLookAt() const
{
	return mLookAt;
}

void Camera::SetLookAt(const Vec3& lookat)
{
	mLookAt = lookat;
	UpdateViewMatrix();
}

const Vec3& Camera::GetUpVector() const
{
	return mUp;
}

bool Camera::IsActive() const
{
	return mActive;
}

void Camera::SetActive(bool active)
{
	mActive = active;
}

float Camera::GetFOV() const
{
	return mFOV;
}

void Camera::SetFOV(float fov)
{
	mFOV = fov;
	UpdateProjectionMatrix();
}

bool Camera::GetAutoAspect() const
{
	return mAutoAspect;
}

void Camera::SetAutoAspect(bool autoAspect)
{
	mAutoAspect = autoAspect;
}

float Camera::GetAspect() const
{
	return mAspect;
}

void Camera::SetAspect(float aspect)
{
	mAspect = aspect;
	UpdateProjectionMatrix();
}

float Camera::GetNearClipDistance() const
{
	return mNear;
}

void Camera::SetNearClipDistance(float near)
{
	mNear = near;
	UpdateProjectionMatrix();
}

float Camera::GetFarClipDistance() const
{
	return mFar;
}

void Camera::SetFarClipDistance(float far)
{
	mFar = far;
	UpdateProjectionMatrix();
}

const Mat4& Camera::GetProjectionMatrix() const
{
	return mProjection;
}

const Mat4& Camera::GetViewMatrix() const
{
	return mView;
}

const Frustum& Camera::GetFrustum() const
{
	return mFrustum;
}

void Camera::Render()
{
	GetDevice()->GetRenderer()->SetMatrix(MT_PROJECTION, mProjection);
	GetDevice()->GetRenderer()->SetMatrix(MT_VIEW, mView);
}

void Camera::UpdateProjectionMatrix()
{
	mProjection.build_projection_perspective_rh(mFOV, mAspect, mNear, mFar);
}

void Camera::UpdateViewMatrix()
{
	mView.build_look_at_rh(mPosition, mPosition + mLookAt, mUp);
}

void Camera::UpdateFrustum()
{
	mFrustum.from_matrix(mProjection * mView);
}

} // namespace crown

<commit_msg>Update Camera.cpp<commit_after>/*
Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto

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

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

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

#include "Camera.h"
#include "Device.h"
#include "Types.h"
#include "Renderer.h"

namespace crown
{

Camera::Camera(const Vec3& position, bool visible, float fov, float aspect, bool active) :
	mPosition(position),
	mLookAt(0, 0, -1),
	mUp(0, 1, 0),
	mFOV(fov),
	mAspect(aspect),
	mNear(0.1f),
	mFar(1000.0f),
	mActive(active),
	mAutoAspect(true)
{
	UpdateProjectionMatrix();
	UpdateViewMatrix();
	UpdateFrustum();
}

Camera::~Camera()
{
}

void Camera::SetPosition(const Vec3& position)
{
	mPosition = position;
	UpdateViewMatrix();
}

const Vec3& Camera::GetLookAt() const
{
	return mLookAt;
}

void Camera::SetLookAt(const Vec3& lookat)
{
	mLookAt = lookat;
	UpdateViewMatrix();
}

const Vec3& Camera::GetUpVector() const
{
	return mUp;
}

bool Camera::IsActive() const
{
	return mActive;
}

void Camera::SetActive(bool active)
{
	mActive = active;
}

float Camera::GetFOV() const
{
	return mFOV;
}

void Camera::SetFOV(float fov)
{
	mFOV = fov;
	UpdateProjectionMatrix();
}

bool Camera::GetAutoAspect() const
{
	return mAutoAspect;
}

void Camera::SetAutoAspect(bool autoAspect)
{
	mAutoAspect = autoAspect;
}

float Camera::GetAspect() const
{
	return mAspect;
}

void Camera::SetAspect(float aspect)
{
	mAspect = aspect;
	UpdateProjectionMatrix();
}

float Camera::GetNearClipDistance() const
{
	return mNear;
}

void Camera::SetNearClipDistance(float near)
{
	mNear = near;
	UpdateProjectionMatrix();
}

float Camera::GetFarClipDistance() const
{
	return mFar;
}

void Camera::SetFarClipDistance(float far)
{
	mFar = far;
	UpdateProjectionMatrix();
}

const Mat4& Camera::GetProjectionMatrix() const
{
	return mProjection;
}

const Mat4& Camera::GetViewMatrix() const
{
	return mView;
}

const Frustum& Camera::GetFrustum() const
{
	return mFrustum;
}

void Camera::Render()
{
	GetDevice()->GetRenderer()->set_matrix(MT_PROJECTION, mProjection);
	GetDevice()->GetRenderer()->set_matrix(MT_VIEW, mView);
}

void Camera::UpdateProjectionMatrix()
{
	mProjection.build_projection_perspective_rh(mFOV, mAspect, mNear, mFar);
}

void Camera::UpdateViewMatrix()
{
	mView.build_look_at_rh(mPosition, mPosition + mLookAt, mUp);
}

void Camera::UpdateFrustum()
{
	mFrustum.from_matrix(mProjection * mView);
}

} // namespace crown

<|endoftext|>


<commit_before>#include <Refal2.h>

namespace Refal2 {

//-----------------------------------------------------------------------------
// CError

void CError::Reset()
{
	ResetSeverity();
	ResetFileName();
	ResetToken();
	ResetMessage();
}

bool CError::IsSet() const
{
	return ( Severity() != ES_None && !Message().empty() );
}

void CError::ResetSeverity()
{
	severity = ES_None;
	resetCache();
}

void CError::SetSeverity( TErrorSeverity _severity )
{
	assert( _severity != ES_None );
	severity = _severity;
	resetCache();
}

void CError::ResetFileName()
{
	fileName.clear();
	resetCache();
}

void CError::SetFileName( const std::string& _fileName )
{
	assert( !_fileName.empty() );
	fileName = _fileName;
	resetCache();
}

void CError::ResetToken()
{
	token.type = TT_None;
	resetCache();
}

void CError::SetTokenData( int line, int position,
	const std::string& wrongText )
{
	token.type = TT_Word;
	token.line = line;
	token.position = position;
	token.word = wrongText;
}

void CError::SetToken( const CToken& _token )
{
	assert( !_token.IsNone() );
	token = _token;
	resetCache();
}

void CError::ResetMessage()
{
	message.clear();
	resetCache();
}

void CError::SetMessage( const std::string& _message )
{
	assert( !_message.empty() );
	message = _message;
	resetCache();
}

const std::string& CError::UserMessage() const
{
	if( userMessage.empty() ) {
		std::ostringstream userMessageStream;
		if( !fileName.empty() ) {
			userMessageStream << fileName << ":";
			if( !token.IsNone() ) {
				userMessageStream << token.line << ":" << token.position << ":";
			}
			userMessageStream << " ";
		} else {
			assert( token.IsNone() );
		}
		switch( Severity() ) {
			case ES_Warning:
				userMessageStream << "warning";
				break;
			case ES_Error:
				userMessageStream << "error";
				break;
			case ES_LinkError:
				userMessageStream << "link error";
				break;
			case ES_FatalError:
				userMessageStream << "fatal error";
				break;
			case ES_None:
			default:
				assert( false );
				break;
		}
		assert( !message.empty() );
		userMessageStream << ": " << message << ".";
		userMessage = userMessageStream.str();
	}
	return userMessage;
}

//-----------------------------------------------------------------------------

CErrorsHelper::CErrorsHelper( IErrorHandler* errorHandler )
{
	CError::Reset();
	Reset();
	SetErrorHandler( errorHandler );
}

void CErrorsHelper::Reset()
{
	errorHandler = nullptr;
	errorSeverity = ES_None;
}

void CErrorsHelper::SetErrorHandler( IErrorHandler* _errorHandler )
{
	errorHandler = _errorHandler;
}

bool CErrorsHelper::HasErrors() const
{
	switch( ErrorSeverity() ) {
		case ES_None:
		case ES_Warning:
			return false;
		case ES_Error:
		case ES_LinkError:
		case ES_FatalError:
			return true;
	}
	assert( false );
	return false;
}

void CErrorsHelper::RaiseError( TErrorSeverity severity,
	const std::string& message )
{
	CError::SetSeverity( severity );
	CError::SetMessage( message );
	raiseError();
	CError::ResetSeverity();
	CError::ResetMessage();
}

void CErrorsHelper::RaiseError( TErrorSeverity severity,
	const std::string& message, const CToken& token )
{
	CError::SetToken( token );
	RaiseError( severity, message );
	CError::ResetToken();
}

void CErrorsHelper::raiseError()
{
	assert( errorHandler != nullptr );
	assert( CError::IsSet() );
	const TErrorSeverity severities[] =
		{ ES_FatalError, ES_LinkError, ES_Error, ES_Warning, ES_None };
	for( int i = 0; i < sizeof( severities ) / sizeof( TErrorSeverity ); i++ ) {
		if( severities[i] == CError::Severity()
			|| severities[i] == errorSeverity )
		{
			errorSeverity = severities[i];
		}
	}
	errorHandler->Error( *this );
}

//-----------------------------------------------------------------------------

} // end of namespace Refal2
<commit_msg>allow print error with position without filename (for stdin)<commit_after>#include <Refal2.h>

namespace Refal2 {

//-----------------------------------------------------------------------------
// CError

void CError::Reset()
{
	ResetSeverity();
	ResetFileName();
	ResetToken();
	ResetMessage();
}

bool CError::IsSet() const
{
	return ( Severity() != ES_None && !Message().empty() );
}

void CError::ResetSeverity()
{
	severity = ES_None;
	resetCache();
}

void CError::SetSeverity( TErrorSeverity _severity )
{
	assert( _severity != ES_None );
	severity = _severity;
	resetCache();
}

void CError::ResetFileName()
{
	fileName.clear();
	resetCache();
}

void CError::SetFileName( const std::string& _fileName )
{
	assert( !_fileName.empty() );
	fileName = _fileName;
	resetCache();
}

void CError::ResetToken()
{
	token.type = TT_None;
	resetCache();
}

void CError::SetTokenData( int line, int position,
	const std::string& wrongText )
{
	token.type = TT_Word;
	token.line = line;
	token.position = position;
	token.word = wrongText;
}

void CError::SetToken( const CToken& _token )
{
	assert( !_token.IsNone() );
	token = _token;
	resetCache();
}

void CError::ResetMessage()
{
	message.clear();
	resetCache();
}

void CError::SetMessage( const std::string& _message )
{
	assert( !_message.empty() );
	message = _message;
	resetCache();
}

const std::string& CError::UserMessage() const
{
	if( userMessage.empty() ) {
		std::ostringstream userMessageStream;
		if( !fileName.empty() ) {
			userMessageStream << fileName << ":";
		}
		if( !token.IsNone() ) {
			userMessageStream << token.line << ":" << token.position << ":";
		}
		if( !fileName.empty() || !token.IsNone() ) {
			userMessageStream << " ";
		}
		switch( Severity() ) {
			case ES_Warning:
				userMessageStream << "warning";
				break;
			case ES_Error:
				userMessageStream << "error";
				break;
			case ES_LinkError:
				userMessageStream << "link error";
				break;
			case ES_FatalError:
				userMessageStream << "fatal error";
				break;
			case ES_None:
			default:
				assert( false );
				break;
		}
		assert( !message.empty() );
		userMessageStream << ": " << message << ".";
		userMessage = userMessageStream.str();
	}
	return userMessage;
}

//-----------------------------------------------------------------------------

CErrorsHelper::CErrorsHelper( IErrorHandler* errorHandler )
{
	CError::Reset();
	Reset();
	SetErrorHandler( errorHandler );
}

void CErrorsHelper::Reset()
{
	errorHandler = nullptr;
	errorSeverity = ES_None;
}

void CErrorsHelper::SetErrorHandler( IErrorHandler* _errorHandler )
{
	errorHandler = _errorHandler;
}

bool CErrorsHelper::HasErrors() const
{
	switch( ErrorSeverity() ) {
		case ES_None:
		case ES_Warning:
			return false;
		case ES_Error:
		case ES_LinkError:
		case ES_FatalError:
			return true;
	}
	assert( false );
	return false;
}

void CErrorsHelper::RaiseError( TErrorSeverity severity,
	const std::string& message )
{
	CError::SetSeverity( severity );
	CError::SetMessage( message );
	raiseError();
	CError::ResetSeverity();
	CError::ResetMessage();
}

void CErrorsHelper::RaiseError( TErrorSeverity severity,
	const std::string& message, const CToken& token )
{
	CError::SetToken( token );
	RaiseError( severity, message );
	CError::ResetToken();
}

void CErrorsHelper::raiseError()
{
	assert( errorHandler != nullptr );
	assert( CError::IsSet() );
	const TErrorSeverity severities[] =
		{ ES_FatalError, ES_LinkError, ES_Error, ES_Warning, ES_None };
	for( int i = 0; i < sizeof( severities ) / sizeof( TErrorSeverity ); i++ ) {
		if( severities[i] == CError::Severity()
			|| severities[i] == errorSeverity )
		{
			errorSeverity = severities[i];
		}
	}
	errorHandler->Error( *this );
}

//-----------------------------------------------------------------------------

} // end of namespace Refal2
<|endoftext|>


<commit_before>/*
The MIT License (MIT)

Copyright (c) 2013 rajendrauppal

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

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

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

#include <iostream>

#include "Exceptions.h"
#include "GcdLcm.h"

using std::cout;
using std::cin;
using std::endl;

int GcdLcm::GCD_Euclidean_Iterative(int m, int n)
{
	if ( (m < 0) || (n < 0) ) throw InvalidInputException();
	if ( !m && !n ) throw InvalidInputException();
	if ( m && !n ) return m;
	if ( !m && n ) return n;

	while ( n ) {
		int temp = n;
		n = m % n;
		m = temp;
	}

	return m;
}

int GcdLcm::GCD_Euclidean_Recursive(int m, int n)
{
	if ( (m < 0) || (n < 0) ) throw InvalidInputException();
	if ( !m && !n ) throw InvalidInputException();
	if ( m && !n ) return m;
	if ( !m && n ) return n;

	return GCD_Euclidean_Recursive(n, m % n);
}

int GcdLcm::GCD_AlternateEuclidean_Iterative(int m, int n)
{
	if ( (m < 0) || (n < 0) ) throw InvalidInputException();
	if ( !m && !n ) throw InvalidInputException();
	if ( m && !n ) return m;
	if ( !m && n ) return n;

	while ( m != n ) {
		if ( m > n )
			m = m - n;
		else
			n = n - m;
	}

	return m;
}

int GcdLcm::GCD_AlternateEuclidean_Recursive(int m, int n)
{
	if ( (m < 0) || (n < 0) ) throw InvalidInputException();
	if ( !m && !n ) throw InvalidInputException();
	if ( m && !n ) return m;
	if ( !m && n ) return n;

	if ( m == n ) return m;
	if ( m > n )
		return GCD_AlternateEuclidean_Recursive(m - n, n);
	else
		return GCD_AlternateEuclidean_Recursive(m, n - m);
}

int GcdLcm::GCD_Binary_Iterative(int m, int n)
{
	return 0;
}

int GcdLcm::GCD_Binary_Recursive(int m, int n)
{
	return 0;
}

int GcdLcm::LCM_Iterative(int m, int n)
{
	return 0;
}

int GcdLcm::LCM_Recursive(int m, int n)
{
	return 0;
}

int GcdLcm::GCD_UsingLCM(int m, int n)
{
	return 0;
}

int main()
{
	GcdLcm gcdlcm;
	int nums[13][2] = {{0,1}, {1,0}, {0,0}, {1,1}, {-1,1}, {1,-1}, {-1,-1}, {1,1}, {2,3}, {10,10}, {121,11}, {24,60}, {36253652,183728732}};
	for ( size_t i = 0; i < 13; ++i ) {
		try
		{
			cout << gcdlcm.GCD_Euclidean_Iterative(nums[i][0], nums[i][1]) << endl;
			cout << gcdlcm.GCD_Euclidean_Recursive(nums[i][0], nums[i][1]) << endl;

			cout << gcdlcm.GCD_AlternateEuclidean_Iterative(nums[i][0], nums[i][1]) << endl;
			cout << gcdlcm.GCD_AlternateEuclidean_Recursive(nums[i][0], nums[i][1]) << endl<<endl;
		}
		catch (CPPExceptions& e)
		{
			cout << e.message() << endl;
		}
	}

	cout << "Press Enter to continue..." << endl;
	cin.get();
	return 0;
}<commit_msg>Implemented Binary GCD algorithm<commit_after>/*
The MIT License (MIT)

Copyright (c) 2013 rajendrauppal

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

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

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

#include <iostream>

#include "Exceptions.h"
#include "GcdLcm.h"

using std::cout;
using std::cin;
using std::endl;

int GcdLcm::GCD_Euclidean_Iterative(int m, int n)
{
	if ( (m < 0) || (n < 0) ) throw InvalidInputException();
	if ( !m && !n ) throw InvalidInputException();
	if ( m && !n ) return m;
	if ( !m && n ) return n;

	while ( n ) {
		int temp = n;
		n = m % n;
		m = temp;
	}

	return m;
}

int GcdLcm::GCD_Euclidean_Recursive(int m, int n)
{
	if ( (m < 0) || (n < 0) ) throw InvalidInputException();
	if ( !m && !n ) throw InvalidInputException();
	if ( m && !n ) return m;
	if ( !m && n ) return n;

	return GCD_Euclidean_Recursive(n, m % n);
}

int GcdLcm::GCD_AlternateEuclidean_Iterative(int m, int n)
{
	if ( (m < 0) || (n < 0) ) throw InvalidInputException();
	if ( !m && !n ) throw InvalidInputException();
	if ( m && !n ) return m;
	if ( !m && n ) return n;

	while ( m != n ) {
		if ( m > n )
			m = m - n;
		else
			n = n - m;
	}

	return m;
}

int GcdLcm::GCD_AlternateEuclidean_Recursive(int m, int n)
{
	if ( (m < 0) || (n < 0) ) throw InvalidInputException();
	if ( !m && !n ) throw InvalidInputException();
	if ( m && !n ) return m;
	if ( !m && n ) return n;

	if ( m == n ) return m;
	if ( m > n )
		return GCD_AlternateEuclidean_Recursive(m - n, n);
	else
		return GCD_AlternateEuclidean_Recursive(m, n - m);
}

int GcdLcm::GCD_Binary_Iterative(int m, int n)
{
	return 0;
}

/* Binary GCD algorithm (Credit: en.wikipedia.org/wiki/Binary_GCD_algorithm)
-----------------------------------------------
m		n		gcd
-----------------------------------------------
even	even	2 * gcd( m/2, n/2 )
even	odd		gcd( m/2, n )
odd		even	gcd( m, n/2 )
odd		odd		m >= n then gcd( (m - n)/2, n )
				m < n  then gcd( (n - m)/2, m )
-----------------------------------------------
*/
int GcdLcm::GCD_Binary_Recursive(int m, int n)
{
	if ( (m < 0) || (n < 0) ) throw InvalidInputException();
	if ( !m && !n ) throw InvalidInputException();
	if ( m && !n ) return m;
	if ( !m && n ) return n;
	if ( m == n ) return m;

	bool m_even = ~m & 1;
	bool n_even = ~n & 1;

	if ( m_even && n_even )
		return GCD_Binary_Recursive( m >> 1, n >> 1 ) << 1;

	if ( m_even && !n_even )
		return GCD_Binary_Recursive( m >> 1, n );

	if ( !m_even && n_even )
		return GCD_Binary_Recursive( m, n >> 1 );

	if ( m >= n )
		return GCD_Binary_Recursive( (m - n) >> 1, n );
	else
		return GCD_Binary_Recursive( (n - m) >> 1, m );
}

int GcdLcm::LCM_Iterative(int m, int n)
{
	return 0;
}

int GcdLcm::LCM_Recursive(int m, int n)
{
	return 0;
}

int GcdLcm::GCD_UsingLCM(int m, int n)
{
	return 0;
}

int main()
{
	GcdLcm gcdlcm;
	int nums[13][2] = {{0,1}, {1,0}, {0,0}, {1,1}, {-1,1}, {1,-1}, {-1,-1}, {1,1}, {2,3}, {10,10}, {121,11}, {24,60}, {36253652,183728732}};
	for ( size_t i = 0; i < 13; ++i ) {
		try
		{
			cout << gcdlcm.GCD_Euclidean_Iterative(nums[i][0], nums[i][1]) << endl;
			cout << gcdlcm.GCD_Euclidean_Recursive(nums[i][0], nums[i][1]) << endl;

			cout << gcdlcm.GCD_AlternateEuclidean_Iterative(nums[i][0], nums[i][1]) << endl;
			cout << gcdlcm.GCD_AlternateEuclidean_Recursive(nums[i][0], nums[i][1]) << endl;

			cout << gcdlcm.GCD_Binary_Recursive(nums[i][0], nums[i][1]) << endl;
		}
		catch (CPPExceptions& e)
		{
			cout << e.message() << endl;
		}
	}

	cout << "Press Enter to continue..." << endl;
	cin.get();
	return 0;
}<|endoftext|>