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

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkAutomaticTopologyMeshSourceTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#include <math.h>
#include <time.h>

#include <iostream>
#include <set>

#include "itkMesh.h"
#include "itkAutomaticTopologyMeshSource.h"

int
itkAutomaticTopologyMeshSourceTest(int, char* [] )
{

  // Declare the type of the Mesh
  typedef itk::Mesh<double>                         MeshType;
  typedef MeshType::PointType                       PointType;
  typedef MeshType::CellType                        CellType;

  typedef itk::AutomaticTopologyMeshSource< MeshType >   MeshSourceType;
  typedef MeshSourceType::IdentifierType                 IdentifierType;
  typedef MeshSourceType::IdentifierArrayType            IdentifierArrayType;

  MeshSourceType::Pointer meshSource;

  meshSource = MeshSourceType::New();

  // Begin using various AddPoint functions to add the vertices of a
  // cube.

  // Point expressed as an itk::Point.

  PointType p;

  p[ 0 ] = 0;
  p[ 1 ] = 0;
  p[ 2 ] = 0;
  meshSource->AddPoint( p );

  // Point expressed as a C array.

  float a[3];
  a[ 0 ] = 1;
  a[ 1 ] = 0;
  a[ 2 ] = 0;
  meshSource->AddPoint( a );

  // Points expressed using their coordinates.
  meshSource->AddPoint( 0, 1, 0 );
  meshSource->AddPoint( 1, 1, 0 );
  meshSource->AddPoint( 0, 0, 1 );
  meshSource->AddPoint( 1, 0, 1 );
  meshSource->AddPoint( 0, 1, 1 );
  meshSource->AddPoint( 1, 1, 1 );

  // Done adding vertices of a cube.

  // Add a cell of each type using an Array of point IDs.  Here we use
  // the fact that the IDs are assigned in order, and the fact that
  // the Add[Cell] methods only use the first N entries of the array.

  IdentifierArrayType idArray( 8 );
  {
  for( IdentifierType i = 0; i < 8; i++ )
    {
    idArray[ i ] = i;
    }
  }

  meshSource->AddVertex( idArray );
  meshSource->AddLine( idArray );
  meshSource->AddTriangle( idArray );
  meshSource->AddQuadrilateral( idArray );
  meshSource->AddTetrahedron( idArray );   // Degenerate; that's OK.
  meshSource->AddHexahedron( idArray );

  // Now add a new cube of points.  It overlaps along one face.

  IdentifierArrayType idArray1( 8 );
  idArray1[ 0 ] = meshSource->AddPoint( 1, 0, 0 );
  idArray1[ 1 ] = meshSource->AddPoint( 2, 0, 0 );
  idArray1[ 2 ] = meshSource->AddPoint( 1, 1, 0 );
  idArray1[ 3 ] = meshSource->AddPoint( 2, 1, 0 );
  idArray1[ 4 ] = meshSource->AddPoint( 1, 0, 1 );
  idArray1[ 5 ] = meshSource->AddPoint( 2, 0, 1 );
  idArray1[ 6 ] = meshSource->AddPoint( 1, 1, 1 );
  idArray1[ 7 ] = meshSource->AddPoint( 2, 1, 1 );

  // Add cells using parameter lists of IDs.

  meshSource->AddVertex( idArray[7] );

  // PROBLEM LINE
  meshSource->AddLine( idArray[6], idArray[7] );

  meshSource->AddTriangle( idArray[5], idArray[6], idArray[7] );

  meshSource->AddQuadrilateral( idArray[4], idArray[5],
                                idArray[6], idArray[7] );

  meshSource->AddTetrahedron( idArray[0], idArray[2],
                              idArray[4], idArray[6] );

  meshSource->AddHexahedron( idArray[0], idArray[1],
                             idArray[2], idArray[3],
                             idArray[4], idArray[5],
                             idArray[6], idArray[7] );

  // Add cells using new point identifiers.

  meshSource->AddVertex( meshSource->AddPoint( 3, 1, 1 ) );

  // PROBLEM LINES
  meshSource->AddLine(
    meshSource->AddPoint( 2, 1, 1 ),
    meshSource->AddPoint( 3, 1, 1 )
    );

  meshSource->AddTriangle(
    meshSource->AddPoint( 3, 0, 1 ),
    meshSource->AddPoint( 2, 1, 1 ),
    meshSource->AddPoint( 3, 1, 1 )
    );

  meshSource->AddQuadrilateral(
    meshSource->AddPoint( 2, 0, 1 ),
    meshSource->AddPoint( 3, 0, 1 ),
    meshSource->AddPoint( 2, 1, 1 ),
    meshSource->AddPoint( 3, 1, 1 )
    );

  meshSource->AddTetrahedron(
    meshSource->AddPoint( 2, 0, 1 ),
    meshSource->AddPoint( 3, 0, 1 ),
    meshSource->AddPoint( 2, 1, 1 ),
    meshSource->AddPoint( 3, 1, 1 )
    );

  meshSource->AddHexahedron(
    meshSource->AddPoint( 2, 0, 0 ),
    meshSource->AddPoint( 3, 0, 0 ),
    meshSource->AddPoint( 2, 1, 0 ),
    meshSource->AddPoint( 3, 1, 0 ),
    meshSource->AddPoint( 2, 0, 1 ),
    meshSource->AddPoint( 3, 0, 1 ),
    meshSource->AddPoint( 2, 1, 1 ),
    meshSource->AddPoint( 3, 1, 1 )
    );

  // Add cells using C arrays of point coordinates.
  MeshSourceType::CoordinateType points[8][3] =
    {
      {3, 0, 0},
      {4, 0, 0},
      {3, 1, 0},
      {4, 1, 0},
      {3, 0, 1},
      {4, 0, 1},
      {3, 1, 1},
      {4, 1, 1}
    };

  meshSource->AddVertex( points[7] );
  meshSource->AddLine( points[6], points[7] );
  meshSource->AddTriangle( points[5], points[6], points[7] );
  meshSource->AddQuadrilateral( points[4], points[5], points[6], points[7] );
  meshSource->AddTetrahedron( points[3], points[5], points[6], points[7] );
  meshSource->AddHexahedron( points[0], points[1], points[2], points[3],
                             points[4], points[5], points[6], points[7] );

  // Print out the resulting mesh data.
  std::cout << MeshType::Pointer(meshSource->GetOutput()) << std::endl;

  // Now do a sanity check.  Create a mesh consisting of a pair of
  // tetrahedra sharing a face and a pair of cubes sharing a face, and
  // then check properties.
  meshSource = MeshSourceType::New();

  meshSource->AddTetrahedron(
    meshSource->AddPoint( 0, 0, 0 ),
    meshSource->AddPoint( 1, 0, 0 ),
    meshSource->AddPoint( 0, 1, 0 ),
    meshSource->AddPoint( 0, 0, 1 )
    );

  meshSource->AddTetrahedron(
    meshSource->AddPoint( 1, 1, 1 ),
    meshSource->AddPoint( 1, 0, 0 ),
    meshSource->AddPoint( 0, 1, 0 ),
    meshSource->AddPoint( 0, 0, 1 )
    );

  meshSource->AddHexahedron(
    meshSource->AddPoint( 2, 0, 0 ),
    meshSource->AddPoint( 3, 0, 0 ),
    meshSource->AddPoint( 2, 1, 0 ),
    meshSource->AddPoint( 3, 1, 0 ),
    meshSource->AddPoint( 2, 0, 1 ),
    meshSource->AddPoint( 3, 0, 1 ),
    meshSource->AddPoint( 2, 1, 1 ),
    meshSource->AddPoint( 3, 1, 1 )
    );

  meshSource->AddHexahedron(
    meshSource->AddPoint( 3, 0, 0 ),
    meshSource->AddPoint( 4, 0, 0 ),
    meshSource->AddPoint( 3, 1, 0 ),
    meshSource->AddPoint( 4, 1, 0 ),
    meshSource->AddPoint( 3, 0, 1 ),
    meshSource->AddPoint( 4, 0, 1 ),
    meshSource->AddPoint( 3, 1, 1 ),
    meshSource->AddPoint( 4, 1, 1 )
    );

  try
    {
    meshSource->Update();
    }
  catch( itk::ExceptionObject & excp )
    {
    std::cerr << "Exception thrown during Update() " << std::endl;
    std::cerr << excp << std::endl;
    return EXIT_FAILURE;
    }

  MeshType* mesh = meshSource->GetOutput();

  // Print out the resulting mesh data.
  std::cout << MeshType::Pointer( mesh ) << std::endl;

  // ... In more detail.

  unsigned int i;

  std::cout << mesh->GetNumberOfPoints() << " points:" << std::endl;
  for( i = 0; i < mesh->GetNumberOfPoints(); i++ )
    {
    PointType point;
    if( mesh->GetPoint( i, &point ) )
      {
      std::cout << i << ": " << point << std::endl;
      }
    }

  std::cout << "\n" << mesh->GetNumberOfCells() << " cells:" << std::endl;
  for( i = 0; i < mesh->GetNumberOfCells(); i++ )
    {
    typedef MeshType::CellAutoPointer CellAutoPointer;
    CellAutoPointer cell;
    if( mesh->GetCell( i, cell ) )
      {
      std::cout << i << ": ";
      typedef CellType::PointIdConstIterator PointIdIterator;
      PointIdIterator pointIter = cell->PointIdsBegin();
      PointIdIterator pointsEnd = cell->PointIdsEnd();
      for( ; pointIter != pointsEnd; ++pointIter )
        {
        std::cout << *pointIter << " ";
        }
      std::cout << std::endl;
      }
    }
  std::cout << "\n";

  for( i = 0; i < mesh->GetNumberOfCells(); i++ )
    {
    typedef MeshType::CellAutoPointer CellAutoPointer;
    CellAutoPointer cell;
    if( mesh->GetCell( i, cell ) )
      {
      if( cell->GetType() == CellType::LINE_CELL )
        {
        std::cout << "Cell " << i << ":\n";

        typedef MeshSourceType::IdentifierType IdentifierType;
        typedef std::set<IdentifierType> NeighborSet;
        NeighborSet cellSet;

        mesh->GetCellBoundaryFeatureNeighbors( 0, i, 0, &cellSet );
        std::cout << "Neighbors across vertex 0: ";
        for( NeighborSet::iterator neighborIter = cellSet.begin();
             neighborIter != cellSet.end(); ++neighborIter )
          {
          std::cout << *neighborIter << " ";
          }
        std::cout << "\n";

        mesh->GetCellBoundaryFeatureNeighbors( 0, i, 1, &cellSet );
        std::cout << "Neighbors across vertex 1: ";
        for( NeighborSet::iterator neighborIter = cellSet.begin();
             neighborIter != cellSet.end(); ++neighborIter )
          {
          std::cout << *neighborIter << " ";
          }
        std::cout << "\n";

        mesh->GetCellNeighbors( i, &cellSet );
        std::cout << "Neighbors having edge as boundary: ";
        for( NeighborSet::iterator neighborIter = cellSet.begin();
             neighborIter != cellSet.end(); ++neighborIter )
          {
          std::cout << *neighborIter << " ";
          }
        std::cout << "\n" << std::endl;

        }
      }
    }

  // Check that the right number of points has been added.

  int numPoints = meshSource->GetOutput()->GetNumberOfPoints();
  if( numPoints != 17 )
    {
    std::cerr << "Mesh shows " << numPoints
              << " points, but 17 were added." << std::endl;
    return EXIT_FAILURE;
    }

  // Check that the right number of cells has been added.

  int numCells = meshSource->GetOutput()->GetNumberOfCells();
  if( numCells != 68 )
    {
    std::cerr << "Mesh shows "
              << numCells
              << " cells, but 68 were added." << std::endl;
    return EXIT_FAILURE;
    }

  // Check that the output is not destroyed when calling Update()
  meshSource->Update();

  numPoints = meshSource->GetOutput()->GetNumberOfPoints();
  numCells  = meshSource->GetOutput()->GetNumberOfCells();
  if( numPoints != 17 || numCells != 68 )
    {
    std::cerr << "Mesh is being changed when invoking Update()" << std::endl;
    return EXIT_FAILURE;
    }

  return EXIT_SUCCESS;

}

<commit_msg>COMP: Added Print for better coverage.<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkAutomaticTopologyMeshSourceTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#include <math.h>
#include <time.h>

#include <iostream>
#include <set>

#include "itkMesh.h"
#include "itkAutomaticTopologyMeshSource.h"

int
itkAutomaticTopologyMeshSourceTest(int, char* [] )
{

  // Declare the type of the Mesh
  typedef itk::Mesh<double>                         MeshType;
  typedef MeshType::PointType                       PointType;
  typedef MeshType::CellType                        CellType;

  typedef itk::AutomaticTopologyMeshSource< MeshType >   MeshSourceType;
  typedef MeshSourceType::IdentifierType                 IdentifierType;
  typedef MeshSourceType::IdentifierArrayType            IdentifierArrayType;

  MeshSourceType::Pointer meshSource;

  meshSource = MeshSourceType::New();

  // Begin using various AddPoint functions to add the vertices of a
  // cube.

  // Point expressed as an itk::Point.

  PointType p;

  p[ 0 ] = 0;
  p[ 1 ] = 0;
  p[ 2 ] = 0;
  meshSource->AddPoint( p );

  // Point expressed as a C array.

  float a[3];
  a[ 0 ] = 1;
  a[ 1 ] = 0;
  a[ 2 ] = 0;
  meshSource->AddPoint( a );

  // Points expressed using their coordinates.
  meshSource->AddPoint( 0, 1, 0 );
  meshSource->AddPoint( 1, 1, 0 );
  meshSource->AddPoint( 0, 0, 1 );
  meshSource->AddPoint( 1, 0, 1 );
  meshSource->AddPoint( 0, 1, 1 );
  meshSource->AddPoint( 1, 1, 1 );

  // Done adding vertices of a cube.

  // Add a cell of each type using an Array of point IDs.  Here we use
  // the fact that the IDs are assigned in order, and the fact that
  // the Add[Cell] methods only use the first N entries of the array.

  IdentifierArrayType idArray( 8 );
  {
  for( IdentifierType i = 0; i < 8; i++ )
    {
    idArray[ i ] = i;
    }
  }

  meshSource->AddVertex( idArray );
  meshSource->AddLine( idArray );
  meshSource->AddTriangle( idArray );
  meshSource->AddQuadrilateral( idArray );
  meshSource->AddTetrahedron( idArray );   // Degenerate; that's OK.
  meshSource->AddHexahedron( idArray );

  // Now add a new cube of points.  It overlaps along one face.

  IdentifierArrayType idArray1( 8 );
  idArray1[ 0 ] = meshSource->AddPoint( 1, 0, 0 );
  idArray1[ 1 ] = meshSource->AddPoint( 2, 0, 0 );
  idArray1[ 2 ] = meshSource->AddPoint( 1, 1, 0 );
  idArray1[ 3 ] = meshSource->AddPoint( 2, 1, 0 );
  idArray1[ 4 ] = meshSource->AddPoint( 1, 0, 1 );
  idArray1[ 5 ] = meshSource->AddPoint( 2, 0, 1 );
  idArray1[ 6 ] = meshSource->AddPoint( 1, 1, 1 );
  idArray1[ 7 ] = meshSource->AddPoint( 2, 1, 1 );

  // Add cells using parameter lists of IDs.

  meshSource->AddVertex( idArray[7] );

  // PROBLEM LINE
  meshSource->AddLine( idArray[6], idArray[7] );

  meshSource->AddTriangle( idArray[5], idArray[6], idArray[7] );

  meshSource->AddQuadrilateral( idArray[4], idArray[5],
                                idArray[6], idArray[7] );

  meshSource->AddTetrahedron( idArray[0], idArray[2],
                              idArray[4], idArray[6] );

  meshSource->AddHexahedron( idArray[0], idArray[1],
                             idArray[2], idArray[3],
                             idArray[4], idArray[5],
                             idArray[6], idArray[7] );

  // Add cells using new point identifiers.

  meshSource->AddVertex( meshSource->AddPoint( 3, 1, 1 ) );

  // PROBLEM LINES
  meshSource->AddLine(
    meshSource->AddPoint( 2, 1, 1 ),
    meshSource->AddPoint( 3, 1, 1 )
    );

  meshSource->AddTriangle(
    meshSource->AddPoint( 3, 0, 1 ),
    meshSource->AddPoint( 2, 1, 1 ),
    meshSource->AddPoint( 3, 1, 1 )
    );

  meshSource->AddQuadrilateral(
    meshSource->AddPoint( 2, 0, 1 ),
    meshSource->AddPoint( 3, 0, 1 ),
    meshSource->AddPoint( 2, 1, 1 ),
    meshSource->AddPoint( 3, 1, 1 )
    );

  meshSource->AddTetrahedron(
    meshSource->AddPoint( 2, 0, 1 ),
    meshSource->AddPoint( 3, 0, 1 ),
    meshSource->AddPoint( 2, 1, 1 ),
    meshSource->AddPoint( 3, 1, 1 )
    );

  meshSource->AddHexahedron(
    meshSource->AddPoint( 2, 0, 0 ),
    meshSource->AddPoint( 3, 0, 0 ),
    meshSource->AddPoint( 2, 1, 0 ),
    meshSource->AddPoint( 3, 1, 0 ),
    meshSource->AddPoint( 2, 0, 1 ),
    meshSource->AddPoint( 3, 0, 1 ),
    meshSource->AddPoint( 2, 1, 1 ),
    meshSource->AddPoint( 3, 1, 1 )
    );

  // Add cells using C arrays of point coordinates.
  MeshSourceType::CoordinateType points[8][3] =
    {
      {3, 0, 0},
      {4, 0, 0},
      {3, 1, 0},
      {4, 1, 0},
      {3, 0, 1},
      {4, 0, 1},
      {3, 1, 1},
      {4, 1, 1}
    };

  meshSource->AddVertex( points[7] );
  meshSource->AddLine( points[6], points[7] );
  meshSource->AddTriangle( points[5], points[6], points[7] );
  meshSource->AddQuadrilateral( points[4], points[5], points[6], points[7] );
  meshSource->AddTetrahedron( points[3], points[5], points[6], points[7] );
  meshSource->AddHexahedron( points[0], points[1], points[2], points[3],
                             points[4], points[5], points[6], points[7] );

  // Print out the resulting mesh data.
  std::cout << MeshType::Pointer(meshSource->GetOutput()) << std::endl;

  // Now do a sanity check.  Create a mesh consisting of a pair of
  // tetrahedra sharing a face and a pair of cubes sharing a face, and
  // then check properties.
  meshSource = MeshSourceType::New();

  meshSource->AddTetrahedron(
    meshSource->AddPoint( 0, 0, 0 ),
    meshSource->AddPoint( 1, 0, 0 ),
    meshSource->AddPoint( 0, 1, 0 ),
    meshSource->AddPoint( 0, 0, 1 )
    );

  meshSource->AddTetrahedron(
    meshSource->AddPoint( 1, 1, 1 ),
    meshSource->AddPoint( 1, 0, 0 ),
    meshSource->AddPoint( 0, 1, 0 ),
    meshSource->AddPoint( 0, 0, 1 )
    );

  meshSource->AddHexahedron(
    meshSource->AddPoint( 2, 0, 0 ),
    meshSource->AddPoint( 3, 0, 0 ),
    meshSource->AddPoint( 2, 1, 0 ),
    meshSource->AddPoint( 3, 1, 0 ),
    meshSource->AddPoint( 2, 0, 1 ),
    meshSource->AddPoint( 3, 0, 1 ),
    meshSource->AddPoint( 2, 1, 1 ),
    meshSource->AddPoint( 3, 1, 1 )
    );

  meshSource->AddHexahedron(
    meshSource->AddPoint( 3, 0, 0 ),
    meshSource->AddPoint( 4, 0, 0 ),
    meshSource->AddPoint( 3, 1, 0 ),
    meshSource->AddPoint( 4, 1, 0 ),
    meshSource->AddPoint( 3, 0, 1 ),
    meshSource->AddPoint( 4, 0, 1 ),
    meshSource->AddPoint( 3, 1, 1 ),
    meshSource->AddPoint( 4, 1, 1 )
    );

  try
    {
    meshSource->Update();
    }
  catch( itk::ExceptionObject & excp )
    {
    std::cerr << "Exception thrown during Update() " << std::endl;
    std::cerr << excp << std::endl;
    return EXIT_FAILURE;
    }

  MeshType* mesh = meshSource->GetOutput();

  // Print out the resulting mesh data.
  std::cout << MeshType::Pointer( mesh ) << std::endl;

  // ... In more detail.

  unsigned int i;

  std::cout << mesh->GetNumberOfPoints() << " points:" << std::endl;
  for( i = 0; i < mesh->GetNumberOfPoints(); i++ )
    {
    PointType point;
    if( mesh->GetPoint( i, &point ) )
      {
      std::cout << i << ": " << point << std::endl;
      }
    }

  std::cout << "\n" << mesh->GetNumberOfCells() << " cells:" << std::endl;
  for( i = 0; i < mesh->GetNumberOfCells(); i++ )
    {
    typedef MeshType::CellAutoPointer CellAutoPointer;
    CellAutoPointer cell;
    if( mesh->GetCell( i, cell ) )
      {
      std::cout << i << ": ";
      typedef CellType::PointIdConstIterator PointIdIterator;
      PointIdIterator pointIter = cell->PointIdsBegin();
      PointIdIterator pointsEnd = cell->PointIdsEnd();
      for( ; pointIter != pointsEnd; ++pointIter )
        {
        std::cout << *pointIter << " ";
        }
      std::cout << std::endl;
      }
    }
  std::cout << "\n";

  for( i = 0; i < mesh->GetNumberOfCells(); i++ )
    {
    typedef MeshType::CellAutoPointer CellAutoPointer;
    CellAutoPointer cell;
    if( mesh->GetCell( i, cell ) )
      {
      if( cell->GetType() == CellType::LINE_CELL )
        {
        std::cout << "Cell " << i << ":\n";

        typedef MeshSourceType::IdentifierType IdentifierType;
        typedef std::set<IdentifierType> NeighborSet;
        NeighborSet cellSet;

        mesh->GetCellBoundaryFeatureNeighbors( 0, i, 0, &cellSet );
        std::cout << "Neighbors across vertex 0: ";
        for( NeighborSet::iterator neighborIter = cellSet.begin();
             neighborIter != cellSet.end(); ++neighborIter )
          {
          std::cout << *neighborIter << " ";
          }
        std::cout << "\n";

        mesh->GetCellBoundaryFeatureNeighbors( 0, i, 1, &cellSet );
        std::cout << "Neighbors across vertex 1: ";
        for( NeighborSet::iterator neighborIter = cellSet.begin();
             neighborIter != cellSet.end(); ++neighborIter )
          {
          std::cout << *neighborIter << " ";
          }
        std::cout << "\n";

        mesh->GetCellNeighbors( i, &cellSet );
        std::cout << "Neighbors having edge as boundary: ";
        for( NeighborSet::iterator neighborIter = cellSet.begin();
             neighborIter != cellSet.end(); ++neighborIter )
          {
          std::cout << *neighborIter << " ";
          }
        std::cout << "\n" << std::endl;

        }
      }
    }

  // Check that the right number of points has been added.

  int numPoints = meshSource->GetOutput()->GetNumberOfPoints();
  if( numPoints != 17 )
    {
    std::cerr << "Mesh shows " << numPoints
              << " points, but 17 were added." << std::endl;
    return EXIT_FAILURE;
    }

  // Check that the right number of cells has been added.

  int numCells = meshSource->GetOutput()->GetNumberOfCells();
  if( numCells != 68 )
    {
    std::cerr << "Mesh shows "
              << numCells
              << " cells, but 68 were added." << std::endl;
    return EXIT_FAILURE;
    }

  // Check that the output is not destroyed when calling Update()
  meshSource->Update();

  numPoints = meshSource->GetOutput()->GetNumberOfPoints();
  numCells  = meshSource->GetOutput()->GetNumberOfCells();
  if( numPoints != 17 || numCells != 68 )
    {
    std::cerr << "Mesh is being changed when invoking Update()" << std::endl;
    return EXIT_FAILURE;
    }

  meshSource->Print(std::cout);
  return EXIT_SUCCESS;

}

<|endoftext|>


<commit_before>/* -*- mode: C++; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
// vim:sts=8:sw=8:ts=8:noet:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s

/* Copyright (c) FFLAS-FFPACK
* Written by Clément Pernet <clement.pernet@imag.fr>
* ========LICENCE========
* This file is part of the library FFLAS-FFPACK.
*
* FFLAS-FFPACK 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
* ========LICENCE========
*/

#include <iostream>

#include "fflas-ffpack/fflas-ffpack.h"
#include "fflas-ffpack/field/modular-balanced.h"
#include "fflas-ffpack/utils/timer.h"
#include "fflas-ffpack/utils/Matio.h"

using namespace std;

int main(int argc, char** argv) {

  // parameter: p, n, iteration, file1, file2

  int    p    = argc>1 ? atoi(argv[1]) : 1009;
  int    n    = argc>2 ? atoi(argv[2]) : 2000;
  size_t iter = argc>3 ? atoi(argv[3]) :    1;
  size_t strat= argc>4 ? atoi(argv[4]) :    1; // 1 for pIter-sRec ; 2 for pRec

  typedef FFPACK::Modular<double> Field;
  typedef Field::Element Element;

  Field F(p);
  Element * A;
  Element * B;

   FFLAS::OMPTimer chrono;
  double time=0.0;

  for (size_t i=0;i<iter;++i){
	  Field::RandIter G(F);
	  if (argc > 5){
		  A = read_field (F, argv[5], &n, &n);
	  }
	  else{
		  A = FFLAS::fflas_new<Element>(n*n);
		  for (size_t j = 0; j< (size_t)n*n; ++j)
			  G.random(*(A+j));
	  }

	  if (argc == 7){
		  B = read_field (F, argv[6], &n, &n);
	  }
	  else{
		  B = FFLAS::fflas_new<Element>(n*n);
		  for (size_t j=0 ; j< (size_t)n*n; ++j)
			  G.random(*(A+j));
	  }

	  for (size_t k=0;k<(size_t)n;++k)
		  while (F.isZero( G.random(*(A+k*(n+1)))));

      const FFLAS::CuttingStrategy Strategy = FFLAS::BLOCK_THREADS;

	  chrono.clear();
	  chrono.start();

      PAR_REGION{
          if (strat == 1) {
              FFLAS::TRSMHelper<FFLAS::StructureHelper::Iterative,
                  FFLAS::ParSeqHelper::Parallel> PH
                  (FFLAS::ParSeqHelper::Parallel(NUM_THREADS,Strategy));

              FFLAS::ftrsm (F, FFLAS::FflasLeft, FFLAS::FflasLower,
                            FFLAS::FflasNoTrans, FFLAS::FflasNonUnit,
                            n,n, F.one, A, n, B, n, PH);
          } else {
              FFLAS::TRSMHelper<FFLAS::StructureHelper::Recursive,
                  FFLAS::ParSeqHelper::Parallel> PH
                  (FFLAS::ParSeqHelper::Parallel(NUM_THREADS,Strategy));

              FFLAS::ftrsm (F, FFLAS::FflasLeft, FFLAS::FflasLower,
                            FFLAS::FflasNoTrans, FFLAS::FflasNonUnit,
                            n,n, F.one, A, n, B, n, PH);
          }

      }
      BARRIER;

	  chrono.stop();
	  time+=chrono.usertime();
      std::cerr << *A << ' ' << *B << std::endl;
	  delete[] A;
	  delete[] B;

  }

  cerr<<"n: "<<n<<" p: "<<p<<" time: "<<time/(double)iter<<" n^3/time/10^9: "<<(double(n)/1000.*double(n)/1000.*double(n)/1000./time*double(iter))<<endl;

  return 0;
}
<commit_msg>coulmn threads for pure rec<commit_after>/* -*- mode: C++; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
// vim:sts=8:sw=8:ts=8:noet:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s

/* Copyright (c) FFLAS-FFPACK
* Written by Clément Pernet <clement.pernet@imag.fr>
* ========LICENCE========
* This file is part of the library FFLAS-FFPACK.
*
* FFLAS-FFPACK 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
* ========LICENCE========
*/

#include <iostream>

#include "fflas-ffpack/fflas-ffpack.h"
#include "fflas-ffpack/field/modular-balanced.h"
#include "fflas-ffpack/utils/timer.h"
#include "fflas-ffpack/utils/Matio.h"

using namespace std;

int main(int argc, char** argv) {

  // parameter: p, n, iteration, file1, file2

  int    p    = argc>1 ? atoi(argv[1]) : 1009;
  int    n    = argc>2 ? atoi(argv[2]) : 2000;
  size_t iter = argc>3 ? atoi(argv[3]) :    1;
  size_t strat= argc>4 ? atoi(argv[4]) :    1; // 1 for pIter-sRec ; 2 for pRec

  typedef FFPACK::Modular<double> Field;
  typedef Field::Element Element;

  Field F(p);
  Element * A;
  Element * B;

   FFLAS::OMPTimer chrono;
  double time=0.0;

  for (size_t i=0;i<iter;++i){
	  Field::RandIter G(F);
	  if (argc > 5){
		  A = read_field (F, argv[5], &n, &n);
	  }
	  else{
		  A = FFLAS::fflas_new<Element>(n*n);
		  for (size_t j = 0; j< (size_t)n*n; ++j)
			  G.random(*(A+j));
	  }

	  if (argc == 7){
		  B = read_field (F, argv[6], &n, &n);
	  }
	  else{
		  B = FFLAS::fflas_new<Element>(n*n);
		  for (size_t j=0 ; j< (size_t)n*n; ++j)
			  G.random(*(A+j));
	  }

	  for (size_t k=0;k<(size_t)n;++k)
		  while (F.isZero( G.random(*(A+k*(n+1)))));

	  chrono.clear();
	  chrono.start();

      PAR_REGION{
          if (strat == 1) {
              FFLAS::TRSMHelper<FFLAS::StructureHelper::Iterative,
                  FFLAS::ParSeqHelper::Parallel> PH
                  (FFLAS::ParSeqHelper::Parallel(NUM_THREADS,FFLAS::BLOCK_THREADS));

              FFLAS::ftrsm (F, FFLAS::FflasLeft, FFLAS::FflasLower,
                            FFLAS::FflasNoTrans, FFLAS::FflasNonUnit,
                            n,n, F.one, A, n, B, n, PH);
          } else {
              FFLAS::TRSMHelper<FFLAS::StructureHelper::Recursive,
                  FFLAS::ParSeqHelper::Parallel> PH
                  (FFLAS::ParSeqHelper::Parallel(NUM_THREADS,FFLAS::COLUMN_THREADS));

              FFLAS::ftrsm (F, FFLAS::FflasLeft, FFLAS::FflasLower,
                            FFLAS::FflasNoTrans, FFLAS::FflasNonUnit,
                            n,n, F.one, A, n, B, n, PH);
          }

      }
      BARRIER;

	  chrono.stop();
	  time+=chrono.usertime();
      std::cerr << *A << ' ' << *B << std::endl;
	  delete[] A;
	  delete[] B;

  }

  cerr<<"n: "<<n<<" p: "<<p<<" time: "<<time/(double)iter<<" n^3/time/10^9: "<<(double(n)/1000.*double(n)/1000.*double(n)/1000./time*double(iter))<<endl;

  return 0;
}
<|endoftext|>


<commit_before>// DynInst headers.
#include "CodeObject.h"
#include "InstructionDecoder.h"
#include "third_party/PicoSHA2/picosha2.h"

#include "disassembly.hpp"
#include "dyninstfeaturegenerator.hpp"
#include "flowgraph.hpp"
#include "flowgraphutil.hpp"
#include "functionsimhash.hpp"
#include "mappedtextfile.hpp"
#include "util.hpp"

// Obtain the first 64 bits of the input file's SHA256 hash.
uint64_t GenerateExecutableID(const std::string& filename) {
  std::ifstream ifs(filename.c_str(), std::ios::binary);
  std::vector<unsigned char> hash(32);

  if (!ifs.is_open()) {
    printf("[E] Could not open executable %s\n", filename.c_str());
    exit(-1);
  }
  picosha2::hash256(std::istreambuf_iterator<char>(ifs),
      std::istreambuf_iterator<char>(), hash.begin(), hash.end());

  uint64_t *temp = reinterpret_cast<uint64_t*>(&hash[0]);
  return __builtin_bswap64(*temp);
}

uint32_t HammingDistance(uint64_t A1, uint64_t A2, uint64_t B1, uint64_t B2) {
  uint32_t distance =
    __builtin_popcountl(A1 ^ B1) +
    __builtin_popcountl(A2 ^ B2);
  return distance;
}

uint32_t HammingDistance(FeatureHash A, FeatureHash B) {
  return HammingDistance(A.first, A.second, B.first, B.second);
}

uint32_t ReadFeatureSet(MappedTextFile* input, std::set<FeatureHash>* result) {
  uint32_t lines = 0;
  do {
    uint32_t token_index = 0;
    do {
      if (token_index != 0) {
        const char* begin;
        const char* end;
        input->GetToken(&begin, &end);
        std::string hash(begin, end-begin);
        result->insert(StringToFeatureHash(hash));
      } else {
        printf("[!] Functions %s ", hash.c_str());
      }
      token_index++;
    } while (input->AdvanceToken());
    printf("(%d features)\n", token_index);
    ++lines;
    if ((lines % 1000) == 0) {
      printf("[!] Parsed %d lines, saw %d features ...\n", lines, result->size());
    }
  } while (input->AdvanceLine());
  input->Reset();
  return lines;
}

void ReadFeatureSet(const std::vector<std::vector<std::string>>& inputlines,
  std::set<FeatureHash>* result) {
  for (const std::vector<std::string>& line : inputlines) {
    for (uint32_t index = 1; index < line.size(); ++index) {
      FeatureHash foo = StringToFeatureHash(line[index]);
      result->insert(StringToFeatureHash(line[index]));
    }
  }
}

bool FileToLineTokens(const std::string& filename,
  std::vector<std::vector<std::string>>* tokenized_lines) {
  std::ifstream inputfile(filename);
  if (!inputfile) {
    return false;
  }

  uint32_t line_index = 0;
  std::string line;
  while (std::getline(inputfile, line)) {
    std::vector<std::string> tokens;
    split(line, ' ', std::back_inserter(tokens));
    tokenized_lines->push_back(tokens);
  }
  return true;
}

FeatureHash StringToFeatureHash(const std::string& hash_as_string) {
  const std::string& token = hash_as_string;
  std::string first_half_string;
  std::string second_half_string;
  if ((token.size() != 32) && (token.size() != 35)) {
    printf("[E] Broken token: '%s'\n", token.c_str());
    return std::make_pair(0, 0);
  }

  if (token.c_str()[2] == '.') {
    first_half_string = token.substr(3, 16);
    second_half_string = token.substr(16+3, std::string::npos);
  } else {
    first_half_string = token.substr(0, 16);
    second_half_string = token.substr(16, std::string::npos);
  }
  const char* first_half = first_half_string.c_str();
  const char* second_half = second_half_string.c_str();
  uint64_t hashA = strtoull(first_half, nullptr, 16);
  uint64_t hashB = strtoull(second_half, nullptr, 16);

  return std::make_pair(hashA, hashB);
}

FeatureHash GetHashForFileAndFunction(FunctionSimHasher& hasher,
  const std::string& filename, const std::string& mode, uint64_t address,
  std::vector<FeatureHash>* feature_hashes) {
  Disassembly disassembly(mode, filename);
  if (!disassembly.Load()) {
    exit(1);
  }
  Dyninst::ParseAPI::CodeObject* code_object = disassembly.getCodeObject();

  // Obtain the list of all functions in the binary.
  const Dyninst::ParseAPI::CodeObject::funclist &functions =
    code_object->funcs();

  bool contains_function = false;
  for (Dyninst::ParseAPI::Function* function : functions) {
    Dyninst::Address function_address = function->addr();
    if (function_address == address) {
      contains_function = true;
      break;
    }
  }

  if (!contains_function) {
    // Make sure the function-to-index is in fact getting indexed.
    printf("[!] Warning: Did not find %lx during auto-analysis of %s, adding.\n",
      address, filename.c_str());
    disassembly.DisassembleFromAddress(address, true);
  }

  if (functions.size() == 0) {
    return std::make_pair(0,0);
  }

  for (Dyninst::ParseAPI::Function* function : functions) {
    Flowgraph graph;
    Dyninst::Address function_address = function->addr();
    if (function_address == address) {
      BuildFlowgraph(function, &graph);

      std::vector<uint64_t> hashes;
      DyninstFeatureGenerator generator(function);
      hasher.CalculateFunctionSimHash(&generator, 128, &hashes, feature_hashes);
      uint64_t hash_A = hashes[0];
      uint64_t hash_B = hashes[1];
      return std::make_pair(hash_A, hash_B);
    }
  }
  return std::make_pair(0,0);
}

<commit_msg>Fix build breakage III<commit_after>// DynInst headers.
#include "CodeObject.h"
#include "InstructionDecoder.h"
#include "third_party/PicoSHA2/picosha2.h"

#include "disassembly.hpp"
#include "dyninstfeaturegenerator.hpp"
#include "flowgraph.hpp"
#include "flowgraphutil.hpp"
#include "functionsimhash.hpp"
#include "mappedtextfile.hpp"
#include "util.hpp"

// Obtain the first 64 bits of the input file's SHA256 hash.
uint64_t GenerateExecutableID(const std::string& filename) {
  std::ifstream ifs(filename.c_str(), std::ios::binary);
  std::vector<unsigned char> hash(32);

  if (!ifs.is_open()) {
    printf("[E] Could not open executable %s\n", filename.c_str());
    exit(-1);
  }
  picosha2::hash256(std::istreambuf_iterator<char>(ifs),
      std::istreambuf_iterator<char>(), hash.begin(), hash.end());

  uint64_t *temp = reinterpret_cast<uint64_t*>(&hash[0]);
  return __builtin_bswap64(*temp);
}

uint32_t HammingDistance(uint64_t A1, uint64_t A2, uint64_t B1, uint64_t B2) {
  uint32_t distance =
    __builtin_popcountl(A1 ^ B1) +
    __builtin_popcountl(A2 ^ B2);
  return distance;
}

uint32_t HammingDistance(FeatureHash A, FeatureHash B) {
  return HammingDistance(A.first, A.second, B.first, B.second);
}

uint32_t ReadFeatureSet(MappedTextFile* input, std::set<FeatureHash>* result) {
  uint32_t lines = 0;
  do {
    uint32_t token_index = 0;
    do {
      if (token_index != 0) {
        const char* begin;
        const char* end;
        input->GetToken(&begin, &end);
        std::string temp_hash(begin, end-begin);
        result->insert(StringToFeatureHash(temp_hash));
      } else {
        printf("[!] Functions %s ", temp_hash.c_str());
      }
      token_index++;
    } while (input->AdvanceToken());
    printf("(%d features)\n", token_index);
    ++lines;
    if ((lines % 1000) == 0) {
      printf("[!] Parsed %d lines, saw %d features ...\n", lines, result->size());
    }
  } while (input->AdvanceLine());
  input->Reset();
  return lines;
}

void ReadFeatureSet(const std::vector<std::vector<std::string>>& inputlines,
  std::set<FeatureHash>* result) {
  for (const std::vector<std::string>& line : inputlines) {
    for (uint32_t index = 1; index < line.size(); ++index) {
      FeatureHash foo = StringToFeatureHash(line[index]);
      result->insert(StringToFeatureHash(line[index]));
    }
  }
}

bool FileToLineTokens(const std::string& filename,
  std::vector<std::vector<std::string>>* tokenized_lines) {
  std::ifstream inputfile(filename);
  if (!inputfile) {
    return false;
  }

  uint32_t line_index = 0;
  std::string line;
  while (std::getline(inputfile, line)) {
    std::vector<std::string> tokens;
    split(line, ' ', std::back_inserter(tokens));
    tokenized_lines->push_back(tokens);
  }
  return true;
}

FeatureHash StringToFeatureHash(const std::string& hash_as_string) {
  const std::string& token = hash_as_string;
  std::string first_half_string;
  std::string second_half_string;
  if ((token.size() != 32) && (token.size() != 35)) {
    printf("[E] Broken token: '%s'\n", token.c_str());
    return std::make_pair(0, 0);
  }

  if (token.c_str()[2] == '.') {
    first_half_string = token.substr(3, 16);
    second_half_string = token.substr(16+3, std::string::npos);
  } else {
    first_half_string = token.substr(0, 16);
    second_half_string = token.substr(16, std::string::npos);
  }
  const char* first_half = first_half_string.c_str();
  const char* second_half = second_half_string.c_str();
  uint64_t hashA = strtoull(first_half, nullptr, 16);
  uint64_t hashB = strtoull(second_half, nullptr, 16);

  return std::make_pair(hashA, hashB);
}

FeatureHash GetHashForFileAndFunction(FunctionSimHasher& hasher,
  const std::string& filename, const std::string& mode, uint64_t address,
  std::vector<FeatureHash>* feature_hashes) {
  Disassembly disassembly(mode, filename);
  if (!disassembly.Load()) {
    exit(1);
  }
  Dyninst::ParseAPI::CodeObject* code_object = disassembly.getCodeObject();

  // Obtain the list of all functions in the binary.
  const Dyninst::ParseAPI::CodeObject::funclist &functions =
    code_object->funcs();

  bool contains_function = false;
  for (Dyninst::ParseAPI::Function* function : functions) {
    Dyninst::Address function_address = function->addr();
    if (function_address == address) {
      contains_function = true;
      break;
    }
  }

  if (!contains_function) {
    // Make sure the function-to-index is in fact getting indexed.
    printf("[!] Warning: Did not find %lx during auto-analysis of %s, adding.\n",
      address, filename.c_str());
    disassembly.DisassembleFromAddress(address, true);
  }

  if (functions.size() == 0) {
    return std::make_pair(0,0);
  }

  for (Dyninst::ParseAPI::Function* function : functions) {
    Flowgraph graph;
    Dyninst::Address function_address = function->addr();
    if (function_address == address) {
      BuildFlowgraph(function, &graph);

      std::vector<uint64_t> hashes;
      DyninstFeatureGenerator generator(function);
      hasher.CalculateFunctionSimHash(&generator, 128, &hashes, feature_hashes);
      uint64_t hash_A = hashes[0];
      uint64_t hash_B = hashes[1];
      return std::make_pair(hash_A, hash_B);
    }
  }
  return std::make_pair(0,0);
}

<|endoftext|>


<commit_before>// Copyright 2008, Google Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//  1. Redistributions of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//  2. 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.
//  3. Neither the name of Google Inc. nor the names of its contributors may be
//     used to endorse or promote products derived from this software without
//     specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.

// This file contains the implementation of some utility functions used
// from within the Regionator which are also available for use in classes
// derived from RegionHandler.

#include "kml/regionator/regionator_util.h"
#include "kml/engine.h"

namespace kmlregionator {

static const int kAlignRegionMaxDepth = 24;

using kmldom::AbstractLatLonBoxPtr;
using kmldom::CoordinatesPtr;
using kmldom::DocumentPtr;
using kmldom::FolderPtr;
using kmldom::KmlFactory;
using kmldom::LatLonAltBoxPtr;
using kmldom::LineStringPtr;
using kmldom::LinkPtr;
using kmldom::LodPtr;
using kmldom::NetworkLinkPtr;
using kmldom::PlacemarkPtr;
using kmldom::PointPtr;
using kmldom::RegionPtr;
using kmlengine::Bbox;

// This creates a new LatLonAltBox setting all fields set in the original.
LatLonAltBoxPtr CloneLatLonAltBox(const LatLonAltBoxPtr& orig) {
  return AsLatLonAltBox(kmlengine::Clone(orig));
}

// This creates a new Lod setting all fields set in the original.
LodPtr CloneLod(const LodPtr& orig) {
  return AsLod(kmlengine::Clone(orig));
}

// This creates a new Region based on the LatLonAltBox and/or Lod found in the
// original Region.
RegionPtr CloneRegion(const RegionPtr& orig) {
  return AsRegion(kmlengine::Clone(orig));
}

bool CreateAlignedAbstractLatLonBox(const AbstractLatLonBoxPtr& llb,
                                    AbstractLatLonBoxPtr aligned_llb) {
  if (!llb || !aligned_llb) {
    return false;
  }
  Bbox qt(180,-180,180,-180);
  Bbox r(llb->get_north(), llb->get_south(), llb->get_east(), llb->get_west());
  if (!r.ContainedByBbox(qt)) {
    return false;
  }
  r.AlignBbox(&qt, 24);
  aligned_llb->set_north(qt.get_north());
  aligned_llb->set_south(qt.get_south());
  aligned_llb->set_east(qt.get_east());
  aligned_llb->set_west(qt.get_west());
  return true;
}

// This creates a new child Region of the given quadrant of the parent.
// The altitude fields of LatLonAltBox are cloned unchanged as are
// all fields in the Lod if there is one.
RegionPtr CreateChildRegion(const RegionPtr& parent, quadrant_t quadrant) {
  KmlFactory* factory = KmlFactory::GetFactory();

  RegionPtr child = factory->CreateRegion();
  if (parent->has_latlonaltbox()) {
    double mid_lat, mid_lon;
    kmlengine::GetCenter(parent->get_latlonaltbox(), &mid_lat, &mid_lon);
    LatLonAltBoxPtr latlonaltbox =
        CloneLatLonAltBox(parent->get_latlonaltbox());
    switch (quadrant) {
      case NW:
        latlonaltbox->set_south(mid_lat);
        latlonaltbox->set_east(mid_lon);
        break;
      case NE:
        latlonaltbox->set_south(mid_lat);
        latlonaltbox->set_west(mid_lon);
        break;
      case SW:
        latlonaltbox->set_north(mid_lat);
        latlonaltbox->set_east(mid_lon);
        break;
      case SE:
        latlonaltbox->set_north(mid_lat);
        latlonaltbox->set_west(mid_lon);
        break;
    }
    child->set_latlonaltbox(latlonaltbox);
  }
  if (parent->has_lod()) {  // Make an exact clone.
    child->set_lod(CloneLod(parent->get_lod()));
  }
  return child;
}

// This is a convenience function to create a LineString Placemark whose
// coordinates are taken from the LatLonAltBox in the Region.  If the Region
// has no LatLonAltBox no LineString is created, but a Placemark with the
// given name is created and returned.
PlacemarkPtr CreateLineStringBox(const string& name, const RegionPtr& region) {
  KmlFactory* factory = KmlFactory::GetFactory();
  PlacemarkPtr placemark = factory->CreatePlacemark();
  placemark->set_name(name);
  if (region->has_latlonaltbox()) {
    double north = region->get_latlonaltbox()->get_north();
    double south = region->get_latlonaltbox()->get_south();
    double east = region->get_latlonaltbox()->get_east();
    double west = region->get_latlonaltbox()->get_west();
    CoordinatesPtr coordinates = factory->CreateCoordinates();
    coordinates->add_latlng(north, west);
    coordinates->add_latlng(north, east);
    coordinates->add_latlng(south, east);
    coordinates->add_latlng(south, west);
    coordinates->add_latlng(south, west);
    LineStringPtr linestring = factory->CreateLineString();
    linestring->set_coordinates(coordinates);
    linestring->set_tessellate("1");
    placemark->set_geometry(linestring);
  }
  return placemark;
}

// This is a convenience function to create a NetworkLink to the specified
// url with onRegion refresh semantics.
NetworkLinkPtr CreateRegionNetworkLink(const RegionPtr& region,
                                       const string& href) {
  KmlFactory* factory = KmlFactory::GetFactory();
  NetworkLinkPtr networklink = factory->CreateNetworkLink();
  networklink->set_region(CloneRegion(region));
  LinkPtr link = factory->CreateLink();
  link->set_href(href);
  link->set_viewrefreshmode(kmldom::VIEWREFRESHMODE_ONREGION);
  networklink->set_link(link);
  return networklink;
}

// This is a convenience function to create a new Document whose Region
// is as specified.
DocumentPtr CreateRegionDocument(const RegionPtr& region) {
  KmlFactory* factory = KmlFactory::GetFactory();
  DocumentPtr document = factory->CreateDocument();
  document->set_region(CloneRegion(region));
  return document;
}

}  // end namespace kmlregionator
<commit_msg>Don't convert string literals to bools. Duh.<commit_after>// Copyright 2008, Google Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//  1. Redistributions of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//  2. 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.
//  3. Neither the name of Google Inc. nor the names of its contributors may be
//     used to endorse or promote products derived from this software without
//     specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.

// This file contains the implementation of some utility functions used
// from within the Regionator which are also available for use in classes
// derived from RegionHandler.

#include "kml/regionator/regionator_util.h"
#include "kml/engine.h"

namespace kmlregionator {

static const int kAlignRegionMaxDepth = 24;

using kmldom::AbstractLatLonBoxPtr;
using kmldom::CoordinatesPtr;
using kmldom::DocumentPtr;
using kmldom::FolderPtr;
using kmldom::KmlFactory;
using kmldom::LatLonAltBoxPtr;
using kmldom::LineStringPtr;
using kmldom::LinkPtr;
using kmldom::LodPtr;
using kmldom::NetworkLinkPtr;
using kmldom::PlacemarkPtr;
using kmldom::PointPtr;
using kmldom::RegionPtr;
using kmlengine::Bbox;

// This creates a new LatLonAltBox setting all fields set in the original.
LatLonAltBoxPtr CloneLatLonAltBox(const LatLonAltBoxPtr& orig) {
  return AsLatLonAltBox(kmlengine::Clone(orig));
}

// This creates a new Lod setting all fields set in the original.
LodPtr CloneLod(const LodPtr& orig) {
  return AsLod(kmlengine::Clone(orig));
}

// This creates a new Region based on the LatLonAltBox and/or Lod found in the
// original Region.
RegionPtr CloneRegion(const RegionPtr& orig) {
  return AsRegion(kmlengine::Clone(orig));
}

bool CreateAlignedAbstractLatLonBox(const AbstractLatLonBoxPtr& llb,
                                    AbstractLatLonBoxPtr aligned_llb) {
  if (!llb || !aligned_llb) {
    return false;
  }
  Bbox qt(180,-180,180,-180);
  Bbox r(llb->get_north(), llb->get_south(), llb->get_east(), llb->get_west());
  if (!r.ContainedByBbox(qt)) {
    return false;
  }
  r.AlignBbox(&qt, 24);
  aligned_llb->set_north(qt.get_north());
  aligned_llb->set_south(qt.get_south());
  aligned_llb->set_east(qt.get_east());
  aligned_llb->set_west(qt.get_west());
  return true;
}

// This creates a new child Region of the given quadrant of the parent.
// The altitude fields of LatLonAltBox are cloned unchanged as are
// all fields in the Lod if there is one.
RegionPtr CreateChildRegion(const RegionPtr& parent, quadrant_t quadrant) {
  KmlFactory* factory = KmlFactory::GetFactory();

  RegionPtr child = factory->CreateRegion();
  if (parent->has_latlonaltbox()) {
    double mid_lat, mid_lon;
    kmlengine::GetCenter(parent->get_latlonaltbox(), &mid_lat, &mid_lon);
    LatLonAltBoxPtr latlonaltbox =
        CloneLatLonAltBox(parent->get_latlonaltbox());
    switch (quadrant) {
      case NW:
        latlonaltbox->set_south(mid_lat);
        latlonaltbox->set_east(mid_lon);
        break;
      case NE:
        latlonaltbox->set_south(mid_lat);
        latlonaltbox->set_west(mid_lon);
        break;
      case SW:
        latlonaltbox->set_north(mid_lat);
        latlonaltbox->set_east(mid_lon);
        break;
      case SE:
        latlonaltbox->set_north(mid_lat);
        latlonaltbox->set_west(mid_lon);
        break;
    }
    child->set_latlonaltbox(latlonaltbox);
  }
  if (parent->has_lod()) {  // Make an exact clone.
    child->set_lod(CloneLod(parent->get_lod()));
  }
  return child;
}

// This is a convenience function to create a LineString Placemark whose
// coordinates are taken from the LatLonAltBox in the Region.  If the Region
// has no LatLonAltBox no LineString is created, but a Placemark with the
// given name is created and returned.
PlacemarkPtr CreateLineStringBox(const string& name, const RegionPtr& region) {
  KmlFactory* factory = KmlFactory::GetFactory();
  PlacemarkPtr placemark = factory->CreatePlacemark();
  placemark->set_name(name);
  if (region->has_latlonaltbox()) {
    double north = region->get_latlonaltbox()->get_north();
    double south = region->get_latlonaltbox()->get_south();
    double east = region->get_latlonaltbox()->get_east();
    double west = region->get_latlonaltbox()->get_west();
    CoordinatesPtr coordinates = factory->CreateCoordinates();
    coordinates->add_latlng(north, west);
    coordinates->add_latlng(north, east);
    coordinates->add_latlng(south, east);
    coordinates->add_latlng(south, west);
    coordinates->add_latlng(south, west);
    LineStringPtr linestring = factory->CreateLineString();
    linestring->set_coordinates(coordinates);
    linestring->set_tessellate(true);
    placemark->set_geometry(linestring);
  }
  return placemark;
}

// This is a convenience function to create a NetworkLink to the specified
// url with onRegion refresh semantics.
NetworkLinkPtr CreateRegionNetworkLink(const RegionPtr& region,
                                       const string& href) {
  KmlFactory* factory = KmlFactory::GetFactory();
  NetworkLinkPtr networklink = factory->CreateNetworkLink();
  networklink->set_region(CloneRegion(region));
  LinkPtr link = factory->CreateLink();
  link->set_href(href);
  link->set_viewrefreshmode(kmldom::VIEWREFRESHMODE_ONREGION);
  networklink->set_link(link);
  return networklink;
}

// This is a convenience function to create a new Document whose Region
// is as specified.
DocumentPtr CreateRegionDocument(const RegionPtr& region) {
  KmlFactory* factory = KmlFactory::GetFactory();
  DocumentPtr document = factory->CreateDocument();
  document->set_region(CloneRegion(region));
  return document;
}

}  // end namespace kmlregionator
<|endoftext|>


<commit_before>// Copyright 2016-2017 John T. Foster, Katy L. Hanson

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at

//    http://www.apache.org/licenses/LICENSE-2.0

// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#include "IGESControl_Reader.hxx"
#include "TColStd_HSequenceOfTransient.hxx"
#include "TopoDS_Edge.hxx"
#include "TopoDS_Shape.hxx"
#include "TopoDS_Vertex.hxx"

#include "Teuchos_RCP.hpp"

#include "tadiga_IGES_geometry.h"

tadiga::IgesGeometry::IgesGeometry(
    const Teuchos::RCP<const Teuchos::Comm<int>>& kComm,
    const Teuchos::RCP<Teuchos::ParameterList>& kGeometryParameters)
    : kComm_(kComm) {
    const auto kFileName = kGeometryParameters->get<std::string>("File Name");

    // Open IGES Reader from OpenCASCADE
    const auto kIgesReader = Teuchos::rcp(new IGESControl_Reader);
    const auto status = kIgesReader->ReadFile(kFileName.c_str());

    // TODO(johntfoster@gmail.com): Check the status of the file

    Handle(TColStd_HSequenceOfTransient) myFacesList =
        kIgesReader->GiveList("iges-faces");
    Handle(TColStd_HSequenceOfTransient) myEdgesList =
        kIgesReader->GiveList("iges-type(110)");
    Handle(TColStd_HSequenceOfTransient) myTabCylinderList =
        kIgesReader->GiveList("iges-type(122)");
    Handle(TColStd_HSequenceOfTransient) myCompCurveList =
        kIgesReader->GiveList("iges-type(102)");
    Handle(TColStd_HSequenceOfTransient) myCurveOnSurfaceList =
        kIgesReader->GiveList("iges-type(142)");
    Handle(TColStd_HSequenceOfTransient) myPointsList =
        kIgesReader->GiveList("iges-type(116)");

    // selects all IGES faces in the file and puts them into a list  called
    // //MyList,

    const auto kIgesFaces = myFacesList->Length();
    const auto kTransFaces = kIgesReader->TransferList(myFacesList);
    const auto kIgesEdges = myEdgesList->Length();
    const auto kTransEdges = kIgesReader->TransferList(myEdgesList);
    const auto kIgesTabCylinder = myTabCylinderList->Length();
    const auto kTransTabCylinder =
        kIgesReader->TransferList(myTabCylinderList);  // translates MyList,
    const auto kIgesCompCurve = myCompCurveList->Length();
    const auto kTransCompCurve = kIgesReader->TransferList(myCompCurveList);
    const auto kIgesCurveOnSurface = myCurveOnSurfaceList->Length();
    const auto kTransCurveOnSurface =
        kIgesReader->TransferList(myCurveOnSurfaceList);
    const auto kIgesPoints = myPointsList->Length();
    const auto kTransPoints = kIgesReader->TransferList(myPointsList);

    std::cout << "IGES Faces: " << kIgesFaces
              << "   Transferred:" << kTransFaces << std::endl;
    std::cout << "IGES Edges: " << kIgesEdges
              << "   Transferred:" << kTransEdges << std::endl;
    std::cout << "IGES Tabulated Cylinder: " << kIgesTabCylinder
              << "   Transferred:" << kTransTabCylinder << std::endl;
    std::cout << "IGES Composite Curve: " << kIgesCompCurve
              << "   Transferred:" << kTransCompCurve << std::endl;
    std::cout << "IGES Curve On Surface: " << kIgesCurveOnSurface
              << "   Transferred:" << kTransCurveOnSurface << std::endl;
    std::cout << "IGES Points: " << kIgesPoints
              << "   Transferred:" << kTransPoints << std::endl;

    TopoDS_Shape sh = kIgesReader->OneShape();
};
<commit_msg>No change to code<commit_after>// Copyright 2016-2017 John T. Foster, Katy L. Hanson

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at

//    http://www.apache.org/licenses/LICENSE-2.0

// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#include "IGESControl_Reader.hxx"
#include "TColStd_HSequenceOfTransient.hxx"
#include "TopoDS_Edge.hxx"
#include "TopoDS_Shape.hxx"
#include "TopoDS_Vertex.hxx"

#include "Teuchos_RCP.hpp"

#include "tadiga_IGES_geometry.h"

tadiga::IgesGeometry::IgesGeometry(
    const Teuchos::RCP<const Teuchos::Comm<int>>& kComm,
    const Teuchos::RCP<Teuchos::ParameterList>& kGeometryParameters)
    : kComm_(kComm) {
    const auto kFileName = kGeometryParameters->get<std::string>("File Name");

    // Open IGES Reader from OpenCASCADE
    const auto kIgesReader = Teuchos::rcp(new IGESControl_Reader);
    const auto status = kIgesReader->ReadFile(kFileName.c_str());

    // TODO(johntfoster@gmail.com): Check the status of the file

    Handle(TColStd_HSequenceOfTransient) myFacesList =
        kIgesReader->GiveList("iges-faces");
    Handle(TColStd_HSequenceOfTransient) myEdgesList =
        kIgesReader->GiveList("iges-type(110)");
    Handle(TColStd_HSequenceOfTransient) myTabCylinderList =
        kIgesReader->GiveList("iges-type(122)");
    Handle(TColStd_HSequenceOfTransient) myCompCurveList =
        kIgesReader->GiveList("iges-type(102)");
    Handle(TColStd_HSequenceOfTransient) myCurveOnSurfaceList =
        kIgesReader->GiveList("iges-type(142)");
    Handle(TColStd_HSequenceOfTransient) myPointsList =
        kIgesReader->GiveList("iges-type(116)");

    // selects all IGES faces in the file and puts them into a list  called
    // //MyList,

    const auto kIgesFaces = myFacesList->Length();
    const auto kTransFaces = kIgesReader->TransferList(myFacesList);
    const auto kIgesEdges = myEdgesList->Length() const auto kTransEdges =
        kIgesReader->TransferList(myEdgesList);
    const auto kIgesTabCylinder = myTabCylinderList->Length();
    const auto kTransTabCylinder =
        kIgesReader->TransferList(myTabCylinderList);  // translates MyList,
    const auto kIgesCompCurve = myCompCurveList->Length();
    const auto kTransCompCurve = kIgesReader->TransferList(myCompCurveList);
    const auto kIgesCurveOnSurface = myCurveOnSurfaceList->Length();
    const auto kTransCurveOnSurface =
        kIgesReader->TransferList(myCurveOnSurfaceList);
    const auto kIgesPoints = myPointsList->Length();
    const auto kTransPoints = kIgesReader->TransferList(myPointsList);

    std::cout << "IGES Faces: " << kIgesFaces
              << "   Transferred:" << kTransFaces << std::endl;
    std::cout << "IGES Edges: " << kIgesEdges
              << "   Transferred:" << kTransEdges << std::endl;
    std::cout << "IGES Tabulated Cylinder: " << kIgesTabCylinder
              << "   Transferred:" << kTransTabCylinder << std::endl;
    std::cout << "IGES Composite Curve: " << kIgesCompCurve
              << "   Transferred:" << kTransCompCurve << std::endl;
    std::cout << "IGES Curve On Surface: " << kIgesCurveOnSurface
              << "   Transferred:" << kTransCurveOnSurface << std::endl;
    std::cout << "IGES Points: " << kIgesPoints
              << "   Transferred:" << kTransPoints << std::endl;

    TopoDS_Shape sh = kIgesReader->OneShape();
};
<|endoftext|>


<commit_before><commit_msg>Allow debug config output to file if ART_DEBUG_CONFIG starts with a letter.<commit_after><|endoftext|>


<commit_before>#include "variable_declaration.hpp"
#include <boost/spirit/include/qi_no_case.hpp>
#include <boost/spirit/include/phoenix_function.hpp>
#include <boost/spirit/include/qi_no_case.hpp>

namespace f2h
{

unsigned int ParameterToUInt(ast::Identifier id)
{
  //TODO search among global parameters
  return 4;
}

template <typename Iterator>
VariableDeclaration<Iterator>::VariableDeclaration(ErrorHandler<Iterator>& error_handler)
  : VariableDeclaration::base_type(var_decl), primary_expression(error_handler), type_spec(error_handler),
    balanced_parentheses(error_handler), bind_attribute(error_handler)
{
  using boost::spirit::ascii::no_case;
  using qi::lit;
  qi::char_type char_;
  qi::alnum_type alnum;
  qi::alpha_type alpha;
  qi::string_type string;
  qi::raw_type raw;
  qi::lexeme_type lexeme;
  qi::uint_type uint_;
  qi::_1_type _1;
  qi::_2_type _2;
  qi::_3_type _3;
  qi::_4_type _4;
  typedef boost::phoenix::function<ErrorHandler<Iterator> > ErrorHandlerFunction;

  initialize_spec = '=' > +(char_ - qi::eol);
  variable_name = primary_expression.identifier >> -(balanced_parentheses) >> -(initialize_spec);
  variable_list = variable_name % ',';

  attribute =   no_case[string("allocatable")]
              | no_case[string("asynchronous")]
              | no_case[string("automatic")]
              | bind_attribute
              | no_case[string("codimension")]
              | no_case[string("contiguous")]
              | (no_case[string("dimension")] >> -(balanced_parentheses))
              | no_case[string("external")]
              | (no_case[string("intent")] >> '(' >> (no_case[string("in")] | no_case[string("out")] | no_case[string("inout")]) >> ')')
              | no_case[string("external")]
              | no_case[string("intrinsic")]
              | no_case[string("optional")]
              | no_case[string("parameter")]
              | no_case[string("pointer")]
              | no_case[string("private")]
              | no_case[string("protected")]
              | no_case[string("public")]
              | no_case[string("save")]
              | no_case[string("static")]
              | no_case[string("target")]
              | no_case[string("value")]
              | no_case[string("volatile")]
              ;

  attribute_list = attribute % ',';

  var_decl_attribute = attribute >> -lit("::") > variable_list;

  var_decl_simple = type_spec >> -lit("::") > variable_list;

  var_decl_extended = type_spec >> ',' > attribute_list >> lit("::") > variable_list;

  var_decl = (var_decl_extended | var_decl_simple | var_decl_attribute) > qi::eol;

  qi::on_error<qi::fail>(var_decl,
      ErrorHandlerFunction(error_handler)(
        "Error! Expecting ", _4, _3));

  //BOOST_SPIRIT_DEBUG_NODES(
  //    (attribute)
  //    (initialize_spec)
  //    (variable_name)
  //    (attribute_list)
  //    (variable_list)
  //    (var_decl_simple)
  //    (var_decl_extended)
  //    (var_decl)
  //    );
}

}
<commit_msg>fixed intent(inout) attribute<commit_after>#include "variable_declaration.hpp"
#include <boost/spirit/include/qi_no_case.hpp>
#include <boost/spirit/include/phoenix_function.hpp>
#include <boost/spirit/include/qi_no_case.hpp>

namespace f2h
{

unsigned int ParameterToUInt(ast::Identifier id)
{
  //TODO search among global parameters
  return 4;
}

template <typename Iterator>
VariableDeclaration<Iterator>::VariableDeclaration(ErrorHandler<Iterator>& error_handler)
  : VariableDeclaration::base_type(var_decl), primary_expression(error_handler), type_spec(error_handler),
    balanced_parentheses(error_handler), bind_attribute(error_handler)
{
  using boost::spirit::ascii::no_case;
  using qi::lit;
  qi::char_type char_;
  qi::alnum_type alnum;
  qi::alpha_type alpha;
  qi::string_type string;
  qi::raw_type raw;
  qi::lexeme_type lexeme;
  qi::uint_type uint_;
  qi::_1_type _1;
  qi::_2_type _2;
  qi::_3_type _3;
  qi::_4_type _4;
  typedef boost::phoenix::function<ErrorHandler<Iterator> > ErrorHandlerFunction;

  initialize_spec = '=' > +(char_ - qi::eol);
  variable_name = primary_expression.identifier >> -(balanced_parentheses) >> -(initialize_spec);
  variable_list = variable_name % ',';

  attribute =   no_case[string("allocatable")]
              | no_case[string("asynchronous")]
              | no_case[string("automatic")]
              | bind_attribute
              | no_case[string("codimension")]
              | no_case[string("contiguous")]
              | (no_case[string("dimension")] >> -(balanced_parentheses))
              | no_case[string("external")]
              | (no_case[string("intent")] >> '(' >> (no_case[string("inout")] | no_case[string("in")] | no_case[string("out")]) >> ')')
              | no_case[string("external")]
              | no_case[string("intrinsic")]
              | no_case[string("optional")]
              | no_case[string("parameter")]
              | no_case[string("pointer")]
              | no_case[string("private")]
              | no_case[string("protected")]
              | no_case[string("public")]
              | no_case[string("save")]
              | no_case[string("static")]
              | no_case[string("target")]
              | no_case[string("value")]
              | no_case[string("volatile")]
              ;

  attribute_list = attribute % ',';

  var_decl_attribute = attribute >> -lit("::") > variable_list;

  var_decl_simple = type_spec >> -lit("::") > variable_list;

  var_decl_extended = type_spec >> ',' > attribute_list >> lit("::") > variable_list;

  var_decl = (var_decl_extended | var_decl_simple | var_decl_attribute) > qi::eol;

  qi::on_error<qi::fail>(var_decl,
      ErrorHandlerFunction(error_handler)(
        "Error! Expecting ", _4, _3));

  //BOOST_SPIRIT_DEBUG_NODES(
  //    (attribute)
  //    (initialize_spec)
  //    (variable_name)
  //    (attribute_list)
  //    (variable_list)
  //    (var_decl_simple)
  //    (var_decl_extended)
  //    (var_decl)
  //    );
}

}
<|endoftext|>


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

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkNarrowBandImageFilterBaseTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2002 Insight Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#include <iostream>
//#include "itkImageFileWriter.h"
#include "itkNarrowBandImageFilterBase.h"
#include "itkCastImageFilter.h"
#include "itkCurvatureFlowFunction.h"
#include "itkRandomImageSource.h"
#include "itkAddImageFilter.h"

namespace itk
{
  template <class TInputImageType, class TOutputImageType>
  class NbTestClass: public NarrowBandImageFilterBase<TInputImageType, TOutputImageType>
  {
     public:
     typedef NbTestClass Self;

     typedef NarrowBandImageFilterBase<TInputImageType, TOutputImageType> Superclass;
     typedef SmartPointer<Self> Pointer;
     typedef SmartPointer<const Self> ConstPointer;
     typedef TOutputImageType ImageType;

    /** Standard method for creation through object factory. */
        itkNewMacro(Self);

    /** Run-time class information. */
     itkTypeMacro(NbTestClass,NarrowBandImageFilterBase);

     typedef CurvatureFlowFunction<TOutputImageType> FiniteFunctionType;

  protected:
    typename FiniteFunctionType::Pointer m_Function;

    NbTestClass ()
    {
      m_Function=FiniteFunctionType::New();
      this->SetDifferenceFunction(m_Function);
    }

    virtual bool Halt ()
    {
      if (this->GetElapsedIterations()==20) return true;
      else return false;
    }

    virtual void Initialize() {
      //Do itkNarrowBandImageFilterBase initialize
      Superclass::Initialize();

      //Create a band
      typename ImageType::SizeType sz= this->GetInput()->GetRequestedRegion().GetSize();
      typename ImageType::IndexType tl= this->GetInput()->GetRequestedRegion().GetIndex();
      typename Superclass::IndexType in;

      for (in[0]=32+tl[0];in[0]<tl[0]+(long int)(sz[0]);in[0]++)
        for (in[1]=tl[1]+32;in[1]<tl[1]+(long int)(sz[1]);in[1]++)
          this->InsertNarrowBandNode (in);
     m_RegionList=m_NarrowBand->SplitBand(this->GetNumberOfThreads());
    }

  };
}

namespace {
// simple signed distance function
template <typename TPoint>
double
SimpleSignedDistance( const TPoint & p )
{
  TPoint center;
  center.Fill( 32 );
  double radius = 19.5;

  double accum = 0.0;
  for( unsigned int j = 0; j < TPoint::PointDimension; j++ )
    {
    accum += vnl_math_sqr( p[j] - center[j] );
    }
  accum = vcl_sqrt( accum );
  return ( accum - radius );

}

}

int itkNarrowBandImageFilterBaseTest(int, char* [])
{
  typedef float PixelType;
  const unsigned int ImageDimension = 2;
  typedef itk::Image<PixelType,ImageDimension> ImageType;
  typedef itk::Point<double,ImageDimension> PointType;

  ImageType::SizeType size = {{64,64}};
  ImageType::IndexType index = {{0,0}};
  ImageType::RegionType region;
  region.SetSize( size );
  region.SetIndex( index );

  ImageType::Pointer inputImage = ImageType::New();
  inputImage->SetLargestPossibleRegion( region );
  inputImage->SetBufferedRegion( region );
  inputImage->SetRequestedRegion( region );
  inputImage->Allocate();

  typedef itk::ImageRegionIteratorWithIndex<ImageType> Iterator;
  Iterator iter( inputImage, region );
  iter.GoToBegin();

  while( !iter.IsAtEnd() )
    {
    PointType point;
    inputImage->TransformIndexToPhysicalPoint( iter.GetIndex(), point );
    iter.Set( SimpleSignedDistance( point ) );
    ++iter;
    }

  typedef itk::RandomImageSource<ImageType> RandomSourceType;
  RandomSourceType::Pointer randomSource = RandomSourceType::New();
  unsigned long tam[2];
  tam[0]=64;
  tam[1]=64;
  randomSource->SetSize(tam);
  randomSource->SetMin(0);
  randomSource->SetMax(10);
  randomSource->Update();

  typedef itk::AddImageFilter<ImageType,ImageType,ImageType> AddFilterType;
  AddFilterType::Pointer addFilter = AddFilterType::New();
  addFilter->SetInput1(inputImage);
  addFilter->SetInput2(randomSource->GetOutput());
  addFilter->Update();

  typedef itk::NbTestClass <ImageType,ImageType> FilterType;

  FilterType::Pointer filter = FilterType::New();
  filter->SetInput(addFilter->GetOutput());

  try {
  filter->Update();
  /* For Debugging
  typedef itk::ImageFileWriter<ImageType> WriterType;
  WriterType::Pointer writer = WriterType::New();
  writer->SetInput( filter->GetOutput() );
  writer->SetFileName( "outputNB.mhd" );
  writer->Write();
 */
  }
  catch (itk::ExceptionObject &err)
    {
      (&err)->Print(std::cerr);
    std::cout << "Test failed." << std::endl;
    return EXIT_FAILURE;
    }

  std::cout << "Test Passed. " << std::endl;
  return EXIT_SUCCESS;

}
<commit_msg>FIX: Narrow Band creation is done in CreateNarrowBand method.<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkNarrowBandImageFilterBaseTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2002 Insight Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#include <iostream>
//#include "itkImageFileWriter.h"
#include "itkNarrowBandImageFilterBase.h"
#include "itkCastImageFilter.h"
#include "itkCurvatureFlowFunction.h"
#include "itkRandomImageSource.h"
#include "itkAddImageFilter.h"

namespace itk
{
  template <class TInputImageType, class TOutputImageType>
  class NbTestClass: public NarrowBandImageFilterBase<TInputImageType, TOutputImageType>
  {
     public:
     typedef NbTestClass Self;

     typedef NarrowBandImageFilterBase<TInputImageType, TOutputImageType> Superclass;
     typedef SmartPointer<Self> Pointer;
     typedef SmartPointer<const Self> ConstPointer;
     typedef TOutputImageType ImageType;

    /** Standard method for creation through object factory. */
        itkNewMacro(Self);

    /** Run-time class information. */
     itkTypeMacro(NbTestClass,NarrowBandImageFilterBase);

     typedef CurvatureFlowFunction<TOutputImageType> FiniteFunctionType;

  protected:
    typename FiniteFunctionType::Pointer m_Function;

    NbTestClass ()
    {
      m_Function=FiniteFunctionType::New();
      this->SetDifferenceFunction(m_Function);
    }

    virtual bool Halt ()
    {
      if (this->GetElapsedIterations()==20) return true;
      else return false;
    }

    virtual void CreateNarrowBand()
    {
      //Create a band
      typename ImageType::SizeType sz= this->GetInput()->GetRequestedRegion().GetSize();
      typename ImageType::IndexType tl= this->GetInput()->GetRequestedRegion().GetIndex();
      typename Superclass::IndexType in;

      for (in[0]=32+tl[0];in[0]<tl[0]+(long int)(sz[0]);in[0]++)
        for (in[1]=tl[1]+32;in[1]<tl[1]+(long int)(sz[1]);in[1]++)
          this->InsertNarrowBandNode (in);
    }
    /*
    virtual void Initialize() {
      //Do itkNarrowBandImageFilterBase initialize
      Superclass::Initialize();

      //Create a band
      typename ImageType::SizeType sz= this->GetInput()->GetRequestedRegion().GetSize();
      typename ImageType::IndexType tl= this->GetInput()->GetRequestedRegion().GetIndex();
      typename Superclass::IndexType in;

      for (in[0]=32+tl[0];in[0]<tl[0]+(long int)(sz[0]);in[0]++)
        for (in[1]=tl[1]+32;in[1]<tl[1]+(long int)(sz[1]);in[1]++)
          this->InsertNarrowBandNode (in);
     m_RegionList=m_NarrowBand->SplitBand(this->GetNumberOfThreads());
    }
    */
  };
}

namespace {
// simple signed distance function
template <typename TPoint>
double
SimpleSignedDistance( const TPoint & p )
{
  TPoint center;
  center.Fill( 32 );
  double radius = 19.5;

  double accum = 0.0;
  for( unsigned int j = 0; j < TPoint::PointDimension; j++ )
    {
    accum += vnl_math_sqr( p[j] - center[j] );
    }
  accum = vcl_sqrt( accum );
  return ( accum - radius );

}

}

int itkNarrowBandImageFilterBaseTest(int, char* [])
{
  typedef float PixelType;
  const unsigned int ImageDimension = 2;
  typedef itk::Image<PixelType,ImageDimension> ImageType;
  typedef itk::Point<double,ImageDimension> PointType;

  ImageType::SizeType size = {{64,64}};
  ImageType::IndexType index = {{0,0}};
  ImageType::RegionType region;
  region.SetSize( size );
  region.SetIndex( index );

  ImageType::Pointer inputImage = ImageType::New();
  inputImage->SetLargestPossibleRegion( region );
  inputImage->SetBufferedRegion( region );
  inputImage->SetRequestedRegion( region );
  inputImage->Allocate();

  typedef itk::ImageRegionIteratorWithIndex<ImageType> Iterator;
  Iterator iter( inputImage, region );
  iter.GoToBegin();

  while( !iter.IsAtEnd() )
    {
    PointType point;
    inputImage->TransformIndexToPhysicalPoint( iter.GetIndex(), point );
    iter.Set( SimpleSignedDistance( point ) );
    ++iter;
    }

  typedef itk::RandomImageSource<ImageType> RandomSourceType;
  RandomSourceType::Pointer randomSource = RandomSourceType::New();
  unsigned long tam[2];
  tam[0]=64;
  tam[1]=64;
  randomSource->SetSize(tam);
  randomSource->SetMin(0);
  randomSource->SetMax(10);
  randomSource->Update();

  typedef itk::AddImageFilter<ImageType,ImageType,ImageType> AddFilterType;
  AddFilterType::Pointer addFilter = AddFilterType::New();
  addFilter->SetInput1(inputImage);
  addFilter->SetInput2(randomSource->GetOutput());
  addFilter->Update();

  typedef itk::NbTestClass <ImageType,ImageType> FilterType;

  FilterType::Pointer filter = FilterType::New();
  filter->SetInput(addFilter->GetOutput());

  try {
  filter->Update();
  /* For Debugging
  typedef itk::ImageFileWriter<ImageType> WriterType;
  WriterType::Pointer writer = WriterType::New();
  writer->SetInput( filter->GetOutput() );
  writer->SetFileName( "outputNB.mhd" );
  writer->Write();
 */
  }
  catch (itk::ExceptionObject &err)
    {
      (&err)->Print(std::cerr);
    std::cout << "Test failed." << std::endl;
    return EXIT_FAILURE;
    }

  std::cout << "Test Passed. " << std::endl;
  return EXIT_SUCCESS;

}
<|endoftext|>


<commit_before>/* implementations of byte-at-a-time virtual read/writes for long mode that
   never cause faults/exceptions and maybe do not affect TLB content */

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

    Bit8u BX_CPP_AttrRegparmN(2)
BX_CPU_C::read_virtual_byte_64_nofail(unsigned s, Bit64u offset, uint8_t *error)
{
    Bit8u data;
    Bit64u laddr = get_laddr64(s, offset); // this is safe

    if (! IsCanonical(laddr)) {
        *error = 1;
        return 0;
    }

    access_read_linear_nofail(laddr, 1, 0, BX_READ, (void *) &data, error);
    return data;
}

int BX_CPU_C::access_read_linear_nofail(bx_address laddr, unsigned len, unsigned curr_pl, unsigned xlate_rw, void *data, uint8_t *error)
{
    BX_ASSERT(xlate_rw == BX_READ || xlate_rw == BX_RW); // this is safe

    Bit32u pageOffset = PAGE_OFFSET(laddr); // this is safe

    bx_TLB_entry *tlbEntry = BX_TLB_ENTRY_OF(laddr); // this is safe

    /* next line DOES THE PAGE TABLE WALK */
    BX_CPU_THIS_PTR address_xlation.paddress1 = translate_linear(tlbEntry, laddr, (curr_pl == 3), xlate_rw);
    BX_CPU_THIS_PTR address_xlation.pages     = 1;
    access_read_physical(BX_CPU_THIS_PTR address_xlation.paddress1, len, data);
    /* previous line SHOULD BE SAFE */

    return 0;
}

bx_phy_address BX_CPU_C::translate_linear_nofail(bx_TLB_entry *tlbEntry, bx_address laddr, unsigned user, unsigned rw)
{
    Bit32u combined_access = 0x06;
    Bit32u lpf_mask = 0xfff; // 4K pages

#if BX_SUPPORT_X86_64
    if (! long_mode()) laddr &= 0xffffffff;
#endif

    bx_phy_address paddress, ppf, poffset = PAGE_OFFSET(laddr);
    unsigned isWrite = rw & 1; // write or r-m-w
    unsigned isExecute = (rw == BX_EXECUTE);

    bx_address lpf = LPFOf(laddr);

    if(BX_CPU_THIS_PTR cr0.get_PG())
    {
        BX_DEBUG(("page walk for address 0x" FMT_LIN_ADDRX, laddr));

#if BX_CPU_LEVEL >= 6
#if BX_SUPPORT_X86_64
        if (long_mode())
            paddress = translate_linear_long_mode(laddr, lpf_mask, combined_access, user, rw);
        else
#endif
            if (BX_CPU_THIS_PTR cr4.get_PAE())
                paddress = translate_linear_PAE(laddr, lpf_mask, combined_access, user, rw);
            else
#endif
                paddress = translate_linear_legacy(laddr, lpf_mask, combined_access, user, rw);

#if BX_CPU_LEVEL >= 5
        if (lpf_mask > 0xfff)
            BX_CPU_THIS_PTR TLB.split_large = 1;
#endif
    }
    else {
        // no paging
        paddress = (bx_phy_address) laddr;
    }

    // Calculate physical memory address and fill in TLB cache entry
#if BX_SUPPORT_VMX >= 2
    if (BX_CPU_THIS_PTR in_vmx_guest) {
        if (SECONDARY_VMEXEC_CONTROL(VMX_VM_EXEC_CTRL3_EPT_ENABLE)) {
            paddress = translate_guest_physical(paddress, laddr, 1, 0, rw);
        }
    }
#endif
#if BX_SUPPORT_SVM
    if (BX_CPU_THIS_PTR in_svm_guest && SVM_NESTED_PAGING_ENABLED) {
        paddress = nested_walk(paddress, rw, 0);
    }
#endif
    paddress = A20ADDR(paddress);
    return paddress;
}
<commit_msg>trim moar fat<commit_after>/* implementations of byte-at-a-time virtual read/writes for long mode that
   never cause faults/exceptions and maybe do not affect TLB content */

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

    Bit8u BX_CPP_AttrRegparmN(2)
BX_CPU_C::read_virtual_byte_64_nofail(unsigned s, Bit64u offset, uint8_t *error)
{
    Bit8u data;
    Bit64u laddr = get_laddr64(s, offset); // this is safe

    if (! IsCanonical(laddr)) {
        *error = 1;
        return 0;
    }

    access_read_linear_nofail(laddr, 1, 0, BX_READ, (void *) &data, error);
    return data;
}

int BX_CPU_C::access_read_linear_nofail(bx_address laddr, unsigned len, unsigned curr_pl, unsigned xlate_rw, void *data, uint8_t *error)
{
    BX_ASSERT(xlate_rw == BX_READ || xlate_rw == BX_RW); // this is safe

    Bit32u pageOffset = PAGE_OFFSET(laddr); // this is safe

    bx_TLB_entry *tlbEntry = BX_TLB_ENTRY_OF(laddr); // this is safe

    /* next line DOES THE PAGE TABLE WALK */
    BX_CPU_THIS_PTR address_xlation.paddress1 = translate_linear_nofail(tlbEntry, laddr, (curr_pl == 3), xlate_rw);
    BX_CPU_THIS_PTR address_xlation.pages     = 1;
    access_read_physical(BX_CPU_THIS_PTR address_xlation.paddress1, len, data);
    /* previous line SHOULD BE SAFE */

    return 0;
}

bx_phy_address BX_CPU_C::translate_linear_nofail(bx_TLB_entry *tlbEntry, bx_address laddr, unsigned user, unsigned rw)
{
    Bit32u combined_access = 0x06;
    Bit32u lpf_mask = 0xfff; // 4K pages

    bx_phy_address paddress, ppf, poffset = PAGE_OFFSET(laddr);
    paddress = translate_linear_long_mode(laddr, lpf_mask, combined_access, user, rw);
    paddress = A20ADDR(paddress);
    return paddress;
}
<|endoftext|>


<commit_before>#include "MemCheck.h"
#include "Win32POGLDeviceContext.h"
#include <vector>

Win32POGLDeviceContext::Win32POGLDeviceContext(IPOGLDevice* device, HDC deviceContext, HGLRC renderContext)
: POGLDeviceContext(device), mDeviceContext(deviceContext),
mRenderContext(renderContext), mBoundToThread(false),
// Extensions
wglCreateContextAttribsARB(nullptr), wglChoosePixelFormatARB(nullptr)
{

}

Win32POGLDeviceContext::~Win32POGLDeviceContext()
{
	if (mRenderContext != nullptr) {
		wglDeleteContext(mRenderContext);
		mRenderContext = nullptr;
	}
}

bool Win32POGLDeviceContext::Initialize(Win32POGLDeviceContext* parentContext)
{
	// Activate the legacy render context (which is supplied in the constructor) so
	// that we can retrieve the necessary extensions
	wglMakeCurrent(mDeviceContext, mRenderContext);
	mRenderContext = nullptr;
	LoadExtensions();
	wglMakeCurrent(nullptr, nullptr);

	//
	// Verify that your graphics card support OpenGL 3.3
	//

	if (wglCreateContextAttribsARB == nullptr) {
		wglMakeCurrent(nullptr, nullptr);
		return false;
	}

	//
	// Set neccessary attributes so that we get an OpenGL 3.3 render context
	//

	std::vector<int> attributes;
	attributes.push_back(WGL_CONTEXT_MAJOR_VERSION_ARB); attributes.push_back(3);
	attributes.push_back(WGL_CONTEXT_MINOR_VERSION_ARB); attributes.push_back(3);
	attributes.push_back(WGL_CONTEXT_PROFILE_MASK_ARB); attributes.push_back(WGL_CONTEXT_CORE_PROFILE_BIT_ARB);
	if (BIT_ISSET(mDevice->GetDeviceInfo()->flags, POGLDeviceInfoFlags::DEBUG_MODE)) {
		attributes.push_back(WGL_CONTEXT_FLAGS_ARB); attributes.push_back(WGL_CONTEXT_DEBUG_BIT_ARB | WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB);
	}
	else {
		attributes.push_back(WGL_CONTEXT_FLAGS_ARB); attributes.push_back(WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB);
	}
	attributes.push_back(0); attributes.push_back(0);

	//
	// Create an OpenGL 3.3 render context
	//

	mRenderContext = (*wglCreateContextAttribsARB)(mDeviceContext, parentContext != nullptr ? parentContext->GetHandlePtr() : 0, &attributes[0]);
	if (mRenderContext == nullptr)
		return false;

	return true;
}

void Win32POGLDeviceContext::Bind()
{
	if (!mBoundToThread) {
		wglMakeCurrent(mDeviceContext, mRenderContext);
		mBoundToThread = true;

		// Make sure to load the extensions from the new library
		LoadExtensions();

		InitializeRenderState();
	}
}

void Win32POGLDeviceContext::Unbind()
{
	assert_with_message(mBoundToThread, "Why is this not bound to the current thread?");
	wglMakeCurrent(0, 0);
	mBoundToThread = false;
}

void Win32POGLDeviceContext::LoadExtensions()
{
	SET_EXTENSION_FUNC(PFNWGLCREATECONTEXTATTRIBSARBPROC, wglCreateContextAttribsARB);
	SET_EXTENSION_FUNC(PFNWGLCHOOSEPIXELFORMATARBPROC, wglChoosePixelFormatARB);

	POGLDeviceContext::LoadExtensions();
}

void* Win32POGLDeviceContext::GetProcAddress(const char* functionName)
{
	return wglGetProcAddress(functionName);
}
<commit_msg>Removed, again, backward compatibility<commit_after>#include "MemCheck.h"
#include "Win32POGLDeviceContext.h"
#include <vector>

Win32POGLDeviceContext::Win32POGLDeviceContext(IPOGLDevice* device, HDC deviceContext, HGLRC renderContext)
: POGLDeviceContext(device), mDeviceContext(deviceContext),
mRenderContext(renderContext), mBoundToThread(false),
// Extensions
wglCreateContextAttribsARB(nullptr), wglChoosePixelFormatARB(nullptr)
{

}

Win32POGLDeviceContext::~Win32POGLDeviceContext()
{
	if (mRenderContext != nullptr) {
		wglDeleteContext(mRenderContext);
		mRenderContext = nullptr;
	}
}

bool Win32POGLDeviceContext::Initialize(Win32POGLDeviceContext* parentContext)
{
	// Activate the legacy render context (which is supplied in the constructor) so
	// that we can retrieve the necessary extensions
	wglMakeCurrent(mDeviceContext, mRenderContext);
	mRenderContext = nullptr;
	LoadExtensions();
	wglMakeCurrent(nullptr, nullptr);

	//
	// Verify that your graphics card support OpenGL 3.3
	//

	if (wglCreateContextAttribsARB == nullptr) {
		wglMakeCurrent(nullptr, nullptr);
		return false;
	}

	//
	// Set neccessary attributes so that we get an OpenGL 3.3 render context
	//

	std::vector<int> attributes;
	attributes.push_back(WGL_CONTEXT_MAJOR_VERSION_ARB); attributes.push_back(3);
	attributes.push_back(WGL_CONTEXT_MINOR_VERSION_ARB); attributes.push_back(3);
	attributes.push_back(WGL_CONTEXT_PROFILE_MASK_ARB); attributes.push_back(WGL_CONTEXT_CORE_PROFILE_BIT_ARB);
	if (BIT_ISSET(mDevice->GetDeviceInfo()->flags, POGLDeviceInfoFlags::DEBUG_MODE)) {
		attributes.push_back(WGL_CONTEXT_FLAGS_ARB); attributes.push_back(WGL_CONTEXT_DEBUG_BIT_ARB);
	}
	attributes.push_back(0); attributes.push_back(0);

	//
	// Create an OpenGL 3.3 render context
	//

	mRenderContext = (*wglCreateContextAttribsARB)(mDeviceContext, parentContext != nullptr ? parentContext->GetHandlePtr() : 0, &attributes[0]);
	if (mRenderContext == nullptr)
		return false;

	return true;
}

void Win32POGLDeviceContext::Bind()
{
	if (!mBoundToThread) {
		wglMakeCurrent(mDeviceContext, mRenderContext);
		mBoundToThread = true;

		// Make sure to load the extensions from the new library
		LoadExtensions();

		InitializeRenderState();
	}
}

void Win32POGLDeviceContext::Unbind()
{
	assert_with_message(mBoundToThread, "Why is this not bound to the current thread?");
	wglMakeCurrent(0, 0);
	mBoundToThread = false;
}

void Win32POGLDeviceContext::LoadExtensions()
{
	SET_EXTENSION_FUNC(PFNWGLCREATECONTEXTATTRIBSARBPROC, wglCreateContextAttribsARB);
	SET_EXTENSION_FUNC(PFNWGLCHOOSEPIXELFORMATARBPROC, wglChoosePixelFormatARB);

	POGLDeviceContext::LoadExtensions();
}

void* Win32POGLDeviceContext::GetProcAddress(const char* functionName)
{
	return wglGetProcAddress(functionName);
}
<|endoftext|>


<commit_before>#include "scheduler.h"
#include "../task/taskexecutor.h"
#include "../log/logger.h"

#include <QDir>
#include <QTimer>
#include <QCoreApplication>
#include <QDebug>
#include <QPointer>

LOGGER(Scheduler);

class Scheduler::Private : public QObject
{
    Q_OBJECT

public:
    Private(Scheduler* q)
    : q(q)
    , path(qApp->applicationDirPath())
    {
        timer.setSingleShot(true);
        connect(&timer, SIGNAL(timeout()), this, SLOT(timeout()));
    }

    Scheduler* q;

    // Properties
    QDir path;
    QTimer timer;
    TestDefinitionList tests;

    QPointer<TaskExecutor> executor;

    // Functions
    void updateTimer();
    int enqueue(const TestDefinitionPtr &testDefinition);

public slots:
    void timeout();
};

void Scheduler::Private::updateTimer()
{
    if (tests.isEmpty()) {
        timer.stop();
        LOG_DEBUG("Scheduling timer stopped");
    } else {
        const TestDefinitionPtr td = tests.at(0);
        int ms = td->timing()->timeLeft();
        if ( ms > 0 )
            timer.start( ms );
        else {
            // If we would call timeout() directly, the testAdded() signal
            // would be emitted after execution.
            timer.start(1);
        }

        LOG_DEBUG(QString("Scheduling timer executes %1 in %2 ms").arg(td->name()).arg(ms));
    }
}

int Scheduler::Private::enqueue(const TestDefinitionPtr& testDefinition)
{
    bool wasEmpty = tests.isEmpty();

    int timeLeft = testDefinition->timing()->timeLeft();

    for(int i=0; i < tests.size(); ++i) {
        const TestDefinitionPtr& td = tests.at(i);
        if (timeLeft < td->timing()->timeLeft()) {
            tests.insert(i, testDefinition);

            if ( wasEmpty || i == 0 )
                updateTimer();

            return i;
        }
    }

    tests.append(testDefinition);

    if ( wasEmpty )
        updateTimer();

    return tests.size()-1;
}

void Scheduler::Private::timeout()
{
    for(int i=0; i < tests.size(); ++i) {
        TestDefinitionPtr td = tests.at(i);

        // We assume they are already sorted - WRONG, SO WRONG!
        if ( td->timing()->timeLeft() > 0 )
            continue;

        q->execute(td);

        tests.removeAt(i);

        if (!td->timing()->reset()) {
            emit q->testRemoved(td, i);

            if (tests.isEmpty())
                break;
            else
                --i;
        } else {
            int pos = enqueue(td);
            if (pos != i) {
                LOG_DEBUG(QString("%1 moved from %2 to %3").arg(td->name()).arg(i).arg(pos));
                emit q->testMoved(td, i, pos);
            }
        }
    }

    updateTimer();
}

Scheduler::Scheduler()
: d(new Private(this))
{
}

Scheduler::~Scheduler()
{
    delete d;
}

void Scheduler::setExecutor(TaskExecutor *executor)
{
    d->executor = executor;
}

TaskExecutor *Scheduler::executor() const
{
    return d->executor;
}

TestDefinitionList Scheduler::tests() const
{
    return d->tests;
}

void Scheduler::enqueue(const TestDefinitionPtr &testDefinition)
{
    int pos = d->enqueue(testDefinition);
    emit testAdded(testDefinition, pos);
}

void Scheduler::dequeue()
{
    // Whatever
}

void Scheduler::execute(const TestDefinitionPtr &testDefinition)
{
    d->executor->execute(testDefinition);
}

#include "scheduler.moc"
<commit_msg>Fixes #19: Duplicate Tasks are not sorted out by scheduler<commit_after>#include "scheduler.h"
#include "../task/taskexecutor.h"
#include "../log/logger.h"

#include <QDir>
#include <QTimer>
#include <QCoreApplication>
#include <QDebug>
#include <QPointer>
#include <QSet>

LOGGER(Scheduler);

class Scheduler::Private : public QObject
{
    Q_OBJECT

public:
    Private(Scheduler* q)
    : q(q)
    , path(qApp->applicationDirPath())
    {
        timer.setSingleShot(true);
        connect(&timer, SIGNAL(timeout()), this, SLOT(timeout()));
    }

    Scheduler* q;

    // Properties
    QDir path;
    QTimer timer;

    TestDefinitionList tests;
    QSet<QUuid> testIds;

    QPointer<TaskExecutor> executor;

    // Functions
    void updateTimer();
    int enqueue(const TestDefinitionPtr &testDefinition);

public slots:
    void timeout();
};

void Scheduler::Private::updateTimer()
{
    if (tests.isEmpty()) {
        timer.stop();
        LOG_DEBUG("Scheduling timer stopped");
    } else {
        const TestDefinitionPtr td = tests.at(0);
        int ms = td->timing()->timeLeft();
        if ( ms > 0 )
            timer.start( ms );
        else {
            // If we would call timeout() directly, the testAdded() signal
            // would be emitted after execution.
            timer.start(1);
        }

        LOG_DEBUG(QString("Scheduling timer executes %1 in %2 ms").arg(td->name()).arg(ms));
    }
}

int Scheduler::Private::enqueue(const TestDefinitionPtr& testDefinition)
{
    if ( testIds.contains(testDefinition->id()) )
        return -1;

    bool wasEmpty = tests.isEmpty();

    int timeLeft = testDefinition->timing()->timeLeft();

    for(int i=0; i < tests.size(); ++i) {
        const TestDefinitionPtr& td = tests.at(i);
        if (timeLeft < td->timing()->timeLeft()) {
            tests.insert(i, testDefinition);
            testIds.insert(testDefinition->id());

            if ( wasEmpty || i == 0 )
                updateTimer();

            return i;
        }
    }

    tests.append(testDefinition);

    if ( wasEmpty )
        updateTimer();

    return tests.size()-1;
}

void Scheduler::Private::timeout()
{
    for(int i=0; i < tests.size(); ++i) {
        TestDefinitionPtr td = tests.at(i);

        // We assume they are already sorted - WRONG, SO WRONG!
        if ( td->timing()->timeLeft() > 0 )
            continue;

        q->execute(td);

        tests.removeAt(i);

        if (!td->timing()->reset()) {
            emit q->testRemoved(td, i);
            testIds.remove(td->id());

            if (tests.isEmpty())
                break;
            else
                --i;
        } else {
            int pos = enqueue(td);
            if (pos != i) {
                LOG_DEBUG(QString("%1 moved from %2 to %3").arg(td->name()).arg(i).arg(pos));
                emit q->testMoved(td, i, pos);
            }
        }
    }

    updateTimer();
}

Scheduler::Scheduler()
: d(new Private(this))
{
}

Scheduler::~Scheduler()
{
    delete d;
}

void Scheduler::setExecutor(TaskExecutor *executor)
{
    d->executor = executor;
}

TaskExecutor *Scheduler::executor() const
{
    return d->executor;
}

TestDefinitionList Scheduler::tests() const
{
    return d->tests;
}

void Scheduler::enqueue(const TestDefinitionPtr &testDefinition)
{
    int pos = d->enqueue(testDefinition);
    emit testAdded(testDefinition, pos);
}

void Scheduler::dequeue()
{
    // Whatever
}

void Scheduler::execute(const TestDefinitionPtr &testDefinition)
{
    d->executor->execute(testDefinition);
}

#include "scheduler.moc"
<|endoftext|>


<commit_before><commit_msg>user name changed<commit_after><|endoftext|>