<commit_before>// Ignore unused parameter warnings coming from cppuint headers
#include <libmesh/ignore_warnings.h>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/TestCase.h>
#include <libmesh/restore_warnings.h>

#include <libmesh/equation_systems.h>
#include <libmesh/serial_mesh.h>
#include <libmesh/mesh_generation.h>
#include <libmesh/edge_edge2.h>
#include <libmesh/face_quad4.h>
#include <libmesh/dof_map.h>
#include <libmesh/linear_implicit_system.h>
#include <libmesh/mesh_refinement.h>

#include "test_comm.h"

using namespace libMesh;

class MixedDimensionMeshTest : public CppUnit::TestCase {
  /**
   * The goal of this test is to ensure that a 2D mesh with 1D elements overlapping
   * on the edge is consistent. That is, they share the same global node numbers and
   * the same dof numbers for a variable.
   */
public:
  CPPUNIT_TEST_SUITE( MixedDimensionMeshTest );

  CPPUNIT_TEST( testMesh );
  CPPUNIT_TEST( testDofOrdering );
  CPPUNIT_TEST( testPointLocatorList );
  CPPUNIT_TEST( testPointLocatorTree );

  CPPUNIT_TEST_SUITE_END();

protected:

  SerialMesh* _mesh;

  void build_mesh()
  {
    _mesh = new SerialMesh(*TestCommWorld);

    /*
      (0,1)           (1,1)
        x---------------x
        |               |
        |               |
        |               |
        |               |
        |               |
        x---------------x
       (0,0)           (1,0)
        |               |
        |               |
        |               |
        |               |
        x---------------x
       (0,-1)          (1,-1)
     */

    _mesh->set_mesh_dimension(2);

    _mesh->add_point( Point(0.0,-1.0), 4 );
    _mesh->add_point( Point(1.0,-1.0), 5 );
    _mesh->add_point( Point(1.0, 0.0), 1 );
    _mesh->add_point( Point(1.0, 1.0), 2 );
    _mesh->add_point( Point(0.0, 1.0), 3 );
    _mesh->add_point( Point(0.0, 0.0), 0 );

    {
      Elem* elem_top = _mesh->add_elem( new Quad4 );
      elem_top->set_node(0) = _mesh->node_ptr(0);
      elem_top->set_node(1) = _mesh->node_ptr(1);
      elem_top->set_node(2) = _mesh->node_ptr(2);
      elem_top->set_node(3) = _mesh->node_ptr(3);

      Elem* elem_bottom = _mesh->add_elem( new Quad4 );
      elem_bottom->set_node(0) = _mesh->node_ptr(4);
      elem_bottom->set_node(1) = _mesh->node_ptr(5);
      elem_bottom->set_node(2) = _mesh->node_ptr(1);
      elem_bottom->set_node(3) = _mesh->node_ptr(0);

      Elem* edge = _mesh->add_elem( new Edge2 );
      edge->set_node(0) = _mesh->node_ptr(0);
      edge->set_node(1) = _mesh->node_ptr(1);
    }

    // libMesh will renumber, but we numbered according to its scheme
    // anyway. We do this because when we call uniformly_refine subsequently,
    // it's going use skip_renumber=false.
    _mesh->prepare_for_use(false /*skip_renumber*/);
  }

public:
  void setUp()
  {
    this->build_mesh();
  }

  void tearDown()
  {
    delete _mesh;
   }

  void testMesh()
  {
    // There'd better be 3 elements
    CPPUNIT_ASSERT_EQUAL( (dof_id_type)3, _mesh->n_elem() );

    // There'd better be only 6 nodes
    CPPUNIT_ASSERT_EQUAL( (dof_id_type)6, _mesh->n_nodes() );

    /* The nodes for the EDGE2 element should have the same global ids
       as the bottom edge of the top QUAD4 element */
    CPPUNIT_ASSERT_EQUAL( _mesh->elem(2)->node(0), _mesh->elem(0)->node(0) );
    CPPUNIT_ASSERT_EQUAL( _mesh->elem(2)->node(1), _mesh->elem(0)->node(1) );

    /* The nodes for the EDGE2 element should have the same global ids
       as the top edge of the bottom QUAD4 element */
    CPPUNIT_ASSERT_EQUAL( _mesh->elem(2)->node(0), _mesh->elem(1)->node(3) );
    CPPUNIT_ASSERT_EQUAL( _mesh->elem(2)->node(1), _mesh->elem(1)->node(2) );

    /* The nodes for the bottom edge of the top QUAD4 element should have
       the same global ids as the top edge of the bottom QUAD4 element */
    CPPUNIT_ASSERT_EQUAL( _mesh->elem(0)->node(0), _mesh->elem(1)->node(3) );
    CPPUNIT_ASSERT_EQUAL( _mesh->elem(0)->node(1), _mesh->elem(1)->node(2) );
  }

  void testDofOrdering()
  {
    EquationSystems es(*_mesh);
    es.add_system<LinearImplicitSystem>("TestDofSystem");
    es.get_system("TestDofSystem").add_variable("u",FIRST);
    es.init();

    DofMap& dof_map = es.get_system("TestDofSystem").get_dof_map();

    std::vector<dof_id_type> top_quad_dof_indices, bottom_quad_dof_indices, edge_dof_indices;

    dof_map.dof_indices( _mesh->elem(0), top_quad_dof_indices );
    dof_map.dof_indices( _mesh->elem(1), bottom_quad_dof_indices );
    dof_map.dof_indices( _mesh->elem(2), edge_dof_indices );

    /* The dofs for the EDGE2 element should be the same
       as the bottom edge of the top QUAD4 dofs */
    CPPUNIT_ASSERT_EQUAL( edge_dof_indices[0], top_quad_dof_indices[0] );
    CPPUNIT_ASSERT_EQUAL( edge_dof_indices[1], top_quad_dof_indices[1] );

    /* The dofs for the EDGE2 element should be the same
       as the top edge of the bottom QUAD4 dofs */
    CPPUNIT_ASSERT_EQUAL( edge_dof_indices[0], bottom_quad_dof_indices[3] );
    CPPUNIT_ASSERT_EQUAL( edge_dof_indices[1], bottom_quad_dof_indices[2] );

    /* The nodes for the bottom edge of the top QUAD4 element should have
       the same global ids as the top edge of the bottom QUAD4 element */
    CPPUNIT_ASSERT_EQUAL( top_quad_dof_indices[0], bottom_quad_dof_indices[3] );
    CPPUNIT_ASSERT_EQUAL( top_quad_dof_indices[1], bottom_quad_dof_indices[2] );
  }

  void testPointLocatorList()
  {
    AutoPtr<PointLocatorBase> locator = PointLocatorBase::build(LIST,*_mesh);

    Point top_point(0.4, 0.5);
    const Elem* top_elem = (*locator)(top_point);
    CPPUNIT_ASSERT(top_elem);

    // We should have gotten back the top quad
    CPPUNIT_ASSERT_EQUAL( (dof_id_type)0, top_elem->id() );

    Point bottom_point(0.5, -0.5);
    const Elem* bottom_elem = (*locator)(bottom_point);
    CPPUNIT_ASSERT(bottom_elem);

    // We should have gotten back the bottom quad
    CPPUNIT_ASSERT_EQUAL( (dof_id_type)1, bottom_elem->id() );
  }

  void testPointLocatorTree()
  {
    AutoPtr<PointLocatorBase> locator = _mesh->sub_point_locator();

    Point top_point(0.5, 0.5);
    const Elem* top_elem = (*locator)(top_point);

    // We should have gotten back the top quad
    CPPUNIT_ASSERT_EQUAL( (dof_id_type)0, top_elem->id() );

    Point bottom_point(0.5, -0.5);
    const Elem* bottom_elem = (*locator)(bottom_point);

    // We should have gotten back the bottom quad
    CPPUNIT_ASSERT_EQUAL( (dof_id_type)1, bottom_elem->id() );
  }

};

class MixedDimensionRefinedMeshTest : public MixedDimensionMeshTest {
  /**
   * The goal of this test is the same as the previous, but now we do a
   * uniform refinement and make sure the result mesh is consistent. i.e.
   * the new node shared between the 1D elements is the same as the node
   * shared on the underlying quads, and so on.
   */
public:
  CPPUNIT_TEST_SUITE( MixedDimensionRefinedMeshTest );

  CPPUNIT_TEST( testMesh );
  CPPUNIT_TEST( testDofOrdering );

  CPPUNIT_TEST_SUITE_END();

  // Yes, this is necessary. Somewhere in those macros is a protected/private
public:

  void setUp()
  {
    /*

        3-------10------2
        |       |       |
        |   5   |   6   |
        8-------7-------9
        |       |       |
        |   3   |   4   |
        0-------6-------1
        |       |       |
        |   9   |  10   |
       13------12-------14
        |       |       |
        |   7   |   8   |
        4-------11------5

     */
    this->build_mesh();
#ifdef LIBMESH_ENABLE_AMR
    MeshRefinement(*_mesh).uniformly_refine(1);
#endif
  }

  void testMesh()
  {
#ifdef LIBMESH_ENABLE_AMR
    // We should have 13 total and 10 active elements.
    CPPUNIT_ASSERT_EQUAL( (dof_id_type)13, _mesh->n_elem() );
    CPPUNIT_ASSERT_EQUAL( (dof_id_type)10, _mesh->n_active_elem() );

    // We should have 15 nodes
    CPPUNIT_ASSERT_EQUAL( (dof_id_type)15, _mesh->n_nodes() );

    // EDGE2,id=11 should have same nodes of bottom of QUAD4, id=3
    CPPUNIT_ASSERT_EQUAL( _mesh->elem(11)->node(0), _mesh->elem(3)->node(0) );
    CPPUNIT_ASSERT_EQUAL( _mesh->elem(11)->node(1), _mesh->elem(3)->node(1) );

    // EDGE2,id=12 should have same nodes of bottom of QUAD4, id=4
    CPPUNIT_ASSERT_EQUAL( _mesh->elem(12)->node(0), _mesh->elem(4)->node(0) );
    CPPUNIT_ASSERT_EQUAL( _mesh->elem(12)->node(1), _mesh->elem(4)->node(1) );

    // EDGE2,id=11 should have same nodes of top of QUAD4, id=9
    CPPUNIT_ASSERT_EQUAL( _mesh->elem(11)->node(0), _mesh->elem(9)->node(3) );
    CPPUNIT_ASSERT_EQUAL( _mesh->elem(11)->node(1), _mesh->elem(9)->node(2) );

    // EDGE2,id=12 should have same nodes of top of QUAD4, id=10
    CPPUNIT_ASSERT_EQUAL( _mesh->elem(12)->node(0), _mesh->elem(10)->node(3) );
    CPPUNIT_ASSERT_EQUAL( _mesh->elem(12)->node(1), _mesh->elem(10)->node(2) );

    // Shared node between the EDGE2 elements should have the same global id
    CPPUNIT_ASSERT_EQUAL( _mesh->elem(11)->node(1), _mesh->elem(12)->node(0) );
#endif
  }

  void testDofOrdering()
  {
#ifdef LIBMESH_ENABLE_AMR
    EquationSystems es(*_mesh);
    es.add_system<LinearImplicitSystem>("TestDofSystem");
    es.get_system("TestDofSystem").add_variable("u",FIRST);
    es.init();

    DofMap& dof_map = es.get_system("TestDofSystem").get_dof_map();

    std::vector<dof_id_type> top_quad3_dof_indices, top_quad4_dof_indices;
    std::vector<dof_id_type> bottom_quad9_dof_indices, bottom_quad10_dof_indices;
    std::vector<dof_id_type> edge11_dof_indices, edge12_dof_indices;

    dof_map.dof_indices( _mesh->elem(3), top_quad3_dof_indices );
    dof_map.dof_indices( _mesh->elem(4), top_quad4_dof_indices );
    dof_map.dof_indices( _mesh->elem(9), bottom_quad9_dof_indices );
    dof_map.dof_indices( _mesh->elem(10), bottom_quad10_dof_indices );
    dof_map.dof_indices( _mesh->elem(11), edge11_dof_indices );
    dof_map.dof_indices( _mesh->elem(12), edge12_dof_indices );

    // EDGE2,id=11 should have same dofs as of bottom of QUAD4, id=3
    CPPUNIT_ASSERT_EQUAL( edge11_dof_indices[0], top_quad3_dof_indices[0] );
    CPPUNIT_ASSERT_EQUAL( edge11_dof_indices[1], top_quad3_dof_indices[1] );

    // EDGE2,id=12 should have same dofs of bottom of QUAD4, id=4
    CPPUNIT_ASSERT_EQUAL( edge12_dof_indices[0], top_quad4_dof_indices[0] );
    CPPUNIT_ASSERT_EQUAL( edge12_dof_indices[1], top_quad4_dof_indices[1] );

    // EDGE2,id=11 should have same dofs of top of QUAD4, id=9
    CPPUNIT_ASSERT_EQUAL( edge11_dof_indices[0], bottom_quad9_dof_indices[3] );
    CPPUNIT_ASSERT_EQUAL( edge11_dof_indices[1], bottom_quad9_dof_indices[2] );

    // EDGE2,id=12 should have same dofs of top of QUAD4, id=10
    CPPUNIT_ASSERT_EQUAL( edge12_dof_indices[0], bottom_quad10_dof_indices[3] );
    CPPUNIT_ASSERT_EQUAL( edge12_dof_indices[1], bottom_quad10_dof_indices[2] );

    //EDGE2 elements should have same shared dof number
    CPPUNIT_ASSERT_EQUAL( edge11_dof_indices[1], edge12_dof_indices[0] );
#endif
  }

};

CPPUNIT_TEST_SUITE_REGISTRATION( MixedDimensionMeshTest );
CPPUNIT_TEST_SUITE_REGISTRATION( MixedDimensionRefinedMeshTest );
<commit_msg>Update MixedDimension test to test out new PointLocator API<commit_after>// Ignore unused parameter warnings coming from cppuint headers
#include <libmesh/ignore_warnings.h>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/TestCase.h>
#include <libmesh/restore_warnings.h>

#include <libmesh/equation_systems.h>
#include <libmesh/serial_mesh.h>
#include <libmesh/mesh_generation.h>
#include <libmesh/edge_edge2.h>
#include <libmesh/face_quad4.h>
#include <libmesh/dof_map.h>
#include <libmesh/linear_implicit_system.h>
#include <libmesh/mesh_refinement.h>

#include "test_comm.h"

using namespace libMesh;

class MixedDimensionMeshTest : public CppUnit::TestCase {
  /**
   * The goal of this test is to ensure that a 2D mesh with 1D elements overlapping
   * on the edge is consistent. That is, they share the same global node numbers and
   * the same dof numbers for a variable.
   */
public:
  CPPUNIT_TEST_SUITE( MixedDimensionMeshTest );

  CPPUNIT_TEST( testMesh );
  CPPUNIT_TEST( testDofOrdering );
  CPPUNIT_TEST( testPointLocatorList );
  CPPUNIT_TEST( testPointLocatorTree );

  CPPUNIT_TEST_SUITE_END();

protected:

  SerialMesh* _mesh;

  void build_mesh()
  {
    _mesh = new SerialMesh(*TestCommWorld);

    /*
      (0,1)           (1,1)
        x---------------x
        |               |
        |               |
        |               |
        |               |
        |               |
        x---------------x
       (0,0)           (1,0)
        |               |
        |               |
        |               |
        |               |
        x---------------x
       (0,-1)          (1,-1)
     */

    _mesh->set_mesh_dimension(2);

    _mesh->add_point( Point(0.0,-1.0), 4 );
    _mesh->add_point( Point(1.0,-1.0), 5 );
    _mesh->add_point( Point(1.0, 0.0), 1 );
    _mesh->add_point( Point(1.0, 1.0), 2 );
    _mesh->add_point( Point(0.0, 1.0), 3 );
    _mesh->add_point( Point(0.0, 0.0), 0 );

    {
      Elem* elem_top = _mesh->add_elem( new Quad4 );
      elem_top->set_node(0) = _mesh->node_ptr(0);
      elem_top->set_node(1) = _mesh->node_ptr(1);
      elem_top->set_node(2) = _mesh->node_ptr(2);
      elem_top->set_node(3) = _mesh->node_ptr(3);

      Elem* elem_bottom = _mesh->add_elem( new Quad4 );
      elem_bottom->set_node(0) = _mesh->node_ptr(4);
      elem_bottom->set_node(1) = _mesh->node_ptr(5);
      elem_bottom->set_node(2) = _mesh->node_ptr(1);
      elem_bottom->set_node(3) = _mesh->node_ptr(0);

      Elem* edge = _mesh->add_elem( new Edge2 );
      edge->set_node(0) = _mesh->node_ptr(0);
      edge->set_node(1) = _mesh->node_ptr(1);
    }

    // libMesh will renumber, but we numbered according to its scheme
    // anyway. We do this because when we call uniformly_refine subsequently,
    // it's going use skip_renumber=false.
    _mesh->prepare_for_use(false /*skip_renumber*/);
  }

public:
  void setUp()
  {
    this->build_mesh();
  }

  void tearDown()
  {
    delete _mesh;
   }

  void testMesh()
  {
    // There'd better be 3 elements
    CPPUNIT_ASSERT_EQUAL( (dof_id_type)3, _mesh->n_elem() );

    // There'd better be only 6 nodes
    CPPUNIT_ASSERT_EQUAL( (dof_id_type)6, _mesh->n_nodes() );

    /* The nodes for the EDGE2 element should have the same global ids
       as the bottom edge of the top QUAD4 element */
    CPPUNIT_ASSERT_EQUAL( _mesh->elem(2)->node(0), _mesh->elem(0)->node(0) );
    CPPUNIT_ASSERT_EQUAL( _mesh->elem(2)->node(1), _mesh->elem(0)->node(1) );

    /* The nodes for the EDGE2 element should have the same global ids
       as the top edge of the bottom QUAD4 element */
    CPPUNIT_ASSERT_EQUAL( _mesh->elem(2)->node(0), _mesh->elem(1)->node(3) );
    CPPUNIT_ASSERT_EQUAL( _mesh->elem(2)->node(1), _mesh->elem(1)->node(2) );

    /* The nodes for the bottom edge of the top QUAD4 element should have
       the same global ids as the top edge of the bottom QUAD4 element */
    CPPUNIT_ASSERT_EQUAL( _mesh->elem(0)->node(0), _mesh->elem(1)->node(3) );
    CPPUNIT_ASSERT_EQUAL( _mesh->elem(0)->node(1), _mesh->elem(1)->node(2) );
  }

  void testDofOrdering()
  {
    EquationSystems es(*_mesh);
    es.add_system<LinearImplicitSystem>("TestDofSystem");
    es.get_system("TestDofSystem").add_variable("u",FIRST);
    es.init();

    DofMap& dof_map = es.get_system("TestDofSystem").get_dof_map();

    std::vector<dof_id_type> top_quad_dof_indices, bottom_quad_dof_indices, edge_dof_indices;

    dof_map.dof_indices( _mesh->elem(0), top_quad_dof_indices );
    dof_map.dof_indices( _mesh->elem(1), bottom_quad_dof_indices );
    dof_map.dof_indices( _mesh->elem(2), edge_dof_indices );

    /* The dofs for the EDGE2 element should be the same
       as the bottom edge of the top QUAD4 dofs */
    CPPUNIT_ASSERT_EQUAL( edge_dof_indices[0], top_quad_dof_indices[0] );
    CPPUNIT_ASSERT_EQUAL( edge_dof_indices[1], top_quad_dof_indices[1] );

    /* The dofs for the EDGE2 element should be the same
       as the top edge of the bottom QUAD4 dofs */
    CPPUNIT_ASSERT_EQUAL( edge_dof_indices[0], bottom_quad_dof_indices[3] );
    CPPUNIT_ASSERT_EQUAL( edge_dof_indices[1], bottom_quad_dof_indices[2] );

    /* The nodes for the bottom edge of the top QUAD4 element should have
       the same global ids as the top edge of the bottom QUAD4 element */
    CPPUNIT_ASSERT_EQUAL( top_quad_dof_indices[0], bottom_quad_dof_indices[3] );
    CPPUNIT_ASSERT_EQUAL( top_quad_dof_indices[1], bottom_quad_dof_indices[2] );
  }

  void testPointLocatorList()
  {
    AutoPtr<PointLocatorBase> locator = PointLocatorBase::build(LIST,*_mesh);

    Point top_point(0.4, 0.5);
    const Elem* top_elem = (*locator)(top_point);
    CPPUNIT_ASSERT(top_elem);

    // We should have gotten back the top quad
    CPPUNIT_ASSERT_EQUAL( (dof_id_type)0, top_elem->id() );

    Point bottom_point(0.5, -0.5);
    const Elem* bottom_elem = (*locator)(bottom_point);
    CPPUNIT_ASSERT(bottom_elem);

    // We should have gotten back the bottom quad
    CPPUNIT_ASSERT_EQUAL( (dof_id_type)1, bottom_elem->id() );

    // Now try to find the 1d element overlapping the interface edge
    Point interface_point(0.2, 0.0);
    const Elem* interface_elem = (*locator)(interface_point,1);

    CPPUNIT_ASSERT(interface_elem);

    // We should have gotten back the bottom quad
    CPPUNIT_ASSERT_EQUAL( (dof_id_type)2, interface_elem->id() );
  }

  void testPointLocatorTree()
  {
    AutoPtr<PointLocatorBase> locator = _mesh->sub_point_locator();

    Point top_point(0.5, 0.5);
    const Elem* top_elem = (*locator)(top_point);

    // We should have gotten back the top quad
    CPPUNIT_ASSERT_EQUAL( (dof_id_type)0, top_elem->id() );

    Point bottom_point(0.5, -0.5);
    const Elem* bottom_elem = (*locator)(bottom_point);

    // We should have gotten back the bottom quad
    CPPUNIT_ASSERT_EQUAL( (dof_id_type)1, bottom_elem->id() );

    // Now try to find the 1d element overlapping the interface edge
    Point interface_point(0.2, 0.0);
    const Elem* interface_elem = (*locator)(interface_point,1);

    CPPUNIT_ASSERT(interface_elem);

    // We should have gotten back the bottom quad
    CPPUNIT_ASSERT_EQUAL( (dof_id_type)2, interface_elem->id() );
  }

};

class MixedDimensionRefinedMeshTest : public MixedDimensionMeshTest {
  /**
   * The goal of this test is the same as the previous, but now we do a
   * uniform refinement and make sure the result mesh is consistent. i.e.
   * the new node shared between the 1D elements is the same as the node
   * shared on the underlying quads, and so on.
   */
public:
  CPPUNIT_TEST_SUITE( MixedDimensionRefinedMeshTest );

  CPPUNIT_TEST( testMesh );
  CPPUNIT_TEST( testDofOrdering );

  CPPUNIT_TEST_SUITE_END();

  // Yes, this is necessary. Somewhere in those macros is a protected/private
public:

  void setUp()
  {
    /*

        3-------10------2
        |       |       |
        |   5   |   6   |
        8-------7-------9
        |       |       |
        |   3   |   4   |
        0-------6-------1
        |       |       |
        |   9   |  10   |
       13------12-------14
        |       |       |
        |   7   |   8   |
        4-------11------5

     */
    this->build_mesh();
#ifdef LIBMESH_ENABLE_AMR
    MeshRefinement(*_mesh).uniformly_refine(1);
#endif
  }

  void testMesh()
  {
#ifdef LIBMESH_ENABLE_AMR
    // We should have 13 total and 10 active elements.
    CPPUNIT_ASSERT_EQUAL( (dof_id_type)13, _mesh->n_elem() );
    CPPUNIT_ASSERT_EQUAL( (dof_id_type)10, _mesh->n_active_elem() );

    // We should have 15 nodes
    CPPUNIT_ASSERT_EQUAL( (dof_id_type)15, _mesh->n_nodes() );

    // EDGE2,id=11 should have same nodes of bottom of QUAD4, id=3
    CPPUNIT_ASSERT_EQUAL( _mesh->elem(11)->node(0), _mesh->elem(3)->node(0) );
    CPPUNIT_ASSERT_EQUAL( _mesh->elem(11)->node(1), _mesh->elem(3)->node(1) );

    // EDGE2,id=12 should have same nodes of bottom of QUAD4, id=4
    CPPUNIT_ASSERT_EQUAL( _mesh->elem(12)->node(0), _mesh->elem(4)->node(0) );
    CPPUNIT_ASSERT_EQUAL( _mesh->elem(12)->node(1), _mesh->elem(4)->node(1) );

    // EDGE2,id=11 should have same nodes of top of QUAD4, id=9
    CPPUNIT_ASSERT_EQUAL( _mesh->elem(11)->node(0), _mesh->elem(9)->node(3) );
    CPPUNIT_ASSERT_EQUAL( _mesh->elem(11)->node(1), _mesh->elem(9)->node(2) );

    // EDGE2,id=12 should have same nodes of top of QUAD4, id=10
    CPPUNIT_ASSERT_EQUAL( _mesh->elem(12)->node(0), _mesh->elem(10)->node(3) );
    CPPUNIT_ASSERT_EQUAL( _mesh->elem(12)->node(1), _mesh->elem(10)->node(2) );

    // Shared node between the EDGE2 elements should have the same global id
    CPPUNIT_ASSERT_EQUAL( _mesh->elem(11)->node(1), _mesh->elem(12)->node(0) );
#endif
  }

  void testDofOrdering()
  {
#ifdef LIBMESH_ENABLE_AMR
    EquationSystems es(*_mesh);
    es.add_system<LinearImplicitSystem>("TestDofSystem");
    es.get_system("TestDofSystem").add_variable("u",FIRST);
    es.init();

    DofMap& dof_map = es.get_system("TestDofSystem").get_dof_map();

    std::vector<dof_id_type> top_quad3_dof_indices, top_quad4_dof_indices;
    std::vector<dof_id_type> bottom_quad9_dof_indices, bottom_quad10_dof_indices;
    std::vector<dof_id_type> edge11_dof_indices, edge12_dof_indices;

    dof_map.dof_indices( _mesh->elem(3), top_quad3_dof_indices );
    dof_map.dof_indices( _mesh->elem(4), top_quad4_dof_indices );
    dof_map.dof_indices( _mesh->elem(9), bottom_quad9_dof_indices );
    dof_map.dof_indices( _mesh->elem(10), bottom_quad10_dof_indices );
    dof_map.dof_indices( _mesh->elem(11), edge11_dof_indices );
    dof_map.dof_indices( _mesh->elem(12), edge12_dof_indices );

    // EDGE2,id=11 should have same dofs as of bottom of QUAD4, id=3
    CPPUNIT_ASSERT_EQUAL( edge11_dof_indices[0], top_quad3_dof_indices[0] );
    CPPUNIT_ASSERT_EQUAL( edge11_dof_indices[1], top_quad3_dof_indices[1] );

    // EDGE2,id=12 should have same dofs of bottom of QUAD4, id=4
    CPPUNIT_ASSERT_EQUAL( edge12_dof_indices[0], top_quad4_dof_indices[0] );
    CPPUNIT_ASSERT_EQUAL( edge12_dof_indices[1], top_quad4_dof_indices[1] );

    // EDGE2,id=11 should have same dofs of top of QUAD4, id=9
    CPPUNIT_ASSERT_EQUAL( edge11_dof_indices[0], bottom_quad9_dof_indices[3] );
    CPPUNIT_ASSERT_EQUAL( edge11_dof_indices[1], bottom_quad9_dof_indices[2] );

    // EDGE2,id=12 should have same dofs of top of QUAD4, id=10
    CPPUNIT_ASSERT_EQUAL( edge12_dof_indices[0], bottom_quad10_dof_indices[3] );
    CPPUNIT_ASSERT_EQUAL( edge12_dof_indices[1], bottom_quad10_dof_indices[2] );

    //EDGE2 elements should have same shared dof number
    CPPUNIT_ASSERT_EQUAL( edge11_dof_indices[1], edge12_dof_indices[0] );
#endif
  }

};

CPPUNIT_TEST_SUITE_REGISTRATION( MixedDimensionMeshTest );
CPPUNIT_TEST_SUITE_REGISTRATION( MixedDimensionRefinedMeshTest );
<|endoftext|>


<commit_before>// Source : https://leetcode.com/problems/reverse-vowels-of-a-string/
// Author : Calinescu Valentin
// Date   : 2016-04-30

/***************************************************************************************
 *
 * Write a function that takes a string as input and reverse only the vowels of a
 * string.
 *
 * Example 1:
 * Given s = "hello", return "holle".
 *
 * Example 2:
 * Given s = "leetcode", return "leotcede".
 *
 ***************************************************************************************/
class Solution {
public:
    string reverseVowels(string s) {
        list <char> vowels;
        set <char> vows;
        vows.insert('a');
        vows.insert('A');
        vows.insert('e');
        vows.insert('E');
        vows.insert('i');
        vows.insert('I');
        vows.insert('o');
        vows.insert('O');
        vows.insert('u');
        vows.insert('U');
        string result;
        for(int i = 0; i < s.size(); i++)
        {
            if(vows.find(s[i]) != vows.end())
                vowels.push_back(s[i]);
        }
        for(int i = 0; i < s.size(); i++)
        {
            if(vows.find(s[i]) != vows.end())
            {
                result.push_back(vowels.back());
                vowels.pop_back();
            }
            else
                result.push_back(s[i]);
        }
        return result;
    }
};
<commit_msg>New solution for "Reverse Vowels of a String"<commit_after>// Source : https://leetcode.com/problems/reverse-vowels-of-a-string/
// Author : Calinescu Valentin, Hao Chen
// Date   : 2016-04-30

/***************************************************************************************
 *
 * Write a function that takes a string as input and reverse only the vowels of a
 * string.
 *
 * Example 1:
 * Given s = "hello", return "holle".
 *
 * Example 2:
 * Given s = "leetcode", return "leotcede".
 *
 ***************************************************************************************/

//Author: Calinescu Valentin
class Solution {
public:
    string reverseVowels(string s) {
        list <char> vowels;
        set <char> vows;
        vows.insert('a');
        vows.insert('A');
        vows.insert('e');
        vows.insert('E');
        vows.insert('i');
        vows.insert('I');
        vows.insert('o');
        vows.insert('O');
        vows.insert('u');
        vows.insert('U');
        string result;
        for(int i = 0; i < s.size(); i++)
        {
            if(vows.find(s[i]) != vows.end())
                vowels.push_back(s[i]);
        }
        for(int i = 0; i < s.size(); i++)
        {
            if(vows.find(s[i]) != vows.end())
            {
                result.push_back(vowels.back());
                vowels.pop_back();
            }
            else
                result.push_back(s[i]);
        }
        return result;
    }
};

// Author: Hao Chen
// 1) preset a dictionary table to look up vowels
// 2) we have two pointer, the `left` one search vowels from the beginning to then end, the `right` one search from the end to the beginning.
// 3) swap the left one and the right one until left >= right.
class Solution {
private:
   bool vowelsTable[256];
public:
    Solution(){
        memset(vowelsTable, 0, sizeof(vowelsTable));
        vowelsTable['a']=true;
        vowelsTable['e']=true;
        vowelsTable['i']=true;
        vowelsTable['o']=true;
        vowelsTable['u']=true;

        vowelsTable['A']=true;
        vowelsTable['E']=true;
        vowelsTable['I']=true;
        vowelsTable['O']=true;
        vowelsTable['U']=true;
    }
    bool isVowels(char ch) {
        return vowelsTable[ch];
    }
    string reverseVowels(string s) {
        int left=0, right=s.size()-1;
        while ( left < right ) {
            while( !isVowels( s[left]) ) left++;
            while( !isVowels( s[right] ) ) right--;
            if (left >= right) break;
            swap(s[left], s[right]);
            left++; right--;
        }
        return s;
    }
};
<|endoftext|>


<commit_before>// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license.  We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.

#include "catch.hpp"
#include "mfem.hpp"

using namespace mfem;

int dimension;
double coeff(const Vector& x)
{
   if (dimension == 2)
   {
      return 1.1 * x[0] + 2.0 * x[1];
   }
   else
   {
      return 1.1 * x[0] + 2.0 * x[1] + 3.0 * x[2];
   }
}

void vectorcoeff(const Vector& x, Vector& y)
{
   y(0) = coeff(x);
   y(1) = -coeff(x);
   if (dimension == 3)
   {
      y(2) = 2.0 * coeff(x);
   }
}

TEST_CASE("ptransfer")
{

   for (int vectorspace = 0; vectorspace <= 1; ++vectorspace)
   {
      for (dimension = 2; dimension <= 3; ++dimension)
      {
         for (int ne = 1; ne <= 3; ++ne)
         {
            for (int order = 1; order <= 4; order *= 2)
            {
               for (int geometric = 0; geometric <= 1; ++geometric)
               {

                  int fineOrder = (geometric == 1) ? order : 2 * order;

                  std::cout << "Testing transfer:\n"
                            << "  Vectorspace:  " << vectorspace << "\n"
                            << "  Dimension:    " << dimension << "\n"
                            << "  Elements:     " << std::pow(ne, dimension) << "\n"
                            << "  Coarse order: " << order << "\n"
                            << "  Fine order:   " << fineOrder << "\n"
                            << "  Geometric:    " << geometric << "\n";

                  Mesh* mesh;
                  if (dimension == 2)
                  {
                     mesh = new Mesh(ne, ne, Element::QUADRILATERAL, 1, 1.0, 1.0);
                  }
                  else
                  {
                     mesh =
                        new Mesh(ne, ne, ne, Element::HEXAHEDRON, 1, 1.0, 1.0, 1.0);
                  }
                  FiniteElementCollection* c_h1_fec =
                     new H1_FECollection(order, dimension);
                  FiniteElementCollection* f_h1_fec = (geometric == 1) ? c_h1_fec : new
                                                      H1_FECollection(fineOrder, dimension);

                  Mesh fineMesh(*mesh);
                  if (geometric)
                  {
                     fineMesh.UniformRefinement();
                  }

                  int spaceDimension = 1;

                  if (vectorspace == 1)
                  {
                     spaceDimension = dimension;
                  }

                  FiniteElementSpace* c_h1_fespace = new FiniteElementSpace(mesh, c_h1_fec,
                                                                            spaceDimension);
                  FiniteElementSpace* f_h1_fespace = new FiniteElementSpace(&fineMesh, f_h1_fec,
                                                                            spaceDimension);

                  Operator* referenceOperator = nullptr;

                  if (geometric == 0)
                  {
                     referenceOperator = new PRefinementTransferOperator(*c_h1_fespace,
                                                                         *f_h1_fespace);
                  }
                  else
                  {
                     referenceOperator = new TransferOperator(*c_h1_fespace,
                                                              *f_h1_fespace);
                  }

                  TensorProductPRefinementTransferOperator tpTransferOperator(
                     *c_h1_fespace, *f_h1_fespace);
                  GridFunction X(c_h1_fespace);
                  GridFunction X_cmp(c_h1_fespace);
                  GridFunction Y_exact(f_h1_fespace);
                  GridFunction Y_std(f_h1_fespace);
                  GridFunction Y_tp(f_h1_fespace);

                  if (vectorspace == 0)
                  {
                     FunctionCoefficient funcCoeff(&coeff);
                     X.ProjectCoefficient(funcCoeff);
                     Y_exact.ProjectCoefficient(funcCoeff);
                  }
                  else
                  {
                     VectorFunctionCoefficient funcCoeff(dimension, &vectorcoeff);
                     X.ProjectCoefficient(funcCoeff);
                     Y_exact.ProjectCoefficient(funcCoeff);
                  }

                  Y_std = 0.0;
                  Y_tp = 0.0;

                  referenceOperator->Mult(X, Y_std);

                  Y_std -= Y_exact;
                  REQUIRE(Y_std.Norml2() < 1e-12);

                  if (vectorspace == 0 && geometric == 0)
                  {
                     tpTransferOperator.Mult(X, Y_tp);

                     Y_tp -= Y_exact;
                     REQUIRE(Y_tp.Norml2() < 1e-12);
                  }

                  if (vectorspace == 0 && geometric == 0)
                  {
                     referenceOperator->MultTranspose(Y_exact, X);
                     tpTransferOperator.MultTranspose(Y_exact, X_cmp);

                     X -= X_cmp;
                     REQUIRE(X.Norml2() < 1e-12);
                  }

                  delete referenceOperator;
                  delete f_h1_fespace;
                  delete c_h1_fespace;
                  if (geometric == 0)
                  {
                     delete f_h1_fec;
                  }
                  delete c_h1_fec;
                  delete mesh;
               }
            }
         }
      }
   }
}
<commit_msg>Added tests for parallel grid transfers<commit_after>// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license.  We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.

#include "catch.hpp"
#include "mfem.hpp"

using namespace mfem;

int dimension;
double coeff(const Vector& x)
{
   if (dimension == 2)
   {
      return 1.1 * x[0] + 2.0 * x[1];
   }
   else
   {
      return 1.1 * x[0] + 2.0 * x[1] + 3.0 * x[2];
   }
}

void vectorcoeff(const Vector& x, Vector& y)
{
   y(0) = coeff(x);
   y(1) = -coeff(x);
   if (dimension == 3)
   {
      y(2) = 2.0 * coeff(x);
   }
}

TEST_CASE("transfer")
{
   for (int vectorspace = 0; vectorspace <= 1; ++vectorspace)
   {
      for (dimension = 2; dimension <= 3; ++dimension)
      {
         for (int ne = 1; ne <= 3; ++ne)
         {
            for (int order = 1; order <= 4; order *= 2)
            {
               for (int geometric = 0; geometric <= 1; ++geometric)
               {

                  int fineOrder = (geometric == 1) ? order : 2 * order;

                  std::cout << "Testing transfer:\n"
                            << "  Vectorspace:  " << vectorspace << "\n"
                            << "  Dimension:    " << dimension << "\n"
                            << "  Elements:     " << std::pow(ne, dimension) << "\n"
                            << "  Coarse order: " << order << "\n"
                            << "  Fine order:   " << fineOrder << "\n"
                            << "  Geometric:    " << geometric << "\n";

                  Mesh* mesh;
                  if (dimension == 2)
                  {
                     mesh = new Mesh(ne, ne, Element::QUADRILATERAL, 1, 1.0, 1.0);
                  }
                  else
                  {
                     mesh =
                        new Mesh(ne, ne, ne, Element::HEXAHEDRON, 1, 1.0, 1.0, 1.0);
                  }
                  FiniteElementCollection* c_h1_fec =
                     new H1_FECollection(order, dimension);
                  FiniteElementCollection* f_h1_fec = (geometric == 1) ? c_h1_fec : new
                                                      H1_FECollection(fineOrder, dimension);

                  Mesh fineMesh(*mesh);
                  if (geometric)
                  {
                     fineMesh.UniformRefinement();
                  }

                  int spaceDimension = 1;

                  if (vectorspace == 1)
                  {
                     spaceDimension = dimension;
                  }

                  FiniteElementSpace* c_h1_fespace = new FiniteElementSpace(mesh, c_h1_fec,
                                                                            spaceDimension);
                  FiniteElementSpace* f_h1_fespace = new FiniteElementSpace(&fineMesh, f_h1_fec,
                                                                            spaceDimension);

                  Operator* referenceOperator = nullptr;

                  if (geometric == 0)
                  {
                     referenceOperator = new PRefinementTransferOperator(*c_h1_fespace,
                                                                         *f_h1_fespace);
                  }
                  else
                  {
                     referenceOperator = new TransferOperator(*c_h1_fespace,
                                                              *f_h1_fespace);
                  }

                  TensorProductPRefinementTransferOperator tpTransferOperator(
                     *c_h1_fespace, *f_h1_fespace);
                  GridFunction X(c_h1_fespace);
                  GridFunction X_cmp(c_h1_fespace);
                  GridFunction Y_exact(f_h1_fespace);
                  GridFunction Y_std(f_h1_fespace);
                  GridFunction Y_tp(f_h1_fespace);

                  if (vectorspace == 0)
                  {
                     FunctionCoefficient funcCoeff(&coeff);
                     X.ProjectCoefficient(funcCoeff);
                     Y_exact.ProjectCoefficient(funcCoeff);
                  }
                  else
                  {
                     VectorFunctionCoefficient funcCoeff(dimension, &vectorcoeff);
                     X.ProjectCoefficient(funcCoeff);
                     Y_exact.ProjectCoefficient(funcCoeff);
                  }

                  Y_std = 0.0;
                  Y_tp = 0.0;

                  referenceOperator->Mult(X, Y_std);

                  Y_std -= Y_exact;
                  REQUIRE(Y_std.Norml2() < 1e-12 * Y_exact.Norml2());

                  if (vectorspace == 0 && geometric == 0)
                  {
                     tpTransferOperator.Mult(X, Y_tp);

                     Y_tp -= Y_exact;
                     REQUIRE(Y_tp.Norml2() < 1e-12 * Y_exact.Norml2());
                  }

                  if (vectorspace == 0 && geometric == 0)
                  {
                     referenceOperator->MultTranspose(Y_exact, X);
                     tpTransferOperator.MultTranspose(Y_exact, X_cmp);

                     X -= X_cmp;
                     REQUIRE(X.Norml2() < 1e-12 * X_cmp.Norml2());
                  }

                  delete referenceOperator;
                  delete f_h1_fespace;
                  delete c_h1_fespace;
                  if (geometric == 0)
                  {
                     delete f_h1_fec;
                  }
                  delete c_h1_fec;
                  delete mesh;
               }
            }
         }
      }
   }
}

#ifdef MFEM_USE_MPI

TEST_CASE("partransfer", "[Parallel]")
{
   for (dimension = 2; dimension <= 3; ++dimension)
   {
      for (int ne = 4; ne <= 5; ++ne)
      {
         for (int order = 1; order <= 4; order *= 2)
         {
            for (int geometric = 0; geometric <= 1; ++geometric)
            {
               int fineOrder = (geometric == 1) ? order : 2 * order;

               int num_procs;
               MPI_Comm_size(MPI_COMM_WORLD, &num_procs);
               int myid;
               MPI_Comm_rank(MPI_COMM_WORLD, &myid);

               if (myid == 0)
               {
                  std::cout << "Testing parallel transfer:\n"
                            << "  Dimension:    " << dimension << "\n"
                            << "  Elements:     " << std::pow(ne, dimension) << "\n"
                            << "  Coarse order: " << order << "\n"
                            << "  Fine order:   " << fineOrder << "\n"
                            << "  Geometric:    " << geometric << "\n";
               }

               Mesh* mesh;
               if (dimension == 2)
               {
                  mesh = new Mesh(ne, ne, Element::QUADRILATERAL, 1, 1.0, 1.0);
               }
               else
               {
                  mesh =
                     new Mesh(ne, ne, ne, Element::HEXAHEDRON, 1, 1.0, 1.0, 1.0);
               }

               Mesh fineMesh(*mesh);
               if (geometric)
               {
                  fineMesh.UniformRefinement();
               }

               ParMesh *pmesh = new ParMesh(MPI_COMM_WORLD, *mesh);
               ParMesh pfineMesh(MPI_COMM_WORLD, *mesh);
               if (geometric)
               {
                  pfineMesh.UniformRefinement();
               }

               FiniteElementCollection* c_h1_fec =
                  new H1_FECollection(order, dimension);
               FiniteElementCollection* f_h1_fec = (geometric == 1) ? c_h1_fec : new
                                                   H1_FECollection(fineOrder, dimension);

               int spaceDimension = 1;

               double referenceRestrictionValue = 0.0;

               // Compute reference values in serial
               {
                  FiniteElementSpace* c_h1_fespace = new FiniteElementSpace(mesh, c_h1_fec,
                                                                            spaceDimension);
                  FiniteElementSpace* f_h1_fespace = new FiniteElementSpace(&fineMesh, f_h1_fec,
                                                                            spaceDimension);

                  Operator* transferOperator = new TransferOperator(*c_h1_fespace,
                                                                    *f_h1_fespace);
                  GridFunction X(c_h1_fespace);
                  GridFunction Y(f_h1_fespace);

                  FunctionCoefficient funcCoeff(&coeff);
                  Y.ProjectCoefficient(funcCoeff);
                  X = 0.0;

                  transferOperator->MultTranspose(Y, X);

                  referenceRestrictionValue = std::sqrt(InnerProduct(X, X));

                  delete transferOperator;
                  delete f_h1_fespace;
                  delete c_h1_fespace;
               }

               ParFiniteElementSpace* c_h1_fespace = new ParFiniteElementSpace(pmesh, c_h1_fec,
                                                                               spaceDimension);
               ParFiniteElementSpace* f_h1_fespace = new ParFiniteElementSpace(&pfineMesh,
                                                                               f_h1_fec,
                                                                               spaceDimension);

               Operator* transferOperator = new TrueTransferOperator(*c_h1_fespace,
                                                                     *f_h1_fespace);
               ParGridFunction X(c_h1_fespace);
               ParGridFunction Y_exact(f_h1_fespace);
               ParGridFunction Y(f_h1_fespace);

               FunctionCoefficient funcCoeff(&coeff);
               X.ProjectCoefficient(funcCoeff);
               Y_exact.ProjectCoefficient(funcCoeff);

               Y = 0.0;

               Vector X_true(c_h1_fespace->GetTrueVSize());
               Vector Y_true(f_h1_fespace->GetTrueVSize());

               c_h1_fespace->GetRestrictionMatrix()->Mult(X, X_true);
               transferOperator->Mult(X_true, Y_true);
               f_h1_fespace->GetProlongationMatrix()->Mult(Y_true, Y);

               Y -= Y_exact;
               REQUIRE(Y.Norml2() < 1e-12 * Y_exact.Norml2());

               f_h1_fespace->GetRestrictionMatrix()->Mult(Y_exact, Y_true);
               transferOperator->MultTranspose(Y_true, X_true);

               double restrictionValue = std::sqrt(InnerProduct(MPI_COMM_WORLD, X_true,
                                                                X_true));
               REQUIRE(std::abs(restrictionValue - referenceRestrictionValue) < 1e-12 *
                       std::abs(referenceRestrictionValue));

               delete transferOperator;
               delete f_h1_fespace;
               delete c_h1_fespace;
               if (geometric == 0)
               {
                  delete f_h1_fec;
               }
               delete c_h1_fec;
               delete pmesh;
               delete mesh;
            }
         }
      }
   }
}

#endif
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: unotest.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 03:51:19 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_testshl2.hxx"
#ifndef _RTL_BOOTSTRAP_HXX_
#include "rtl/bootstrap.hxx"
#endif

#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif

#ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_
#include <com/sun/star/uno/XComponentContext.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif

#ifndef CPPUNIT_SIMPLEHEADER_HXX
#include <cppunit/simpleheader.hxx>
#endif

#ifndef _CPPUHELPER_BOOTSTRAP_HXX_
#include <cppuhelper/bootstrap.hxx>
#endif

#ifndef _COM_SUN_STAR_XML_SAX_XPARSER_HPP_
#include <com/sun/star/xml/sax/XParser.hpp>
#endif

namespace css = com::sun::star;
namespace lang = css::lang;
namespace uno  = css::uno;
namespace sax = css::xml::sax;

// StringHelper
inline void operator <<= (rtl::OString& _rAsciiString, const rtl::OUString& _rUnicodeString)
{
    _rAsciiString = rtl::OUStringToOString(_rUnicodeString,RTL_TEXTENCODING_ASCII_US);
}

namespace unotest
{
//------------------------------------------------------------------------
// testing constructors
//------------------------------------------------------------------------

    class  ctor : public CppUnit::TestFixture
    {
    public:
        void ctor_001()
            {
                uno::Reference< lang::XMultiServiceFactory > xFactory( ::comphelper::getProcessServiceFactory() );
                if (xFactory.is())
                {
                    // sample, get a xParser instance
                    uno::Reference< sax::XParser > xParser;
                    xParser = uno::Reference< sax::XParser > (
                        xFactory->createInstance(
                            ::rtl::OUString::createFromAscii("com.sun.star.xml.sax.Parser")), uno::UNO_QUERY);

                    CPPUNIT_ASSERT_MESSAGE("can't get sax::Parser", xParser.is());
                }
            }

        CPPUNIT_TEST_SUITE(ctor);
        CPPUNIT_TEST(ctor_001);
        CPPUNIT_TEST_SUITE_END();
    };

    // -----------------------------------------------------------------------------
    CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(unotest::ctor, "unotest");
} // unotest

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

// this macro creates an empty function, which will called by the RegisterAllFunctions()
// to let the user the possibility to also register some functions by hand.

void RegisterAdditionalFunctions(FktRegFuncPtr _pFunc)
{
    uno::Reference<lang::XMultiServiceFactory> xMS;

    try
    {
        uno::Reference< uno::XComponentContext > xComponentContext = cppu::defaultBootstrap_InitialComponentContext();
        xMS.set(xComponentContext->getServiceManager(), uno::UNO_QUERY);
        comphelper::setProcessServiceFactory(xMS);
    }
    catch (::com::sun::star::uno::Exception e )
    {
        rtl::OString aError;
        aError <<= e.Message;
        printf("Error: %s\n", aError.getStr());
    }
}
// NOADDITIONAL;
<commit_msg>INTEGRATION: CWS rpt23fix02 (1.3.24); FILE MERGED 2007/07/23 11:16:00 lla 1.3.24.1: #i79902# make demos buildable<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: unotest.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: hr $ $Date: 2007-08-03 10:17:52 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_testshl2.hxx"
#ifndef _RTL_BOOTSTRAP_HXX_
#include "rtl/bootstrap.hxx"
#endif

#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif

#ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_
#include <com/sun/star/uno/XComponentContext.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif

#ifndef CPPUNIT_SIMPLEHEADER_HXX
#include <cppunit/simpleheader.hxx>
#endif

#ifndef _CPPUHELPER_BOOTSTRAP_HXX_
#include <cppuhelper/bootstrap.hxx>
#endif

#ifndef _COM_SUN_STAR_XML_SAX_XPARSER_HPP_
#include <com/sun/star/xml/sax/XParser.hpp>
#endif

namespace css = com::sun::star;
namespace lang = css::lang;
namespace uno  = css::uno;
namespace sax = css::xml::sax;

// StringHelper
inline void operator <<= (rtl::OString& _rAsciiString, const rtl::OUString& _rUnicodeString)
{
    _rAsciiString = rtl::OUStringToOString(_rUnicodeString,RTL_TEXTENCODING_ASCII_US);
}

namespace unotest
{
//------------------------------------------------------------------------
// testing constructors
//------------------------------------------------------------------------

    class  ctor : public CppUnit::TestFixture
    {
    public:
        void ctor_001()
            {
                uno::Reference< lang::XMultiServiceFactory > xFactory( ::comphelper::getProcessServiceFactory() );
                if (xFactory.is())
                {
                    // sample, get a xParser instance
                    uno::Reference< sax::XParser > xParser;
                    xParser = uno::Reference< sax::XParser > (
                        xFactory->createInstance(
                            ::rtl::OUString::createFromAscii("com.sun.star.xml.sax.Parser")), uno::UNO_QUERY);

                    CPPUNIT_ASSERT_MESSAGE("can't get sax::Parser", xParser.is());
                }
            }

        CPPUNIT_TEST_SUITE(ctor);
        CPPUNIT_TEST(ctor_001);
        CPPUNIT_TEST_SUITE_END();
    };

    // -----------------------------------------------------------------------------
    CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(unotest::ctor, "unotest");
} // unotest

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

// this macro creates an empty function, which will called by the RegisterAllFunctions()
// to let the user the possibility to also register some functions by hand.

void RegisterAdditionalFunctions(FktRegFuncPtr _pFunc)
{
    (void) _pFunc;
    uno::Reference<lang::XMultiServiceFactory> xMS;

    try
    {
        uno::Reference< uno::XComponentContext > xComponentContext = cppu::defaultBootstrap_InitialComponentContext();
        xMS.set(xComponentContext->getServiceManager(), uno::UNO_QUERY);
        comphelper::setProcessServiceFactory(xMS);
    }
    catch (::com::sun::star::uno::Exception e )
    {
        rtl::OString aError;
        aError <<= e.Message;
        printf("Error: %s\n", aError.getStr());
    }
}
// NOADDITIONAL;
<|endoftext|>


<commit_before>#include "resultmodel.h"
#include "resultscheduler.h"
#include "../types.h"
#include "task/scheduledefinition.h"
#include "scheduler/scheduler.h"
#include "client.h"
#include "log/logger.h"

#include <QPointer>
#include <QUuid>
#include <QHash>

LOGGER("ResultModel");

class ResultModel::Private : public QObject
{
    Q_OBJECT

public:
    Private(ResultModel *q)
    : q(q)
    {
        scheduler = Client::instance()->scheduler();
    }

    void sort(ExtResultList &list)
    {
        for (int n = 0; n <list.count(); n++)
        {
            for (int i = n + 1; i < list.count(); i++)
            {
                QString valorN = scheduler->taskByTaskId(TaskId(list.at(n).value("task_id").toUInt())).method();
                QString valorI = scheduler->taskByTaskId(TaskId(list.at(i).value("task_id").toUInt())).method();

                if (valorN.toUpper() > valorI.toUpper())
                {
                    list.move(i, n);
                    n = 0;
                }
            }
        }
    }

    ResultModel *q;

    QPointer<ResultScheduler> resultScheduler;
    QPointer<Scheduler> scheduler;

    QHash<TaskId, int> identToResult;
    ExtResultList results;

public slots:
    void resultAdded(const QVariantMap &result);
    void resultModified(const QVariantMap &result);
};

void ResultModel::Private::resultAdded(const QVariantMap &result)
{
    int position = results.size();

    q->beginInsertRows(QModelIndex(), position, position);
    identToResult.insert(TaskId(result.value("task_id").toInt()), position);
    results = resultScheduler->results();
    sort(results);
    q->endInsertRows();
}

void ResultModel::Private::resultModified(const QVariantMap &result)
{
    int pos = identToResult.value(TaskId(result.value("task_id").toInt()));

    if (pos == -1)
    {
        LOG_ERROR("invalid ident");
        return;
    }

    results = resultScheduler->results();
    sort(results);

    QModelIndex index = q->indexFromTaskId(TaskId(result.value("task_id").toInt()));

    if (!index.isValid())
    {
        LOG_ERROR("invalid index");
        return;
    }

    emit q->dataChanged(index, index);
}

ResultModel::ResultModel(QObject *parent)
: QAbstractTableModel(parent)
, d(new Private(this))
{
}

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

void ResultModel::setScheduler(ResultScheduler *scheduler)
{
    if (d->resultScheduler == scheduler)
    {
        return;
    }

    if (d->resultScheduler)
    {
        disconnect(d->resultScheduler.data(), SIGNAL(resultAdded(QVariantMap)), d, SLOT(resultAdded(QVariantMap)));
        disconnect(d->resultScheduler.data(), SIGNAL(resultModified(QVariantMap)), d, SLOT(resultModified(QVariantMap)));
    }

    d->resultScheduler = scheduler;

    if (d->resultScheduler)
    {
        connect(d->resultScheduler.data(), SIGNAL(resultAdded(QVariantMap)), d, SLOT(resultAdded(QVariantMap)));
        connect(d->resultScheduler.data(), SIGNAL(resultModified(QVariantMap)), d, SLOT(resultModified(QVariantMap)));
    }

    emit schedulerChanged();
    reset();
}

ResultScheduler *ResultModel::scheduler() const
{
    return d->resultScheduler;
}

QModelIndex ResultModel::indexFromTaskId(const TaskId &taskId) const
{
    int pos = d->identToResult.value(taskId);

    if (pos == -1)
    {
        return QModelIndex();
    }
    else
    {
        return createIndex(pos, 0);
    }
}

void ResultModel::reset()
{
    beginResetModel();

    if (!d->resultScheduler.isNull())
    {
        d->results = d->resultScheduler->results();
        d->sort(d->results);
    }

    endResetModel();
}

QVariant ResultModel::get(int index) const
{
    if (index < 0 || index >= d->results.size())
    {
        return QVariant();
    }

    return d->results.at(index);
}

QHash<int, QByteArray> ResultModel::roleNames() const
{
    QHash<int, QByteArray> roleNames;
    roleNames.insert(TaskIdRole, "taskId");
    roleNames.insert(DateTimeRole, "dateTime");
    roleNames.insert(ResultsRole, "results");
    roleNames.insert(MeasurementRole, "name");
    roleNames.insert(SecondColumnRole, "secondColumn");
    return roleNames;
}

int ResultModel::rowCount(const QModelIndex &parent) const
{
    if (parent.isValid())
    {
        return 0;
    }

    return d->results.size();
}

int ResultModel::columnCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent);
    return 5;
}

QVariant ResultModel::data(const QModelIndex &index, int role) const
{
    const QVariantMap &result = d->results.at(index.row());

    if (role == Qt::DisplayRole)
    {
        role = TaskIdRole + index.column();
    }

    switch (role)
    {
    case TaskIdRole:
        return result.value("task_id").toInt();

    case DateTimeRole:
        return result.value("report_time");
        //case ResultsRole: return report->results(); // TODO: Scripting can't do anything with that

    case MeasurementRole:
        return d->scheduler->taskByTaskId(TaskId(result.value("task_id").toInt())).method().toUpper();

    case SecondColumnRole:
        QVariantMap map = d->scheduler->taskByTaskId(TaskId(result.value("task_id").toInt())).toVariant().toMap();
        QVariantMap options = map.value("options").toMap();
        QString out;
        QStringList names;

        // option names for the second column may vary
        names << "host" << "url";

        foreach (const QString &name, names)
        {
            if (options.contains(name))
            {
                out = options.value(name).toString();
                break;
            }
        }

        // cut off last bit if it's too long
        if (out.length() > 35)
        {
            out = out.mid(0, 32) + "...";
        }

        return out;
    }

    return QVariant();
}

QVariant ResultModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if (role != Qt::DisplayRole || orientation != Qt::Horizontal)
    {
        return QVariant();
    }

    section += TaskIdRole;

    switch (section)
    {
    case TaskIdRole:
        return tr("Task Id");

    case DateTimeRole:
        return tr("Date-Time");

    case ResultsRole:
        return tr("Results");

    default:
        return QVariant();
    }
}

#include "resultmodel.moc"
<commit_msg>replace bubble sort with std::sort<commit_after>#include "resultmodel.h"
#include "resultscheduler.h"
#include "../types.h"
#include "task/scheduledefinition.h"
#include "scheduler/scheduler.h"
#include "client.h"
#include "log/logger.h"

#include <QPointer>
#include <QUuid>
#include <QHash>

LOGGER("ResultModel");

class ResultModel::Private : public QObject
{
    Q_OBJECT

public:
    Private(ResultModel *q)
    : q(q)
    , methodSort(this)
    {
        scheduler = Client::instance()->scheduler();
    }

    struct MethodSort
    {
        ResultModel::Private *p;

        MethodSort(ResultModel::Private *p)
            : p(p)
        {}

        bool operator() (const QVariantMap &a, const QVariantMap &b)
        {
            // sort by method name, ascending
            return (p->scheduler->taskByTaskId(TaskId(a.value("task_id").toUInt())).method() <
                    p->scheduler->taskByTaskId(TaskId(b.value("task_id").toUInt())).method());
        }
    };

    ResultModel *q;

    MethodSort methodSort;

    QPointer<ResultScheduler> resultScheduler;
    QPointer<Scheduler> scheduler;

    QHash<TaskId, int> identToResult;
    ExtResultList results;

public slots:
    void resultAdded(const QVariantMap &result);
    void resultModified(const QVariantMap &result);
};

void ResultModel::Private::resultAdded(const QVariantMap &result)
{
    int position = results.size();

    q->beginInsertRows(QModelIndex(), position, position);
    identToResult.insert(TaskId(result.value("task_id").toInt()), position);
    results = resultScheduler->results();
    std::sort(results.begin(), results.end(), methodSort);
    q->endInsertRows();
}

void ResultModel::Private::resultModified(const QVariantMap &result)
{
    int pos = identToResult.value(TaskId(result.value("task_id").toInt()));

    if (pos == -1)
    {
        LOG_ERROR("invalid ident");
        return;
    }

    results = resultScheduler->results();
    std::sort(results.begin(), results.end(), methodSort);

    QModelIndex index = q->indexFromTaskId(TaskId(result.value("task_id").toInt()));

    if (!index.isValid())
    {
        LOG_ERROR("invalid index");
        return;
    }

    emit q->dataChanged(index, index);
}

ResultModel::ResultModel(QObject *parent)
: QAbstractTableModel(parent)
, d(new Private(this))
{
}

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

void ResultModel::setScheduler(ResultScheduler *scheduler)
{
    if (d->resultScheduler == scheduler)
    {
        return;
    }

    if (d->resultScheduler)
    {
        disconnect(d->resultScheduler.data(), SIGNAL(resultAdded(QVariantMap)), d, SLOT(resultAdded(QVariantMap)));
        disconnect(d->resultScheduler.data(), SIGNAL(resultModified(QVariantMap)), d, SLOT(resultModified(QVariantMap)));
    }

    d->resultScheduler = scheduler;

    if (d->resultScheduler)
    {
        connect(d->resultScheduler.data(), SIGNAL(resultAdded(QVariantMap)), d, SLOT(resultAdded(QVariantMap)));
        connect(d->resultScheduler.data(), SIGNAL(resultModified(QVariantMap)), d, SLOT(resultModified(QVariantMap)));
    }

    emit schedulerChanged();
    reset();
}

ResultScheduler *ResultModel::scheduler() const
{
    return d->resultScheduler;
}

QModelIndex ResultModel::indexFromTaskId(const TaskId &taskId) const
{
    int pos = d->identToResult.value(taskId);

    if (pos == -1)
    {
        return QModelIndex();
    }
    else
    {
        return createIndex(pos, 0);
    }
}

void ResultModel::reset()
{
    beginResetModel();

    if (!d->resultScheduler.isNull())
    {
        d->results = d->resultScheduler->results();
        std::sort(d->results.begin(), d->results.end(), d->methodSort);
    }

    endResetModel();
}

QVariant ResultModel::get(int index) const
{
    if (index < 0 || index >= d->results.size())
    {
        return QVariant();
    }

    return d->results.at(index);
}

QHash<int, QByteArray> ResultModel::roleNames() const
{
    QHash<int, QByteArray> roleNames;
    roleNames.insert(TaskIdRole, "taskId");
    roleNames.insert(DateTimeRole, "dateTime");
    roleNames.insert(ResultsRole, "results");
    roleNames.insert(MeasurementRole, "name");
    roleNames.insert(SecondColumnRole, "secondColumn");
    return roleNames;
}

int ResultModel::rowCount(const QModelIndex &parent) const
{
    if (parent.isValid())
    {
        return 0;
    }

    return d->results.size();
}

int ResultModel::columnCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent);
    return 5;
}

QVariant ResultModel::data(const QModelIndex &index, int role) const
{
    const QVariantMap &result = d->results.at(index.row());

    if (role == Qt::DisplayRole)
    {
        role = TaskIdRole + index.column();
    }

    switch (role)
    {
    case TaskIdRole:
        return result.value("task_id").toInt();

    case DateTimeRole:
        return result.value("report_time");
        //case ResultsRole: return report->results(); // TODO: Scripting can't do anything with that

    case MeasurementRole:
        return d->scheduler->taskByTaskId(TaskId(result.value("task_id").toInt())).method().toUpper();

    case SecondColumnRole:
        QVariantMap map = d->scheduler->taskByTaskId(TaskId(result.value("task_id").toInt())).toVariant().toMap();
        QVariantMap options = map.value("options").toMap();
        QString out;
        QStringList names;

        // option names for the second column may vary
        names << "host" << "url";

        foreach (const QString &name, names)
        {
            if (options.contains(name))
            {
                out = options.value(name).toString();
                break;
            }
        }

        // cut off last bit if it's too long
        if (out.length() > 35)
        {
            out = out.mid(0, 32) + "...";
        }

        return out;
    }

    return QVariant();
}

QVariant ResultModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if (role != Qt::DisplayRole || orientation != Qt::Horizontal)
    {
        return QVariant();
    }

    section += TaskIdRole;

    switch (section)
    {
    case TaskIdRole:
        return tr("Task Id");

    case DateTimeRole:
        return tr("Date-Time");

    case ResultsRole:
        return tr("Results");

    default:
        return QVariant();
    }
}

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


<commit_before>/* Copyright 2015 Samsung Electronics Co., LTD
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "bitmap_image.h"
#include "bitmap_transparency.h"
#include "astc_transparency.h"

namespace gvr {
BitmapImage::BitmapImage(int format) :
            Image(Image::BITMAP, format),mData(NULL),
            mBitmap(NULL), mJava(NULL), mHasTransparency(false)
{
}

BitmapImage::~BitmapImage()
{
    if (mJava)
    {
        std::lock_guard<std::mutex> lock(mUpdateLock);
        clearData(getCurrentEnv(mJava));
    }
}

void BitmapImage::update(JNIEnv* env, int width, int height, jbyteArray data)
{
    std::lock_guard<std::mutex> lock(mUpdateLock);
    env->GetJavaVM(&mJava);
    clearData(env);
    mWidth = width;
    mHeight = height;
    mFormat = GL_RGBA; // PixelFormat::A8;
    mIsCompressed = false;

    if (data != NULL)
    {
        mData = static_cast<jbyteArray>(env->NewGlobalRef(data));
        signalUpdate();
        LOGV("Texture: BitmapImage::update(byteArray)");
    }
}

void BitmapImage::update(JNIEnv* env, jobject bitmap, bool hasAlpha, int format)
{
    std::lock_guard<std::mutex> lock(mUpdateLock);
    env->GetJavaVM(&mJava);
    clearData(env);
    if (bitmap != NULL)
    {
        mBitmap = static_cast<jbyteArray>(env->NewGlobalRef(bitmap));
        mFormat = format;
        mIsBuffer = false;
        LOGV("Texture: BitmapImage::update(bitmap)");
        if( hasAlpha ) {
            if(bitmap_has_transparency(env, bitmap)) {
                set_transparency(true);
            } else {
                // TODO: warning: bitmap has an alpha channel with no translucent/transparent pixels.
            }
        }
        signalUpdate();
    }
}

void BitmapImage::update(JNIEnv* env, int xoffset, int yoffset, int width, int height, int format, int type, jobject buffer)
{
    std::lock_guard<std::mutex> lock(mUpdateLock);
    env->GetJavaVM(&mJava);
    clearData(env);
    if (buffer != NULL)
    {
        mXOffset = xoffset;
        mYOffset = yoffset;
        mWidth = width;
        mHeight = height;
        mFormat = format;
        mType = type;
        mBitmap = env->NewGlobalRef(buffer);
        mIsBuffer = true;
        LOGV("Texture: BitmapImage::update(buffer)");
        signalUpdate();
    }
}

void BitmapImage::update(JNIEnv *env, int width, int height, int imageSize,
                         jbyteArray data, int levels, const int* dataOffsets)
{
    std::lock_guard<std::mutex> lock(mUpdateLock);
    env->GetJavaVM(&mJava);
    clearData(env);
    mWidth = width;
    mHeight = height;
    mLevels = levels;
    mIsCompressed = true;
    mImageSize = imageSize;
    setDataOffsets(dataOffsets, levels);
    if (data != NULL)
    {
        mData = static_cast<jbyteArray>(env->NewGlobalRef(data));
        mPixels = env->GetByteArrayElements(mData, 0);
        LOGV("Texture: BitmapImage::update(byteArray, offsets)");
        set_transparency(hasAlpha(mFormat));
        env->ReleaseByteArrayElements(mData, mPixels, 0);
        mPixels = NULL;
        signalUpdate();
    }
}

void BitmapImage::clearData(JNIEnv* env)
{
    if (mData != NULL)
    {
        env->DeleteGlobalRef(mData);
        mData = NULL;
    }
    if (mBitmap != NULL)
    {
        env->DeleteGlobalRef(mBitmap);
        mBitmap = NULL;
    }
    mIsCompressed = false;
}

bool BitmapImage::hasAlpha(int format) {
    switch(format) {
        case GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2:
        case GL_COMPRESSED_RG11_EAC:
        case GL_COMPRESSED_SIGNED_RG11_EAC:
        case GL_COMPRESSED_RGBA8_ETC2_EAC:
        case GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:
            return true;
            break;
        case GL_COMPRESSED_RGBA_ASTC_4x4_KHR:
        case GL_COMPRESSED_RGBA_ASTC_5x4_KHR:
        case GL_COMPRESSED_RGBA_ASTC_5x5_KHR:
        case GL_COMPRESSED_RGBA_ASTC_6x5_KHR:
        case GL_COMPRESSED_RGBA_ASTC_6x6_KHR:
        case GL_COMPRESSED_RGBA_ASTC_8x5_KHR:
        case GL_COMPRESSED_RGBA_ASTC_8x6_KHR:
        case GL_COMPRESSED_RGBA_ASTC_8x8_KHR:
        case GL_COMPRESSED_RGBA_ASTC_10x5_KHR:
        case GL_COMPRESSED_RGBA_ASTC_10x6_KHR:
        case GL_COMPRESSED_RGBA_ASTC_10x8_KHR:
        case GL_COMPRESSED_RGBA_ASTC_10x10_KHR:
        case GL_COMPRESSED_RGBA_ASTC_12x10_KHR:
        case GL_COMPRESSED_RGBA_ASTC_12x12_KHR:
        case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:
        case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:
        case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:
        case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:
        case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:
        case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:
        case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:
        case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:
        case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:
        case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:
        case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:
        case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:
        case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:
        case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:
            return astc_has_transparency(mPixels, mImageSize);
            break;
        default:
            return false;
    }
}

}

<commit_msg>Fix for compressed textures not being shown if loaded again and again<commit_after>/* Copyright 2015 Samsung Electronics Co., LTD
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "bitmap_image.h"
#include "bitmap_transparency.h"
#include "astc_transparency.h"

namespace gvr {
BitmapImage::BitmapImage(int format) :
            Image(Image::BITMAP, format),mData(NULL),
            mBitmap(NULL), mJava(NULL), mHasTransparency(false)
{
}

BitmapImage::~BitmapImage()
{
    if (mJava)
    {
        std::lock_guard<std::mutex> lock(mUpdateLock);
        clearData(getCurrentEnv(mJava));
    }
}

void BitmapImage::update(JNIEnv* env, int width, int height, jbyteArray data)
{
    std::lock_guard<std::mutex> lock(mUpdateLock);
    env->GetJavaVM(&mJava);
    clearData(env);
    mWidth = width;
    mHeight = height;
    mFormat = GL_RGBA; // PixelFormat::A8;
    mIsCompressed = false;

    if (data != NULL)
    {
        mData = static_cast<jbyteArray>(env->NewGlobalRef(data));
        signalUpdate();
        LOGV("Texture: BitmapImage::update(byteArray)");
    }
}

void BitmapImage::update(JNIEnv* env, jobject bitmap, bool hasAlpha, int format)
{
    std::lock_guard<std::mutex> lock(mUpdateLock);
    env->GetJavaVM(&mJava);
    clearData(env);
    if (bitmap != NULL)
    {
        mBitmap = static_cast<jbyteArray>(env->NewGlobalRef(bitmap));
        mFormat = format;
        mIsBuffer = false;
        LOGV("Texture: BitmapImage::update(bitmap)");
        if( hasAlpha ) {
            if(bitmap_has_transparency(env, bitmap)) {
                set_transparency(true);
            } else {
                // TODO: warning: bitmap has an alpha channel with no translucent/transparent pixels.
            }
        }
        signalUpdate();
    }
}

void BitmapImage::update(JNIEnv* env, int xoffset, int yoffset, int width, int height, int format, int type, jobject buffer)
{
    std::lock_guard<std::mutex> lock(mUpdateLock);
    env->GetJavaVM(&mJava);
    clearData(env);
    if (buffer != NULL)
    {
        mXOffset = xoffset;
        mYOffset = yoffset;
        mWidth = width;
        mHeight = height;
        mFormat = format;
        mType = type;
        mBitmap = env->NewGlobalRef(buffer);
        mIsBuffer = true;
        LOGV("Texture: BitmapImage::update(buffer)");
        signalUpdate();
    }
}

void BitmapImage::update(JNIEnv *env, int width, int height, int imageSize,
                         jbyteArray data, int levels, const int* dataOffsets)
{
    std::lock_guard<std::mutex> lock(mUpdateLock);
    env->GetJavaVM(&mJava);
    clearData(env);
    mWidth = width;
    mHeight = height;
    mLevels = levels;
    mIsCompressed = true;
    mImageSize = imageSize;
    setDataOffsets(dataOffsets, levels);
    if (data != NULL)
    {
        mData = static_cast<jbyteArray>(env->NewGlobalRef(data));
        mPixels = env->GetByteArrayElements(mData, 0);
        LOGV("Texture: BitmapImage::update(byteArray, offsets)");
        set_transparency(hasAlpha(mFormat));
        env->ReleaseByteArrayElements(mData, mPixels, 0);
        mPixels = NULL;
        signalUpdate();
    }
}

void BitmapImage::clearData(JNIEnv* env)
{
    if (mData != NULL)
    {
        env->DeleteGlobalRef(mData);
        mData = NULL;
    }
    if (mBitmap != NULL)
    {
        env->DeleteGlobalRef(mBitmap);
        mBitmap = NULL;
    }
}

bool BitmapImage::hasAlpha(int format) {
    switch(format) {
        case GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2:
        case GL_COMPRESSED_RG11_EAC:
        case GL_COMPRESSED_SIGNED_RG11_EAC:
        case GL_COMPRESSED_RGBA8_ETC2_EAC:
        case GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:
            return true;
            break;
        case GL_COMPRESSED_RGBA_ASTC_4x4_KHR:
        case GL_COMPRESSED_RGBA_ASTC_5x4_KHR:
        case GL_COMPRESSED_RGBA_ASTC_5x5_KHR:
        case GL_COMPRESSED_RGBA_ASTC_6x5_KHR:
        case GL_COMPRESSED_RGBA_ASTC_6x6_KHR:
        case GL_COMPRESSED_RGBA_ASTC_8x5_KHR:
        case GL_COMPRESSED_RGBA_ASTC_8x6_KHR:
        case GL_COMPRESSED_RGBA_ASTC_8x8_KHR:
        case GL_COMPRESSED_RGBA_ASTC_10x5_KHR:
        case GL_COMPRESSED_RGBA_ASTC_10x6_KHR:
        case GL_COMPRESSED_RGBA_ASTC_10x8_KHR:
        case GL_COMPRESSED_RGBA_ASTC_10x10_KHR:
        case GL_COMPRESSED_RGBA_ASTC_12x10_KHR:
        case GL_COMPRESSED_RGBA_ASTC_12x12_KHR:
        case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:
        case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:
        case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:
        case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:
        case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:
        case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:
        case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:
        case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:
        case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:
        case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:
        case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:
        case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:
        case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:
        case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:
            return astc_has_transparency(mPixels, mImageSize);
            break;
        default:
            return false;
    }
}

}

<|endoftext|>


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

#include "reloadpromptutils.h"

#include <QtCore/QCoreApplication>
#include <QtCore/QDir>
#include <QtGui/QMessageBox>
#include <QtGui/QPushButton>
#include <QtGui/QAbstractButton>

using namespace Utils;

QTCREATOR_UTILS_EXPORT Utils::ReloadPromptAnswer
    Utils::reloadPrompt(const QString &fileName, bool modified, QWidget *parent)
{

    const QString title = QCoreApplication::translate("Utils::reloadPrompt", "File Changed");
    QString msg;

    if (modified)
        msg = QCoreApplication::translate("Utils::reloadPrompt",
                                          "The unsaved file %1 has been changed outside Qt Creator. Do you want to reload it and discard your changes?");
    else
        msg = QCoreApplication::translate("Utils::reloadPrompt",
                                          "The file %1 has changed outside Qt Creator. Do you want to reload it?");
    msg = msg.arg(QFileInfo(fileName).fileName());
    return reloadPrompt(title, msg, QDir::toNativeSeparators(fileName), parent);
}

QTCREATOR_UTILS_EXPORT Utils::ReloadPromptAnswer
    Utils::reloadPrompt(const QString &title, const QString &prompt, const QString &details, QWidget *parent)
{
    QMessageBox msg(parent);
    msg.setStandardButtons(QMessageBox::Yes|QMessageBox::YesToAll|QMessageBox::No|QMessageBox::NoToAll);
    msg.setDefaultButton(QMessageBox::YesToAll);
    msg.setWindowTitle(title);
    msg.setText(prompt);
    msg.setDetailedText(details);

    switch (msg.exec()) {
    case QMessageBox::Yes:
        return  ReloadCurrent;
    case QMessageBox::YesToAll:
        return ReloadAll;
    case QMessageBox::No:
        return ReloadSkipCurrent;
    default:
        break;
    }
    return ReloadNone;
}

QTCREATOR_UTILS_EXPORT Utils::FileDeletedPromptAnswer
        Utils::fileDeletedPrompt(const QString &fileName, bool triggerExternally, QWidget *parent)
{
    const QString title = QCoreApplication::translate("Utils::fileDeletedPrompt", "File has been removed");
    QString msg;
    if (triggerExternally)
        msg = QCoreApplication::translate("Utils::fileDeletedPrompt",
                                          "The file %1 has been removed outside Qt Creator. Do you want to save it under a different name, or close the editor?").arg(QDir::toNativeSeparators(fileName));
    else
        msg = QCoreApplication::translate("Utils::fileDeletedPrompt",
                                          "The file %1 was removed. Do you want to save it under a different name, or close the editor?").arg(QDir::toNativeSeparators(fileName));
    QMessageBox box(QMessageBox::Question, title, msg, QMessageBox::NoButton, parent);
    QPushButton *close = box.addButton(QCoreApplication::translate("Utils::fileDeletedPrompt", "Close"), QMessageBox::RejectRole);
    QPushButton *saveas = box.addButton(QCoreApplication::translate("Utils::fileDeletedPrompt", "Save as..."), QMessageBox::ActionRole);
    QPushButton *save = box.addButton(QCoreApplication::translate("Utils::fileDeletedPrompt", "Save"), QMessageBox::AcceptRole);
    box.setDefaultButton(saveas);
    box.exec();
    QAbstractButton *clickedbutton = box.clickedButton();
    if (clickedbutton == close) {
        return FileDeletedClose;
    } else if (clickedbutton == saveas) {
        return FileDeletedSaveAs;
    } else if (clickedbutton == save) {
        return FileDeletedSave;
    }
    return FileDeletedClose;
}
<commit_msg>add keyboard accelerators to the "file deleted" prompt message box<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (info@qt.nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at info@qt.nokia.com.
**
**************************************************************************/

#include "reloadpromptutils.h"

#include <QtCore/QCoreApplication>
#include <QtCore/QDir>
#include <QtGui/QMessageBox>
#include <QtGui/QPushButton>
#include <QtGui/QAbstractButton>

using namespace Utils;

QTCREATOR_UTILS_EXPORT Utils::ReloadPromptAnswer
    Utils::reloadPrompt(const QString &fileName, bool modified, QWidget *parent)
{

    const QString title = QCoreApplication::translate("Utils::reloadPrompt", "File Changed");
    QString msg;

    if (modified)
        msg = QCoreApplication::translate("Utils::reloadPrompt",
                                          "The unsaved file %1 has been changed outside Qt Creator. Do you want to reload it and discard your changes?");
    else
        msg = QCoreApplication::translate("Utils::reloadPrompt",
                                          "The file %1 has changed outside Qt Creator. Do you want to reload it?");
    msg = msg.arg(QFileInfo(fileName).fileName());
    return reloadPrompt(title, msg, QDir::toNativeSeparators(fileName), parent);
}

QTCREATOR_UTILS_EXPORT Utils::ReloadPromptAnswer
    Utils::reloadPrompt(const QString &title, const QString &prompt, const QString &details, QWidget *parent)
{
    QMessageBox msg(parent);
    msg.setStandardButtons(QMessageBox::Yes|QMessageBox::YesToAll|QMessageBox::No|QMessageBox::NoToAll);
    msg.setDefaultButton(QMessageBox::YesToAll);
    msg.setWindowTitle(title);
    msg.setText(prompt);
    msg.setDetailedText(details);

    switch (msg.exec()) {
    case QMessageBox::Yes:
        return  ReloadCurrent;
    case QMessageBox::YesToAll:
        return ReloadAll;
    case QMessageBox::No:
        return ReloadSkipCurrent;
    default:
        break;
    }
    return ReloadNone;
}

QTCREATOR_UTILS_EXPORT Utils::FileDeletedPromptAnswer
        Utils::fileDeletedPrompt(const QString &fileName, bool triggerExternally, QWidget *parent)
{
    const QString title = QCoreApplication::translate("Utils::fileDeletedPrompt", "File has been removed");
    QString msg;
    if (triggerExternally)
        msg = QCoreApplication::translate("Utils::fileDeletedPrompt",
                                          "The file %1 has been removed outside Qt Creator. Do you want to save it under a different name, or close the editor?").arg(QDir::toNativeSeparators(fileName));
    else
        msg = QCoreApplication::translate("Utils::fileDeletedPrompt",
                                          "The file %1 was removed. Do you want to save it under a different name, or close the editor?").arg(QDir::toNativeSeparators(fileName));
    QMessageBox box(QMessageBox::Question, title, msg, QMessageBox::NoButton, parent);
    QPushButton *close = box.addButton(QCoreApplication::translate("Utils::fileDeletedPrompt", "&Close"), QMessageBox::RejectRole);
    QPushButton *saveas = box.addButton(QCoreApplication::translate("Utils::fileDeletedPrompt", "Save &as..."), QMessageBox::ActionRole);
    QPushButton *save = box.addButton(QCoreApplication::translate("Utils::fileDeletedPrompt", "&Save"), QMessageBox::AcceptRole);
    box.setDefaultButton(saveas);
    box.exec();
    QAbstractButton *clickedbutton = box.clickedButton();
    if (clickedbutton == close) {
        return FileDeletedClose;
    } else if (clickedbutton == saveas) {
        return FileDeletedSaveAs;
    } else if (clickedbutton == save) {
        return FileDeletedSave;
    }
    return FileDeletedClose;
}
<|endoftext|>


<commit_before>#include "AssembledSystem.h"
#include <helper.h>

#include <iostream>

namespace sofa {
namespace component {
namespace linearsolver {

AssembledSystem::AssembledSystem(unsigned m, unsigned n)
	: m(m),
	  n(n),
	  dt(0)
{
	if( !m ) return;

	// M.resize(m, m);
	// K.resize(m, m);

	H.resize(m, m);
	P.resize(m, m);

	f = vec::Zero( m );
	v = vec::Zero( m );
	p = vec::Zero( m );

	if( n ) {
		J.resize(n, m);

		C.resize(n, n);
		phi = vec::Zero(n);
		lambda = vec::Zero(n);

	}

}

unsigned AssembledSystem::size() const { return m + n; }

void AssembledSystem::debug(SReal /*thres*/) const {

	std::cerr << "f: " << std::endl
	          << f.transpose() << std::endl
	          << "v: " << std::endl
	          << v.transpose() << std::endl
	          << "p:" << std::endl
	          << p.transpose() << std::endl;

	std::cerr << "H:" << std::endl
	          << H << std::endl
	          << "P:" << std::endl
	          << P << std::endl;
	if( n ) {
		std::cerr << "phi:" << std::endl
		          << phi.transpose() << std::endl;

		std::cerr << "lambda:" << std::endl
		          << lambda.transpose() << std::endl;

		std::cerr << "J:" << std::endl
		          << J << std::endl
		          << "C:" << std::endl
		          << C << std::endl;
	}

}

bool AssembledSystem::isDiagonalDominant() const
{
    typedef typename mat::Index Index;

    mat PH = P*H;

    if( n )
    {
        mat PJt = P*J.transpose();

        for( unsigned i=0 ; i<m ; ++i )
        {
            real d = helper::rabs(PH.coeff(i,i));

            real o = -d;
            for( Index j=0 ; j<PH.cols()  ; ++j ) o += helper::rabs(PH.coeff(i,j));
            for( Index j=0 ; j<PJt.cols() ; ++j ) o += helper::rabs(PJt.coeff(i,j));

            if( o > d ) return false;
        }

        for( unsigned i=0 ; i<n ; ++i )
        {
            real d = helper::rabs(C.coeff(i,i));

            real o = -d;
            for( Index j=0 ; j<C.cols() ; ++j ) o += helper::rabs(C.coeff(i,j));
            for( Index j=0 ; j<J.cols() ; ++j ) o += helper::rabs(J.coeff(i,j));

            if( o > d ) return false;
        }
    }
    else
    {
        for( unsigned i=0 ; i<m ; ++i )
        {
            real d = helper::rabs(PH.coeff(i,i));

            real o = -d;
            for( Index j=0 ; j<PH.cols() ; ++j ) o += helper::rabs(PH.coeff(i,j));

            if( o > d ) return false;
        }
    }

    return true;
}

}
}
}
<commit_msg>r9753/sofa : Compliant: fixed compilation on gcc-4.4<commit_after>#include "AssembledSystem.h"
#include <helper.h>

#include <iostream>

namespace sofa {
namespace component {
namespace linearsolver {

AssembledSystem::AssembledSystem(unsigned m, unsigned n)
	: m(m),
	  n(n),
	  dt(0)
{
	if( !m ) return;

	// M.resize(m, m);
	// K.resize(m, m);

	H.resize(m, m);
	P.resize(m, m);

	f = vec::Zero( m );
	v = vec::Zero( m );
	p = vec::Zero( m );

	if( n ) {
		J.resize(n, m);

		C.resize(n, n);
		phi = vec::Zero(n);
		lambda = vec::Zero(n);

	}

}

unsigned AssembledSystem::size() const { return m + n; }

void AssembledSystem::debug(SReal /*thres*/) const {

	std::cerr << "f: " << std::endl
	          << f.transpose() << std::endl
	          << "v: " << std::endl
	          << v.transpose() << std::endl
	          << "p:" << std::endl
	          << p.transpose() << std::endl;

	std::cerr << "H:" << std::endl
	          << H << std::endl
	          << "P:" << std::endl
	          << P << std::endl;
	if( n ) {
		std::cerr << "phi:" << std::endl
		          << phi.transpose() << std::endl;

		std::cerr << "lambda:" << std::endl
		          << lambda.transpose() << std::endl;

		std::cerr << "J:" << std::endl
		          << J << std::endl
		          << "C:" << std::endl
		          << C << std::endl;
	}

}

bool AssembledSystem::isDiagonalDominant() const
{
    typedef mat::Index Index;

    mat PH = P*H;

    if( n )
    {
        mat PJt = P*J.transpose();

        for( unsigned i=0 ; i<m ; ++i )
        {
            real d = helper::rabs(PH.coeff(i,i));

            real o = -d;
            for( Index j=0 ; j<PH.cols()  ; ++j ) o += helper::rabs(PH.coeff(i,j));
            for( Index j=0 ; j<PJt.cols() ; ++j ) o += helper::rabs(PJt.coeff(i,j));

            if( o > d ) return false;
        }

        for( unsigned i=0 ; i<n ; ++i )
        {
            real d = helper::rabs(C.coeff(i,i));

            real o = -d;
            for( Index j=0 ; j<C.cols() ; ++j ) o += helper::rabs(C.coeff(i,j));
            for( Index j=0 ; j<J.cols() ; ++j ) o += helper::rabs(J.coeff(i,j));

            if( o > d ) return false;
        }
    }
    else
    {
        for( unsigned i=0 ; i<m ; ++i )
        {
            real d = helper::rabs(PH.coeff(i,i));

            real o = -d;
            for( Index j=0 ; j<PH.cols() ; ++j ) o += helper::rabs(PH.coeff(i,j));

            if( o > d ) return false;
        }
    }

    return true;
}

}
}
}
<|endoftext|>