<commit_before>/****************************************************************************
 * Copyright (c) 2012-2018 by the DataTransferKit authors                   *
 * All rights reserved.                                                     *
 *                                                                          *
 * This file is part of the DataTransferKit library. DataTransferKit is     *
 * distributed under a BSD 3-clause license. For the licensing terms see    *
 * the LICENSE file in the top-level directory.                             *
 *                                                                          *
 * SPDX-License-Identifier: BSD-3-Clause                                    *
 ****************************************************************************/
/*!
 * \file
 * \brief C adapter to DTK Maps.
 */
#ifndef DTK_C_API_MAP_HPP
#define DTK_C_API_MAP_HPP

#include <DTK_C_API.h>
#include <DTK_C_API.hpp>
#include <DTK_MovingLeastSquaresOperator.hpp>
#include <DTK_NearestNeighborOperator.hpp>
#include <DTK_ParallelTraits.hpp>
#include <DTK_PointCloudOperator.hpp>
#include <DTK_UserApplication.hpp>

#include <Teuchos_DefaultMpiComm.hpp>

#include <boost/property_tree/json_parser.hpp>
#include <boost/property_tree/ptree.hpp>

#include <mpi.h>

#include <memory>
#include <string>
#include <tuple>

namespace DataTransferKit
{
//---------------------------------------------------------------------------//
// Map interface base class. This allows us to hide the device template
// parameter in MapImpl when we do the casting in the C interface
// implementation. We won't know what device type we have in a template when
// calling the C interface and we don't need to - the apply function
// implementation details will dispatch to the correct device type based on
// the construction.
struct DTK_Map
{
    virtual ~DTK_Map() = default;

    virtual void apply( const std::string &source_field_name,
                        const std::string &target_field_name ) = 0;
};

//---------------------------------------------------------------------------//
template <class MapExecSpace, class SourceMemSpace, class TargetMemSpace>
struct DTK_MapImpl : public DTK_Map
{
    using map_device_type = typename MapExecSpace::device_type;

    DTK_MapImpl( MPI_Comm comm, DTK_UserApplicationHandle source,
                 DTK_UserApplicationHandle target,
                 boost::property_tree::ptree const &ptree )
        : _source( reinterpret_cast<DTK_Registry *>( source )->_registry )
        , _target( reinterpret_cast<DTK_Registry *>( target )->_registry )
    {
        // Create a Teuchos comm from the MPI comm.
        auto teuchos_comm = Teuchos::rcp( new Teuchos::MpiComm<int>( comm ) );

        // FOR NOW JUST CREATE A NEAREST NEIGHBOR OPERATOR FOR DEMONSTRATION
        // PURPOSES. THIS WILL BE REPLACED BY A PROPER FACTORY.

        // Get coordinates from the source and target.
        auto source_nodes = _source.getNodeList().coordinates;
        auto target_nodes = _target.getNodeList().coordinates;

        // For now things are layout left in the interface so copy to a
        // matching layout that is compatible with the operator.
        Kokkos::View<Coordinate **, map_device_type> source_nodes_copy(
            "src_nodes_copy", source_nodes.extent( 0 ),
            source_nodes.extent( 1 ) );
        Kokkos::deep_copy( source_nodes_copy, source_nodes );
        Kokkos::View<Coordinate **, map_device_type> target_nodes_copy(
            "tgt_nodes_copy", target_nodes.extent( 0 ),
            target_nodes.extent( 1 ) );
        Kokkos::deep_copy( target_nodes_copy, target_nodes );

        // Create a nearest neighbor operator.
        _map = std::unique_ptr<NearestNeighborOperator<map_device_type>>(
            new NearestNeighborOperator<map_device_type>(
                teuchos_comm, source_nodes_copy, target_nodes_copy ) );
    }

    void apply( const std::string &source_field_name,
                const std::string &target_field_name ) override
    {
        // Create fields.
        auto source_field = _source.getField( source_field_name );
        auto target_field = _target.getField( target_field_name );

        // Pull the data from the source.
        _source.pullField( source_field_name, source_field );

        // Copy to a compatible layout. Nearest neighbor operator needs a
        // compatible layout and only 1 dimension
        int num_src = source_field.dofs.extent( 0 );
        Kokkos::View<double *, map_device_type> source_field_copy(
            "source_field_copy", num_src );
        Kokkos::deep_copy(
            source_field_copy,
            Kokkos::subview( source_field.dofs, Kokkos::ALL, 0 ) );
        int num_tgt = target_field.dofs.extent( 0 );
        Kokkos::View<double *, map_device_type> target_field_copy(
            "target_field_copy", num_tgt );

        // Apply the map.
        _map->apply( source_field_copy, target_field_copy );

        // Copy the transferred field back to the original target layout.
        Kokkos::deep_copy( Kokkos::subview( target_field.dofs, Kokkos::ALL, 0 ),
                           target_field_copy );

        // Push the data to the target.
        _target.pushField( target_field_name, target_field );
    }

    UserApplication<double, SourceMemSpace> _source;
    UserApplication<double, TargetMemSpace> _target;
    std::unique_ptr<PointCloudOperator<map_device_type>> _map;
};

//---------------------------------------------------------------------------//
// Execution space validation.
bool validExecutionSpace( DTK_ExecutionSpace space )
{
    switch ( space )
    {
    case DTK_SERIAL:
#if defined( KOKKOS_ENABLE_SERIAL )
        return true;
        break;
#else
        return false;
        break;
#endif

    case DTK_OPENMP:
#if defined( KOKKOS_ENABLE_OPENMP )
        return true;
        break;
#else
        return false;
        break;
#endif

    case DTK_CUDA:
#if defined( KOKKOS_ENABLE_CUDA )
        return true;
        break;
#else
        return false;
        break;
#endif
    default:
        return false;
        break;
    }
}

// Memory space validation.
bool validMemorySpace( DTK_MemorySpace space )
{
    switch ( space )
    {
    case DTK_HOST_SPACE:
#if defined( KOKKOS_ENABLE_SERIAL ) || defined( KOKKOS_ENABLE_OPENMP )
        return true;
        break;
#else
        return false;
        break;
#endif
    case DTK_CUDAUVM_SPACE:
#if defined( KOKKOS_ENABLE_CUDA )
        return true;
        break;
#else
        return false;
        break;
#endif
    default:
        return false;
        break;
    }
}

// Map space validation.
bool validMapSpaces( DTK_ExecutionSpace map_space, DTK_MemorySpace source_space,
                     DTK_MemorySpace target_space )
{
    return validExecutionSpace( map_space ) &&
           validMemorySpace( source_space ) && validMemorySpace( target_space );
}

//---------------------------------------------------------------------------//
// Create a map.
DTK_Map *createMap( DTK_ExecutionSpace map_space, MPI_Comm comm,
                    DTK_UserApplicationHandle source,
                    DTK_UserApplicationHandle target, const char *options )
{
    // Parse options.
    std::stringstream ss;
    ss.str( options );
    boost::property_tree::ptree ptree;
    boost::property_tree::read_json( ss, ptree );

    // Get the map type.
    const std::string map_type( ptree.get<std::string>( "Map Type" ) );

    // Until a factory is added only nearest neighbor is supported.
    DTK_INSIST( "Nearest Neighbor" == map_type );

    // Get the user source and target memory spaces.
    DTK_MemorySpace src_space =
        reinterpret_cast<DataTransferKit::DTK_Registry *>( source )->_space;
    DTK_MemorySpace tgt_space =
        reinterpret_cast<DataTransferKit::DTK_Registry *>( target )->_space;

    // Check up front that we have been asked for execution and memory spaces
    // that are available in the kokkos build. This lets use a little cleaner
    // macro logic below because we know we will get a valid map space
    // already.
    DTK_INSIST( validMapSpaces( map_space, src_space, tgt_space ) );

    DTK_Map *map;
    switch ( map_space )
    {
    case DTK_SERIAL:
#if defined( KOKKOS_ENABLE_SERIAL )
        switch ( src_space )
        {
        case DTK_HOST_SPACE:
            switch ( tgt_space )
            {
            case DTK_HOST_SPACE:
                map = new DTK_MapImpl<Serial, HostSpace, HostSpace>(
                    comm, source, target, ptree );
                break;

            case DTK_CUDAUVM_SPACE:
#if defined( KOKKOS_ENABLE_CUDA )
                map = new DTK_MapImpl<Serial, HostSpace, CudaUVMSpace>(
                    comm, source, target, ptree );
#endif
                break;
            }
            break;

        case DTK_CUDAUVM_SPACE:
#if defined( KOKKOS_ENABLE_CUDA )
            switch ( tgt_space )
            {
            case DTK_HOST_SPACE:
                map = new DTK_MapImpl<Serial, CudaUVMSpace, HostSpace>(
                    comm, source, target, ptree );
                break;

            case DTK_CUDAUVM_SPACE:
                map = new DTK_MapImpl<Serial, CudaUVMSpace, CudaUVMSpace>(
                    comm, source, target, ptree );
                break;
            }
#endif
            break;
        }
#endif
        break;

    case DTK_OPENMP:
#if defined( KOKKOS_ENABLE_OPENMP )
        switch ( src_space )
        {
        case DTK_HOST_SPACE:
            switch ( tgt_space )
            {
            case DTK_HOST_SPACE:
                map = new DTK_MapImpl<OpenMP, HostSpace, HostSpace>(
                    comm, source, target, ptree );
                break;

            case DTK_CUDAUVM_SPACE:
#if defined( KOKKOS_ENABLE_CUDA )
                map = new DTK_MapImpl<OpenMP, HostSpace, CudaUVMSpace>(
                    comm, source, target, ptree );
#endif
                break;
            }
            break;

        case DTK_CUDAUVM_SPACE:
#if defined( KOKKOS_ENABLE_CUDA )
            switch ( tgt_space )
            {
            case DTK_HOST_SPACE:
                map = new DTK_MapImpl<OpenMP, CudaUVMSpace, HostSpace>(
                    comm, source, target, ptree );
                break;

            case DTK_CUDAUVM_SPACE:
                map = new DTK_MapImpl<OpenMP, CudaUVMSpace, CudaUVMSpace>(
                    comm, source, target, ptree );
                break;
            }
#endif
            break;
        }
#endif
        break;

    case DTK_CUDA:
#if defined( KOKKOS_ENABLE_CUDA )
        switch ( src_space )
        {
        case DTK_HOST_SPACE:
#if defined( KOKKOS_ENABLE_SERIAL ) || defined( KOKKOS_ENABLE_OPENMP )
            switch ( tgt_space )
            {
            case DTK_HOST_SPACE:
                map = new DTK_MapImpl<Cuda, HostSpace, HostSpace>(
                    comm, source, target, ptree );
                break;

            case DTK_CUDAUVM_SPACE:
                map = new DTK_MapImpl<Cuda, HostSpace, CudaUVMSpace>(
                    comm, source, target, ptree );
                break;
            }
#endif
            break;

        case DTK_CUDAUVM_SPACE:
            switch ( tgt_space )
            {
            case DTK_HOST_SPACE:
#if defined( KOKKOS_ENABLE_SERIAL ) || defined( KOKKOS_ENABLE_OPENMP )
                map = new DTK_MapImpl<Cuda, CudaUVMSpace, HostSpace>(
                    comm, source, target, ptree );
#endif
                break;
            case DTK_CUDAUVM_SPACE:
                map = new DTK_MapImpl<Cuda, CudaUVMSpace, CudaUVMSpace>(
                    comm, source, target, ptree );
                break;
            }
            break;
        }
#endif
        break;
    }

    return map;
}

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

} // namespace DataTransferKit

#endif // DTK_C_API_MAP_HPP
<commit_msg>Get map type to create from the property tree<commit_after>/****************************************************************************
 * Copyright (c) 2012-2018 by the DataTransferKit authors                   *
 * All rights reserved.                                                     *
 *                                                                          *
 * This file is part of the DataTransferKit library. DataTransferKit is     *
 * distributed under a BSD 3-clause license. For the licensing terms see    *
 * the LICENSE file in the top-level directory.                             *
 *                                                                          *
 * SPDX-License-Identifier: BSD-3-Clause                                    *
 ****************************************************************************/
/*!
 * \file
 * \brief C adapter to DTK Maps.
 */
#ifndef DTK_C_API_MAP_HPP
#define DTK_C_API_MAP_HPP

#include <DTK_C_API.h>
#include <DTK_C_API.hpp>
#include <DTK_MovingLeastSquaresOperator.hpp>
#include <DTK_NearestNeighborOperator.hpp>
#include <DTK_ParallelTraits.hpp>
#include <DTK_PointCloudOperator.hpp>
#include <DTK_UserApplication.hpp>

#include <Teuchos_DefaultMpiComm.hpp>

#include <boost/property_tree/json_parser.hpp>
#include <boost/property_tree/ptree.hpp>

#include <mpi.h>

#include <memory>
#include <string>
#include <tuple>

namespace DataTransferKit
{
//---------------------------------------------------------------------------//
// Map interface base class. This allows us to hide the device template
// parameter in MapImpl when we do the casting in the C interface
// implementation. We won't know what device type we have in a template when
// calling the C interface and we don't need to - the apply function
// implementation details will dispatch to the correct device type based on
// the construction.
struct DTK_Map
{
    virtual ~DTK_Map() = default;

    virtual void apply( const std::string &source_field_name,
                        const std::string &target_field_name ) = 0;
};

//---------------------------------------------------------------------------//
template <class MapExecSpace, class SourceMemSpace, class TargetMemSpace>
struct DTK_MapImpl : public DTK_Map
{
    using map_device_type = typename MapExecSpace::device_type;

    DTK_MapImpl( MPI_Comm comm, DTK_UserApplicationHandle source,
                 DTK_UserApplicationHandle target,
                 boost::property_tree::ptree const &ptree )
        : _source( reinterpret_cast<DTK_Registry *>( source )->_registry )
        , _target( reinterpret_cast<DTK_Registry *>( target )->_registry )
    {
        // Create a Teuchos comm from the MPI comm.
        auto teuchos_comm = Teuchos::rcp( new Teuchos::MpiComm<int>( comm ) );

        // FOR NOW JUST CREATE A NEAREST NEIGHBOR OPERATOR FOR DEMONSTRATION
        // PURPOSES. THIS WILL BE REPLACED BY A PROPER FACTORY.

        // Get coordinates from the source and target.
        auto source_nodes = _source.getNodeList().coordinates;
        auto target_nodes = _target.getNodeList().coordinates;

        // For now things are layout left in the interface so copy to a
        // matching layout that is compatible with the operator.
        Kokkos::View<Coordinate **, map_device_type> source_nodes_copy(
            "src_nodes_copy", source_nodes.extent( 0 ),
            source_nodes.extent( 1 ) );
        Kokkos::deep_copy( source_nodes_copy, source_nodes );
        Kokkos::View<Coordinate **, map_device_type> target_nodes_copy(
            "tgt_nodes_copy", target_nodes.extent( 0 ),
            target_nodes.extent( 1 ) );
        Kokkos::deep_copy( target_nodes_copy, target_nodes );

        auto const which_map = ptree.get<std::string>( "Map Type" );
        if ( which_map == "Nearest Neighbor" || which_map == "NN" )
            _map = std::unique_ptr<NearestNeighborOperator<map_device_type>>(
                new NearestNeighborOperator<map_device_type>(
                    teuchos_comm, source_nodes_copy, target_nodes_copy ) );
    }

    void apply( const std::string &source_field_name,
                const std::string &target_field_name ) override
    {
        // Create fields.
        auto source_field = _source.getField( source_field_name );
        auto target_field = _target.getField( target_field_name );

        // Pull the data from the source.
        _source.pullField( source_field_name, source_field );

        // Copy to a compatible layout. Nearest neighbor operator needs a
        // compatible layout and only 1 dimension
        int num_src = source_field.dofs.extent( 0 );
        Kokkos::View<double *, map_device_type> source_field_copy(
            "source_field_copy", num_src );
        Kokkos::deep_copy(
            source_field_copy,
            Kokkos::subview( source_field.dofs, Kokkos::ALL, 0 ) );
        int num_tgt = target_field.dofs.extent( 0 );
        Kokkos::View<double *, map_device_type> target_field_copy(
            "target_field_copy", num_tgt );

        // Apply the map.
        _map->apply( source_field_copy, target_field_copy );

        // Copy the transferred field back to the original target layout.
        Kokkos::deep_copy( Kokkos::subview( target_field.dofs, Kokkos::ALL, 0 ),
                           target_field_copy );

        // Push the data to the target.
        _target.pushField( target_field_name, target_field );
    }

    UserApplication<double, SourceMemSpace> _source;
    UserApplication<double, TargetMemSpace> _target;
    std::unique_ptr<PointCloudOperator<map_device_type>> _map;
};

//---------------------------------------------------------------------------//
// Execution space validation.
bool validExecutionSpace( DTK_ExecutionSpace space )
{
    switch ( space )
    {
    case DTK_SERIAL:
#if defined( KOKKOS_ENABLE_SERIAL )
        return true;
        break;
#else
        return false;
        break;
#endif

    case DTK_OPENMP:
#if defined( KOKKOS_ENABLE_OPENMP )
        return true;
        break;
#else
        return false;
        break;
#endif

    case DTK_CUDA:
#if defined( KOKKOS_ENABLE_CUDA )
        return true;
        break;
#else
        return false;
        break;
#endif
    default:
        return false;
        break;
    }
}

// Memory space validation.
bool validMemorySpace( DTK_MemorySpace space )
{
    switch ( space )
    {
    case DTK_HOST_SPACE:
#if defined( KOKKOS_ENABLE_SERIAL ) || defined( KOKKOS_ENABLE_OPENMP )
        return true;
        break;
#else
        return false;
        break;
#endif
    case DTK_CUDAUVM_SPACE:
#if defined( KOKKOS_ENABLE_CUDA )
        return true;
        break;
#else
        return false;
        break;
#endif
    default:
        return false;
        break;
    }
}

// Map space validation.
bool validMapSpaces( DTK_ExecutionSpace map_space, DTK_MemorySpace source_space,
                     DTK_MemorySpace target_space )
{
    return validExecutionSpace( map_space ) &&
           validMemorySpace( source_space ) && validMemorySpace( target_space );
}

//---------------------------------------------------------------------------//
// Create a map.
DTK_Map *createMap( DTK_ExecutionSpace map_space, MPI_Comm comm,
                    DTK_UserApplicationHandle source,
                    DTK_UserApplicationHandle target, const char *options )
{
    // Parse options.
    std::stringstream ss;
    ss.str( options );
    boost::property_tree::ptree ptree;
    boost::property_tree::read_json( ss, ptree );

    // Get the map type.
    const std::string map_type( ptree.get<std::string>( "Map Type" ) );

    // Until a factory is added only nearest neighbor is supported.
    DTK_INSIST( "Nearest Neighbor" == map_type );

    // Get the user source and target memory spaces.
    DTK_MemorySpace src_space =
        reinterpret_cast<DataTransferKit::DTK_Registry *>( source )->_space;
    DTK_MemorySpace tgt_space =
        reinterpret_cast<DataTransferKit::DTK_Registry *>( target )->_space;

    // Check up front that we have been asked for execution and memory spaces
    // that are available in the kokkos build. This lets use a little cleaner
    // macro logic below because we know we will get a valid map space
    // already.
    DTK_INSIST( validMapSpaces( map_space, src_space, tgt_space ) );

    DTK_Map *map;
    switch ( map_space )
    {
    case DTK_SERIAL:
#if defined( KOKKOS_ENABLE_SERIAL )
        switch ( src_space )
        {
        case DTK_HOST_SPACE:
            switch ( tgt_space )
            {
            case DTK_HOST_SPACE:
                map = new DTK_MapImpl<Serial, HostSpace, HostSpace>(
                    comm, source, target, ptree );
                break;

            case DTK_CUDAUVM_SPACE:
#if defined( KOKKOS_ENABLE_CUDA )
                map = new DTK_MapImpl<Serial, HostSpace, CudaUVMSpace>(
                    comm, source, target, ptree );
#endif
                break;
            }
            break;

        case DTK_CUDAUVM_SPACE:
#if defined( KOKKOS_ENABLE_CUDA )
            switch ( tgt_space )
            {
            case DTK_HOST_SPACE:
                map = new DTK_MapImpl<Serial, CudaUVMSpace, HostSpace>(
                    comm, source, target, ptree );
                break;

            case DTK_CUDAUVM_SPACE:
                map = new DTK_MapImpl<Serial, CudaUVMSpace, CudaUVMSpace>(
                    comm, source, target, ptree );
                break;
            }
#endif
            break;
        }
#endif
        break;

    case DTK_OPENMP:
#if defined( KOKKOS_ENABLE_OPENMP )
        switch ( src_space )
        {
        case DTK_HOST_SPACE:
            switch ( tgt_space )
            {
            case DTK_HOST_SPACE:
                map = new DTK_MapImpl<OpenMP, HostSpace, HostSpace>(
                    comm, source, target, ptree );
                break;

            case DTK_CUDAUVM_SPACE:
#if defined( KOKKOS_ENABLE_CUDA )
                map = new DTK_MapImpl<OpenMP, HostSpace, CudaUVMSpace>(
                    comm, source, target, ptree );
#endif
                break;
            }
            break;

        case DTK_CUDAUVM_SPACE:
#if defined( KOKKOS_ENABLE_CUDA )
            switch ( tgt_space )
            {
            case DTK_HOST_SPACE:
                map = new DTK_MapImpl<OpenMP, CudaUVMSpace, HostSpace>(
                    comm, source, target, ptree );
                break;

            case DTK_CUDAUVM_SPACE:
                map = new DTK_MapImpl<OpenMP, CudaUVMSpace, CudaUVMSpace>(
                    comm, source, target, ptree );
                break;
            }
#endif
            break;
        }
#endif
        break;

    case DTK_CUDA:
#if defined( KOKKOS_ENABLE_CUDA )
        switch ( src_space )
        {
        case DTK_HOST_SPACE:
#if defined( KOKKOS_ENABLE_SERIAL ) || defined( KOKKOS_ENABLE_OPENMP )
            switch ( tgt_space )
            {
            case DTK_HOST_SPACE:
                map = new DTK_MapImpl<Cuda, HostSpace, HostSpace>(
                    comm, source, target, ptree );
                break;

            case DTK_CUDAUVM_SPACE:
                map = new DTK_MapImpl<Cuda, HostSpace, CudaUVMSpace>(
                    comm, source, target, ptree );
                break;
            }
#endif
            break;

        case DTK_CUDAUVM_SPACE:
            switch ( tgt_space )
            {
            case DTK_HOST_SPACE:
#if defined( KOKKOS_ENABLE_SERIAL ) || defined( KOKKOS_ENABLE_OPENMP )
                map = new DTK_MapImpl<Cuda, CudaUVMSpace, HostSpace>(
                    comm, source, target, ptree );
#endif
                break;
            case DTK_CUDAUVM_SPACE:
                map = new DTK_MapImpl<Cuda, CudaUVMSpace, CudaUVMSpace>(
                    comm, source, target, ptree );
                break;
            }
            break;
        }
#endif
        break;
    }

    return map;
}

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

} // namespace DataTransferKit

#endif // DTK_C_API_MAP_HPP
<|endoftext|>


<commit_before>#include "chrono_parallel/collision/ChCCollisionSystemBulletParallel.h"

namespace chrono {
namespace collision {

/*
 void defaultChronoNearCallback(btBroadphasePair& collisionPair, btCollisionDispatcher& dispatcher, btDispatcherInfo& dispatchInfo)
 {
 btCollisionDispatcher::defaultNearCallback(collisionPair, dispatcher, dispatchInfo);
 if (broad_callback)
 broad_callback(collisionPair, dispatcher, dispatchInfo);
 }
*/

ChCollisionSystemBulletParallel::ChCollisionSystemBulletParallel(ChParallelDataManager* dc,
                                                                 unsigned int max_objects,
                                                                 double scene_size)
: data_container(dc)
  {
   // btDefaultCollisionConstructionInfo conf_info(...); ***TODO***
   bt_collision_configuration = new btDefaultCollisionConfiguration();
   bt_dispatcher = new btCollisionDispatcher(bt_collision_configuration);

   //***OLD***

   btScalar sscene_size = (btScalar) scene_size;
   btVector3 worldAabbMin(-sscene_size, -sscene_size, -sscene_size);
   btVector3 worldAabbMax(sscene_size, sscene_size, sscene_size);
   bt_broadphase = new bt32BitAxisSweep3(worldAabbMin, worldAabbMax, max_objects, 0, true);  // true for disabling raycast accelerator

   //***NEW***
   //bt_broadphase = new btDbvtBroadphase();

   bt_collision_world = new btCollisionWorld(bt_dispatcher, bt_broadphase, bt_collision_configuration);

   // custom collision for sphere-sphere case ***OBSOLETE***
   //bt_dispatcher->registerCollisionCreateFunc(SPHERE_SHAPE_PROXYTYPE,SPHERE_SHAPE_PROXYTYPE,new btSphereSphereCollisionAlgorithm::CreateFunc);

   // register custom collision for GIMPACT mesh case too
   btGImpactCollisionAlgorithm::registerAlgorithm(bt_dispatcher);

   counter = 0;
}

ChCollisionSystemBulletParallel::~ChCollisionSystemBulletParallel() {
   if (bt_collision_world)
      delete bt_collision_world;
   if (bt_broadphase)
      delete bt_broadphase;
   if (bt_dispatcher)
      delete bt_dispatcher;
   if (bt_collision_configuration)
      delete bt_collision_configuration;
}

void ChCollisionSystemBulletParallel::Clear(void) {
   int numManifolds = bt_collision_world->getDispatcher()->getNumManifolds();
   for (int i = 0; i < numManifolds; i++) {
      btPersistentManifold* contactManifold = bt_collision_world->getDispatcher()->getManifoldByIndexInternal(i);
      contactManifold->clearManifold();
   }
}

void ChCollisionSystemBulletParallel::Add(ChCollisionModel* model) {
   ChModelBullet* bmodel = static_cast<ChModelBullet*>(model);
   if (bmodel->GetBulletModel()->getCollisionShape()) {
      bmodel->SyncPosition();
      bmodel->GetBulletModel()->setCompanionId(counter);
      bt_collision_world->addCollisionObject(bmodel->GetBulletModel(), bmodel->GetFamilyGroup(), bmodel->GetFamilyMask());
      counter++;
      data_container->num_shapes++;
   }
}

void ChCollisionSystemBulletParallel::Remove(ChCollisionModel* model) {
  ChModelBullet* bmodel = static_cast<ChModelBullet*>(model);
  if (bmodel->GetBulletModel()->getCollisionShape()) {
      bt_collision_world->removeCollisionObject(bmodel->GetBulletModel());
   }
}

void ChCollisionSystemBulletParallel::Run() {
   data_container->system_timer.start("collision_broad");
   if (bt_collision_world) {
      bt_collision_world->performDiscreteCollisionDetection();
   }
   data_container->system_timer.stop("collision_broad");

}
void ChCollisionSystemBulletParallel::ReportContacts(ChContactContainerBase* mcontactcontainer) {
   data_container->system_timer.start("collision_narrow");
   data_container->host_data.norm_rigid_rigid.clear();
   data_container->host_data.cpta_rigid_rigid.clear();
   data_container->host_data.cptb_rigid_rigid.clear();
   data_container->host_data.dpth_rigid_rigid.clear();
   data_container->host_data.bids_rigid_rigid.clear();
   data_container->num_contacts = 0;
   //mcontactcontainer->BeginAddContact();
   ChCollisionInfo icontact;

   int numManifolds = bt_collision_world->getDispatcher()->getNumManifolds();
   for (int i = 0; i < numManifolds; i++) {
      btPersistentManifold* contactManifold = bt_collision_world->getDispatcher()->getManifoldByIndexInternal(i);
      btCollisionObject* obA = static_cast<btCollisionObject*>(contactManifold->getBody0());
      btCollisionObject* obB = static_cast<btCollisionObject*>(contactManifold->getBody1());
      contactManifold->refreshContactPoints(obA->getWorldTransform(), obB->getWorldTransform());

      icontact.modelA = (ChCollisionModel*) obA->getUserPointer();
      icontact.modelB = (ChCollisionModel*) obB->getUserPointer();

      double envelopeA = icontact.modelA->GetEnvelope();
      double envelopeB = icontact.modelB->GetEnvelope();

      double marginA = icontact.modelA->GetSafeMargin();
      double marginB = icontact.modelB->GetSafeMargin();

      bool activeA = ((ChBody*) (icontact.modelA->GetPhysicsItem()))->IsActive();
      bool activeB = ((ChBody*) (icontact.modelB->GetPhysicsItem()))->IsActive();

      if (activeA == 0 && activeB == 0) {
         continue;
      }

      // Execute custom broadphase callback, if any
      bool do_narrow_contactgeneration = true;
      if (this->broad_callback)
         do_narrow_contactgeneration = this->broad_callback->BroadCallback(icontact.modelA, icontact.modelB);

      if (do_narrow_contactgeneration) {
         int numContacts = contactManifold->getNumContacts();

         for (int j = 0; j < numContacts; j++) {
            btManifoldPoint& pt = contactManifold->getContactPoint(j);

            if (pt.getDistance() < marginA + marginB)  // to discard "too far" constraints (the Bullet engine also has its threshold)
                  {

               btVector3 ptA = pt.getPositionWorldOnA();
               btVector3 ptB = pt.getPositionWorldOnB();

               icontact.vpA.Set(ptA.getX(), ptA.getY(), ptA.getZ());
               icontact.vpB.Set(ptB.getX(), ptB.getY(), ptB.getZ());

               icontact.vN.Set(-pt.m_normalWorldOnB.getX(), -pt.m_normalWorldOnB.getY(), -pt.m_normalWorldOnB.getZ());
               icontact.vN.Normalize();

               double ptdist = pt.getDistance();

               icontact.vpA = icontact.vpA - icontact.vN * envelopeA;
               icontact.vpB = icontact.vpB + icontact.vN * envelopeB;

               //Required because parallel code expects the offset to be done before hand, this is for performance reasons later on.
               icontact.vpA = icontact.vpA - ((ChBody*) (icontact.modelA->GetPhysicsItem()))->GetPos();
               icontact.vpB = icontact.vpB - ((ChBody*) (icontact.modelB->GetPhysicsItem()))->GetPos();

               icontact.distance = ptdist + envelopeA + envelopeB;

               icontact.reaction_cache = pt.reactions_cache;

               // Execute some user custom callback, if any
               if (this->narrow_callback)
                  this->narrow_callback->NarrowCallback(icontact);

               // Add to contact container
               //mcontactcontainer->AddContact(icontact);

               data_container->host_data.norm_rigid_rigid.push_back(R3(icontact.vN.x, icontact.vN.y, icontact.vN.z));
               data_container->host_data.cpta_rigid_rigid.push_back(R3(icontact.vpA.x, icontact.vpA.y, icontact.vpA.z));
               data_container->host_data.cptb_rigid_rigid.push_back(R3(icontact.vpB.x, icontact.vpB.y, icontact.vpB.z));
               data_container->host_data.dpth_rigid_rigid.push_back(icontact.distance);
               data_container->host_data.bids_rigid_rigid.push_back(I2(obA->getCompanionId(), obB->getCompanionId()));
               data_container->num_contacts++;

            }

         }
      }
      //you can un-comment out this line, and then all points are removed
      //contactManifold->clearManifold();
   }

   //mcontactcontainer->EndAddContact();
   data_container->system_timer.stop("collision_narrow");
}
}  // END_OF_NAMESPACE____
}  // END_OF_NAMESPACE____

<commit_msg>The contact points for the bullet collision system do not need to be offset.<commit_after>#include "chrono_parallel/collision/ChCCollisionSystemBulletParallel.h"

namespace chrono {
namespace collision {

/*
 void defaultChronoNearCallback(btBroadphasePair& collisionPair, btCollisionDispatcher& dispatcher, btDispatcherInfo& dispatchInfo)
 {
 btCollisionDispatcher::defaultNearCallback(collisionPair, dispatcher, dispatchInfo);
 if (broad_callback)
 broad_callback(collisionPair, dispatcher, dispatchInfo);
 }
*/

ChCollisionSystemBulletParallel::ChCollisionSystemBulletParallel(ChParallelDataManager* dc,
                                                                 unsigned int max_objects,
                                                                 double scene_size)
: data_container(dc)
  {
   // btDefaultCollisionConstructionInfo conf_info(...); ***TODO***
   bt_collision_configuration = new btDefaultCollisionConfiguration();
   bt_dispatcher = new btCollisionDispatcher(bt_collision_configuration);

   //***OLD***

   btScalar sscene_size = (btScalar) scene_size;
   btVector3 worldAabbMin(-sscene_size, -sscene_size, -sscene_size);
   btVector3 worldAabbMax(sscene_size, sscene_size, sscene_size);
   bt_broadphase = new bt32BitAxisSweep3(worldAabbMin, worldAabbMax, max_objects, 0, true);  // true for disabling raycast accelerator

   //***NEW***
   //bt_broadphase = new btDbvtBroadphase();

   bt_collision_world = new btCollisionWorld(bt_dispatcher, bt_broadphase, bt_collision_configuration);

   // custom collision for sphere-sphere case ***OBSOLETE***
   //bt_dispatcher->registerCollisionCreateFunc(SPHERE_SHAPE_PROXYTYPE,SPHERE_SHAPE_PROXYTYPE,new btSphereSphereCollisionAlgorithm::CreateFunc);

   // register custom collision for GIMPACT mesh case too
   btGImpactCollisionAlgorithm::registerAlgorithm(bt_dispatcher);

   counter = 0;
}

ChCollisionSystemBulletParallel::~ChCollisionSystemBulletParallel() {
   if (bt_collision_world)
      delete bt_collision_world;
   if (bt_broadphase)
      delete bt_broadphase;
   if (bt_dispatcher)
      delete bt_dispatcher;
   if (bt_collision_configuration)
      delete bt_collision_configuration;
}

void ChCollisionSystemBulletParallel::Clear(void) {
   int numManifolds = bt_collision_world->getDispatcher()->getNumManifolds();
   for (int i = 0; i < numManifolds; i++) {
      btPersistentManifold* contactManifold = bt_collision_world->getDispatcher()->getManifoldByIndexInternal(i);
      contactManifold->clearManifold();
   }
}

void ChCollisionSystemBulletParallel::Add(ChCollisionModel* model) {
   ChModelBullet* bmodel = static_cast<ChModelBullet*>(model);
   if (bmodel->GetBulletModel()->getCollisionShape()) {
      bmodel->SyncPosition();
      bmodel->GetBulletModel()->setCompanionId(counter);
      bt_collision_world->addCollisionObject(bmodel->GetBulletModel(), bmodel->GetFamilyGroup(), bmodel->GetFamilyMask());
      counter++;
      data_container->num_shapes++;
   }
}

void ChCollisionSystemBulletParallel::Remove(ChCollisionModel* model) {
  ChModelBullet* bmodel = static_cast<ChModelBullet*>(model);
  if (bmodel->GetBulletModel()->getCollisionShape()) {
      bt_collision_world->removeCollisionObject(bmodel->GetBulletModel());
   }
}

void ChCollisionSystemBulletParallel::Run() {
   data_container->system_timer.start("collision_broad");
   if (bt_collision_world) {
      bt_collision_world->performDiscreteCollisionDetection();
   }
   data_container->system_timer.stop("collision_broad");

}
void ChCollisionSystemBulletParallel::ReportContacts(ChContactContainerBase* mcontactcontainer) {
   data_container->system_timer.start("collision_narrow");
   data_container->host_data.norm_rigid_rigid.clear();
   data_container->host_data.cpta_rigid_rigid.clear();
   data_container->host_data.cptb_rigid_rigid.clear();
   data_container->host_data.dpth_rigid_rigid.clear();
   data_container->host_data.bids_rigid_rigid.clear();
   data_container->num_contacts = 0;
   //mcontactcontainer->BeginAddContact();
   ChCollisionInfo icontact;

   int numManifolds = bt_collision_world->getDispatcher()->getNumManifolds();
   for (int i = 0; i < numManifolds; i++) {
      btPersistentManifold* contactManifold = bt_collision_world->getDispatcher()->getManifoldByIndexInternal(i);
      btCollisionObject* obA = static_cast<btCollisionObject*>(contactManifold->getBody0());
      btCollisionObject* obB = static_cast<btCollisionObject*>(contactManifold->getBody1());
      contactManifold->refreshContactPoints(obA->getWorldTransform(), obB->getWorldTransform());

      icontact.modelA = (ChCollisionModel*) obA->getUserPointer();
      icontact.modelB = (ChCollisionModel*) obB->getUserPointer();

      double envelopeA = icontact.modelA->GetEnvelope();
      double envelopeB = icontact.modelB->GetEnvelope();

      double marginA = icontact.modelA->GetSafeMargin();
      double marginB = icontact.modelB->GetSafeMargin();

      bool activeA = ((ChBody*) (icontact.modelA->GetPhysicsItem()))->IsActive();
      bool activeB = ((ChBody*) (icontact.modelB->GetPhysicsItem()))->IsActive();

      if (activeA == 0 && activeB == 0) {
         continue;
      }

      // Execute custom broadphase callback, if any
      bool do_narrow_contactgeneration = true;
      if (this->broad_callback)
         do_narrow_contactgeneration = this->broad_callback->BroadCallback(icontact.modelA, icontact.modelB);

      if (do_narrow_contactgeneration) {
         int numContacts = contactManifold->getNumContacts();

         for (int j = 0; j < numContacts; j++) {
            btManifoldPoint& pt = contactManifold->getContactPoint(j);

            if (pt.getDistance() < marginA + marginB)  // to discard "too far" constraints (the Bullet engine also has its threshold)
                  {

               btVector3 ptA = pt.getPositionWorldOnA();
               btVector3 ptB = pt.getPositionWorldOnB();

               icontact.vpA.Set(ptA.getX(), ptA.getY(), ptA.getZ());
               icontact.vpB.Set(ptB.getX(), ptB.getY(), ptB.getZ());

               icontact.vN.Set(-pt.m_normalWorldOnB.getX(), -pt.m_normalWorldOnB.getY(), -pt.m_normalWorldOnB.getZ());
               icontact.vN.Normalize();

               double ptdist = pt.getDistance();

               icontact.vpA = icontact.vpA - icontact.vN * envelopeA;
               icontact.vpB = icontact.vpB + icontact.vN * envelopeB;

               icontact.distance = ptdist + envelopeA + envelopeB;

               icontact.reaction_cache = pt.reactions_cache;

               // Execute some user custom callback, if any
               if (this->narrow_callback)
                  this->narrow_callback->NarrowCallback(icontact);

               // Add to contact container
               //mcontactcontainer->AddContact(icontact);

               data_container->host_data.norm_rigid_rigid.push_back(R3(icontact.vN.x, icontact.vN.y, icontact.vN.z));
               data_container->host_data.cpta_rigid_rigid.push_back(R3(icontact.vpA.x, icontact.vpA.y, icontact.vpA.z));
               data_container->host_data.cptb_rigid_rigid.push_back(R3(icontact.vpB.x, icontact.vpB.y, icontact.vpB.z));
               data_container->host_data.dpth_rigid_rigid.push_back(icontact.distance);
               data_container->host_data.bids_rigid_rigid.push_back(I2(obA->getCompanionId(), obB->getCompanionId()));
               data_container->num_contacts++;

            }

         }
      }
      //you can un-comment out this line, and then all points are removed
      //contactManifold->clearManifold();
   }

   //mcontactcontainer->EndAddContact();
   data_container->system_timer.stop("collision_narrow");
}
}  // END_OF_NAMESPACE____
}  // END_OF_NAMESPACE____

<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/utils/imageProcs/p9_tor.H $               */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
#ifndef _P9_TOR_H_
#define _P9_TOR_H_

#include "p9_ring_identification.H"
#include "p9_ringId.H"
#include "p9_infrastruct_help.H"
#include "p9_xip_image.h"

#define NUM_RING_IDS              P9_NUM_RINGS

typedef struct
{
    uint32_t sizeOfThis;
    uint16_t sizeOfCmsk;
    uint16_t sizeOfMeta; // Exact size of meta data. Arbitrary size. Not null terminated.
} RingLayout_t;

//
// Temporary define until in TOR header by Giri.
//
//
// Temporary define until in TOR header by Giri.
//
typedef struct
{
    uint32_t TorNumDdLevels;
    uint32_t reserved;
} TorNumDdLevels_t;

typedef struct
{
    uint32_t TorDdLevelAndOffset;
    uint32_t TorDdBlockSize;
} TorDdLevelBlock_t;

typedef struct
{
    uint32_t TorPpeTypeOffset;
    uint32_t TorPpeBlockSize;
} TorPpeBlock_t;

#define MAX_CPLT_SBE                                  13
#define IMGBUILD_TGR_RING_FOUND                        0
#define IMGBUILD_TGR_RING_BLOCKS_FOUND                 0
#define IMGBUILD_TGR_RING_NOT_FOUND                    1  // Ring is not found in HW image.
#define IMGBUILD_TGR_INVALID_RING_ID                   2  // Ring is invalid or mismatch.
#define IMGBUILD_TGR_AMBIGUOUS_API_PARMS               3  // Ring search in HW iamge got ambiguous condition.
#define IMGBUILD_TGR_SECTION_NOT_FOUND                 4
#define IMGBUILD_TGR_DD_LVL_INFO_NOT_FOUND             5
#define IMGBUILD_TGR_OP_BUFFER_INVALID                 6
#define IMGBUILD_TGR_OP_BUFFER_SIZE_EXCEEDED           7
#define IMGBUILD_INVALID_INSTANCEID                    8
#define IMGBUILD_TGR_IMAGE_DOES_NOT_SUPPORT_CME       10
#define IMGBUILD_TGR_IMAGE_DOES_NOT_SUPPORT_SGPE      11
#define IMGBUILD_TGR_IMAGE_DOES_NOT_SUPPORT_DD_LEVEL  12
#define IMGBUILD_TGR_IMAGE_DOES_NOT_SUPPORT_PPE_LEVEL 13

#define MY_INF(_fmt_, _args_...) printf(_fmt_, ##_args_)
#define MY_ERR(_fmt_, _args_...) printf(_fmt_, ##_args_)
#define MY_DBG(_fmt_, _args_...) printf(_fmt_, ##_args_)

extern const char* ringVariantName[];
extern const char* ppeTypeName[];

typedef enum
RingBlockType   // Different options to extract data using tor_get_ring API
{
    SINGLE_RING      = 0x00,
    DD_LEVEL_RINGS   = 0x01,
    PPE_LEVEL_RINGS  = 0x02,
    CPLT_LEVEL_RINGS = 0x03
} RingBlockType_t;

typedef enum RingType      // Different type of Rings
{
    COMMON   = 0x00,
    INSTANCE = 0x01,
    ALLRING  = 0x02
} RingType_t;

typedef enum RingVariant   // Base variables
{
    BASE     = 0x00,
    CC       = 0x01,
    RL       = 0x02,
    OVERRIDE = 0x03,
    OVERLAY  = 0x04,
    NUM_RING_VARIANTS = 0x05
} RingVariant_t;

//
// PPE types
//
typedef enum PpeType
{
    SBE           = 0x00,     // Ppe type partition in Ringsection
    CME           = 0x01,
    SGPE          = 0x02,
    NUM_PPE_TYPES = 0x03
} PpeType_t;

typedef enum RingSectionId
{
    SECTION_RING    = 0x00,    //.ring section ID
    SECTION_OVRD    = 0x01,    //.Override section ID
    SECTION_OVRL    = 0x02     //.Overlay section ID
} RingSectionId_t;

typedef enum SbeTorId
{
    PERV_CPLT = 0,
    N0_CPLT =   1,
    N1_CPLT =   2,
    N2_CPLT =   3,
    N3_CPLT =   4,
    XB_CPLT =   5,
    MC_CPLT =   6,
    OB_CPLT =   7,
    PCI0_CPLT = 8,
    PCI1_CPLT = 9,
    PCI2_CPLT = 10,
    EQ_CPLT   = 11,
    EC_CPLT   = 12,
    SBEALL  =   13
} SbeTorId_t;
typedef enum CmeTorId
{
    CME0_CPLT    = 0,
    CME1_CPLT    = 1,
    CME2_CPLT    = 2,
    CME3_CPLT    = 3,
    CME4_CPLT    = 4,
    CME5_CPLT    = 5,
    CME6_CPLT    = 6,
    CME7_CPLT    = 7,
    CME8_CPLT    = 8,
    CME9_CPLT    = 9,
    CME10_CPLT   = 10,
    CME11_CPLT   = 11,
    CMEALL       = 12
} CmeTorId_t;
///
/// ****************************************************************************
/// Function declares.
/// ****************************************************************************
///

int get_ring_from_sbe_image ( void*
                              i_ringSectionPtr, // Image pointer
                              uint64_t        i_magic,          // Image Magic Number
                              RingID          i_ringId,         // Unique ring ID
                              uint16_t        i_ddLevel,        // DD level details
                              RingType_t&     io_RingType,      // 0: Common 1: Instance
                              RingVariant_t   i_RingVariant,    // Base, cache contained, Risk level,
                              // Override and Overlay
                              uint8_t&        io_instanceId,    // required Instance
                              RingBlockType_t RingBlockType,    // 0: single ring,  1: ddLevel block
                              void**          io_ringBlockPtr,  // RS4 Container data or block data
                              uint32_t&       io_ringBlockSize, // size of data copied into ring block pointer
                              char*           o_ringName,       // Name of ring
                              uint32_t        dbgl);            // Debug option

int get_ring_from_sgpe_image ( void*
                               i_ringSectionPtr, // Image pointer
                               RingID          i_ringId,         // Unique ring ID
                               uint16_t        i_ddLevel,        // DD level details
                               RingType_t&      io_RingType,       // 0: Common 1: Instance
                               RingVariant_t   i_RingVariant,    // Base, cache contained, Risk level,
                               // Override and Overlay
                               uint8_t&         io_instanceId,    // required Instance
                               RingBlockType_t RingBlockType,    // 0: single ring,  1: ddLevel block
                               void**          io_ringBlockPtr,   // RS4 Container data or block data
                               uint32_t&       io_ringBlockSize, // size of data copied into ring block pointer
                               char*           o_ringName,       // Name of ring
                               uint32_t        dbgl);            // Debug option

int get_ring_from_cme_image ( void*           i_ringSectionPtr, // Image pointer
                              RingID          i_ringId,         // Unique ring ID
                              uint16_t        i_ddLevel,        // DD level details
                              RingType_t&      io_RingType,       // 0: Common 1: Instance
                              RingVariant_t   i_RingVariant,    // Base, cache contained, Risk level,
                              // Override and Overlay
                              uint8_t&        io_instanceId,    // required Instance
                              RingBlockType_t RingBlockType,    // 0: single ring,  1: ddLevel block
                              void**          io_ringBlockPtr,   // RS4 Container data or block data
                              uint32_t&       io_ringBlockSize, // size of data copied into ring block pointer
                              char*           o_ringName,       // Name of ring
                              uint32_t        dbgl);            // Debug option

int tor_get_ring(  void*
                   i_ringSectionPtr, // Ring address Ptr any of .rings, .overrides and .overlays.
                   uint64_t        i_magic,             // Image Magic Number
                   RingID          i_ringId,         // Unique ring ID
                   uint16_t        i_ddLevel,        // DD level info
                   PpeType_t       i_PpeType,        // PPE type : SBE, CME, etc
                   RingType_t&      io_RingType,       // 0: Common 1: Instance
                   RingVariant_t   i_RingVariant,    // Base, Cache etc
                   uint8_t&        io_instanceId,     // chiplet instance ID
                   RingBlockType_t i_RingBlockType,  // 0: single ring,  1: ring block
                   void**          io_ringBlockPtr,  // Addr of ring buffer
                   uint32_t&       io_ringBlockSize, // size of ring data
                   char*           o_ringName        // Ring name
                );

int tor_get_single_ring ( void*
                          i_ringSectionPt,     // Ring address Ptr any of .rings, .overrides and .overlays.
                          uint16_t      i_ddLevel,           // DD level info
                          RingID        i_ringId,            // Unique ring ID
                          PpeType_t     i_PpeType,           // ppe Type
                          RingVariant_t
                          i_RingVariant,       // Base, cache contained, Risk level, Override and Overlay
                          uint8_t       i_instanceId,        // Chiplet Instance ID
                          void**        io_ringBlockPtr,     // Addr of ring buffer
                          uint32_t&     io_ringBlockSize );  // size of ring data

int tor_get_block_of_rings ( void*
                             i_ringSectionPt,  // Ring address Ptr any of .rings, .overrides and .overlays.
                             uint16_t      i_ddLevel,        // DD level
                             PpeType_t     i_PpeType,        // ppe Type
                             RingType_t    i_RingType,       // Common Or Instance
                             RingVariant_t i_RingVariant,    // base,cache,etc
                             uint8_t       i_instanceId,     // Chiplet Instance ID
                             void**        io_ringBlockPtr,  // Addr of ring buffer
                             uint32_t&     io_ringBlockSize  // size of ring data
                           );

#endif //_P9_TOR_H_
<commit_msg>p9_tor: cleaning up use of p9_xip_image<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/utils/imageProcs/p9_tor.H $               */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
#ifndef _P9_TOR_H_
#define _P9_TOR_H_

#include "p9_ring_identification.H"
#include "p9_ringId.H"
#include "p9_infrastruct_help.H"

#define NUM_RING_IDS              P9_NUM_RINGS

typedef struct
{
    uint32_t sizeOfThis;
    uint16_t sizeOfCmsk;
    uint16_t sizeOfMeta; // Exact size of meta data. Arbitrary size. Not null terminated.
} RingLayout_t;

//
// Temporary define until in TOR header by Giri.
//
//
// Temporary define until in TOR header by Giri.
//
typedef struct
{
    uint32_t TorNumDdLevels;
    uint32_t reserved;
} TorNumDdLevels_t;

typedef struct
{
    uint32_t TorDdLevelAndOffset;
    uint32_t TorDdBlockSize;
} TorDdLevelBlock_t;

typedef struct
{
    uint32_t TorPpeTypeOffset;
    uint32_t TorPpeBlockSize;
} TorPpeBlock_t;

#define MAX_CPLT_SBE                                  13
#define IMGBUILD_TGR_RING_FOUND                        0
#define IMGBUILD_TGR_RING_BLOCKS_FOUND                 0
#define IMGBUILD_TGR_RING_NOT_FOUND                    1  // Ring is not found in HW image.
#define IMGBUILD_TGR_INVALID_RING_ID                   2  // Ring is invalid or mismatch.
#define IMGBUILD_TGR_AMBIGUOUS_API_PARMS               3  // Ring search in HW iamge got ambiguous condition.
#define IMGBUILD_TGR_SECTION_NOT_FOUND                 4
#define IMGBUILD_TGR_DD_LVL_INFO_NOT_FOUND             5
#define IMGBUILD_TGR_OP_BUFFER_INVALID                 6
#define IMGBUILD_TGR_OP_BUFFER_SIZE_EXCEEDED           7
#define IMGBUILD_INVALID_INSTANCEID                    8
#define IMGBUILD_TGR_IMAGE_DOES_NOT_SUPPORT_CME       10
#define IMGBUILD_TGR_IMAGE_DOES_NOT_SUPPORT_SGPE      11
#define IMGBUILD_TGR_IMAGE_DOES_NOT_SUPPORT_DD_LEVEL  12
#define IMGBUILD_TGR_IMAGE_DOES_NOT_SUPPORT_PPE_LEVEL 13

#define MY_INF(_fmt_, _args_...) printf(_fmt_, ##_args_)
#define MY_ERR(_fmt_, _args_...) printf(_fmt_, ##_args_)
#define MY_DBG(_fmt_, _args_...) printf(_fmt_, ##_args_)

extern const char* ringVariantName[];
extern const char* ppeTypeName[];

typedef enum
RingBlockType   // Different options to extract data using tor_get_ring API
{
    SINGLE_RING      = 0x00,
    DD_LEVEL_RINGS   = 0x01,
    PPE_LEVEL_RINGS  = 0x02,
    CPLT_LEVEL_RINGS = 0x03
} RingBlockType_t;

typedef enum RingType      // Different type of Rings
{
    COMMON   = 0x00,
    INSTANCE = 0x01,
    ALLRING  = 0x02
} RingType_t;

typedef enum RingVariant   // Base variables
{
    BASE     = 0x00,
    CC       = 0x01,
    RL       = 0x02,
    OVERRIDE = 0x03,
    OVERLAY  = 0x04,
    NUM_RING_VARIANTS = 0x05
} RingVariant_t;

//
// PPE types
//
typedef enum PpeType
{
    SBE           = 0x00,     // Ppe type partition in Ringsection
    CME           = 0x01,
    SGPE          = 0x02,
    NUM_PPE_TYPES = 0x03
} PpeType_t;

typedef enum RingSectionId
{
    SECTION_RING    = 0x00,    //.ring section ID
    SECTION_OVRD    = 0x01,    //.Override section ID
    SECTION_OVRL    = 0x02     //.Overlay section ID
} RingSectionId_t;

typedef enum SbeTorId
{
    PERV_CPLT = 0,
    N0_CPLT =   1,
    N1_CPLT =   2,
    N2_CPLT =   3,
    N3_CPLT =   4,
    XB_CPLT =   5,
    MC_CPLT =   6,
    OB_CPLT =   7,
    PCI0_CPLT = 8,
    PCI1_CPLT = 9,
    PCI2_CPLT = 10,
    EQ_CPLT   = 11,
    EC_CPLT   = 12,
    SBEALL  =   13
} SbeTorId_t;
typedef enum CmeTorId
{
    CME0_CPLT    = 0,
    CME1_CPLT    = 1,
    CME2_CPLT    = 2,
    CME3_CPLT    = 3,
    CME4_CPLT    = 4,
    CME5_CPLT    = 5,
    CME6_CPLT    = 6,
    CME7_CPLT    = 7,
    CME8_CPLT    = 8,
    CME9_CPLT    = 9,
    CME10_CPLT   = 10,
    CME11_CPLT   = 11,
    CMEALL       = 12
} CmeTorId_t;
///
/// ****************************************************************************
/// Function declares.
/// ****************************************************************************
///

int get_ring_from_sbe_image ( void*
                              i_ringSectionPtr, // Image pointer
                              uint64_t        i_magic,          // Image Magic Number
                              RingID          i_ringId,         // Unique ring ID
                              uint16_t        i_ddLevel,        // DD level details
                              RingType_t&     io_RingType,      // 0: Common 1: Instance
                              RingVariant_t   i_RingVariant,    // Base, cache contained, Risk level,
                              // Override and Overlay
                              uint8_t&        io_instanceId,    // required Instance
                              RingBlockType_t RingBlockType,    // 0: single ring,  1: ddLevel block
                              void**          io_ringBlockPtr,  // RS4 Container data or block data
                              uint32_t&       io_ringBlockSize, // size of data copied into ring block pointer
                              char*           o_ringName,       // Name of ring
                              uint32_t        dbgl);            // Debug option

int get_ring_from_sgpe_image ( void*
                               i_ringSectionPtr, // Image pointer
                               RingID          i_ringId,         // Unique ring ID
                               uint16_t        i_ddLevel,        // DD level details
                               RingType_t&      io_RingType,       // 0: Common 1: Instance
                               RingVariant_t   i_RingVariant,    // Base, cache contained, Risk level,
                               // Override and Overlay
                               uint8_t&         io_instanceId,    // required Instance
                               RingBlockType_t RingBlockType,    // 0: single ring,  1: ddLevel block
                               void**          io_ringBlockPtr,   // RS4 Container data or block data
                               uint32_t&       io_ringBlockSize, // size of data copied into ring block pointer
                               char*           o_ringName,       // Name of ring
                               uint32_t        dbgl);            // Debug option

int get_ring_from_cme_image ( void*           i_ringSectionPtr, // Image pointer
                              RingID          i_ringId,         // Unique ring ID
                              uint16_t        i_ddLevel,        // DD level details
                              RingType_t&      io_RingType,       // 0: Common 1: Instance
                              RingVariant_t   i_RingVariant,    // Base, cache contained, Risk level,
                              // Override and Overlay
                              uint8_t&        io_instanceId,    // required Instance
                              RingBlockType_t RingBlockType,    // 0: single ring,  1: ddLevel block
                              void**          io_ringBlockPtr,   // RS4 Container data or block data
                              uint32_t&       io_ringBlockSize, // size of data copied into ring block pointer
                              char*           o_ringName,       // Name of ring
                              uint32_t        dbgl);            // Debug option

int tor_get_ring(  void*
                   i_ringSectionPtr, // Ring address Ptr any of .rings, .overrides and .overlays.
                   uint64_t        i_magic,             // Image Magic Number
                   RingID          i_ringId,         // Unique ring ID
                   uint16_t        i_ddLevel,        // DD level info
                   PpeType_t       i_PpeType,        // PPE type : SBE, CME, etc
                   RingType_t&      io_RingType,       // 0: Common 1: Instance
                   RingVariant_t   i_RingVariant,    // Base, Cache etc
                   uint8_t&        io_instanceId,     // chiplet instance ID
                   RingBlockType_t i_RingBlockType,  // 0: single ring,  1: ring block
                   void**          io_ringBlockPtr,  // Addr of ring buffer
                   uint32_t&       io_ringBlockSize, // size of ring data
                   char*           o_ringName        // Ring name
                );

int tor_get_single_ring ( void*
                          i_ringSectionPt,     // Ring address Ptr any of .rings, .overrides and .overlays.
                          uint16_t      i_ddLevel,           // DD level info
                          RingID        i_ringId,            // Unique ring ID
                          PpeType_t     i_PpeType,           // ppe Type
                          RingVariant_t
                          i_RingVariant,       // Base, cache contained, Risk level, Override and Overlay
                          uint8_t       i_instanceId,        // Chiplet Instance ID
                          void**        io_ringBlockPtr,     // Addr of ring buffer
                          uint32_t&     io_ringBlockSize );  // size of ring data

int tor_get_block_of_rings ( void*
                             i_ringSectionPt,  // Ring address Ptr any of .rings, .overrides and .overlays.
                             uint16_t      i_ddLevel,        // DD level
                             PpeType_t     i_PpeType,        // ppe Type
                             RingType_t    i_RingType,       // Common Or Instance
                             RingVariant_t i_RingVariant,    // base,cache,etc
                             uint8_t       i_instanceId,     // Chiplet Instance ID
                             void**        io_ringBlockPtr,  // Addr of ring buffer
                             uint32_t&     io_ringBlockSize  // size of ring data
                           );

#endif //_P9_TOR_H_
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: cmd_run.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: np $ $Date: 2002-11-14 18:02:02 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef ADC_CMD_RUN_HXX
#define ADC_CMD_RUN_HXX

// USED SERVICES
    // BASE CLASSES
#include <cosv/comdline.hxx>
    // COMPONENTS
    // PARAMETERS

namespace ary
{
     class Repository;

    namespace n22
    {
         class Repository;
    }
}

namespace autodoc
{
    class FileCollector_Ifc;
    class ParseToolsFactory_Ifc;
    class CodeParser_Ifc;
    class DocumentationParser_Ifc;
    class IdlParser;

namespace command
{
    class Parse;
     class S_ProjectData;
     struct S_LanguageInfo;

namespace run
{

/** Performs an ::autodoc::command::Parse .
*/
class Parser
{
  public:
                        Parser(
                            const Parse &       i_command );
                        ~Parser();

    bool                Perform();

  private:
    // Locals
    CodeParser_Ifc &    Get_CppParser();
    IdlParser &         Get_IdlParser();
    void                Create_CppParser();
    void                Create_IdlParser();
    const ParseToolsFactory_Ifc &
                        ParseToolsFactory();
    uintt               GatherFiles(
                            FileCollector_Ifc & o_rFiles,
                            const S_ProjectData &
                                                i_rProject );
    // DATA
    const Parse &       rCommand;

    Dyn<CodeParser_Ifc> pCppParser;
    Dyn<DocumentationParser_Ifc>
                        pCppDocuInterpreter;
    Dyn<IdlParser>      pIdlParser;
};

// IMPLEMENTATION

}   // namespace run
}   // namespace command
}   // namespace autodoc

#endif

<commit_msg>INTEGRATION: CWS adc8 (1.3.82); FILE MERGED 2004/07/02 10:58:59 np 1.3.82.1: #i30967#<commit_after>/*************************************************************************
 *
 *  $RCSfile: cmd_run.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2004-07-12 15:35:36 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef ADC_CMD_RUN_HXX
#define ADC_CMD_RUN_HXX

// USED SERVICES
    // BASE CLASSES
#include <cosv/comdline.hxx>
    // COMPONENTS
    // PARAMETERS

namespace ary
{
     class Repository;

    namespace n22
    {
         class Repository;
    }
}

namespace autodoc
{
    class FileCollector_Ifc;
    class ParseToolsFactory_Ifc;
    class CodeParser_Ifc;
    class DocumentationParser_Ifc;
    class IdlParser;

namespace command
{
    class Parse;
     class S_ProjectData;
     struct S_LanguageInfo;

namespace run
{

/** Performs an ::autodoc::command::Parse .
*/
class Parser
{
  public:
                        Parser(
                            const Parse &       i_command );
                        ~Parser();

    bool                Perform();

  private:
    // Locals
    CodeParser_Ifc &    Get_CppParser();
    IdlParser &         Get_IdlParser();
    void                Create_CppParser();
    void                Create_IdlParser();
    const ParseToolsFactory_Ifc &
                        ParseToolsFactory();
    uintt               GatherFiles(
                            FileCollector_Ifc & o_rFiles,
                            const S_ProjectData &
                                                i_rProject );
    // DATA
    const Parse &       rCommand;

    Dyn<CodeParser_Ifc> pCppParser;
    Dyn<DocumentationParser_Ifc>
                        pCppDocuInterpreter;
    Dyn<IdlParser>      pIdlParser;
};

// IMPLEMENTATION

}   // namespace run
}   // namespace command
}   // namespace autodoc

#endif
<|endoftext|>


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

#pragma GCC diagnostic push
#if defined(__GNUC__) && !defined(__clang__)
# pragma GCC diagnostic ignored "-Wunused-local-typedefs"
#endif
#include <boost/program_options.hpp>
#pragma GCC diagnostic pop

#include "conf/configuration.hh"
#include "conf/fill_configuration.hh"

namespace pnmc { namespace conf {

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

namespace po = boost::program_options;

const std::string version
  = "Petri Net Model Checker (built " + std::string(__DATE__) + " " + std::string(__TIME__)  + ")";

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

input_format
file_type(const po::variables_map& vm)
{
  const bool bpn = vm.count("bpn");
  const bool prod = vm.count("prod");
  const bool tina = vm.count("tina");

  if (not (bpn or prod or tina))
  {
    return input_format::xml;
  }
  else if (not (bpn xor prod xor tina))
  {
    throw po::error("Can specify only one input format.");
  }
  else
  {
    if (bpn)
    {
      return input_format::bpn;
    }
    else if (prod)
    {
      return input_format::prod;
    }
    else // tina
    {
      return input_format::tina;
    }
  }
}

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

boost::optional<pnmc_configuration>
fill_configuration(int argc, char** argv)
{
  pnmc_configuration conf;

  po::options_description general_options("General options");
  general_options.add_options()
    ( "help"                  , "Show this help")
    ( "version"               , "Show version")
  ;

  po::options_description file_options("Input file options");
  file_options.add_options()
    ("bpn"                      , "Parse BPN format")
    ("prod"                     , "Parse PROD format")
    ("tina"                     , "Parse TINA format")
    ("xml"                      , "Parse pnmc's XML format (default)")
  ;

  po::options_description order_options("Order options");
  order_options.add_options()
    ("show-order"             , "Show the order")
    ("random-order"           , "Random order")
    ("flat"                   , "Don't use hierarchy informations")
    ("order-min-height"       , po::value<unsigned int>()->default_value(10)
                              , "Minimal number of variables at every level of the SDD")
  ;

  po::options_description hom_options("Homomorphisms options");
  hom_options.add_options()
    ("show-relation"          , "Show the transition relation")
  ;

  po::options_description stats_options("Statistics options");
  stats_options.add_options()
    ("show-hash-stats"          , "Show the hash tables statistics")
    ("show-time"                , "Show miscellaneous execution times")
  ;

  po::options_description petri_options("Petri net options");
  petri_options.add_options()
    ("dead-transitions"         , "Compute dead transitions")
    ("dead-states"              , "Compute dead states")
    ("marking-bound"            , po::value<unsigned int>()->default_value(0)
                                , "Limit the marking")
  ;

  po::options_description hidden_options("Hidden options");
  hidden_options.add_options()
    ("export-to-lua", po::value<std::string>(), "Export the final SDD to a Lua structure")
    ("input-file", po::value<std::string>(), "The Petri net file to analyse")
    ("delete-file", "Delete model file after reading it")
  ;

  po::positional_options_description p;
  p.add("input-file", 1);

  po::options_description cmdline_options;
  cmdline_options
  	.add(general_options)
    .add(file_options)
    .add(order_options)
    .add(hom_options)
    .add(petri_options)
    .add(stats_options)
  	.add(hidden_options);

  po::variables_map vm;
  po::parsed_options parsed = po::command_line_parser(argc, argv)
                                    .options(cmdline_options)
                                    .positional(p)
                                    .allow_unregistered()
                                    .run();
  po::store(parsed, vm);
  po::notify(vm);

  std::vector<std::string> unrecognized
    = po::collect_unrecognized(parsed.options,po::exclude_positional);

  if (vm.count("help") or unrecognized.size() > 0)
  {
    std::cout << version << std::endl;
    std::cout << "Usage: " << argv[0] << " [options] file " << std::endl << std::endl;
    std::cout << general_options << std::endl;
    std::cout << file_options << std::endl;
    std::cout << order_options << std::endl;
    std::cout << hom_options << std::endl;
    std::cout << petri_options << std::endl;
    std::cout << stats_options << std::endl;
    return boost::optional<pnmc_configuration>();
  }

  if (vm.count("version"))
  {
    std::cout << version << std::endl;
    return boost::optional<pnmc_configuration>();
  }

  if (not vm.count("input-file"))
  {
    throw po::error("No file specified.");
  }

  conf.file_name = vm["input-file"].as<std::string>();
  conf.file_type = file_type(vm);
  conf.read_stdin = conf.file_name == "-";
  conf.delete_file = vm.count("delete-file");
  conf.order_show = vm.count("show-order");
  conf.order_random = vm.count("random-order");
  conf.order_force_flat = vm.count("flat");
  conf.order_min_height = vm["order-min-height"].as<unsigned int>();
  conf.show_relation = vm.count("show-relation");
  conf.show_hash_tables_stats = vm.count("show-hash-stats");
  conf.show_time = vm.count("show-time");
  conf.compute_dead_transitions = vm.count("dead-transitions");
  conf.compute_dead_states = vm.count("dead-states");
  conf.export_to_lua = vm.count("export-to-lua");
  conf.marking_bound = vm["marking-bound"].as<unsigned int>();
  if (conf.export_to_lua)
  {
    conf.export_to_lua_file = vm["export-to-lua"].as<std::string>();
  }

  return conf;
}

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

}} // namespace pnmc::conf
<commit_msg>Prefix options.<commit_after>#include <iostream>
#include <string>

#pragma GCC diagnostic push
#if defined(__GNUC__) && !defined(__clang__)
# pragma GCC diagnostic ignored "-Wunused-local-typedefs"
#endif
#include <boost/program_options.hpp>
#pragma GCC diagnostic pop

#include "conf/configuration.hh"
#include "conf/fill_configuration.hh"

namespace pnmc { namespace conf {

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

namespace po = boost::program_options;

const std::string version
  = "Petri Net Model Checker (built " + std::string(__DATE__) + " " + std::string(__TIME__)  + ")";

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

input_format
file_type(const po::variables_map& vm)
{
  const bool bpn = vm.count("bpn");
  const bool prod = vm.count("prod");
  const bool tina = vm.count("tina");

  if (not (bpn or prod or tina))
  {
    return input_format::xml;
  }
  else if (not (bpn xor prod xor tina))
  {
    throw po::error("Can specify only one input format.");
  }
  else
  {
    if (bpn)
    {
      return input_format::bpn;
    }
    else if (prod)
    {
      return input_format::prod;
    }
    else // tina
    {
      return input_format::tina;
    }
  }
}

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

boost::optional<pnmc_configuration>
fill_configuration(int argc, char** argv)
{
  pnmc_configuration conf;

  po::options_description general_options("General options");
  general_options.add_options()
    ( "help"                  , "Show this help")
    ( "version"               , "Show version")
  ;

  po::options_description file_options("Input file options");
  file_options.add_options()
    ("bpn"                      , "Parse BPN format")
    ("prod"                     , "Parse PROD format")
    ("tina"                     , "Parse TINA format")
    ("xml"                      , "Parse pnmc's XML format (default)")
  ;

  po::options_description order_options("Order options");
  order_options.add_options()
    ("order-show"             , "Show the order")
    ("order-random"           , "Random order")
    ("order-flat"             , "Don't use hierarchy informations")
    ("order-min-height"       , po::value<unsigned int>()->default_value(10)
                              , "Minimal number of variables at every level of the SDD")
  ;

  po::options_description hom_options("Homomorphisms options");
  hom_options.add_options()
    ("relation-show"          , "Show the transition relation")
  ;

  po::options_description stats_options("Statistics options");
  stats_options.add_options()
    ("show-hash-stats"          , "Show the hash tables statistics")
    ("show-time"                , "Show miscellaneous execution times")
  ;

  po::options_description petri_options("Petri net options");
  petri_options.add_options()
    ("dead-transitions"         , "Compute dead transitions")
    ("dead-states"              , "Compute dead states")
    ("marking-bound"            , po::value<unsigned int>()->default_value(0)
                                , "Limit the marking")
  ;

  po::options_description hidden_options("Hidden options");
  hidden_options.add_options()
    ("export-to-lua", po::value<std::string>(), "Export the final SDD to a Lua structure")
    ("input-file", po::value<std::string>(), "The Petri net file to analyse")
    ("delete-file", "Delete model file after reading it")
  ;

  po::positional_options_description p;
  p.add("input-file", 1);

  po::options_description cmdline_options;
  cmdline_options
  	.add(general_options)
    .add(file_options)
    .add(order_options)
    .add(hom_options)
    .add(petri_options)
    .add(stats_options)
  	.add(hidden_options);

  po::variables_map vm;
  po::parsed_options parsed = po::command_line_parser(argc, argv)
                                    .options(cmdline_options)
                                    .positional(p)
                                    .allow_unregistered()
                                    .run();
  po::store(parsed, vm);
  po::notify(vm);

  std::vector<std::string> unrecognized
    = po::collect_unrecognized(parsed.options,po::exclude_positional);

  if (vm.count("help") or unrecognized.size() > 0)
  {
    std::cout << version << std::endl;
    std::cout << "Usage: " << argv[0] << " [options] file " << std::endl << std::endl;
    std::cout << general_options << std::endl;
    std::cout << file_options << std::endl;
    std::cout << order_options << std::endl;
    std::cout << hom_options << std::endl;
    std::cout << petri_options << std::endl;
    std::cout << stats_options << std::endl;
    return boost::optional<pnmc_configuration>();
  }

  if (vm.count("version"))
  {
    std::cout << version << std::endl;
    return boost::optional<pnmc_configuration>();
  }

  if (not vm.count("input-file"))
  {
    throw po::error("No file specified.");
  }

  conf.file_name = vm["input-file"].as<std::string>();
  conf.file_type = file_type(vm);
  conf.read_stdin = conf.file_name == "-";
  conf.delete_file = vm.count("delete-file");
  conf.order_show = vm.count("show-order");
  conf.order_random = vm.count("random-order");
  conf.order_force_flat = vm.count("flat");
  conf.order_min_height = vm["order-min-height"].as<unsigned int>();
  conf.show_relation = vm.count("show-relation");
  conf.show_hash_tables_stats = vm.count("show-hash-stats");
  conf.show_time = vm.count("show-time");
  conf.compute_dead_transitions = vm.count("dead-transitions");
  conf.compute_dead_states = vm.count("dead-states");
  conf.export_to_lua = vm.count("export-to-lua");
  conf.marking_bound = vm["marking-bound"].as<unsigned int>();
  if (conf.export_to_lua)
  {
    conf.export_to_lua_file = vm["export-to-lua"].as<std::string>();
  }

  return conf;
}

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

}} // namespace pnmc::conf
<|endoftext|>


<commit_before>// Copyright (c) 2019 Matthew J. Smith and Overkit contributors
// License: MIT (http://opensource.org/licenses/MIT)

#include "ovk/core/Assembler.hpp"

#include "ovk/core/Array.hpp"
#include "ovk/core/ArrayOps.hpp"
#include "ovk/core/ArrayView.hpp"
#include "ovk/core/Comm.hpp"
#include "ovk/core/ConnectivityComponent.hpp"
#include "ovk/core/ConnectivityM.hpp"
#include "ovk/core/ConnectivityN.hpp"
#include "ovk/core/Context.hpp"
#include "ovk/core/Debug.hpp"
#include "ovk/core/DistributedField.hpp"
#include "ovk/core/Domain.hpp"
#include "ovk/core/Event.hpp"
#include "ovk/core/Field.hpp"
#include "ovk/core/FloatingRef.hpp"
#include "ovk/core/Geometry.hpp"
#include "ovk/core/GeometryComponent.hpp"
#include "ovk/core/Global.hpp"
#include "ovk/core/Grid.hpp"
#include "ovk/core/Map.hpp"
#include "ovk/core/OverlapComponent.hpp"
#include "ovk/core/OverlapM.hpp"
#include "ovk/core/OverlapN.hpp"
#include "ovk/core/Partition.hpp"
#include "ovk/core/Range.hpp"
#include "ovk/core/Set.hpp"
#include "ovk/core/State.hpp"
#include "ovk/core/StateComponent.hpp"
#include "ovk/core/Tuple.hpp"

#include <mpi.h>

#include <memory>
#include <string>
#include <utility>

namespace ovk {

void assembler::Assemble() {

  const domain &Domain = *Domain_;
  core::logger &Logger = Context_->core_Logger();

  MPI_Barrier(Domain.Comm());

  Logger.LogStatus(Domain.Comm().Rank() == 0, 0, "Assembling domain %s using assembler %s...",
    Domain.Name(), *Name_);

  InitializeAssembly_();

  AssemblyManifest_.DetectOverlap.Clear();
  AssemblyManifest_.InferBoundaries.Clear();
  AssemblyManifest_.CutBoundaryHoles.Clear();
  AssemblyManifest_.ComputeOcclusion.Clear();
  AssemblyManifest_.ApplyPadding.Clear();
  AssemblyManifest_.ApplySmoothing.Clear();
  AssemblyManifest_.MinimizeOverlap.Clear();
  AssemblyManifest_.GenerateConnectivity.Clear();

  MPI_Barrier(Domain.Comm());

  Logger.LogStatus(Domain.Comm().Rank() == 0, 0, "Done assembling domain %s using assembler %s.",
    Domain.Name(), *Name_);

}

void assembler::InitializeAssembly_() {

  const domain &Domain = *Domain_;
  int NumDims = Domain.Dimension();
  auto &GeometryComponent = Domain.Component<geometry_component>(GeometryComponentID_);
  auto &StateComponent = Domain.Component<state_component>(StateComponentID_);
  assembly_data &AssemblyData = *AssemblyData_;

  for (int GridID : Domain.GridIDs()) {
    OVK_DEBUG_ASSERT(GeometryComponent.GeometryExists(GridID), "No geometry data for grid %s.",
      Domain.GridInfo(GridID).Name());
    OVK_DEBUG_ASSERT(StateComponent.StateExists(GridID), "No state data for grid %s.",
      Domain.GridInfo(GridID).Name());
  }

  range VertexOffsetRange = MakeEmptyRange(NumDims);
  for (int iDim = 0; iDim < NumDims; ++iDim) {
    VertexOffsetRange.Begin(iDim) = 0;
    VertexOffsetRange.End(iDim) = 2;
  }

  array<request> Requests;
  Requests.Reserve(2*Domain.LocalGridCount());

  auto FlagsMatchAll = [](state_flags Flags, state_flags Mask) -> bool {
    return (Flags & Mask) == Mask;
  };

  for (int GridID : Domain.LocalGridIDs()) {
    const grid &Grid = Domain.Grid(GridID);
    const range &ExtendedRange = Grid.ExtendedRange();
    const range &CellLocalRange = Grid.CellLocalRange();
    auto &Flags = StateComponent.State(GridID).Flags();
    core::partition_pool PartitionPool(Context_, Grid.Comm(), Grid.Partition().NeighborRanks());
    PartitionPool.Insert(Grid.SharedPartition());
    PartitionPool.Insert(Grid.SharedCellPartition());
    local_grid_aux_data &LocalGridAuxData = AssemblyData.LocalGridAuxData.Insert(GridID,
      std::move(PartitionPool));
    distributed_field<bool> &ActiveMask = LocalGridAuxData.ActiveMask;
    distributed_field<bool> &CellActiveMask = LocalGridAuxData.CellActiveMask;
    distributed_field<bool> &DomainBoundaryMask = LocalGridAuxData.DomainBoundaryMask;
    distributed_field<bool> &InternalBoundaryMask = LocalGridAuxData.InternalBoundaryMask;
    ActiveMask.Assign(Grid.SharedPartition());
    for (int k = ExtendedRange.Begin(2); k < ExtendedRange.End(2); ++k) {
      for (int j = ExtendedRange.Begin(1); j < ExtendedRange.End(1); ++j) {
        for (int i = ExtendedRange.Begin(0); i < ExtendedRange.End(0); ++i) {
          ActiveMask(i,j,k) = FlagsMatchAll(Flags(i,j,k), state_flags::ACTIVE);
        }
      }
    }
    CellActiveMask.Assign(Grid.SharedCellPartition());
    for (int k = CellLocalRange.Begin(2); k < CellLocalRange.End(2); ++k) {
      for (int j = CellLocalRange.Begin(1); j < CellLocalRange.End(1); ++j) {
        for (int i = CellLocalRange.Begin(0); i < CellLocalRange.End(0); ++i) {
          tuple<int> Cell = {i,j,k};
          CellActiveMask(Cell) = true;
          for (int o = VertexOffsetRange.Begin(2); o < VertexOffsetRange.End(2); ++o) {
            for (int n = VertexOffsetRange.Begin(1); n < VertexOffsetRange.End(1); ++n) {
              for (int m = VertexOffsetRange.Begin(0); m < VertexOffsetRange.End(0); ++m) {
                tuple<int> Vertex = {Cell(0)+m,Cell(1)+n,Cell(2)+o};
                CellActiveMask(Cell) = CellActiveMask(Cell) && ActiveMask(Vertex);
              }
            }
          }
        }
      }
    }
    Requests.Append(CellActiveMask.Exchange());
    DomainBoundaryMask.Assign(Grid.SharedPartition());
    for (int k = ExtendedRange.Begin(2); k < ExtendedRange.End(2); ++k) {
      for (int j = ExtendedRange.Begin(1); j < ExtendedRange.End(1); ++j) {
        for (int i = ExtendedRange.Begin(0); i < ExtendedRange.End(0); ++i) {
          DomainBoundaryMask(i,j,k) = FlagsMatchAll(Flags(i,j,k), state_flags::ACTIVE |
            state_flags::DOMAIN_BOUNDARY);
        }
      }
    }
    InternalBoundaryMask.Assign(Grid.SharedPartition());
    for (int k = ExtendedRange.Begin(2); k < ExtendedRange.End(2); ++k) {
      for (int j = ExtendedRange.Begin(1); j < ExtendedRange.End(1); ++j) {
        for (int i = ExtendedRange.Begin(0); i < ExtendedRange.End(0); ++i) {
          InternalBoundaryMask(i,j,k) = FlagsMatchAll(Flags(i,j,k), state_flags::ACTIVE |
            state_flags::INTERNAL_BOUNDARY);
        }
      }
    }
  }

  WaitAll(Requests);

}

}
<commit_msg>cosmetic change<commit_after>// Copyright (c) 2019 Matthew J. Smith and Overkit contributors
// License: MIT (http://opensource.org/licenses/MIT)

#include "ovk/core/Assembler.hpp"

#include "ovk/core/Array.hpp"
#include "ovk/core/ArrayOps.hpp"
#include "ovk/core/ArrayView.hpp"
#include "ovk/core/Comm.hpp"
#include "ovk/core/ConnectivityComponent.hpp"
#include "ovk/core/ConnectivityM.hpp"
#include "ovk/core/ConnectivityN.hpp"
#include "ovk/core/Context.hpp"
#include "ovk/core/Debug.hpp"
#include "ovk/core/DistributedField.hpp"
#include "ovk/core/Domain.hpp"
#include "ovk/core/Event.hpp"
#include "ovk/core/Field.hpp"
#include "ovk/core/FloatingRef.hpp"
#include "ovk/core/Geometry.hpp"
#include "ovk/core/GeometryComponent.hpp"
#include "ovk/core/Global.hpp"
#include "ovk/core/Grid.hpp"
#include "ovk/core/Map.hpp"
#include "ovk/core/OverlapComponent.hpp"
#include "ovk/core/OverlapM.hpp"
#include "ovk/core/OverlapN.hpp"
#include "ovk/core/Partition.hpp"
#include "ovk/core/Range.hpp"
#include "ovk/core/Set.hpp"
#include "ovk/core/State.hpp"
#include "ovk/core/StateComponent.hpp"
#include "ovk/core/Tuple.hpp"

#include <mpi.h>

#include <memory>
#include <string>
#include <utility>

namespace ovk {

void assembler::Assemble() {

  const domain &Domain = *Domain_;
  core::logger &Logger = Context_->core_Logger();

  MPI_Barrier(Domain.Comm());

  Logger.LogStatus(Domain.Comm().Rank() == 0, 0, "Assembling domain %s using assembler %s...",
    Domain.Name(), *Name_);

  InitializeAssembly_();

  AssemblyManifest_.DetectOverlap.Clear();
  AssemblyManifest_.InferBoundaries.Clear();
  AssemblyManifest_.CutBoundaryHoles.Clear();
  AssemblyManifest_.ComputeOcclusion.Clear();
  AssemblyManifest_.ApplyPadding.Clear();
  AssemblyManifest_.ApplySmoothing.Clear();
  AssemblyManifest_.MinimizeOverlap.Clear();
  AssemblyManifest_.GenerateConnectivity.Clear();

  MPI_Barrier(Domain.Comm());

  Logger.LogStatus(Domain.Comm().Rank() == 0, 0, "Done assembling domain %s using assembler %s.",
    Domain.Name(), *Name_);

}

void assembler::InitializeAssembly_() {

  const domain &Domain = *Domain_;
  int NumDims = Domain.Dimension();
  auto &GeometryComponent = Domain.Component<geometry_component>(GeometryComponentID_);
  auto &StateComponent = Domain.Component<state_component>(StateComponentID_);
  assembly_data &AssemblyData = *AssemblyData_;

  for (int GridID : Domain.GridIDs()) {
    OVK_DEBUG_ASSERT(GeometryComponent.GeometryExists(GridID), "No geometry data for grid %s.",
      Domain.GridInfo(GridID).Name());
    OVK_DEBUG_ASSERT(StateComponent.StateExists(GridID), "No state data for grid %s.",
      Domain.GridInfo(GridID).Name());
  }

  range VertexOffsetRange = MakeEmptyRange(NumDims);
  for (int iDim = 0; iDim < NumDims; ++iDim) {
    VertexOffsetRange.Begin(iDim) = 0;
    VertexOffsetRange.End(iDim) = 2;
  }

  array<request> Requests;
  Requests.Reserve(2*Domain.LocalGridCount());

  auto FlagsMatchAll = [](state_flags Flags, state_flags Mask) -> bool {
    return (Flags & Mask) == Mask;
  };

  for (int GridID : Domain.LocalGridIDs()) {
    const grid &Grid = Domain.Grid(GridID);
    const range &ExtendedRange = Grid.ExtendedRange();
    const range &CellLocalRange = Grid.CellLocalRange();
    auto &Flags = StateComponent.State(GridID).Flags();
    core::partition_pool PartitionPool(Context_, Grid.Comm(), Grid.Partition().NeighborRanks());
    PartitionPool.Insert(Grid.SharedPartition());
    PartitionPool.Insert(Grid.SharedCellPartition());
    local_grid_aux_data &GridAuxData = AssemblyData.LocalGridAuxData.Insert(GridID,
      std::move(PartitionPool));
    distributed_field<bool> &ActiveMask = GridAuxData.ActiveMask;
    distributed_field<bool> &CellActiveMask = GridAuxData.CellActiveMask;
    distributed_field<bool> &DomainBoundaryMask = GridAuxData.DomainBoundaryMask;
    distributed_field<bool> &InternalBoundaryMask = GridAuxData.InternalBoundaryMask;
    ActiveMask.Assign(Grid.SharedPartition());
    for (int k = ExtendedRange.Begin(2); k < ExtendedRange.End(2); ++k) {
      for (int j = ExtendedRange.Begin(1); j < ExtendedRange.End(1); ++j) {
        for (int i = ExtendedRange.Begin(0); i < ExtendedRange.End(0); ++i) {
          ActiveMask(i,j,k) = FlagsMatchAll(Flags(i,j,k), state_flags::ACTIVE);
        }
      }
    }
    CellActiveMask.Assign(Grid.SharedCellPartition());
    for (int k = CellLocalRange.Begin(2); k < CellLocalRange.End(2); ++k) {
      for (int j = CellLocalRange.Begin(1); j < CellLocalRange.End(1); ++j) {
        for (int i = CellLocalRange.Begin(0); i < CellLocalRange.End(0); ++i) {
          tuple<int> Cell = {i,j,k};
          CellActiveMask(Cell) = true;
          for (int o = VertexOffsetRange.Begin(2); o < VertexOffsetRange.End(2); ++o) {
            for (int n = VertexOffsetRange.Begin(1); n < VertexOffsetRange.End(1); ++n) {
              for (int m = VertexOffsetRange.Begin(0); m < VertexOffsetRange.End(0); ++m) {
                tuple<int> Vertex = {Cell(0)+m,Cell(1)+n,Cell(2)+o};
                CellActiveMask(Cell) = CellActiveMask(Cell) && ActiveMask(Vertex);
              }
            }
          }
        }
      }
    }
    Requests.Append(CellActiveMask.Exchange());
    DomainBoundaryMask.Assign(Grid.SharedPartition());
    for (int k = ExtendedRange.Begin(2); k < ExtendedRange.End(2); ++k) {
      for (int j = ExtendedRange.Begin(1); j < ExtendedRange.End(1); ++j) {
        for (int i = ExtendedRange.Begin(0); i < ExtendedRange.End(0); ++i) {
          DomainBoundaryMask(i,j,k) = FlagsMatchAll(Flags(i,j,k), state_flags::ACTIVE |
            state_flags::DOMAIN_BOUNDARY);
        }
      }
    }
    InternalBoundaryMask.Assign(Grid.SharedPartition());
    for (int k = ExtendedRange.Begin(2); k < ExtendedRange.End(2); ++k) {
      for (int j = ExtendedRange.Begin(1); j < ExtendedRange.End(1); ++j) {
        for (int i = ExtendedRange.Begin(0); i < ExtendedRange.End(0); ++i) {
          InternalBoundaryMask(i,j,k) = FlagsMatchAll(Flags(i,j,k), state_flags::ACTIVE |
            state_flags::INTERNAL_BOUNDARY);
        }
      }
    }
  }

  WaitAll(Requests);

}

}
<|endoftext|>