<commit_before>#include <cstdlib>

#include "ipc-lick.hpp"

void free_nonnull(void *p) {
    if(p)
        free(p);
}

lickdir_t *copy_lickdir_t(lickdir_t *src) {
    lickdir_t *dst = (lickdir_t *)malloc(sizeof(lickdir_t));
    dst->lick = strdup2(src->lick);
    dst->drive = strdup2(src->drive);
    dst->entry = strdup2(src->entry);
    dst->menu = strdup2(src->menu);
    dst->res = strdup2(src->res);
    dst->err = strdup2(src->err);
    return dst;
}

void exchange_lick(ipc *p, lickdir_t *&lick) {
    if(lick == NULL)
        lick = (lickdir_t *)malloc(sizeof(lickdir_t));
    p
        ->exchange_str(lick->lick)
        ->exchange_str(lick->drive)
        ->exchange_str(lick->entry)
        ->exchange_str(lick->menu)
        ->exchange_str(lick->res)
        ->exchange_str(lick->err)
    ;
}

// IPC_INSTALL

ipc_install::ipc_install(const char *id, const char *name, const char *iso,
        const char *install_dir, lickdir_t *lick) {
    this->id = strdup2(id);
    this->name = strdup2(name);
    this->iso = strdup2(iso);
    this->install_dir = strdup2(install_dir);
    this->lick = copy_lickdir_t(lick);
}

ipc_install::~ipc_install() {
    free_nonnull(id);
    free_nonnull(name);
    free_nonnull(iso);
    free_nonnull(install_dir);
    free_lick_dir(lick);
}

void ipc_install::exchange(ipc *p) {
    p
        ->exchange_str(id)
        ->exchange_str(name)
        ->exchange_str(iso)
        ->exchange_str(install_dir)
    ;
    exchange_lick(p, lick);
}

// IPC_UNINSTALL

ipc_uninstall::ipc_uninstall(const char *id, lickdir_t *lick) {
    this->id = strdup2(id);
    this->lick = copy_lickdir_t(lick);
}
ipc_uninstall::~ipc_uninstall() {
    free_nonnull(id);
    free_lick_dir(lick);
}
void ipc_uninstall::exchange(ipc *p) {
    p
        ->exchange_str(id)
    ;
    exchange_lick(p, lick);
}

// IPC_LOADER

ipc_loader::ipc_loader(int install, lickdir_t *lick) {
    this->install = install;
    this->lick = copy_lickdir_t(lick);
}
ipc_loader::~ipc_loader() {
    free_lick_dir(lick);
}
void ipc_loader::exchange(ipc *p) {
    p
        ->exchange(install)
    ;
    exchange_lick(p, lick);
}

// IPC_STATUS

ipc_status::ipc_status(int ret, const char *err) {
    this->ret = ret;
    this->err = strdup2(err);
}
ipc_status::~ipc_status() {
    free_nonnull(err);
}
void send_status_inner(ipc *p, int ret, const char *err) {
    p
        ->exchange(ret)
        ->exchange_str(err)
    ;
}
void ipc_status::exchange(ipc *p) {
    send_status_inner(p, ret, err);
}

// IPC_ERROR

ipc_error::ipc_error(const char *err) {
    this->err = strdup2(err);
}
ipc_error::~ipc_error() {
    free_nonnull(err);
}
void send_error_inner(ipc *p, const char *err) {
    p
        ->exchange_str(err)
    ;
}
void ipc_error::exchange(ipc *p) {
    send_error_inner(p, err);
}

ipc_lick *recv_command(ipc *p) {
    IPC_COMMANDS type;
    p->exchange(type);
    if(p->had_error())
        return NULL;

    ipc_lick *c;
    switch(type) {
    case IPC_EXIT:
        c = new ipc_exit();
        break;
    case IPC_READY:
        c = new ipc_ready();
        break;
    case IPC_INSTALL:
        c = new ipc_install();
        break;
    case IPC_UNINSTALL:
        c = new ipc_uninstall();
        break;
    case IPC_CHECK_LOADER:
        c = new ipc_check_loader();
        break;
    case IPC_LOADER:
        c = new ipc_loader();
        break;
    case IPC_STATUS:
        c = new ipc_status();
        break;
    default:
        return NULL;
    }
    c->exchange(p);
    return c;
}

void send_command(ipc *p, IPC_COMMANDS c) {
    p->exchange(c);
}

void send_command(ipc *p, ipc_lick *c) {
    IPC_COMMANDS type = c->type();
    send_command(p, type);
    c->exchange(p);
}

void send_status(ipc *p, int ret, const char *err) {
    send_command(p, IPC_STATUS);
    send_status_inner(p, ret, err);
}

void send_error(ipc *p, const char *err) {
    send_command(p, IPC_ERROR);
    send_error_inner(p, err);
}
<commit_msg>FIX: fix reading errors and status messages<commit_after>#include <cstdlib>

#include "ipc-lick.hpp"

void free_nonnull(void *p) {
    if(p)
        free(p);
}

lickdir_t *copy_lickdir_t(lickdir_t *src) {
    lickdir_t *dst = (lickdir_t *)malloc(sizeof(lickdir_t));
    dst->lick = strdup2(src->lick);
    dst->drive = strdup2(src->drive);
    dst->entry = strdup2(src->entry);
    dst->menu = strdup2(src->menu);
    dst->res = strdup2(src->res);
    dst->err = strdup2(src->err);
    return dst;
}

void exchange_lick(ipc *p, lickdir_t *&lick) {
    if(lick == NULL)
        lick = (lickdir_t *)malloc(sizeof(lickdir_t));
    p
        ->exchange_str(lick->lick)
        ->exchange_str(lick->drive)
        ->exchange_str(lick->entry)
        ->exchange_str(lick->menu)
        ->exchange_str(lick->res)
        ->exchange_str(lick->err)
    ;
}

// IPC_INSTALL

ipc_install::ipc_install(const char *id, const char *name, const char *iso,
        const char *install_dir, lickdir_t *lick) {
    this->id = strdup2(id);
    this->name = strdup2(name);
    this->iso = strdup2(iso);
    this->install_dir = strdup2(install_dir);
    this->lick = copy_lickdir_t(lick);
}

ipc_install::~ipc_install() {
    free_nonnull(id);
    free_nonnull(name);
    free_nonnull(iso);
    free_nonnull(install_dir);
    free_lick_dir(lick);
}

void ipc_install::exchange(ipc *p) {
    p
        ->exchange_str(id)
        ->exchange_str(name)
        ->exchange_str(iso)
        ->exchange_str(install_dir)
    ;
    exchange_lick(p, lick);
}

// IPC_UNINSTALL

ipc_uninstall::ipc_uninstall(const char *id, lickdir_t *lick) {
    this->id = strdup2(id);
    this->lick = copy_lickdir_t(lick);
}
ipc_uninstall::~ipc_uninstall() {
    free_nonnull(id);
    free_lick_dir(lick);
}
void ipc_uninstall::exchange(ipc *p) {
    p
        ->exchange_str(id)
    ;
    exchange_lick(p, lick);
}

// IPC_LOADER

ipc_loader::ipc_loader(int install, lickdir_t *lick) {
    this->install = install;
    this->lick = copy_lickdir_t(lick);
}
ipc_loader::~ipc_loader() {
    free_lick_dir(lick);
}
void ipc_loader::exchange(ipc *p) {
    p
        ->exchange(install)
    ;
    exchange_lick(p, lick);
}

// IPC_STATUS

ipc_status::ipc_status(int ret, const char *err) {
    this->ret = ret;
    this->err = strdup2(err);
}
ipc_status::~ipc_status() {
    free_nonnull(err);
}
void send_status_inner(ipc *p, int &ret, char *&err) {
    p
        ->exchange(ret)
        ->exchange_str(err)
    ;
}
void ipc_status::exchange(ipc *p) {
    send_status_inner(p, ret, err);
}

// IPC_ERROR

ipc_error::ipc_error(const char *err) {
    this->err = strdup2(err);
}
ipc_error::~ipc_error() {
    free_nonnull(err);
}
void send_error_inner(ipc *p, char *&err) {
    p
        ->exchange_str(err)
    ;
}
void ipc_error::exchange(ipc *p) {
    send_error_inner(p, err);
}

ipc_lick *recv_command(ipc *p) {
    IPC_COMMANDS type;
    p->exchange(type);
    if(p->had_error())
        return NULL;

    ipc_lick *c;
    switch(type) {
    case IPC_EXIT:
        c = new ipc_exit();
        break;
    case IPC_READY:
        c = new ipc_ready();
        break;
    case IPC_INSTALL:
        c = new ipc_install();
        break;
    case IPC_UNINSTALL:
        c = new ipc_uninstall();
        break;
    case IPC_CHECK_LOADER:
        c = new ipc_check_loader();
        break;
    case IPC_LOADER:
        c = new ipc_loader();
        break;
    case IPC_STATUS:
        c = new ipc_status();
        break;
    case IPC_ERROR:
        c = new ipc_error();
        break;
    default:
        return NULL;
    }
    c->exchange(p);
    return c;
}

void send_command(ipc *p, IPC_COMMANDS c) {
    p->exchange(c);
}

void send_command(ipc *p, ipc_lick *c) {
    IPC_COMMANDS type = c->type();
    send_command(p, type);
    c->exchange(p);
}

void send_status(ipc *p, int ret, const char *err) {
    send_command(p, IPC_STATUS);
    send_status_inner(p, ret, (char *&)err);
}

void send_error(ipc *p, const char *err) {
    send_command(p, IPC_ERROR);
    send_error_inner(p, (char *&)err);
}
<|endoftext|>


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

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

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

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

// C++ includes

// Local includes
#include "libmesh/cell_prism.h"
#include "libmesh/cell_prism6.h"
#include "libmesh/face_quad4.h"
#include "libmesh/face_tri3.h"

namespace libMesh
{

// ------------------------------------------------------------
// Prism class static member initializations

// We need to require C++11...
const Real Prism::_master_points[18][3] =
  {
    {0, 0, -1},
    {1, 0, -1},
    {0, 1, -1},
    {0, 0, 1},
    {1, 0, 1},
    {0, 1, 1},
    {0.5, 0, -1},
    {0.5, 0.5, -1},
    {0, 0.5, -1},
    {0, 0, 0},
    {1, 0, 0},
    {0, 1, 0},
    {0.5, 0, 1},
    {0.5, 0.5, 1},
    {0, 0.5, 1},
    {0.5, 0, 0},
    {0.5, 0.5, 0},
    {0, 0.5, 0}
  };

// ------------------------------------------------------------
// Prism class member functions
dof_id_type Prism::key (const unsigned int s) const
{
  libmesh_assert_less (s, this->n_sides());

  switch (s)
    {
    case 0:  // the triangular face at z=0

      return
        this->compute_key (this->node(0),
                           this->node(2),
                           this->node(1));

    case 1:  // the quad face at y=0

      return
        this->compute_key (this->node(0),
                           this->node(1),
                           this->node(4),
                           this->node(3));

    case 2:  // the other quad face

      return
        this->compute_key (this->node(1),
                           this->node(2),
                           this->node(5),
                           this->node(4));

    case 3: // the quad face at x=0

      return
        this->compute_key (this->node(2),
                           this->node(0),
                           this->node(3),
                           this->node(5));
    case 4: // the triangular face at z=1

      return
        this->compute_key (this->node(3),
                           this->node(4),
                           this->node(5));

    default:
      libmesh_error_msg("Invalid side " << s);
    }

  libmesh_error_msg("We'll never get here!");
  return 0;
}

UniquePtr<Elem> Prism::side (const unsigned int i) const
{
  libmesh_assert_less (i, this->n_sides());

  Elem* face = NULL;

  switch (i)
    {
    case 0:  // the triangular face at z=0
      {
        face = new Tri3;

        face->set_node(0) = this->get_node(0);
        face->set_node(1) = this->get_node(2);
        face->set_node(2) = this->get_node(1);

        break;
      }
    case 1:  // the quad face at y=0
      {
        face = new Quad4;

        face->set_node(0) = this->get_node(0);
        face->set_node(1) = this->get_node(1);
        face->set_node(2) = this->get_node(4);
        face->set_node(3) = this->get_node(3);

        break;
      }
    case 2:  // the other quad face
      {
        face = new Quad4;

        face->set_node(0) = this->get_node(1);
        face->set_node(1) = this->get_node(2);
        face->set_node(2) = this->get_node(5);
        face->set_node(3) = this->get_node(4);

        break;
      }
    case 3: // the quad face at x=0
      {
        face = new Quad4;

        face->set_node(0) = this->get_node(2);
        face->set_node(1) = this->get_node(0);
        face->set_node(2) = this->get_node(3);
        face->set_node(3) = this->get_node(5);

        break;
      }
    case 4: // the triangular face at z=1
      {
        face = new Tri3;

        face->set_node(0) = this->get_node(3);
        face->set_node(1) = this->get_node(4);
        face->set_node(2) = this->get_node(5);

        break;
      }
    default:
      libmesh_error_msg("Invalid side i = " << i);
    }

  return UniquePtr<Elem>(face);
}

bool Prism::is_child_on_side(const unsigned int c,
                             const unsigned int s) const
{
  libmesh_assert_less (c, this->n_children());
  libmesh_assert_less (s, this->n_sides());

  for (unsigned int i = 0; i != 4; ++i)
    if (Prism6::side_elems_map[s][i] == c)
      return true;
  return false;
}

bool Prism::is_edge_on_side(const unsigned int e,
                            const unsigned int s) const
{
  libmesh_assert_less (e, this->n_edges());
  libmesh_assert_less (s, this->n_sides());

  return (is_node_on_side(Prism6::edge_nodes_map[e][0],s) &&
          is_node_on_side(Prism6::edge_nodes_map[e][1],s));
}

const unsigned short int Prism::_second_order_vertex_child_number[18] =
  {
    99,99,99,99,99,99, // Vertices
    0,1,0,0,1,2,3,4,3, // Edges
    0,1,0              // Faces
  };

const unsigned short int Prism::_second_order_vertex_child_index[18] =
  {
    99,99,99,99,99,99, // Vertices
    1,2,2,3,4,5,4,5,5, // Edges
    4,5,5              // Faces
  };

const unsigned short int Prism::_second_order_adjacent_vertices[9][2] =
  {
    { 0,  1}, // vertices adjacent to node 6
    { 1,  2}, // vertices adjacent to node 7
    { 0,  2}, // vertices adjacent to node 8

    { 0,  3}, // vertices adjacent to node 9
    { 1,  4}, // vertices adjacent to node 10
    { 2,  5}, // vertices adjacent to node 11

    { 3,  4}, // vertices adjacent to node 12
    { 4,  5}, // vertices adjacent to node 13
    { 3,  5}  // vertices adjacent to node 14
  };

} // namespace libMesh
<commit_msg>Refactor Prism::key(side)<commit_after>// The libMesh Finite Element Library.
// Copyright (C) 2002-2015 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner

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

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

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

// C++ includes

// Local includes
#include "libmesh/cell_prism.h"
#include "libmesh/cell_prism6.h"
#include "libmesh/face_quad4.h"
#include "libmesh/face_tri3.h"

namespace libMesh
{

// ------------------------------------------------------------
// Prism class static member initializations

// We need to require C++11...
const Real Prism::_master_points[18][3] =
  {
    {0, 0, -1},
    {1, 0, -1},
    {0, 1, -1},
    {0, 0, 1},
    {1, 0, 1},
    {0, 1, 1},
    {0.5, 0, -1},
    {0.5, 0.5, -1},
    {0, 0.5, -1},
    {0, 0, 0},
    {1, 0, 0},
    {0, 1, 0},
    {0.5, 0, 1},
    {0.5, 0.5, 1},
    {0, 0.5, 1},
    {0.5, 0, 0},
    {0.5, 0.5, 0},
    {0, 0.5, 0}
  };

// ------------------------------------------------------------
// Prism class member functions
dof_id_type Prism::key (const unsigned int s) const
{
  libmesh_assert_less (s, this->n_sides());

  switch (s)
    {
    case 0: // the triangular face at z=0
    case 4: // the triangular face at z=1
      return this->compute_key (this->node(Prism6::side_nodes_map[s][0]),
                                this->node(Prism6::side_nodes_map[s][1]),
                                this->node(Prism6::side_nodes_map[s][2]));

    case 1: // the quad face at y=0
    case 2: // the other quad face
    case 3: // the quad face at x=0
      return this->compute_key (this->node(Prism6::side_nodes_map[s][0]),
                                this->node(Prism6::side_nodes_map[s][1]),
                                this->node(Prism6::side_nodes_map[s][2]),
                                this->node(Prism6::side_nodes_map[s][3]));

    default:
      libmesh_error_msg("Invalid side " << s);
    }

  libmesh_error_msg("We'll never get here!");
  return 0;
}

UniquePtr<Elem> Prism::side (const unsigned int i) const
{
  libmesh_assert_less (i, this->n_sides());

  Elem* face = NULL;

  switch (i)
    {
    case 0:  // the triangular face at z=0
      {
        face = new Tri3;

        face->set_node(0) = this->get_node(0);
        face->set_node(1) = this->get_node(2);
        face->set_node(2) = this->get_node(1);

        break;
      }
    case 1:  // the quad face at y=0
      {
        face = new Quad4;

        face->set_node(0) = this->get_node(0);
        face->set_node(1) = this->get_node(1);
        face->set_node(2) = this->get_node(4);
        face->set_node(3) = this->get_node(3);

        break;
      }
    case 2:  // the other quad face
      {
        face = new Quad4;

        face->set_node(0) = this->get_node(1);
        face->set_node(1) = this->get_node(2);
        face->set_node(2) = this->get_node(5);
        face->set_node(3) = this->get_node(4);

        break;
      }
    case 3: // the quad face at x=0
      {
        face = new Quad4;

        face->set_node(0) = this->get_node(2);
        face->set_node(1) = this->get_node(0);
        face->set_node(2) = this->get_node(3);
        face->set_node(3) = this->get_node(5);

        break;
      }
    case 4: // the triangular face at z=1
      {
        face = new Tri3;

        face->set_node(0) = this->get_node(3);
        face->set_node(1) = this->get_node(4);
        face->set_node(2) = this->get_node(5);

        break;
      }
    default:
      libmesh_error_msg("Invalid side i = " << i);
    }

  return UniquePtr<Elem>(face);
}

bool Prism::is_child_on_side(const unsigned int c,
                             const unsigned int s) const
{
  libmesh_assert_less (c, this->n_children());
  libmesh_assert_less (s, this->n_sides());

  for (unsigned int i = 0; i != 4; ++i)
    if (Prism6::side_elems_map[s][i] == c)
      return true;
  return false;
}

bool Prism::is_edge_on_side(const unsigned int e,
                            const unsigned int s) const
{
  libmesh_assert_less (e, this->n_edges());
  libmesh_assert_less (s, this->n_sides());

  return (is_node_on_side(Prism6::edge_nodes_map[e][0],s) &&
          is_node_on_side(Prism6::edge_nodes_map[e][1],s));
}

const unsigned short int Prism::_second_order_vertex_child_number[18] =
  {
    99,99,99,99,99,99, // Vertices
    0,1,0,0,1,2,3,4,3, // Edges
    0,1,0              // Faces
  };

const unsigned short int Prism::_second_order_vertex_child_index[18] =
  {
    99,99,99,99,99,99, // Vertices
    1,2,2,3,4,5,4,5,5, // Edges
    4,5,5              // Faces
  };

const unsigned short int Prism::_second_order_adjacent_vertices[9][2] =
  {
    { 0,  1}, // vertices adjacent to node 6
    { 1,  2}, // vertices adjacent to node 7
    { 0,  2}, // vertices adjacent to node 8

    { 0,  3}, // vertices adjacent to node 9
    { 1,  4}, // vertices adjacent to node 10
    { 2,  5}, // vertices adjacent to node 11

    { 3,  4}, // vertices adjacent to node 12
    { 4,  5}, // vertices adjacent to node 13
    { 3,  5}  // vertices adjacent to node 14
  };

} // namespace libMesh
<|endoftext|>


<commit_before>// $Id: face_quad4.C,v 1.21 2005-06-16 23:03:52 roystgnr Exp $

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

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

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

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

// C++ includes

// Local includes
#include "side.h"
#include "edge_edge2.h"
#include "face_quad4.h"

// ------------------------------------------------------------
// Quad class static member initialization
const unsigned int Quad4::side_nodes_map[4][2] =
{
  {0, 1}, // Side 0
  {1, 2}, // Side 1
  {2, 3}, // Side 2
  {3, 0}  // Side 3
};

#ifdef ENABLE_AMR

const float Quad4::_embedding_matrix[4][4][4] =
{
  // embedding matrix for child 0
  {
    // 0    1    2    3
    {1.0, 0.0, 0.0, 0.0}, // 0
    {0.5, 0.5, 0.0, 0.0}, // 1
    {.25, .25, .25, .25}, // 2
    {0.5, 0.0, 0.0, 0.5}  // 3
  },

  // embedding matrix for child 1
  {
    // 0    1    2    3
    {0.5, 0.5, 0.0, 0.0}, // 0
    {0.0, 1.0, 0.0, 0.0}, // 1
    {0.0, 0.5, 0.5, 0.0}, // 2
    {.25, .25, .25, .25}  // 3
  },

  // embedding matrix for child 2
  {
    // 0    1    2    3
    {0.5, 0.0, 0.0, 0.5}, // 0
    {.25, .25, .25, .25}, // 1
    {0.0, 0.0, 0.5, 0.5}, // 2
    {0.0, 0.0, 0.0, 1.0}  // 3
  },

  // embedding matrix for child 3
  {
    // 0    1    2    3
    {.25, .25, .25, .25}, // 0
    {0.0, 0.5, 0.5, 0.0}, // 1
    {0.0, 0.0, 1.0, 0.0}, // 2
    {0.0, 0.0, 0.5, 0.5}  // 3
  }
};

#endif

// ------------------------------------------------------------
// Quad4 class member functions

bool Quad4::is_vertex(const unsigned int) const
{
  return true;
}

bool Quad4::is_edge(const unsigned int) const
{
  return false;
}

bool Quad4::is_face(const unsigned int) const
{
  return false;
}

bool Quad4::is_node_on_side(const unsigned int n,
			    const unsigned int s) const
{
  assert(s < n_sides());
  for (unsigned int i = 0; i != 2; ++i)
    if (side_nodes_map[s][i] == n)
      return true;
  return false;
}

bool Quad4::has_affine_map() const
{
  return (this->node(3) - this->node(0) ==
          this->node(2) - this->node(1));
}

AutoPtr<Elem> Quad4::build_side (const unsigned int i) const
{
  assert (i < this->n_sides());

  AutoPtr<Elem> ap(new Side<Edge2,Quad4>(this,i));
  return ap;

//   switch (i)
//     {
//     case 0:
//       {
// 	Edge2* edge = new Edge2;

// 	edge->set_node(0) = this->get_node(0);
// 	edge->set_node(1) = this->get_node(1);

// 	AutoPtr<Elem> ap(edge);  return ap;
//       }
//     case 1:
//       {
// 	Edge2* edge = new Edge2;

// 	edge->set_node(0) = this->get_node(1);
// 	edge->set_node(1) = this->get_node(2);

// 	AutoPtr<Elem> ap(edge);  return ap;
//       }
//     case 2:
//       {
// 	Edge2* edge = new Edge2;

// 	edge->set_node(0) = this->get_node(2);
// 	edge->set_node(1) = this->get_node(3);

// 	AutoPtr<Elem> ap(edge);  return ap;
//       }
//     case 3:
//       {
// 	Edge2* edge = new Edge2;

// 	edge->set_node(0) = this->get_node(3);
// 	edge->set_node(1) = this->get_node(0);

// 	AutoPtr<Elem> ap(edge);  return ap;
//       }
//     default:
//       {
// 	error();
//       }
//     }

//   // We will never get here...  Look at the code above.
//   AutoPtr<Elem> ap(NULL);  return ap;
}

void Quad4::connectivity(const unsigned int sf,
			 const IOPackage iop,
			 std::vector<unsigned int>& conn) const
{
  assert (sf < this->n_sub_elem());
  assert (iop != INVALID_IO_PACKAGE);

  // Create storage.
  conn.resize(4);

  switch (iop)
    {
    case TECPLOT:
      {
	conn[0] = this->node(0)+1;
	conn[1] = this->node(1)+1;
	conn[2] = this->node(2)+1;
	conn[3] = this->node(3)+1;
	return;
      }

    case VTK:
      {
	conn[0] = this->node(0);
	conn[1] = this->node(1);
	conn[2] = this->node(2);
	conn[3] = this->node(3);
	return;
      }

    default:
      error();
    }

  error();
}
<commit_msg>Fix stupid error in has_affine_map<commit_after>// $Id: face_quad4.C,v 1.22 2006-06-07 19:19:26 roystgnr Exp $

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

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

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

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

// C++ includes

// Local includes
#include "side.h"
#include "edge_edge2.h"
#include "face_quad4.h"

// ------------------------------------------------------------
// Quad class static member initialization
const unsigned int Quad4::side_nodes_map[4][2] =
{
  {0, 1}, // Side 0
  {1, 2}, // Side 1
  {2, 3}, // Side 2
  {3, 0}  // Side 3
};

#ifdef ENABLE_AMR

const float Quad4::_embedding_matrix[4][4][4] =
{
  // embedding matrix for child 0
  {
    // 0    1    2    3
    {1.0, 0.0, 0.0, 0.0}, // 0
    {0.5, 0.5, 0.0, 0.0}, // 1
    {.25, .25, .25, .25}, // 2
    {0.5, 0.0, 0.0, 0.5}  // 3
  },

  // embedding matrix for child 1
  {
    // 0    1    2    3
    {0.5, 0.5, 0.0, 0.0}, // 0
    {0.0, 1.0, 0.0, 0.0}, // 1
    {0.0, 0.5, 0.5, 0.0}, // 2
    {.25, .25, .25, .25}  // 3
  },

  // embedding matrix for child 2
  {
    // 0    1    2    3
    {0.5, 0.0, 0.0, 0.5}, // 0
    {.25, .25, .25, .25}, // 1
    {0.0, 0.0, 0.5, 0.5}, // 2
    {0.0, 0.0, 0.0, 1.0}  // 3
  },

  // embedding matrix for child 3
  {
    // 0    1    2    3
    {.25, .25, .25, .25}, // 0
    {0.0, 0.5, 0.5, 0.0}, // 1
    {0.0, 0.0, 1.0, 0.0}, // 2
    {0.0, 0.0, 0.5, 0.5}  // 3
  }
};

#endif

// ------------------------------------------------------------
// Quad4 class member functions

bool Quad4::is_vertex(const unsigned int) const
{
  return true;
}

bool Quad4::is_edge(const unsigned int) const
{
  return false;
}

bool Quad4::is_face(const unsigned int) const
{
  return false;
}

bool Quad4::is_node_on_side(const unsigned int n,
			    const unsigned int s) const
{
  assert(s < n_sides());
  for (unsigned int i = 0; i != 2; ++i)
    if (side_nodes_map[s][i] == n)
      return true;
  return false;
}

bool Quad4::has_affine_map() const
{
  return (this->point(3) - this->point(0) ==
          this->point(2) - this->point(1));
}

AutoPtr<Elem> Quad4::build_side (const unsigned int i) const
{
  assert (i < this->n_sides());

  AutoPtr<Elem> ap(new Side<Edge2,Quad4>(this,i));
  return ap;

//   switch (i)
//     {
//     case 0:
//       {
// 	Edge2* edge = new Edge2;

// 	edge->set_node(0) = this->get_node(0);
// 	edge->set_node(1) = this->get_node(1);

// 	AutoPtr<Elem> ap(edge);  return ap;
//       }
//     case 1:
//       {
// 	Edge2* edge = new Edge2;

// 	edge->set_node(0) = this->get_node(1);
// 	edge->set_node(1) = this->get_node(2);

// 	AutoPtr<Elem> ap(edge);  return ap;
//       }
//     case 2:
//       {
// 	Edge2* edge = new Edge2;

// 	edge->set_node(0) = this->get_node(2);
// 	edge->set_node(1) = this->get_node(3);

// 	AutoPtr<Elem> ap(edge);  return ap;
//       }
//     case 3:
//       {
// 	Edge2* edge = new Edge2;

// 	edge->set_node(0) = this->get_node(3);
// 	edge->set_node(1) = this->get_node(0);

// 	AutoPtr<Elem> ap(edge);  return ap;
//       }
//     default:
//       {
// 	error();
//       }
//     }

//   // We will never get here...  Look at the code above.
//   AutoPtr<Elem> ap(NULL);  return ap;
}

void Quad4::connectivity(const unsigned int sf,
			 const IOPackage iop,
			 std::vector<unsigned int>& conn) const
{
  assert (sf < this->n_sub_elem());
  assert (iop != INVALID_IO_PACKAGE);

  // Create storage.
  conn.resize(4);

  switch (iop)
    {
    case TECPLOT:
      {
	conn[0] = this->node(0)+1;
	conn[1] = this->node(1)+1;
	conn[2] = this->node(2)+1;
	conn[3] = this->node(3)+1;
	return;
      }

    case VTK:
      {
	conn[0] = this->node(0);
	conn[1] = this->node(1);
	conn[2] = this->node(2);
	conn[3] = this->node(3);
	return;
      }

    default:
      error();
    }

  error();
}
<|endoftext|>


<commit_before>#include "../config.h"
#include "horde3dwindow.h"
#include "cameranodeobject.h"

#include <Horde3DUtils.h>

#include <QtCore/QPropertyAnimation>
#include <QtCore/QCoreApplication>
#include <QtCore/QDir>
#include <QtGui/QOpenGLFunctions>
#include <QtGui/QOpenGLFramebufferObject>
#include <QtQuick/QQuickWindow>
#include <QtQuick/QSGSimpleTextureNode>

#include <GL/gl.h>

static const bool USE_SEPARATE_CONTEXT = false;

Horde3DWindow::Horde3DWindow(QWindow *parent) :
		QQuickWindow(parent),
		m_samples(0),
		m_initialized(false),
		m_dirtyView(false),
		m_animTime(0.0f),
		m_qtContext(NULL),
		m_h3dContext(NULL)
{
	connect(this, SIGNAL(beforeRendering()), this, SLOT(onBeforeRendering()), Qt::DirectConnection);
	connect(this, SIGNAL(initFinished()), this, SLOT(onInitFinished()), Qt::QueuedConnection);
} // end Horde3DWindow

Horde3DWindow::~Horde3DWindow()
{
	if(m_h3dContext)
	{
		m_h3dContext->deleteLater();
		m_h3dContext = NULL;
	} // end if
} // end ~Horde3DWindow

void Horde3DWindow::renderHorde()
{
	m_animTime += 0.4f;

	// Do animation blending
	h3dSetModelAnimParams(m_knight, 0, m_animTime, 0.5f);
	h3dSetModelAnimParams(m_knight, 1, m_animTime, 0.5f);
	h3dUpdateModel(m_knight, H3DModelUpdateFlags::Animation | H3DModelUpdateFlags::Geometry);

	if(m_camera)
	{
		if(!USE_SEPARATE_CONTEXT || (m_qtContext && m_h3dContext))
		{
			restoreH3DState();

			h3dRender(m_camera);
			h3dFinalizeFrame();

			saveH3DState();
		} // end if
	} // end if
} // end renderHorde

void Horde3DWindow::resizeEvent(QResizeEvent* event)
{
	qDebug() << "Horde3DWindow::resizeEvent(" << event->oldSize() << "->" << event->size() << ")";

	if(event->size() != event->oldSize())
	{
		m_size = event->size();
		m_dirtyView = true;
	} // end if

	QQuickWindow::resizeEvent(event);
} // end geometryChanged

void Horde3DWindow::printHordeMessages()
{
	int msgLevel;
	float msgTime;
	const char* message;

	while((message = h3dGetMessage(&msgLevel, &msgTime)) && strlen(message) > 0)
	{
		qDebug() << msgLevel << "message from Horde3D at" << msgTime << ":" << message;
	} // end while
} // end printHordeMessages

void Horde3DWindow::restoreH3DState()
{
	if(USE_SEPARATE_CONTEXT)
	{
		m_qtContext->doneCurrent();
		m_h3dContext->makeCurrent(this);
	}
	else
	{
		glPushAttrib(GL_ALL_ATTRIB_BITS);
	} // end if

	QOpenGLFunctions glFunctions(QOpenGLContext::currentContext());
	glFunctions.glUseProgram(0);

	if(renderTarget())
	{
		renderTarget()->bind();
	} // end if
} // end restoreH3DState

void Horde3DWindow::saveH3DState()
{
	if(renderTarget())
	{
		renderTarget()->release();
	} // end if

	if(USE_SEPARATE_CONTEXT)
	{
		m_h3dContext->doneCurrent();
		m_qtContext->makeCurrent(this);
	}
	else
	{
		glPopAttrib();
	} // end if
} // end saveH3DState

void Horde3DWindow::updateView()
{
	if(m_initialized)
	{
		qDebug() << "Horde3DWindow::updateView()";

		int deviceWidth = m_size.width();
		int deviceHeight = m_size.height();

		// Resize viewport
		h3dSetNodeParamI(m_camera, H3DCamera::ViewportXI, 0);
		h3dSetNodeParamI(m_camera, H3DCamera::ViewportYI, 0);
		h3dSetNodeParamI(m_camera, H3DCamera::ViewportWidthI, deviceWidth);
		h3dSetNodeParamI(m_camera, H3DCamera::ViewportHeightI, deviceHeight);

		// Set virtual camera parameters
		float aspectRatio = static_cast<float>(deviceWidth) / deviceHeight;
		h3dSetupCameraView(m_camera, 45.0f, aspectRatio, 0.1f, 1000.0f);
		h3dSetNodeTransform(m_camera,
				0, 40, -40,
				//-40, 40, -70,
				23, -166, 180,
				1, 1, 1
				);

		H3DRes cameraPipeRes = h3dGetNodeParamI(m_camera, H3DCamera::PipeResI);
		h3dResizePipelineBuffers(cameraPipeRes, deviceWidth, deviceHeight);

		m_dirtyView = false;
	} // end if
} // end updateView

void Horde3DWindow::timerEvent(QTimerEvent *)
{
	update();
} // end timerEvent

void Horde3DWindow::onBeforeRendering()
{
	if(!m_initialized)
	{
		init();
	} // end if

	if(m_dirtyView)
	{
		updateView();
	} // end if

	if(USE_SEPARATE_CONTEXT)
	{
		if(m_h3dContext && (m_h3dContext->format() != m_qtContext->format()))
		{
			m_h3dContext->deleteLater();
			m_h3dContext = NULL;
		} // end if

		if(!m_h3dContext)
		{
			qDebug() << "Creating new OpenGL context.";
			// Create a new shared OpenGL context to be used exclusively by Horde3D
			m_h3dContext = new QOpenGLContext();
			m_h3dContext->setFormat(requestedFormat());
			m_h3dContext->setShareContext(m_qtContext);
			m_h3dContext->create();
		} // end if
	} // end if

	renderHorde();

	printHordeMessages();
} // end onBeforeRendering

void Horde3DWindow::onInitFinished()
{
	startTimer(16);
} // end onInitFinished

void Horde3DWindow::init()
{
	qDebug() << "Horde3DWindow::init()";

	m_qtContext = openglContext();
	m_samples = m_qtContext->format().samples();

	if(!h3dInit())
	{
		qCritical() << "h3dInit failed";
	} // end if

	int textureAnisotropy = 8;
	if(!h3dSetOption(H3DOptions::MaxAnisotropy, textureAnisotropy))
	{
		qDebug() << "Couldn't set texture anisotropy to" << textureAnisotropy << "!";
	} // end if

	if(!h3dSetOption(H3DOptions::SampleCount, m_samples))
	{
		qDebug() << "Couldn't set antialiasing samples to" << m_samples << "!";
	} // end if

	H3DRes pipeline = h3dAddResource(H3DResTypes::Pipeline, "pipelines/forward.pipeline.xml", 0);
	H3DRes knight = h3dAddResource(H3DResTypes::SceneGraph, "models/knight/knight.scene.xml", 0);
	H3DRes knightAnim1Res = h3dAddResource( H3DResTypes::Animation, "animations/knight_order.anim", 0 );
	H3DRes knightAnim2Res = h3dAddResource( H3DResTypes::Animation, "animations/knight_attack.anim", 0 );

	h3dutLoadResourcesFromDisk("Content");

	m_knight = h3dAddNodes(H3DRootNode, knight);
	h3dSetNodeTransform(m_knight,
			0, 0, 0,
			0, 0, 0,
			1, 1, 1
			);
	h3dSetupModelAnimStage(m_knight, 0, knightAnim1Res, 0, "", false);
	h3dSetupModelAnimStage(m_knight, 1, knightAnim2Res, 0, "", false);

	m_camera = h3dAddCameraNode(H3DRootNode, "cam", pipeline);
	h3dSetNodeParamF(m_camera, H3DCamera::FarPlaneF, 0, 100000);

	m_cameraObject = new CameraNodeObject(m_camera);
	m_cameraQObject = static_cast<QObject *>(m_cameraObject);

	setClearBeforeRendering(false);

	printHordeMessages();
	qDebug() << "--------- Initialization Finished ---------";

	m_initialized = true;
	emit initFinished();
} // end init
<commit_msg>Attempt at fixing rendering on retina screens.<commit_after>#include "../config.h"
#include "horde3dwindow.h"
#include "cameranodeobject.h"

#include <Horde3DUtils.h>

#include <QtCore/QPropertyAnimation>
#include <QtCore/QCoreApplication>
#include <QtCore/QDir>
#include <QtGui/QOpenGLFunctions>
#include <QtGui/QOpenGLFramebufferObject>
#include <QtGui/QScreen>
#include <QtQuick/QQuickWindow>
#include <QtQuick/QSGSimpleTextureNode>

#include <GL/gl.h>

static const bool USE_SEPARATE_CONTEXT = false;

Horde3DWindow::Horde3DWindow(QWindow *parent) :
		QQuickWindow(parent),
		m_samples(0),
		m_initialized(false),
		m_dirtyView(false),
		m_animTime(0.0f),
		m_qtContext(NULL),
		m_h3dContext(NULL)
{
	connect(this, SIGNAL(beforeRendering()), this, SLOT(onBeforeRendering()), Qt::DirectConnection);
	connect(this, SIGNAL(initFinished()), this, SLOT(onInitFinished()), Qt::QueuedConnection);
} // end Horde3DWindow

Horde3DWindow::~Horde3DWindow()
{
	if(m_h3dContext)
	{
		m_h3dContext->deleteLater();
		m_h3dContext = NULL;
	} // end if
} // end ~Horde3DWindow

void Horde3DWindow::renderHorde()
{
	m_animTime += 0.4f;

	// Do animation blending
	h3dSetModelAnimParams(m_knight, 0, m_animTime, 0.5f);
	h3dSetModelAnimParams(m_knight, 1, m_animTime, 0.5f);
	h3dUpdateModel(m_knight, H3DModelUpdateFlags::Animation | H3DModelUpdateFlags::Geometry);

	if(m_camera)
	{
		if(!USE_SEPARATE_CONTEXT || (m_qtContext && m_h3dContext))
		{
			restoreH3DState();

			h3dRender(m_camera);
			h3dFinalizeFrame();

			saveH3DState();
		} // end if
	} // end if
} // end renderHorde

void Horde3DWindow::resizeEvent(QResizeEvent* event)
{
	qDebug() << "Horde3DWindow::resizeEvent(" << event->oldSize() << "->" << event->size() << "); devicePixelRatio:" << screen()->devicePixelRatio();

	if(event->size() != event->oldSize())
	{
		m_size = event->size() * screen()->devicePixelRatio();
		m_dirtyView = true;
	} // end if

	QQuickWindow::resizeEvent(event);
} // end geometryChanged

void Horde3DWindow::printHordeMessages()
{
	int msgLevel;
	float msgTime;
	const char* message;

	while((message = h3dGetMessage(&msgLevel, &msgTime)) && strlen(message) > 0)
	{
		qDebug() << msgLevel << "message from Horde3D at" << msgTime << ":" << message;
	} // end while
} // end printHordeMessages

void Horde3DWindow::restoreH3DState()
{
	if(USE_SEPARATE_CONTEXT)
	{
		m_qtContext->doneCurrent();
		m_h3dContext->makeCurrent(this);
	}
	else
	{
		glPushAttrib(GL_ALL_ATTRIB_BITS);
	} // end if

	QOpenGLFunctions glFunctions(QOpenGLContext::currentContext());
	glFunctions.glUseProgram(0);

	if(renderTarget())
	{
		renderTarget()->bind();
	} // end if
} // end restoreH3DState

void Horde3DWindow::saveH3DState()
{
	if(renderTarget())
	{
		renderTarget()->release();
	} // end if

	if(USE_SEPARATE_CONTEXT)
	{
		m_h3dContext->doneCurrent();
		m_qtContext->makeCurrent(this);
	}
	else
	{
		glPopAttrib();
	} // end if
} // end saveH3DState

void Horde3DWindow::updateView()
{
	if(m_initialized)
	{
		qDebug() << "Horde3DWindow::updateView()";

		int deviceWidth = m_size.width();
		int deviceHeight = m_size.height();

		// Resize viewport
		h3dSetNodeParamI(m_camera, H3DCamera::ViewportXI, 0);
		h3dSetNodeParamI(m_camera, H3DCamera::ViewportYI, 0);
		h3dSetNodeParamI(m_camera, H3DCamera::ViewportWidthI, deviceWidth);
		h3dSetNodeParamI(m_camera, H3DCamera::ViewportHeightI, deviceHeight);

		// Set virtual camera parameters
		float aspectRatio = static_cast<float>(deviceWidth) / deviceHeight;
		h3dSetupCameraView(m_camera, 45.0f, aspectRatio, 0.1f, 1000.0f);
		h3dSetNodeTransform(m_camera,
				0, 40, -40,
				//-40, 40, -70,
				23, -166, 180,
				1, 1, 1
				);

		H3DRes cameraPipeRes = h3dGetNodeParamI(m_camera, H3DCamera::PipeResI);
		h3dResizePipelineBuffers(cameraPipeRes, deviceWidth, deviceHeight);

		m_dirtyView = false;
	} // end if
} // end updateView

void Horde3DWindow::timerEvent(QTimerEvent *)
{
	update();
} // end timerEvent

void Horde3DWindow::onBeforeRendering()
{
	if(!m_initialized)
	{
		init();
	} // end if

	if(m_dirtyView)
	{
		updateView();
	} // end if

	if(USE_SEPARATE_CONTEXT)
	{
		if(m_h3dContext && (m_h3dContext->format() != m_qtContext->format()))
		{
			m_h3dContext->deleteLater();
			m_h3dContext = NULL;
		} // end if

		if(!m_h3dContext)
		{
			qDebug() << "Creating new OpenGL context.";
			// Create a new shared OpenGL context to be used exclusively by Horde3D
			m_h3dContext = new QOpenGLContext();
			m_h3dContext->setFormat(requestedFormat());
			m_h3dContext->setShareContext(m_qtContext);
			m_h3dContext->create();
		} // end if
	} // end if

	renderHorde();

	printHordeMessages();
} // end onBeforeRendering

void Horde3DWindow::onInitFinished()
{
	startTimer(16);
} // end onInitFinished

void Horde3DWindow::init()
{
	qDebug() << "Horde3DWindow::init()";

	m_qtContext = openglContext();
	m_samples = m_qtContext->format().samples();

	if(!h3dInit())
	{
		qCritical() << "h3dInit failed";
	} // end if

	int textureAnisotropy = 8;
	if(!h3dSetOption(H3DOptions::MaxAnisotropy, textureAnisotropy))
	{
		qDebug() << "Couldn't set texture anisotropy to" << textureAnisotropy << "!";
	} // end if

	if(!h3dSetOption(H3DOptions::SampleCount, m_samples))
	{
		qDebug() << "Couldn't set antialiasing samples to" << m_samples << "!";
	} // end if

	H3DRes pipeline = h3dAddResource(H3DResTypes::Pipeline, "pipelines/forward.pipeline.xml", 0);
	H3DRes knight = h3dAddResource(H3DResTypes::SceneGraph, "models/knight/knight.scene.xml", 0);
	H3DRes knightAnim1Res = h3dAddResource( H3DResTypes::Animation, "animations/knight_order.anim", 0 );
	H3DRes knightAnim2Res = h3dAddResource( H3DResTypes::Animation, "animations/knight_attack.anim", 0 );

	h3dutLoadResourcesFromDisk("Content");

	m_knight = h3dAddNodes(H3DRootNode, knight);
	h3dSetNodeTransform(m_knight,
			0, 0, 0,
			0, 0, 0,
			1, 1, 1
			);
	h3dSetupModelAnimStage(m_knight, 0, knightAnim1Res, 0, "", false);
	h3dSetupModelAnimStage(m_knight, 1, knightAnim2Res, 0, "", false);

	m_camera = h3dAddCameraNode(H3DRootNode, "cam", pipeline);
	h3dSetNodeParamF(m_camera, H3DCamera::FarPlaneF, 0, 100000);

	m_cameraObject = new CameraNodeObject(m_camera);
	m_cameraQObject = static_cast<QObject *>(m_cameraObject);

	setClearBeforeRendering(false);

	printHordeMessages();
	qDebug() << "--------- Initialization Finished ---------";

	m_initialized = true;
	emit initFinished();
} // end init
<|endoftext|>


<commit_before>#include "DirectShowCam.h"

CDirectShowCam::CDirectShowCam(LPCTSTR szDeviceName):CCamera(szDeviceName)
{
	m_CamType = L"color";
	m_pDSCam = NULL;
}
CDirectShowCam::~CDirectShowCam()
{
	if (m_pDSCam)
	{
		delete m_pDSCam;
		m_pDSCam = NULL;
	}

}
BOOL CDirectShowCam::enumerate(rho::Vector<rho::String>& arIDs, rho::Hashtable<rho::String, eCamType>& camLookUp)
{
	BOOL bRetStatus= FALSE;
	DEVMGR_DEVICE_INFORMATION di;
	// The driver material doesn't ship as part of the SDK. This GUID is hardcoded
	// here to be able to enumerate the camera drivers and pass the name of the driver to the video capture filter
	GUID guidCamera = {0xCB998A05, 0x122C, 0x4166, 0x84, 0x6A, 0x93, 0x3E, 0x4D, 0x7E, 0x3C, 0x86};

	di.dwSize = sizeof(di);
	HANDLE hFirstDevice = FindFirstDevice(DeviceSearchByGuid, &guidCamera, &di);
	if((hFirstDevice != INVALID_HANDLE_VALUE) ||(hFirstDevice != NULL) || (di.hDevice != NULL))
	{
		bRetStatus = TRUE;
		arIDs.addElement(rho::common::convertToStringA(di.szLegacyName));
		camLookUp.put(rho::common::convertToStringA(di.szLegacyName), eColorCam );
		//search for next device in a loop
		while(FindNextDevice(hFirstDevice, &di))
		{
			arIDs.addElement(rho::common::convertToStringA(di.szLegacyName));
			camLookUp.put(rho::common::convertToStringA(di.szLegacyName), eColorCam );

		}
	}
	return bRetStatus;

}
void CDirectShowCam::takeFullScreen()
{
	LOG(INFO) + __FUNCTION__ ;
	if(false == m_IsCameraRunning)
	{
		if(m_PreviewOn == false)
		{
			CamConfig cfg;
			if (m_pDSCam)
			{
				delete m_pDSCam;
			}
			m_pDSCam = new CDShowCam();
			if(m_pDSCam)
			{
				if(m_pDSCam->initFilterGraph())
				{
					cfg.sCamID = m_szDeviceName;
					cfg.bIsAudioEnb = FALSE;	// no audio capture
					cfg.bIsCapEnb = TRUE;		// enable capture
					cfg.bIsPrvEnb = TRUE;		// enable preview
					cfg.bIsStillEnb = TRUE;		// enable still capture

					if(m_pDSCam->BuildFilterGraph(cfg))
					{
						RECT pos;
						HWND hWndViewer = m_ViewFinder.CreateViewerWindow(pos, eFullScreen);
						if(m_pDSCam->SetupPreview(hWndViewer, pos))
						{
							m_PreviewOn = true;
							m_IsCameraRunning = true;
							setCameraProperties();
						}

					}
				}
			}
			if(false == m_PreviewOn)
			{
				//if preview failed
				if (m_pDSCam)
				{
					delete m_pDSCam;
					m_pDSCam = NULL;
				}
			}

		}
	}
}
BOOL CDirectShowCam::showPreview()
{
	BOOL bPreviewStatus = FALSE;
    LOG(INFO) + __FUNCTION__ ;
	if(m_IsCameraRunning == false)
	{
		if(m_PreviewOn == false)
		{
			CamConfig cfg;
			if (m_pDSCam)
			{
				delete m_pDSCam;
			}
			m_pDSCam = new CDShowCam();
			if(m_pDSCam)
			{
				if(m_pDSCam->initFilterGraph())
				{
					cfg.sCamID = m_szDeviceName;
					cfg.bIsAudioEnb = FALSE;	// no audio capture
					cfg.bIsCapEnb = TRUE;		// enable capture
					cfg.bIsPrvEnb = TRUE;		// enable preview
					cfg.bIsStillEnb = TRUE;		// enable still capture

					if(m_pDSCam->BuildFilterGraph(cfg))
					{
						RECT pos;
						pos.left = m_PreviewLeft;
						pos.top = m_PreviewTop;
						pos.right = m_PreviewWidth;
						pos.bottom = m_PreviewHeight;
						HWND hWndViewer = m_ViewFinder.CreateViewerWindow(pos, eConfigurable);
						pos.left=0;
						pos.top=0;
						if(m_pDSCam->SetupPreview(hWndViewer, pos))
						{
							m_PreviewOn = true;
							m_IsCameraRunning = true;
							setCameraProperties();
						}

					}
				}

			}
			if(false == m_PreviewOn)
			{
				//if preview failed
				if (m_pDSCam)
				{
					delete m_pDSCam;
					m_pDSCam = NULL;
				}
			}
		}
	}
	return bPreviewStatus;

}
BOOL CDirectShowCam::hidePreview()
{
	LOG(INFO) + __FUNCTION__ 	;
	BOOL bRetStatus = FALSE;
	if (m_PreviewOn)
	{
		m_ViewFinder.DestroyViewerWindow();
		if (m_pDSCam)
		{
			if(FALSE== m_pDSCam->StopGrp())
			{
				LOG(ERROR) + __FUNCTION__ + L" Stop camera failed";
			}
			delete m_pDSCam;
			m_pDSCam = NULL;
			m_PreviewOn = false;
		    m_IsCameraRunning = false;
			bRetStatus = TRUE;

		}

	}
	return bRetStatus;
}
void CDirectShowCam::Capture()
{
	LOG(INFO) + __FUNCTION__ ;
	HRESULT hr;
	if(m_PreviewOn)
	{

		PlaySound(m_CaptureSound.c_str(),NULL,SND_FILENAME|SND_ASYNC);

		if(m_pDSCam)
		{
			rho::StringW fileName = m_FileName + L".jpg";
			hr= m_pDSCam->CaptureStill(fileName);
			if(SUCCEEDED(hr))
			{
				//  Rather than get bogged down the Direct Show again we'll just
				//  read the file back in from disk.
				HANDLE hFile = CreateFile(fileName.c_str(), GENERIC_READ, 0, NULL, OPEN_EXISTING,
					FILE_ATTRIBUTE_NORMAL, NULL);

				if(hFile)
				{
					DWORD dwFileSize = GetFileSize(hFile, NULL);
					if (dwFileSize > 0)
					{

						rho::String imageUri;
						if(m_eOutputFormat == eDataUri)
						{

							bool fileReadSuccess = true;
							DWORD dwImageBufSize;///< Variable for Buffer size of captured image
							LPVOID pImageBuffer;///< Buffer to save captured image
							pImageBuffer = new BYTE[dwFileSize];
							dwImageBufSize = dwFileSize;
							DWORD dwBytesRead = 0;
							do
							{
								if (!ReadFile(hFile, pImageBuffer, dwFileSize, &dwBytesRead, NULL))
								{
									//  Some error has occured reading the file
									LOG(ERROR) + L"Unable to send image data as URI, could not read data";
									UpdateCallbackStatus("error","Unable to send image data as URI, could not read data","");
									delete[] pImageBuffer;
									pImageBuffer = NULL;
									fileReadSuccess = false;
									break;
								}
							}
							while (dwBytesRead != 0);
							if(fileReadSuccess)
							{
								GetDataURI((BYTE*)pImageBuffer, dwImageBufSize, imageUri);
								delete[] pImageBuffer;
								pImageBuffer = NULL;
								//update callback
								UpdateCallbackStatus("ok","",imageUri);

							}

						}
						else
						{
							imageUri = rho::common::convertToStringA(fileName).c_str();
							//update callback
							UpdateCallbackStatus("ok","",imageUri);
						}

					}
					else
					{
						LOG(ERROR) + L"Unable to send image data as URI, size was unexpected";
						UpdateCallbackStatus("error","Unable to send image data as URI, size was unexpected","");
					}

				}
				else
				{
					LOG(ERROR) + L"Unable to send image data as URI, could not find captured image";
					UpdateCallbackStatus("error", "Unable to send image data as URI, could not find captured image","");

				}
				CloseHandle(hFile);

			}
			else
			{
				UpdateCallbackStatus("error","Image Capture operation failed.","");
			}
		}

	}
}
void CDirectShowCam::SetFlashMode()
{
	if(m_PreviewOn)
	{
		HRESULT hr;
		CamPropTbl propTbl;
		propTbl.p = CameraControl_Flash;
		hr = m_pDSCam->Get_PropRng(&propTbl);
		if (hr != E_PROP_ID_UNSUPPORTED)
		{
			propTbl.plVal = m_FlashMode ? propTbl.plMax : propTbl.plMin;
			m_pDSCam->Set_PropVal( &propTbl);
		}
	}
}

void CDirectShowCam::setCameraProperties()
{
	if(m_PreviewOn)
	{
		SetFlashMode();
		SetReolution();
	}

}
void CDirectShowCam::RedrawViewerWnd(RECT& pos)
{
	if(m_PreviewOn)
	{
		CCamera::RedrawViewerWnd(pos);
		if(m_pDSCam)
		{
			m_pDSCam->ResizePreview(pos.right, pos.bottom);
		}
	}
}
void CDirectShowCam::SetReolution()
{
	if(m_PreviewOn)
	{
		//  Set the resolution of the saved image
		if (!(m_DesiredHeight == -1 && m_DesiredWidth == -1))
		{
			PinType myPIN = S;
			ImageRes myRes;
			myRes.nHeight = m_DesiredHeight;
			myRes.nWidth = m_DesiredWidth;
			if (!m_pDSCam->Set_Resolution(&myRes, myPIN))
			{
				//  Something went wrong setting the desired Image resolution
				LOG(ERROR) + L"Set Image Resolution failed";
			}
		}
	}
}
<commit_msg>FindClose added after enumeration complete<commit_after>#include "DirectShowCam.h"

CDirectShowCam::CDirectShowCam(LPCTSTR szDeviceName):CCamera(szDeviceName)
{
	m_CamType = L"color";
	m_pDSCam = NULL;
}
CDirectShowCam::~CDirectShowCam()
{
	if (m_pDSCam)
	{
		delete m_pDSCam;
		m_pDSCam = NULL;
	}

}
BOOL CDirectShowCam::enumerate(rho::Vector<rho::String>& arIDs, rho::Hashtable<rho::String, eCamType>& camLookUp)
{
	BOOL bRetStatus= FALSE;
	DEVMGR_DEVICE_INFORMATION di;
	// The driver material doesn't ship as part of the SDK. This GUID is hardcoded
	// here to be able to enumerate the camera drivers and pass the name of the driver to the video capture filter
	GUID guidCamera = {0xCB998A05, 0x122C, 0x4166, 0x84, 0x6A, 0x93, 0x3E, 0x4D, 0x7E, 0x3C, 0x86};

	di.dwSize = sizeof(di);
	HANDLE hFirstDevice = FindFirstDevice(DeviceSearchByGuid, &guidCamera, &di);
	if((hFirstDevice != INVALID_HANDLE_VALUE) ||(hFirstDevice != NULL) || (di.hDevice != NULL))
	{
		bRetStatus = TRUE;
		arIDs.addElement(rho::common::convertToStringA(di.szLegacyName));
		camLookUp.put(rho::common::convertToStringA(di.szLegacyName), eColorCam );
		//search for next device in a loop
		while(FindNextDevice(hFirstDevice, &di))
		{
			arIDs.addElement(rho::common::convertToStringA(di.szLegacyName));
			camLookUp.put(rho::common::convertToStringA(di.szLegacyName), eColorCam );
			FindClose(di.hDevice);

		}
		FindClose(hFirstDevice);
	}
	return bRetStatus;

}
void CDirectShowCam::takeFullScreen()
{
	LOG(INFO) + __FUNCTION__ ;
	if(false == m_IsCameraRunning)
	{
		if(m_PreviewOn == false)
		{
			CamConfig cfg;
			if (m_pDSCam)
			{
				delete m_pDSCam;
			}
			m_pDSCam = new CDShowCam();
			if(m_pDSCam)
			{
				if(m_pDSCam->initFilterGraph())
				{
					cfg.sCamID = m_szDeviceName;
					cfg.bIsAudioEnb = FALSE;	// no audio capture
					cfg.bIsCapEnb = TRUE;		// enable capture
					cfg.bIsPrvEnb = TRUE;		// enable preview
					cfg.bIsStillEnb = TRUE;		// enable still capture

					if(m_pDSCam->BuildFilterGraph(cfg))
					{
						RECT pos;
						HWND hWndViewer = m_ViewFinder.CreateViewerWindow(pos, eFullScreen);
						if(m_pDSCam->SetupPreview(hWndViewer, pos))
						{
							m_PreviewOn = true;
							m_IsCameraRunning = true;
							setCameraProperties();
						}

					}
				}
			}
			if(false == m_PreviewOn)
			{
				//if preview failed
				if (m_pDSCam)
				{
					delete m_pDSCam;
					m_pDSCam = NULL;
				}
			}

		}
	}
}
BOOL CDirectShowCam::showPreview()
{
	BOOL bPreviewStatus = FALSE;
    LOG(INFO) + __FUNCTION__ ;
	if(m_IsCameraRunning == false)
	{
		if(m_PreviewOn == false)
		{
			CamConfig cfg;
			if (m_pDSCam)
			{
				delete m_pDSCam;
			}
			m_pDSCam = new CDShowCam();
			if(m_pDSCam)
			{
				if(m_pDSCam->initFilterGraph())
				{
					cfg.sCamID = m_szDeviceName;
					cfg.bIsAudioEnb = FALSE;	// no audio capture
					cfg.bIsCapEnb = TRUE;		// enable capture
					cfg.bIsPrvEnb = TRUE;		// enable preview
					cfg.bIsStillEnb = TRUE;		// enable still capture

					if(m_pDSCam->BuildFilterGraph(cfg))
					{
						RECT pos;
						pos.left = m_PreviewLeft;
						pos.top = m_PreviewTop;
						pos.right = m_PreviewWidth;
						pos.bottom = m_PreviewHeight;
						HWND hWndViewer = m_ViewFinder.CreateViewerWindow(pos, eConfigurable);
						pos.left=0;
						pos.top=0;
						if(m_pDSCam->SetupPreview(hWndViewer, pos))
						{
							m_PreviewOn = true;
							m_IsCameraRunning = true;
							setCameraProperties();
						}

					}
				}

			}
			if(false == m_PreviewOn)
			{
				//if preview failed
				if (m_pDSCam)
				{
					delete m_pDSCam;
					m_pDSCam = NULL;
				}
			}
		}
	}
	return bPreviewStatus;

}
BOOL CDirectShowCam::hidePreview()
{
	LOG(INFO) + __FUNCTION__ 	;
	BOOL bRetStatus = FALSE;
	if (m_PreviewOn)
	{
		m_ViewFinder.DestroyViewerWindow();
		if (m_pDSCam)
		{
			if(FALSE== m_pDSCam->StopGrp())
			{
				LOG(ERROR) + __FUNCTION__ + L" Stop camera failed";
			}
			delete m_pDSCam;
			m_pDSCam = NULL;
			m_PreviewOn = false;
		    m_IsCameraRunning = false;
			bRetStatus = TRUE;

		}

	}
	return bRetStatus;
}
void CDirectShowCam::Capture()
{
	LOG(INFO) + __FUNCTION__ ;
	HRESULT hr;
	if(m_PreviewOn)
	{

		PlaySound(m_CaptureSound.c_str(),NULL,SND_FILENAME|SND_ASYNC);

		if(m_pDSCam)
		{
			rho::StringW fileName = m_FileName + L".jpg";
			hr= m_pDSCam->CaptureStill(fileName);
			if(SUCCEEDED(hr))
			{
				//  Rather than get bogged down the Direct Show again we'll just
				//  read the file back in from disk.
				HANDLE hFile = CreateFile(fileName.c_str(), GENERIC_READ, 0, NULL, OPEN_EXISTING,
					FILE_ATTRIBUTE_NORMAL, NULL);

				if(hFile)
				{
					DWORD dwFileSize = GetFileSize(hFile, NULL);
					if (dwFileSize > 0)
					{

						rho::String imageUri;
						if(m_eOutputFormat == eDataUri)
						{

							bool fileReadSuccess = true;
							DWORD dwImageBufSize;///< Variable for Buffer size of captured image
							LPVOID pImageBuffer;///< Buffer to save captured image
							pImageBuffer = new BYTE[dwFileSize];
							dwImageBufSize = dwFileSize;
							DWORD dwBytesRead = 0;
							do
							{
								if (!ReadFile(hFile, pImageBuffer, dwFileSize, &dwBytesRead, NULL))
								{
									//  Some error has occured reading the file
									LOG(ERROR) + L"Unable to send image data as URI, could not read data";
									UpdateCallbackStatus("error","Unable to send image data as URI, could not read data","");
									delete[] pImageBuffer;
									pImageBuffer = NULL;
									fileReadSuccess = false;
									break;
								}
							}
							while (dwBytesRead != 0);
							if(fileReadSuccess)
							{
								GetDataURI((BYTE*)pImageBuffer, dwImageBufSize, imageUri);
								delete[] pImageBuffer;
								pImageBuffer = NULL;
								//update callback
								UpdateCallbackStatus("ok","",imageUri);

							}

						}
						else
						{
							imageUri = rho::common::convertToStringA(fileName).c_str();
							//update callback
							UpdateCallbackStatus("ok","",imageUri);
						}

					}
					else
					{
						LOG(ERROR) + L"Unable to send image data as URI, size was unexpected";
						UpdateCallbackStatus("error","Unable to send image data as URI, size was unexpected","");
					}

				}
				else
				{
					LOG(ERROR) + L"Unable to send image data as URI, could not find captured image";
					UpdateCallbackStatus("error", "Unable to send image data as URI, could not find captured image","");

				}
				CloseHandle(hFile);

			}
			else
			{
				UpdateCallbackStatus("error","Image Capture operation failed.","");
			}
		}

	}
}
void CDirectShowCam::SetFlashMode()
{
	if(m_PreviewOn)
	{
		HRESULT hr;
		CamPropTbl propTbl;
		propTbl.p = CameraControl_Flash;
		hr = m_pDSCam->Get_PropRng(&propTbl);
		if (hr != E_PROP_ID_UNSUPPORTED)
		{
			propTbl.plVal = m_FlashMode ? propTbl.plMax : propTbl.plMin;
			m_pDSCam->Set_PropVal( &propTbl);
		}
	}
}

void CDirectShowCam::setCameraProperties()
{
	if(m_PreviewOn)
	{
		SetFlashMode();
		SetReolution();
	}

}
void CDirectShowCam::RedrawViewerWnd(RECT& pos)
{
	if(m_PreviewOn)
	{
		CCamera::RedrawViewerWnd(pos);
		if(m_pDSCam)
		{
			m_pDSCam->ResizePreview(pos.right, pos.bottom);
		}
	}
}
void CDirectShowCam::SetReolution()
{
	if(m_PreviewOn)
	{
		//  Set the resolution of the saved image
		if (!(m_DesiredHeight == -1 && m_DesiredWidth == -1))
		{
			PinType myPIN = S;
			ImageRes myRes;
			myRes.nHeight = m_DesiredHeight;
			myRes.nWidth = m_DesiredWidth;
			if (!m_pDSCam->Set_Resolution(&myRes, myPIN))
			{
				//  Something went wrong setting the desired Image resolution
				LOG(ERROR) + L"Set Image Resolution failed";
			}
		}
	}
}
<|endoftext|>


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

#include "modules/perception/obstacle/lidar/tracker/hm_tracker/hm_tracker.h"

#include <pcl/io/pcd_io.h>
#include <pcl/kdtree/kdtree.h>
#include <pcl/kdtree/kdtree_flann.h>
#include <fstream>
#include <iomanip>
#include <map>
#include <sstream>

#include "gtest/gtest.h"
#include "modules/common/log.h"
#include "modules/perception/common/perception_gflags.h"
#include "modules/perception/lib/config_manager/config_manager.h"
#include "modules/perception/lib/pcl_util/pcl_types.h"
#include "modules/perception/obstacle/common/file_system_util.h"
#include "modules/perception/obstacle/common/pose_util.h"
#include "modules/perception/obstacle/lidar/object_builder/min_box/min_box.h"

namespace apollo {
namespace perception {

class HmObjectTrackerTest : public testing::Test {
 protected:
  void SetUp() {
    RegisterFactoryHmObjectTracker();
    FLAGS_work_root = "modules/perception";
    FLAGS_config_manager_path = "conf/config_manager.config";
    if (!ConfigManager::instance()->Init()) {
      AERROR << "failed to init ConfigManager";
      return;
    }
    hm_tracker_ = new HmObjectTracker();
    object_builder_ = new MinBoxObjectBuilder();
    object_builder_->Init();
    object_builder_options_.ref_center =
        Eigen::Vector3d(0, 0, -1.7);  // velodyne height
    tracker_options_.velodyne_trans.reset(new Eigen::Matrix4d);
  }
  void TearDown() {
    delete hm_tracker_;
    hm_tracker_ = NULL;
    delete object_builder_;
    object_builder_ = NULL;
  }

 protected:
  HmObjectTracker* hm_tracker_;
  MinBoxObjectBuilder* object_builder_;
  ObjectBuilderOptions object_builder_options_;
  TrackerOptions tracker_options_;
};

bool ConstructObjects(const std::string& filename,
                      std::vector<ObjectPtr>* objects) {
  std::ifstream ifs(filename);
  if (!ifs.is_open()) {
    AERROR << "failed to open file" << filename;
    return false;
  }
  std::string type;
  int no_point = 0;
  float tmp = 0;
  while (ifs >> type) {
    ifs >> tmp >> tmp >> tmp >> no_point;
    ObjectPtr obj(new Object());
    obj->cloud->resize(no_point);
    for (int j = 0; j < no_point; ++j) {
      ifs >> obj->cloud->points[j].x >> obj->cloud->points[j].y >>
          obj->cloud->points[j].z >> obj->cloud->points[j].intensity;
    }
    (*objects).push_back(obj);
  }
  return true;
}

bool LoadPclPcds(const std::string filename,
                 pcl_util::PointCloudPtr* cloud_out) {
  pcl::PointCloud<pcl_util::PointXYZIT> org_cloud;
  if (pcl::io::loadPCDFile(filename, org_cloud) < 0) {
    AERROR << "failed to load pcd file: " << filename;
    return false;
  }
  (*cloud_out)->points.reserve(org_cloud.points.size());
  for (size_t i = 0; i < org_cloud.points.size(); ++i) {
    pcl_util::Point pt;
    pt.x = org_cloud.points[i].x;
    pt.y = org_cloud.points[i].y;
    pt.z = org_cloud.points[i].z;
    pt.intensity = org_cloud.points[i].intensity;
    if (isnan(org_cloud.points[i].x)) continue;
    (*cloud_out)->push_back(pt);
  }
  return true;
}

bool SaveTrackingResults(const std::vector<ObjectPtr>& objects,
                         const Eigen::Matrix4d& pose_v2w, const int frame_id,
                         pcl_util::PointCloudPtr* cloud,
                         const std::string& filename) {
  std::ofstream fout(filename.c_str(), std::ios::out);
  if (!fout) {
    AERROR << filename << " is not exist!";
    return false;
  }
  fout << frame_id << " " << objects.size() << std::endl;
  typename pcl::PointCloud<pcl_util::Point>::Ptr trans_cloud(
      new pcl::PointCloud<pcl_util::Point>());

  Eigen::Matrix4d pose_velo2w = pose_v2w;
  pcl::copyPointCloud(*(*cloud), *trans_cloud);
  transform_point_cloud<pcl_util::Point>(*trans_cloud, pose_v2w);
  pcl::KdTreeFLANN<pcl_util::Point> pcl_kdtree;
  pcl_kdtree.setInputCloud(trans_cloud);
  std::vector<int> k_indices;
  std::vector<float> k_sqrt_dist;
  Eigen::Matrix4d pose_w2v = pose_velo2w.inverse();

  for (size_t i = 0; i < objects.size(); ++i) {
    Eigen::Vector3f coord_dir(0, 1, 0);
    Eigen::Vector4d dir_velo =
        pose_w2v * Eigen::Vector4d(objects[i]->direction[0],
                                   objects[i]->direction[1],
                                   objects[i]->direction[2], 0);
    Eigen::Vector4d ct_velo =
        pose_w2v * Eigen::Vector4d(objects[i]->center[0], objects[i]->center[1],
                                   objects[i]->center[2], 0);
    Eigen::Vector3f dir_velo3(dir_velo[0], dir_velo[1], dir_velo[2]);
    double theta = VectorTheta2dXy(coord_dir, dir_velo3);
    std::string type = "unknown";
    fout << objects[i]->id << " " << objects[i]->track_id << " " << type << " "
         << std::setprecision(10) << ct_velo[0] << " " << ct_velo[1] << " "
         << ct_velo[2] << " " << objects[i]->length << " " << objects[i]->width
         << " " << objects[i]->height << " " << theta << " " << 0 << " " << 0
         << " " << objects[i]->velocity[0] << " " << objects[i]->velocity[1]
         << " " << objects[i]->velocity[2] << " " << objects[i]->cloud->size()
         << " ";
    for (size_t j = 0; j < objects[i]->cloud->size(); ++j) {
      const pcl_util::Point& pt = objects[i]->cloud->points[j];
      pcl_util::Point query_pt;
      query_pt.x = pt.x;
      query_pt.y = pt.y;
      query_pt.z = pt.z;
      k_indices.resize(1);
      k_sqrt_dist.resize(1);
      pcl_kdtree.nearestKSearch(query_pt, 1, k_indices, k_sqrt_dist);
      fout << k_indices[0] << " ";
    }
    fout << std::endl;
  }
  return true;
}

TEST_F(HmObjectTrackerTest, demo_tracking) {
  // test initialization of hm tracker
  EXPECT_TRUE(hm_tracker_->Init());
  // test tracking via hm tracker
  std::string data_path = "modules/perception/data/hm_tracker_test/";
  std::vector<std::string> pcd_filenames;
  GetFileNamesInFolderById(data_path, ".pcd", &pcd_filenames);
  std::vector<std::string> seg_filenames;
  GetFileNamesInFolderById(data_path, ".seg", &seg_filenames);
  std::vector<std::string> pose_filenames;
  GetFileNamesInFolderById(data_path, ".pose", &pose_filenames);
  int frame_id = -1;
  double time_stamp = 0.0;
  EXPECT_GT(pcd_filenames.size(), 0);
  EXPECT_EQ(pcd_filenames.size(), seg_filenames.size());
  EXPECT_EQ(pcd_filenames.size(), pose_filenames.size());
  Eigen::Vector3d global_offset(0, 0, 0);
  for (size_t i = 0; i < seg_filenames.size(); ++i) {
    // load frame clouds
    pcl_util::PointCloudPtr cloud(new pcl_util::PointCloud);
    EXPECT_TRUE(LoadPclPcds(data_path + pcd_filenames[i], &cloud));
    // read pose
    Eigen::Matrix4d pose = Eigen::Matrix4d::Identity();
    if (!ReadPoseFile(data_path + pose_filenames[i], &pose, &frame_id,
                      &time_stamp)) {
      AERROR << "failed to read pose";
      return;
    }
    if (i == 0) {
      global_offset(0) = pose(0, 3);
      global_offset(1) = pose(1, 3);
      global_offset(2) = pose(2, 3);
    }
    pose(0, 3) -= global_offset(0);
    pose(1, 3) -= global_offset(1);
    pose(2, 3) -= global_offset(2);
    // read segments
    std::vector<ObjectPtr> objects;
    if (!ConstructObjects(data_path + seg_filenames[i], &objects)) {
      AERROR << "failed to read segments";
      return;
    }
    // build objects
    object_builder_->Build(object_builder_options_, &objects);
    // test tracking
    *(tracker_options_.velodyne_trans) = pose;
    std::vector<ObjectPtr> result_objects;
    // assert tracking succesfully
    EXPECT_TRUE(hm_tracker_->Track(objects, time_stamp, tracker_options_,
                                   &result_objects));
    // assert reports completly
    EXPECT_TRUE(result_objects.size() >= objects.size());
    std::map<int, int> id_pool;
    for (size_t j = 0; j < result_objects.size(); ++j) {
      int track_id = result_objects[j]->track_id;
      // assert no duplicated track id in the same frame
      EXPECT_TRUE(id_pool.find(track_id) == id_pool.end());
      id_pool[track_id] = 1;
    }
  }
}

}  // namespace perception
}  // namespace apollo
<commit_msg>perception: fix compile problem.<commit_after>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

#include "modules/perception/obstacle/lidar/tracker/hm_tracker/hm_tracker.h"

#include <pcl/io/pcd_io.h>
#include <pcl/kdtree/kdtree.h>
#include <pcl/kdtree/kdtree_flann.h>
#include <fstream>
#include <iomanip>
#include <map>
#include <sstream>

#include "gtest/gtest.h"
#include "modules/common/log.h"
#include "modules/perception/common/perception_gflags.h"
#include "modules/perception/lib/config_manager/config_manager.h"
#include "modules/perception/lib/pcl_util/pcl_types.h"
#include "modules/perception/obstacle/common/file_system_util.h"
#include "modules/perception/obstacle/common/pose_util.h"
#include "modules/perception/obstacle/lidar/object_builder/min_box/min_box.h"

namespace apollo {
namespace perception {

class HmObjectTrackerTest : public testing::Test {
 protected:
  void SetUp() {
    RegisterFactoryHmObjectTracker();
    FLAGS_work_root = "modules/perception";
    FLAGS_config_manager_path = "conf/config_manager.config";
    if (!ConfigManager::instance()->Init()) {
      AERROR << "failed to init ConfigManager";
      return;
    }
    hm_tracker_ = new HmObjectTracker();
    object_builder_ = new MinBoxObjectBuilder();
    object_builder_->Init();
    object_builder_options_.ref_center =
        Eigen::Vector3d(0, 0, -1.7);  // velodyne height
    tracker_options_.velodyne_trans.reset(new Eigen::Matrix4d);
  }
  void TearDown() {
    delete hm_tracker_;
    hm_tracker_ = NULL;
    delete object_builder_;
    object_builder_ = NULL;
  }

 protected:
  HmObjectTracker* hm_tracker_;
  MinBoxObjectBuilder* object_builder_;
  ObjectBuilderOptions object_builder_options_;
  TrackerOptions tracker_options_;
};

bool ConstructObjects(const std::string& filename,
                      std::vector<ObjectPtr>* objects) {
  std::ifstream ifs(filename);
  if (!ifs.is_open()) {
    AERROR << "failed to open file" << filename;
    return false;
  }
  std::string type;
  int no_point = 0;
  float tmp = 0;
  while (ifs >> type) {
    ifs >> tmp >> tmp >> tmp >> no_point;
    ObjectPtr obj(new Object());
    obj->cloud->resize(no_point);
    for (int j = 0; j < no_point; ++j) {
      ifs >> obj->cloud->points[j].x >> obj->cloud->points[j].y >>
          obj->cloud->points[j].z >> obj->cloud->points[j].intensity;
    }
    (*objects).push_back(obj);
  }
  return true;
}

bool LoadPclPcds(const std::string filename,
                 pcl_util::PointCloudPtr* cloud_out) {
  pcl::PointCloud<pcl_util::PointXYZIT> org_cloud;
  if (pcl::io::loadPCDFile(filename, org_cloud) < 0) {
    AERROR << "failed to load pcd file: " << filename;
    return false;
  }
  (*cloud_out)->points.reserve(org_cloud.points.size());
  for (size_t i = 0; i < org_cloud.points.size(); ++i) {
    pcl_util::Point pt;
    pt.x = org_cloud.points[i].x;
    pt.y = org_cloud.points[i].y;
    pt.z = org_cloud.points[i].z;
    pt.intensity = org_cloud.points[i].intensity;
    if (isnan(org_cloud.points[i].x)) continue;
    (*cloud_out)->push_back(pt);
  }
  return true;
}

bool SaveTrackingResults(const std::vector<ObjectPtr>& objects,
                         const Eigen::Matrix4d& pose_v2w, const int frame_id,
                         pcl_util::PointCloudPtr* cloud,
                         const std::string& filename) {
  std::ofstream fout(filename.c_str(), std::ios::out);
  if (!fout) {
    AERROR << filename << " is not exist!";
    return false;
  }
  fout << frame_id << " " << objects.size() << std::endl;
  typename pcl::PointCloud<pcl_util::Point>::Ptr trans_cloud(
      new pcl::PointCloud<pcl_util::Point>());

  Eigen::Matrix4d pose_velo2w = pose_v2w;
  pcl::copyPointCloud(*(*cloud), *trans_cloud);
  TransformPointCloud<pcl_util::Point>(pose_v2w, trans_cloud);
  pcl::KdTreeFLANN<pcl_util::Point> pcl_kdtree;
  pcl_kdtree.setInputCloud(trans_cloud);
  std::vector<int> k_indices;
  std::vector<float> k_sqrt_dist;
  Eigen::Matrix4d pose_w2v = pose_velo2w.inverse();

  for (size_t i = 0; i < objects.size(); ++i) {
    Eigen::Vector3f coord_dir(0, 1, 0);
    Eigen::Vector4d dir_velo =
        pose_w2v * Eigen::Vector4d(objects[i]->direction[0],
                                   objects[i]->direction[1],
                                   objects[i]->direction[2], 0);
    Eigen::Vector4d ct_velo =
        pose_w2v * Eigen::Vector4d(objects[i]->center[0], objects[i]->center[1],
                                   objects[i]->center[2], 0);
    Eigen::Vector3f dir_velo3(dir_velo[0], dir_velo[1], dir_velo[2]);
    double theta = VectorTheta2dXy(coord_dir, dir_velo3);
    std::string type = "unknown";
    fout << objects[i]->id << " " << objects[i]->track_id << " " << type << " "
         << std::setprecision(10) << ct_velo[0] << " " << ct_velo[1] << " "
         << ct_velo[2] << " " << objects[i]->length << " " << objects[i]->width
         << " " << objects[i]->height << " " << theta << " " << 0 << " " << 0
         << " " << objects[i]->velocity[0] << " " << objects[i]->velocity[1]
         << " " << objects[i]->velocity[2] << " " << objects[i]->cloud->size()
         << " ";
    for (size_t j = 0; j < objects[i]->cloud->size(); ++j) {
      const pcl_util::Point& pt = objects[i]->cloud->points[j];
      pcl_util::Point query_pt;
      query_pt.x = pt.x;
      query_pt.y = pt.y;
      query_pt.z = pt.z;
      k_indices.resize(1);
      k_sqrt_dist.resize(1);
      pcl_kdtree.nearestKSearch(query_pt, 1, k_indices, k_sqrt_dist);
      fout << k_indices[0] << " ";
    }
    fout << std::endl;
  }
  return true;
}

TEST_F(HmObjectTrackerTest, demo_tracking) {
  // test initialization of hm tracker
  EXPECT_TRUE(hm_tracker_->Init());
  // test tracking via hm tracker
  std::string data_path = "modules/perception/data/hm_tracker_test/";
  std::vector<std::string> pcd_filenames;
  GetFileNamesInFolderById(data_path, ".pcd", &pcd_filenames);
  std::vector<std::string> seg_filenames;
  GetFileNamesInFolderById(data_path, ".seg", &seg_filenames);
  std::vector<std::string> pose_filenames;
  GetFileNamesInFolderById(data_path, ".pose", &pose_filenames);
  int frame_id = -1;
  double time_stamp = 0.0;
  EXPECT_GT(pcd_filenames.size(), 0);
  EXPECT_EQ(pcd_filenames.size(), seg_filenames.size());
  EXPECT_EQ(pcd_filenames.size(), pose_filenames.size());
  Eigen::Vector3d global_offset(0, 0, 0);
  for (size_t i = 0; i < seg_filenames.size(); ++i) {
    // load frame clouds
    pcl_util::PointCloudPtr cloud(new pcl_util::PointCloud);
    EXPECT_TRUE(LoadPclPcds(data_path + pcd_filenames[i], &cloud));
    // read pose
    Eigen::Matrix4d pose = Eigen::Matrix4d::Identity();
    if (!ReadPoseFile(data_path + pose_filenames[i], &pose, &frame_id,
                      &time_stamp)) {
      AERROR << "failed to read pose";
      return;
    }
    if (i == 0) {
      global_offset(0) = pose(0, 3);
      global_offset(1) = pose(1, 3);
      global_offset(2) = pose(2, 3);
    }
    pose(0, 3) -= global_offset(0);
    pose(1, 3) -= global_offset(1);
    pose(2, 3) -= global_offset(2);
    // read segments
    std::vector<ObjectPtr> objects;
    if (!ConstructObjects(data_path + seg_filenames[i], &objects)) {
      AERROR << "failed to read segments";
      return;
    }
    // build objects
    object_builder_->Build(object_builder_options_, &objects);
    // test tracking
    *(tracker_options_.velodyne_trans) = pose;
    std::vector<ObjectPtr> result_objects;
    // assert tracking succesfully
    EXPECT_TRUE(hm_tracker_->Track(objects, time_stamp, tracker_options_,
                                   &result_objects));
    // assert reports completly
    EXPECT_TRUE(result_objects.size() >= objects.size());
    std::map<int, int> id_pool;
    for (size_t j = 0; j < result_objects.size(); ++j) {
      int track_id = result_objects[j]->track_id;
      // assert no duplicated track id in the same frame
      EXPECT_TRUE(id_pool.find(track_id) == id_pool.end());
      id_pool[track_id] = 1;
    }
  }
}

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


<commit_before>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html

#include "GrainForceAndTorqueInterface.h"
#include "GrainForcesPostprocessor.h"

registerMooseObject("PhaseFieldApp", GrainForcesPostprocessor);

template <>
InputParameters
validParams<GrainForcesPostprocessor>()
{
  InputParameters params = validParams<VectorPostprocessor>();
  params.addClassDescription("Outputs the values from GrainForcesPostprocessor");
  params.addParam<UserObjectName>(
      "grain_force", "Specify userobject that gives center of mass and volume of grains");
  return params;
}

GrainForcesPostprocessor::GrainForcesPostprocessor(const InputParameters & parameters)
  : GeneralVectorPostprocessor(parameters),
    _grain_force_torque_vector(declareVector("grain_force_torque_vector")),
    _grain_force_torque(getUserObject<GrainForceAndTorqueInterface>("grain_force")),
    _grain_forces(_grain_force_torque.getForceValues()),
    _grain_torques(_grain_force_torque.getTorqueValues()),
    _grain_num(0)
{
}

void
GrainForcesPostprocessor::initialize()
{
  _grain_num = _grain_forces.size();

  // for each grain a force and a torque vector with 3 components each are serialized into the
  // output vector
  _grain_force_torque_vector.resize(_grain_num * 2 * 3);
}

void
GrainForcesPostprocessor::execute()
{
  for (unsigned int i = 0; i < _grain_num; ++i)
  {
    _grain_force_torque_vector[6 * i + 0] = _grain_forces[i](0);
    _grain_force_torque_vector[6 * i + 1] = _grain_forces[i](1);
    _grain_force_torque_vector[6 * i + 2] = _grain_forces[i](2);
    _grain_force_torque_vector[6 * i + 3] = _grain_torques[i](0);
    _grain_force_torque_vector[6 * i + 4] = _grain_torques[i](1);
    _grain_force_torque_vector[6 * i + 5] = _grain_torques[i](2);
  }
}
<commit_msg>Fixing validParams in GrainForcesPostprocessor<commit_after>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html

#include "GrainForceAndTorqueInterface.h"
#include "GrainForcesPostprocessor.h"

registerMooseObject("PhaseFieldApp", GrainForcesPostprocessor);

template <>
InputParameters
validParams<GrainForcesPostprocessor>()
{
  InputParameters params = validParams<GeneralVectorPostprocessor>();
  params.addClassDescription("Outputs the values from GrainForcesPostprocessor");
  params.addParam<UserObjectName>(
      "grain_force", "Specify userobject that gives center of mass and volume of grains");
  return params;
}

GrainForcesPostprocessor::GrainForcesPostprocessor(const InputParameters & parameters)
  : GeneralVectorPostprocessor(parameters),
    _grain_force_torque_vector(declareVector("grain_force_torque_vector")),
    _grain_force_torque(getUserObject<GrainForceAndTorqueInterface>("grain_force")),
    _grain_forces(_grain_force_torque.getForceValues()),
    _grain_torques(_grain_force_torque.getTorqueValues()),
    _grain_num(0)
{
}

void
GrainForcesPostprocessor::initialize()
{
  _grain_num = _grain_forces.size();

  // for each grain a force and a torque vector with 3 components each are serialized into the
  // output vector
  _grain_force_torque_vector.resize(_grain_num * 2 * 3);
}

void
GrainForcesPostprocessor::execute()
{
  for (unsigned int i = 0; i < _grain_num; ++i)
  {
    _grain_force_torque_vector[6 * i + 0] = _grain_forces[i](0);
    _grain_force_torque_vector[6 * i + 1] = _grain_forces[i](1);
    _grain_force_torque_vector[6 * i + 2] = _grain_forces[i](2);
    _grain_force_torque_vector[6 * i + 3] = _grain_torques[i](0);
    _grain_force_torque_vector[6 * i + 4] = _grain_torques[i](1);
    _grain_force_torque_vector[6 * i + 5] = _grain_torques[i](2);
  }
}
<|endoftext|>