<commit_before>/****************** <VPR heading BEGIN do not edit this line> *****************
 *
 * VR Juggler Portable Runtime
 *
 * Original Authors:
 *   Allen Bierbaum, Patrick Hartling, Kevin Meinert, Carolina Cruz-Neira
 *
 * -----------------------------------------------------------------
 * File:          $RCSfile$
 * Date modified: $Date$
 * Version:       $Revision$
 * -----------------------------------------------------------------
 *
 ****************** <VPR heading END do not edit this line> ******************/

/*************** <auto-copyright.pl BEGIN do not edit this line> **************
 *
 * VR Juggler is (C) Copyright 1998, 1999, 2000, 2001 by Iowa State University
 *
 * Original Authors:
 *   Allen Bierbaum, Christopher Just,
 *   Patrick Hartling, Kevin Meinert,
 *   Carolina Cruz-Neira, Albert Baker
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 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
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library 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.
 *
 *************** <auto-copyright.pl END do not edit this line> ***************/

#include <vpr/vprConfig.h>

#include <stdlib.h>
#include <string.h>

#include <vpr/Util/Assert.h>
#include <vpr/Util/Debug.h>
#include <vpr/md/SIM/Controller.h>
#include <vpr/md/SIM/SocketManager.h>
#include <vpr/md/SIM/IO/Socket/SocketImplSIM.h>

namespace vpr
{

SocketImplSIM::~SocketImplSIM ()
{
   if ( mNodeAssigned )
   {
      // Release the node to which we were bound.
      vpr::sim::Controller::instance()->getSocketManager().unbind(this);
      mNodeAssigned = false;
   }

   // cant do this because accept retuns an imp, which gets deleted
   // after constructing the returned Socket_t
/*
   if (this->isOpen())
   {
      std::cout<<"~SocketImplSIM(), closing...\n"<<std::flush;
      this->close();
   }
*/
}

vpr::ReturnStatus SocketImplSIM::close ()
{
   vpr::ReturnStatus status;

   if ( mPeer != NULL )
   {
      // We tell our peer that we are disconnecting.  This is a little
      // different than how real sockets work, but since we communicate
      // directly with our peer, this is a reasonable thing to do.
      mPeer->disconnect();
      mPeer = NULL;
   }

   status = vpr::sim::Controller::instance()->getSocketManager().unbind(this);

   if ( status.success() )
   {
      mNodeAssigned = false;
   }

   mOpen  = false;
   mBound = false;

   return status;
}

vpr::ReturnStatus SocketImplSIM::bind ()
{
   vpr::ReturnStatus status;

   if ( vpr::InetAddr::AnyAddr == mLocalAddr )
   {
      status =
         vpr::sim::Controller::instance()->getSocketManager().bindUnusedPort(this,
                                                                             mLocalAddr);
      vprASSERT(status.success() && "Failed to assign port number to socket");
   }

   vprDEBUG(vprDBG_ALL, vprDBG_STATE_LVL)
      << "SocketImplSIM::bind(): Assigning socket to a node in the graph\n"
      << vprDEBUG_FLUSH;
   status =
      vpr::sim::Controller::instance()->getSocketManager().assignToNode(this,
                                                                        mLocalAddr);
   vprASSERT(status.success() && "Failed to assign socket to a node");

   status = vpr::sim::Controller::instance()->getSocketManager().bind(this, mLocalAddr);
   mBound = status.success();

   return status;
}

vpr::ReturnStatus SocketImplSIM::connect (vpr::Interval timeout)
{
   vpr::ReturnStatus status;
   vprASSERT(mOpen && "An unopened socket cannot connect");

   if ( ! mNodeAssigned )
   {
      if ( vpr::InetAddr::AnyAddr == mLocalAddr )
      {
         status =
            vpr::sim::Controller::instance()->getSocketManager().bindUnusedPort(this,
                                                                                mLocalAddr);
         vprASSERT(status.success() && "Failed to assign port number to socket");
      }

      vprDEBUG(vprDBG_ALL, vprDBG_STATE_LVL)
         << "SocketImplSIM::connect(): Assigning socket to a node in the "
         << "graph\n" << vprDEBUG_FLUSH;
      status =
         vpr::sim::Controller::instance()->getSocketManager().assignToNode(this,
                                                                           mLocalAddr);
   }

   vprASSERT(mNodeAssigned && "A node-less socket cannot connect");
   status =
      vpr::sim::Controller::instance()->getSocketManager().connect(this, &mPeer,
                                                                   mRemoteAddr,
                                                                   mPathToPeer,
                                                                   timeout);
   mBound = mConnected = status.success();

   // Now that we are connected (or queued to get connected), we do not have
   // to manipulate our local address as is done in the real VPR sockets.
   // In a real OS, the local address would be set automatically, so that's
   // what the Sim Socket Manager does.

   return status;
}

vpr::Uint32 SocketImplSIM::availableBytes ()
{
   vpr::Guard<vpr::Mutex> guard(mArrivedQueueMutex);
   vpr::Uint32 bytes = 0;

   for ( std::vector<vpr::sim::MessagePtr>::iterator i = mArrivedQueue.begin();
         i != mArrivedQueue.end();
         i++ )
   {
      bytes += (*i)->getSize();
   }

   return bytes;
}

vpr::ReturnStatus SocketImplSIM::read_i (void* buffer,
                                         const vpr::Uint32 length,
                                         vpr::Uint32& data_read,
                                         vpr::Interval timeout )
{
   vpr:: ReturnStatus status;
   vprASSERT(mOpen && "Cannot read on an unopened socket");

   // This is a rather long critical sectino, but we need to be sure that the
   // arrvied queue stays in a consistent state while we are working.
   mArrivedQueueMutex.acquire();
   {
      if ( mArrivedQueue.size() > 0 )
      {
         vpr::sim::MessagePtr message;
         size_t copy_len, msg_size;

         // Remove the message from the arrival queue.
         message = mArrivedQueue[0];

         msg_size = message->getSize();

         // Use the smaller of length and msg_size for the actual amount of
         // data to copy.
         copy_len = (length > msg_size) ? msg_size : length;

         // Complete the read operation.
         memcpy(buffer, message->getBody(), copy_len);
         data_read = copy_len;

         if ( message->resize(copy_len) == 0 )
         {
            mArrivedQueue.erase(mArrivedQueue.begin());
         }
      }
      // Nothing is in the queue, so we tell the caller that the operation is
      // in progress.
      else
      {
         status.setCode(vpr::ReturnStatus::WouldBlock);
         data_read = 0;
      }
   }
   mArrivedQueueMutex.release();

   return status;
}

vpr::ReturnStatus SocketImplSIM::write_i (const void* buffer,
                                          const vpr::Uint32 length,
                                          vpr::Uint32& data_written,
                                          vpr::Interval timeout)
{
   vpr::ReturnStatus status;

   if ( mPeer == NULL )
   {
      status.setCode(vpr::ReturnStatus::Fail);
      data_written = 0;
   }
   else
   {
      data_written = length;

      vprDEBUG(vprDBG_ALL, vprDBG_HEX_LVL)
         << "Sending message from " << mLocalAddr << " to " << mRemoteAddr
         << ".  Message (size " << length << "): " << std::hex << buffer
         << std::dec << std::endl << vprDEBUG_FLUSH;

      vpr::sim::MessagePtr msg(new vpr::sim::Message(buffer, length));
      msg->setPath(mPathToPeer, this, mPeer);
      vpr::sim::Controller::instance()->getSocketManager().sendMessage(msg);
   }

   return status;
}

vpr::ReturnStatus SocketImplSIM::getOption (const vpr::SocketOptions::Types option,
                                            struct vpr::SocketOptions::Data& data)
{
   return vpr::ReturnStatus();
}

vpr::ReturnStatus SocketImplSIM::setOption (const vpr::SocketOptions::Types option,
                                            const struct vpr::SocketOptions::Data& data)
{
   return vpr::ReturnStatus();
}

vpr::ReturnStatus SocketImplSIM::inExceptState ()
{
   // XXX: For now, we never go into an exceptional state.
   return vpr::ReturnStatus(vpr::ReturnStatus::Fail);
}

// ============================================================================
// Protected methods.
// ============================================================================

SocketImplSIM::SocketImplSIM (const vpr::SocketTypes::Type sock_type)
   : mOpen(false), mBound(false), mConnected(false), mOpenBlocking(false),
     mBlocking(false), mType(sock_type), mReuseAddr(false), mPeer(NULL),
     mNodeAssigned(false)
{
   /* Do nothing. */ ;
//   vpr::ReturnStatus status;
//   status = vpr::sim::Controller::instance()->getSocketManager().assignToNode(this);
//
//   vprASSERT(status.success() && "Failed to assign new socket to a node");
}

SocketImplSIM::SocketImplSIM (const vpr::InetAddr& local_addr,
                              const vpr::InetAddr& remote_addr,
                              const vpr::SocketTypes::Type sock_type)
   : mOpen(false), mBound(false), mConnected(false), mOpenBlocking(false),
     mBlocking(false), mLocalAddr(local_addr), mRemoteAddr(remote_addr),
     mType(sock_type), mPeer(NULL), mNodeAssigned(false)
{
   /* Do nothing. */ ;
//   vpr::ReturnStatus status;
//   status = vpr::sim::Controller::instance()->getSocketManager().assignToNode(this, local_addr);
//
//   vprASSERT(status.success() && "Failed to assign new socket to a node");
}

void SocketImplSIM::disconnect ()
{
   // XXX: This is potentially not the best way to disconnect, but it's the
   // best I have come up with so far.
   mPeer = NULL;
}

} // End of vpr namespace
<commit_msg>In write_i(), when compiling debugging code, print out the full message in 4-byte blocks just before sending it.  This is still at vprDBG_HEX_LVL, but it ensures that the entire message gets printed.<commit_after>/****************** <VPR heading BEGIN do not edit this line> *****************
 *
 * VR Juggler Portable Runtime
 *
 * Original Authors:
 *   Allen Bierbaum, Patrick Hartling, Kevin Meinert, Carolina Cruz-Neira
 *
 * -----------------------------------------------------------------
 * File:          $RCSfile$
 * Date modified: $Date$
 * Version:       $Revision$
 * -----------------------------------------------------------------
 *
 ****************** <VPR heading END do not edit this line> ******************/

/*************** <auto-copyright.pl BEGIN do not edit this line> **************
 *
 * VR Juggler is (C) Copyright 1998, 1999, 2000, 2001 by Iowa State University
 *
 * Original Authors:
 *   Allen Bierbaum, Christopher Just,
 *   Patrick Hartling, Kevin Meinert,
 *   Carolina Cruz-Neira, Albert Baker
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 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
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library 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.
 *
 *************** <auto-copyright.pl END do not edit this line> ***************/

#include <vpr/vprConfig.h>

#include <stdlib.h>
#include <string.h>

#include <vpr/Util/Assert.h>
#include <vpr/Util/Debug.h>
#include <vpr/md/SIM/Controller.h>
#include <vpr/md/SIM/SocketManager.h>
#include <vpr/md/SIM/IO/Socket/SocketImplSIM.h>

namespace vpr
{

SocketImplSIM::~SocketImplSIM ()
{
   if ( mNodeAssigned )
   {
      // Release the node to which we were bound.
      vpr::sim::Controller::instance()->getSocketManager().unbind(this);
      mNodeAssigned = false;
   }

   // cant do this because accept retuns an imp, which gets deleted
   // after constructing the returned Socket_t
/*
   if (this->isOpen())
   {
      std::cout<<"~SocketImplSIM(), closing...\n"<<std::flush;
      this->close();
   }
*/
}

vpr::ReturnStatus SocketImplSIM::close ()
{
   vpr::ReturnStatus status;

   if ( mPeer != NULL )
   {
      // We tell our peer that we are disconnecting.  This is a little
      // different than how real sockets work, but since we communicate
      // directly with our peer, this is a reasonable thing to do.
      mPeer->disconnect();
      mPeer = NULL;
   }

   status = vpr::sim::Controller::instance()->getSocketManager().unbind(this);

   if ( status.success() )
   {
      mNodeAssigned = false;
   }

   mOpen  = false;
   mBound = false;

   return status;
}

vpr::ReturnStatus SocketImplSIM::bind ()
{
   vpr::ReturnStatus status;

   if ( vpr::InetAddr::AnyAddr == mLocalAddr )
   {
      status =
         vpr::sim::Controller::instance()->getSocketManager().bindUnusedPort(this,
                                                                             mLocalAddr);
      vprASSERT(status.success() && "Failed to assign port number to socket");
   }

   vprDEBUG(vprDBG_ALL, vprDBG_STATE_LVL)
      << "SocketImplSIM::bind(): Assigning socket to a node in the graph\n"
      << vprDEBUG_FLUSH;
   status =
      vpr::sim::Controller::instance()->getSocketManager().assignToNode(this,
                                                                        mLocalAddr);
   vprASSERT(status.success() && "Failed to assign socket to a node");

   status = vpr::sim::Controller::instance()->getSocketManager().bind(this, mLocalAddr);
   mBound = status.success();

   return status;
}

vpr::ReturnStatus SocketImplSIM::connect (vpr::Interval timeout)
{
   vpr::ReturnStatus status;
   vprASSERT(mOpen && "An unopened socket cannot connect");

   if ( ! mNodeAssigned )
   {
      if ( vpr::InetAddr::AnyAddr == mLocalAddr )
      {
         status =
            vpr::sim::Controller::instance()->getSocketManager().bindUnusedPort(this,
                                                                                mLocalAddr);
         vprASSERT(status.success() && "Failed to assign port number to socket");
      }

      vprDEBUG(vprDBG_ALL, vprDBG_STATE_LVL)
         << "SocketImplSIM::connect(): Assigning socket to a node in the "
         << "graph\n" << vprDEBUG_FLUSH;
      status =
         vpr::sim::Controller::instance()->getSocketManager().assignToNode(this,
                                                                           mLocalAddr);
   }

   vprASSERT(mNodeAssigned && "A node-less socket cannot connect");
   status =
      vpr::sim::Controller::instance()->getSocketManager().connect(this, &mPeer,
                                                                   mRemoteAddr,
                                                                   mPathToPeer,
                                                                   timeout);
   mBound = mConnected = status.success();

   // Now that we are connected (or queued to get connected), we do not have
   // to manipulate our local address as is done in the real VPR sockets.
   // In a real OS, the local address would be set automatically, so that's
   // what the Sim Socket Manager does.

   return status;
}

vpr::Uint32 SocketImplSIM::availableBytes ()
{
   vpr::Guard<vpr::Mutex> guard(mArrivedQueueMutex);
   vpr::Uint32 bytes = 0;

   for ( std::vector<vpr::sim::MessagePtr>::iterator i = mArrivedQueue.begin();
         i != mArrivedQueue.end();
         i++ )
   {
      bytes += (*i)->getSize();
   }

   return bytes;
}

vpr::ReturnStatus SocketImplSIM::read_i (void* buffer,
                                         const vpr::Uint32 length,
                                         vpr::Uint32& data_read,
                                         vpr::Interval timeout )
{
   vpr:: ReturnStatus status;
   vprASSERT(mOpen && "Cannot read on an unopened socket");

   // This is a rather long critical sectino, but we need to be sure that the
   // arrvied queue stays in a consistent state while we are working.
   mArrivedQueueMutex.acquire();
   {
      if ( mArrivedQueue.size() > 0 )
      {
         vpr::sim::MessagePtr message;
         size_t copy_len, msg_size;

         // Remove the message from the arrival queue.
         message = mArrivedQueue[0];

         msg_size = message->getSize();

         // Use the smaller of length and msg_size for the actual amount of
         // data to copy.
         copy_len = (length > msg_size) ? msg_size : length;

         // Complete the read operation.
         memcpy(buffer, message->getBody(), copy_len);
         data_read = copy_len;

         if ( message->resize(copy_len) == 0 )
         {
            mArrivedQueue.erase(mArrivedQueue.begin());
         }
      }
      // Nothing is in the queue, so we tell the caller that the operation is
      // in progress.
      else
      {
         status.setCode(vpr::ReturnStatus::WouldBlock);
         data_read = 0;
      }
   }
   mArrivedQueueMutex.release();

   return status;
}

vpr::ReturnStatus SocketImplSIM::write_i (const void* buffer,
                                          const vpr::Uint32 length,
                                          vpr::Uint32& data_written,
                                          vpr::Interval timeout)
{
   vpr::ReturnStatus status;

   if ( mPeer == NULL )
   {
      status.setCode(vpr::ReturnStatus::Fail);
      data_written = 0;
   }
   else
   {
      data_written = length;

#ifdef VPR_DEBUG
      vpr::Uint32 remainder;
      const char* msg_ptr = (const char*) buffer;
      remainder = length % 4;

      vprDEBUG(vprDBG_ALL, vprDBG_HEX_LVL)
         << "SocketImplSIM::write_i(): Message (" << length
         << " bytes in 4-byte hex blocks):" << vprDEBUG_FLUSH;

      for ( vpr::Uint32 i = 0; i < length; i += 4 )
      {
         if ( i % 16 == 0 )
         {
            vprDEBUG_NEXT(vprDBG_ALL, vprDBG_HEX_LVL)
               << "\n" << std::hex << std::setfill('0') << std::setw(8)
               << *((vpr::Uint32*) (&msg_ptr[i])) << " " << vprDEBUG_FLUSH;
         }
         else
         {
            vprDEBUG_CONT(vprDBG_ALL, vprDBG_HEX_LVL)
               << std::hex << std::setfill('0') << std::setw(8)
               << *((vpr::Uint32*) (&msg_ptr[i])) << " " << vprDEBUG_FLUSH;
         }
      }

      for ( vpr::Uint32 i = 0; i < remainder; i++ )
      {
         vprDEBUG_CONT(vprDBG_ALL, vprDBG_HEX_LVL) << "00" << vprDEBUG_FLUSH;
      }

      vprDEBUG_NEXT(vprDBG_ALL, vprDBG_HEX_LVL)
         << "\n---------------------------\n" << std::dec << vprDEBUG_FLUSH;
#endif

      vpr::sim::MessagePtr msg(new vpr::sim::Message(buffer, length));
      msg->setPath(mPathToPeer, this, mPeer);
      vpr::sim::Controller::instance()->getSocketManager().sendMessage(msg);
   }

   return status;
}

vpr::ReturnStatus SocketImplSIM::getOption (const vpr::SocketOptions::Types option,
                                            struct vpr::SocketOptions::Data& data)
{
   return vpr::ReturnStatus();
}

vpr::ReturnStatus SocketImplSIM::setOption (const vpr::SocketOptions::Types option,
                                            const struct vpr::SocketOptions::Data& data)
{
   return vpr::ReturnStatus();
}

vpr::ReturnStatus SocketImplSIM::inExceptState ()
{
   // XXX: For now, we never go into an exceptional state.
   return vpr::ReturnStatus(vpr::ReturnStatus::Fail);
}

// ============================================================================
// Protected methods.
// ============================================================================

SocketImplSIM::SocketImplSIM (const vpr::SocketTypes::Type sock_type)
   : mOpen(false), mBound(false), mConnected(false), mOpenBlocking(false),
     mBlocking(false), mType(sock_type), mReuseAddr(false), mPeer(NULL),
     mNodeAssigned(false)
{
   /* Do nothing. */ ;
//   vpr::ReturnStatus status;
//   status = vpr::sim::Controller::instance()->getSocketManager().assignToNode(this);
//
//   vprASSERT(status.success() && "Failed to assign new socket to a node");
}

SocketImplSIM::SocketImplSIM (const vpr::InetAddr& local_addr,
                              const vpr::InetAddr& remote_addr,
                              const vpr::SocketTypes::Type sock_type)
   : mOpen(false), mBound(false), mConnected(false), mOpenBlocking(false),
     mBlocking(false), mLocalAddr(local_addr), mRemoteAddr(remote_addr),
     mType(sock_type), mPeer(NULL), mNodeAssigned(false)
{
   /* Do nothing. */ ;
//   vpr::ReturnStatus status;
//   status = vpr::sim::Controller::instance()->getSocketManager().assignToNode(this, local_addr);
//
//   vprASSERT(status.success() && "Failed to assign new socket to a node");
}

void SocketImplSIM::disconnect ()
{
   // XXX: This is potentially not the best way to disconnect, but it's the
   // best I have come up with so far.
   mPeer = NULL;
}

} // End of vpr namespace
<|endoftext|>


<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author:  Vassil Vassilev <vvasilev@cern.ch>
// author:  Baozeng Ding <sploving1@gmail.com>
//------------------------------------------------------------------------------

#include "NullDerefProtectionTransformer.h"

#include "cling/Interpreter/Transaction.h"

#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/AST/Mangle.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/Sema/Sema.h"
#include "clang/Sema/SemaDiagnostic.h"

#include "llvm/IR/Module.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/InstIterator.h"

extern "C" {
  int printf(const char *...);
  int getchar(void);
  bool shouldProceed(void *S, void *T) {
    int input;
    clang::Sema *Sem = (clang::Sema *)S;
    clang::DiagnosticsEngine& Diag = Sem->getDiagnostics();
    cling::Transaction* Trans = (cling::Transaction*)T;
    clang::SourceLocation Loc = Trans->getWrapperFD()->getLocation();
    Diag.Report(Loc, clang::diag::warn_null_ptr_deref);
    input = getchar();
    getchar();
    if (input == 'y' || input == 'Y') return false;
    else return true;
  }
}

using namespace clang;

namespace cling {

  NullDerefProtectionTransformer::NullDerefProtectionTransformer(Sema *S)
    : TransactionTransformer(S), FailBB(0), Builder(0), Inst(0) {}

  NullDerefProtectionTransformer::~NullDerefProtectionTransformer()
  {}

  void NullDerefProtectionTransformer::Transform() {
    using namespace clang;
    FunctionDecl* FD = getTransaction()->getWrapperFD();
    if (!FD)
      return;

    // Copied from Interpreter.cpp;
    if (!m_MangleCtx)
      m_MangleCtx.reset(FD->getASTContext().createMangleContext());

    std::string mangledName;
    if (m_MangleCtx->shouldMangleDeclName(FD)) {
      llvm::raw_string_ostream RawStr(mangledName);
      switch(FD->getKind()) {
      case Decl::CXXConstructor:
        //Ctor_Complete,          // Complete object ctor
        //Ctor_Base,              // Base object ctor
        //Ctor_CompleteAllocating // Complete object allocating ctor (unused)
        m_MangleCtx->mangleCXXCtor(cast<CXXConstructorDecl>(FD),
                                   Ctor_Complete, RawStr);
        break;

      case Decl::CXXDestructor:
        //Dtor_Deleting, // Deleting dtor
        //Dtor_Complete, // Complete object dtor
        //Dtor_Base      // Base object dtor
        m_MangleCtx->mangleCXXDtor(cast<CXXDestructorDecl>(FD),
                                   Dtor_Deleting, RawStr);
        break;

      default :
        m_MangleCtx->mangleName(FD, RawStr);
        break;
      }
      RawStr.flush();
    } else {
      mangledName = FD->getNameAsString();
    }

    // Find the function in the module.
    llvm::Function* F = getTransaction()->getModule()->getFunction(mangledName);
    if (F)
      runOnFunction(*F);
  }

  llvm::BasicBlock* NullDerefProtectionTransformer::getTrapBB() {
    llvm::Function* Fn = Inst->getParent()->getParent();
    llvm::Module* Md = Fn->getParent();
    llvm::LLVMContext& ctx = Fn->getContext();

    llvm::BasicBlock::iterator PreInsertInst = Builder->GetInsertPoint();
    FailBB = llvm::BasicBlock::Create(ctx, "FailBlock", Fn);
    Builder->SetInsertPoint(FailBB);

    std::vector<llvm::Type*> ArgTys;
    llvm::Type* VoidTy = llvm::Type::getInt8PtrTy(ctx);
    ArgTys.push_back(VoidTy);
    ArgTys.push_back(VoidTy);
    llvm::FunctionType* FTy
      = llvm::FunctionType::get(llvm::Type::getInt1Ty(ctx), ArgTys, false);

    llvm::Function* CallBackFn
      = cast<llvm::Function>(Md->getOrInsertFunction("shouldProceed", FTy));

    void* SemaRef = (void*)m_Sema;
    // copied from JIT.cpp
    llvm::Constant* SemaRefCnt = 0;
    llvm::Type* constantIntTy = 0;
    if (sizeof(void*) == 4)
      constantIntTy = llvm::Type::getInt32Ty(ctx);
    else
      constantIntTy = llvm::Type::getInt64Ty(ctx);

    SemaRefCnt = llvm::ConstantInt::get(constantIntTy, (uintptr_t)SemaRef);
    llvm::Value* Arg1 = llvm::ConstantExpr::getIntToPtr(SemaRefCnt, VoidTy);

    Transaction* Trans = getTransaction();
    void* TransRef = (void*) Trans;
    llvm::Constant* TransRefCnt = llvm::ConstantInt::get(constantIntTy,
                                                       (uintptr_t)TransRef);
    llvm::Value* Arg2 = llvm::ConstantExpr::getIntToPtr(TransRefCnt, VoidTy);

    llvm::CallInst* CI = Builder->CreateCall2(CallBackFn, Arg1, Arg2);

    llvm::Value* TrueVl = llvm::ConstantInt::get(ctx, llvm::APInt(1, 1));
    llvm::Value* RetVl = CI;
    llvm::ICmpInst*Cmp
      = new llvm::ICmpInst(*FailBB, llvm::CmpInst::ICMP_EQ, RetVl, TrueVl, "");

    llvm::BasicBlock *HandleBB = llvm::BasicBlock::Create(ctx,"HandleBlock", Fn);
    llvm::BranchInst::Create(HandleBB, Inst->getParent(), Cmp, FailBB);

    llvm::ReturnInst::Create(Fn->getContext(), HandleBB);
    Builder->SetInsertPoint(PreInsertInst);
    return FailBB;
  }

  void NullDerefProtectionTransformer::instrumentLoadInst(llvm::LoadInst *LI) {
    llvm::Value* Addr = LI->getOperand(0);
    if(llvm::isa<llvm::GlobalVariable>(Addr))
      return;

    llvm::PointerType* PTy = llvm::cast<llvm::PointerType>(Addr->getType());
    llvm::Type* ElTy = PTy->getElementType();
    if (!ElTy->isPointerTy()) {
      llvm::BasicBlock* OldBB = LI->getParent();
      llvm::ICmpInst* Cmp
        = new llvm::ICmpInst(LI, llvm::CmpInst::ICMP_EQ, Addr,
                             llvm::Constant::getNullValue(Addr->getType()), "");

      llvm::Instruction *Inst = Builder->GetInsertPoint();
      llvm::BasicBlock *NewBB = OldBB->splitBasicBlock(Inst);

      OldBB->getTerminator()->eraseFromParent();
      llvm::BranchInst::Create(getTrapBB(), NewBB, Cmp, OldBB);
    }
  }

  void NullDerefProtectionTransformer::instrumentStoreInst(llvm::StoreInst *SI){
    llvm::Value* Addr = SI->getOperand(1);
   if(llvm::isa<llvm::GlobalVariable>(Addr))
      return;

    llvm::PointerType* PTy = llvm::cast<llvm::PointerType>(Addr->getType());
    llvm::Type* ElTy = PTy -> getElementType();
    if (!ElTy->isPointerTy()) {
      llvm::BasicBlock* OldBB = SI->getParent();
      llvm::ICmpInst* Cmp
        = new llvm::ICmpInst(SI, llvm::CmpInst::ICMP_EQ, Addr,
                             llvm::Constant::getNullValue(Addr->getType()), "");

      llvm::Instruction* Inst = Builder->GetInsertPoint();
      llvm::BasicBlock* NewBB = OldBB->splitBasicBlock(Inst);

      OldBB->getTerminator()->eraseFromParent();
      llvm::BranchInst::Create(getTrapBB(), NewBB, Cmp, OldBB);
    }
  }

  bool NullDerefProtectionTransformer::runOnFunction(llvm::Function &F) {
    llvm::IRBuilder<> TheBuilder(F.getContext());
    Builder = &TheBuilder;

    std::vector<llvm::Instruction*> WorkList;
    for (llvm::inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i) {
      llvm::Instruction* I = &*i;
      if (llvm::isa<llvm::LoadInst>(I) || llvm::isa<llvm::StoreInst>(I))
        WorkList.push_back(I);
      }

    for (std::vector<llvm::Instruction*>::iterator i = WorkList.begin(),
           e = WorkList.end(); i != e; ++i) {
      Inst = *i;

      Builder->SetInsertPoint(Inst);
      if (llvm::LoadInst* LI = llvm::dyn_cast<llvm::LoadInst>(Inst)) {
        instrumentLoadInst(LI);
      } else if (llvm::StoreInst* SI = llvm::dyn_cast<llvm::StoreInst>(Inst)) {
        instrumentStoreInst(SI);
      } else {
        llvm_unreachable("unknown Instruction type");
      }
    }
    return true;
  }
} // end namespace cling
<commit_msg>Use isatty first, before getchar()<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author:  Vassil Vassilev <vvasilev@cern.ch>
// author:  Baozeng Ding <sploving1@gmail.com>
//------------------------------------------------------------------------------

#include "NullDerefProtectionTransformer.h"

#include "cling/Interpreter/Transaction.h"

#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/AST/Mangle.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/Sema/Sema.h"
#include "clang/Sema/SemaDiagnostic.h"

#include "llvm/IR/Module.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/InstIterator.h"

#include "stdio.h"

extern "C" {
  bool shouldProceed(void *S, void *T) {
    clang::Sema *Sem = (clang::Sema *)S;
    clang::DiagnosticsEngine& Diag = Sem->getDiagnostics();
    cling::Transaction* Trans = (cling::Transaction*)T;
    clang::SourceLocation Loc = Trans->getWrapperFD()->getLocation();
    Diag.Report(Loc, clang::diag::warn_null_ptr_deref);
    if (isatty(fileno(stdin))) {
      int input = getchar();
      getchar();
      if (input == 'y' || input == 'Y')
        return false;
    }
    return true;
  }
}

using namespace clang;

namespace cling {

  NullDerefProtectionTransformer::NullDerefProtectionTransformer(Sema *S)
    : TransactionTransformer(S), FailBB(0), Builder(0), Inst(0) {}

  NullDerefProtectionTransformer::~NullDerefProtectionTransformer()
  {}

  void NullDerefProtectionTransformer::Transform() {
    using namespace clang;
    FunctionDecl* FD = getTransaction()->getWrapperFD();
    if (!FD)
      return;

    // Copied from Interpreter.cpp;
    if (!m_MangleCtx)
      m_MangleCtx.reset(FD->getASTContext().createMangleContext());

    std::string mangledName;
    if (m_MangleCtx->shouldMangleDeclName(FD)) {
      llvm::raw_string_ostream RawStr(mangledName);
      switch(FD->getKind()) {
      case Decl::CXXConstructor:
        //Ctor_Complete,          // Complete object ctor
        //Ctor_Base,              // Base object ctor
        //Ctor_CompleteAllocating // Complete object allocating ctor (unused)
        m_MangleCtx->mangleCXXCtor(cast<CXXConstructorDecl>(FD),
                                   Ctor_Complete, RawStr);
        break;

      case Decl::CXXDestructor:
        //Dtor_Deleting, // Deleting dtor
        //Dtor_Complete, // Complete object dtor
        //Dtor_Base      // Base object dtor
        m_MangleCtx->mangleCXXDtor(cast<CXXDestructorDecl>(FD),
                                   Dtor_Deleting, RawStr);
        break;

      default :
        m_MangleCtx->mangleName(FD, RawStr);
        break;
      }
      RawStr.flush();
    } else {
      mangledName = FD->getNameAsString();
    }

    // Find the function in the module.
    llvm::Function* F = getTransaction()->getModule()->getFunction(mangledName);
    if (F)
      runOnFunction(*F);
  }

  llvm::BasicBlock* NullDerefProtectionTransformer::getTrapBB() {
    llvm::Function* Fn = Inst->getParent()->getParent();
    llvm::Module* Md = Fn->getParent();
    llvm::LLVMContext& ctx = Fn->getContext();

    llvm::BasicBlock::iterator PreInsertInst = Builder->GetInsertPoint();
    FailBB = llvm::BasicBlock::Create(ctx, "FailBlock", Fn);
    Builder->SetInsertPoint(FailBB);

    std::vector<llvm::Type*> ArgTys;
    llvm::Type* VoidTy = llvm::Type::getInt8PtrTy(ctx);
    ArgTys.push_back(VoidTy);
    ArgTys.push_back(VoidTy);
    llvm::FunctionType* FTy
      = llvm::FunctionType::get(llvm::Type::getInt1Ty(ctx), ArgTys, false);

    llvm::Function* CallBackFn
      = cast<llvm::Function>(Md->getOrInsertFunction("shouldProceed", FTy));

    void* SemaRef = (void*)m_Sema;
    // copied from JIT.cpp
    llvm::Constant* SemaRefCnt = 0;
    llvm::Type* constantIntTy = 0;
    if (sizeof(void*) == 4)
      constantIntTy = llvm::Type::getInt32Ty(ctx);
    else
      constantIntTy = llvm::Type::getInt64Ty(ctx);

    SemaRefCnt = llvm::ConstantInt::get(constantIntTy, (uintptr_t)SemaRef);
    llvm::Value* Arg1 = llvm::ConstantExpr::getIntToPtr(SemaRefCnt, VoidTy);

    Transaction* Trans = getTransaction();
    void* TransRef = (void*) Trans;
    llvm::Constant* TransRefCnt = llvm::ConstantInt::get(constantIntTy,
                                                       (uintptr_t)TransRef);
    llvm::Value* Arg2 = llvm::ConstantExpr::getIntToPtr(TransRefCnt, VoidTy);

    llvm::CallInst* CI = Builder->CreateCall2(CallBackFn, Arg1, Arg2);

    llvm::Value* TrueVl = llvm::ConstantInt::get(ctx, llvm::APInt(1, 1));
    llvm::Value* RetVl = CI;
    llvm::ICmpInst*Cmp
      = new llvm::ICmpInst(*FailBB, llvm::CmpInst::ICMP_EQ, RetVl, TrueVl, "");

    llvm::BasicBlock *HandleBB = llvm::BasicBlock::Create(ctx,"HandleBlock", Fn);
    llvm::BranchInst::Create(HandleBB, Inst->getParent(), Cmp, FailBB);

    llvm::ReturnInst::Create(Fn->getContext(), HandleBB);
    Builder->SetInsertPoint(PreInsertInst);
    return FailBB;
  }

  void NullDerefProtectionTransformer::instrumentLoadInst(llvm::LoadInst *LI) {
    llvm::Value* Addr = LI->getOperand(0);
    if(llvm::isa<llvm::GlobalVariable>(Addr))
      return;

    llvm::PointerType* PTy = llvm::cast<llvm::PointerType>(Addr->getType());
    llvm::Type* ElTy = PTy->getElementType();
    if (!ElTy->isPointerTy()) {
      llvm::BasicBlock* OldBB = LI->getParent();
      llvm::ICmpInst* Cmp
        = new llvm::ICmpInst(LI, llvm::CmpInst::ICMP_EQ, Addr,
                             llvm::Constant::getNullValue(Addr->getType()), "");

      llvm::Instruction *Inst = Builder->GetInsertPoint();
      llvm::BasicBlock *NewBB = OldBB->splitBasicBlock(Inst);

      OldBB->getTerminator()->eraseFromParent();
      llvm::BranchInst::Create(getTrapBB(), NewBB, Cmp, OldBB);
    }
  }

  void NullDerefProtectionTransformer::instrumentStoreInst(llvm::StoreInst *SI){
    llvm::Value* Addr = SI->getOperand(1);
   if(llvm::isa<llvm::GlobalVariable>(Addr))
      return;

    llvm::PointerType* PTy = llvm::cast<llvm::PointerType>(Addr->getType());
    llvm::Type* ElTy = PTy -> getElementType();
    if (!ElTy->isPointerTy()) {
      llvm::BasicBlock* OldBB = SI->getParent();
      llvm::ICmpInst* Cmp
        = new llvm::ICmpInst(SI, llvm::CmpInst::ICMP_EQ, Addr,
                             llvm::Constant::getNullValue(Addr->getType()), "");

      llvm::Instruction* Inst = Builder->GetInsertPoint();
      llvm::BasicBlock* NewBB = OldBB->splitBasicBlock(Inst);

      OldBB->getTerminator()->eraseFromParent();
      llvm::BranchInst::Create(getTrapBB(), NewBB, Cmp, OldBB);
    }
  }

  bool NullDerefProtectionTransformer::runOnFunction(llvm::Function &F) {
    llvm::IRBuilder<> TheBuilder(F.getContext());
    Builder = &TheBuilder;

    std::vector<llvm::Instruction*> WorkList;
    for (llvm::inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i) {
      llvm::Instruction* I = &*i;
      if (llvm::isa<llvm::LoadInst>(I) || llvm::isa<llvm::StoreInst>(I))
        WorkList.push_back(I);
      }

    for (std::vector<llvm::Instruction*>::iterator i = WorkList.begin(),
           e = WorkList.end(); i != e; ++i) {
      Inst = *i;

      Builder->SetInsertPoint(Inst);
      if (llvm::LoadInst* LI = llvm::dyn_cast<llvm::LoadInst>(Inst)) {
        instrumentLoadInst(LI);
      } else if (llvm::StoreInst* SI = llvm::dyn_cast<llvm::StoreInst>(Inst)) {
        instrumentStoreInst(SI);
      } else {
        llvm_unreachable("unknown Instruction type");
      }
    }
    return true;
  }
} // end namespace cling
<|endoftext|>


<commit_before>// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/browser/net/url_request_buffer_job.h"

#include <string>

#include "atom/common/atom_constants.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "net/base/mime_util.h"
#include "net/base/net_errors.h"

namespace atom {

namespace {

std::string GetExtFromURL(const GURL& url) {
  std::string spec = url.spec();
  size_t index = spec.find_last_of('.');
  if (index == std::string::npos || index == spec.size())
    return std::string();
  return spec.substr(index + 1, spec.size() - index - 1);
}

}  // namespace

URLRequestBufferJob::URLRequestBufferJob(
    net::URLRequest* request, net::NetworkDelegate* network_delegate)
    : JsAsker<net::URLRequestSimpleJob>(request, network_delegate),
      status_code_(net::HTTP_NOT_IMPLEMENTED) {
}

void URLRequestBufferJob::StartAsync(std::unique_ptr<base::Value> options) {
  const base::Value* binary = nullptr;
  if (options->IsType(base::Value::Type::DICTIONARY)) {
    base::DictionaryValue* dict =
        static_cast<base::DictionaryValue*>(options.get());
    dict->GetString("mimeType", &mime_type_);
    dict->GetString("charset", &charset_);
    dict->GetBinary("data", &binary);
  } else if (options->IsType(base::Value::Type::BINARY)) {
    options->GetAsBinary(&binary);
  }

  if (mime_type_.empty()) {
    std::string ext = GetExtFromURL(request()->url());
#if defined(OS_WIN)
    net::GetWellKnownMimeTypeFromExtension(base::UTF8ToUTF16(ext), &mime_type_);
#else
    net::GetWellKnownMimeTypeFromExtension(ext, &mime_type_);
#endif
  }

  if (!binary) {
    NotifyStartError(net::URLRequestStatus(
          net::URLRequestStatus::FAILED, net::ERR_NOT_IMPLEMENTED));
    return;
  }

  data_ = new base::RefCountedBytes(
      reinterpret_cast<const unsigned char*>(binary->GetBlob().data()),
      binary->GetBlob().size());
  status_code_ = net::HTTP_OK;
  net::URLRequestSimpleJob::Start();
}

void URLRequestBufferJob::GetResponseInfo(net::HttpResponseInfo* info) {
  std::string status("HTTP/1.1 200 OK");
  status.append(base::IntToString(status_code_));
  status.append(" ");
  status.append(net::GetHttpReasonPhrase(status_code_));
  status.append("\0\0", 2);
  auto* headers = new net::HttpResponseHeaders(status);

  headers->AddHeader(kCORSHeader);

  if (!mime_type_.empty()) {
    std::string content_type_header(net::HttpRequestHeaders::kContentType);
    content_type_header.append(": ");
    content_type_header.append(mime_type_);
    headers->AddHeader(content_type_header);
  }

  info->headers = headers;
}

int URLRequestBufferJob::GetRefCountedData(
    std::string* mime_type,
    std::string* charset,
    scoped_refptr<base::RefCountedMemory>* data,
    const net::CompletionCallback& callback) const {
  *mime_type = mime_type_;
  *charset = charset_;
  *data = data_;
  return net::OK;
}

}  // namespace atom
<commit_msg>Remove base::Value::GetAsBinary<commit_after>// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/browser/net/url_request_buffer_job.h"

#include <string>

#include "atom/common/atom_constants.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "net/base/mime_util.h"
#include "net/base/net_errors.h"

namespace atom {

namespace {

std::string GetExtFromURL(const GURL& url) {
  std::string spec = url.spec();
  size_t index = spec.find_last_of('.');
  if (index == std::string::npos || index == spec.size())
    return std::string();
  return spec.substr(index + 1, spec.size() - index - 1);
}

}  // namespace

URLRequestBufferJob::URLRequestBufferJob(
    net::URLRequest* request, net::NetworkDelegate* network_delegate)
    : JsAsker<net::URLRequestSimpleJob>(request, network_delegate),
      status_code_(net::HTTP_NOT_IMPLEMENTED) {
}

void URLRequestBufferJob::StartAsync(std::unique_ptr<base::Value> options) {
  const base::Value* binary = nullptr;
  if (options->IsType(base::Value::Type::DICTIONARY)) {
    base::DictionaryValue* dict =
        static_cast<base::DictionaryValue*>(options.get());
    dict->GetString("mimeType", &mime_type_);
    dict->GetString("charset", &charset_);
    dict->GetBinary("data", &binary);
  } else if (options->IsType(base::Value::Type::BINARY)) {
    binary = options.get();
  }

  if (mime_type_.empty()) {
    std::string ext = GetExtFromURL(request()->url());
#if defined(OS_WIN)
    net::GetWellKnownMimeTypeFromExtension(base::UTF8ToUTF16(ext), &mime_type_);
#else
    net::GetWellKnownMimeTypeFromExtension(ext, &mime_type_);
#endif
  }

  if (!binary) {
    NotifyStartError(net::URLRequestStatus(
          net::URLRequestStatus::FAILED, net::ERR_NOT_IMPLEMENTED));
    return;
  }

  data_ = new base::RefCountedBytes(
      reinterpret_cast<const unsigned char*>(binary->GetBlob().data()),
      binary->GetBlob().size());
  status_code_ = net::HTTP_OK;
  net::URLRequestSimpleJob::Start();
}

void URLRequestBufferJob::GetResponseInfo(net::HttpResponseInfo* info) {
  std::string status("HTTP/1.1 200 OK");
  status.append(base::IntToString(status_code_));
  status.append(" ");
  status.append(net::GetHttpReasonPhrase(status_code_));
  status.append("\0\0", 2);
  auto* headers = new net::HttpResponseHeaders(status);

  headers->AddHeader(kCORSHeader);

  if (!mime_type_.empty()) {
    std::string content_type_header(net::HttpRequestHeaders::kContentType);
    content_type_header.append(": ");
    content_type_header.append(mime_type_);
    headers->AddHeader(content_type_header);
  }

  info->headers = headers;
}

int URLRequestBufferJob::GetRefCountedData(
    std::string* mime_type,
    std::string* charset,
    scoped_refptr<base::RefCountedMemory>* data,
    const net::CompletionCallback& callback) const {
  *mime_type = mime_type_;
  *charset = charset_;
  *data = data_;
  return net::OK;
}

}  // namespace atom
<|endoftext|>


<commit_before>// ---------------------------------------------------------------------
//
// Copyright (C) 2009 - 2016 by the deal.II authors
//
// This file is part of the deal.II library.
//
// The deal.II library is free software; you can use it, 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.
// The full text of the license can be found in the file LICENSE at
// the top level of the deal.II distribution.
//
// ---------------------------------------------------------------------

#include <deal.II/base/config.h>

#ifdef DEAL_II_WITH_P4EST

#include <deal.II/lac/vector.h>
#include <deal.II/lac/block_vector.h>
#include <deal.II/lac/la_parallel_vector.h>
#include <deal.II/lac/la_parallel_block_vector.h>
#include <deal.II/lac/petsc_parallel_vector.h>
#include <deal.II/lac/petsc_parallel_block_vector.h>
#include <deal.II/lac/trilinos_vector.h>
#include <deal.II/lac/trilinos_parallel_block_vector.h>

#include <deal.II/distributed/solution_transfer.h>
#include <deal.II/distributed/tria.h>
#include <deal.II/dofs/dof_tools.h>
#include <deal.II/dofs/dof_accessor.h>
#include <deal.II/grid/tria_accessor.h>
#include <deal.II/grid/tria_iterator.h>

#include <functional>

DEAL_II_NAMESPACE_OPEN

namespace parallel
{
  namespace distributed
  {

    template<int dim, typename VectorType, typename DoFHandlerType>
    SolutionTransfer<dim, VectorType, DoFHandlerType>::SolutionTransfer (const DoFHandlerType &dof)
      :
      dof_handler(&dof, typeid(*this).name()),
      offset (numbers::invalid_unsigned_int)
    {
      Assert (dynamic_cast<const parallel::distributed::Triangulation<dim>*>
              (&dof_handler->get_triangulation()) != nullptr,
              ExcMessage("parallel::distributed::SolutionTransfer requires a parallel::distributed::Triangulation object."));
    }

    template<int dim, typename VectorType, typename DoFHandlerType>
    SolutionTransfer<dim, VectorType, DoFHandlerType>::~SolutionTransfer ()
    {}

    template<int dim, typename VectorType, typename DoFHandlerType>
    void
    SolutionTransfer<dim, VectorType, DoFHandlerType>::
    prepare_for_coarsening_and_refinement (const std::vector<const VectorType *> &all_in)
    {
      input_vectors = all_in;
      register_data_attach( get_data_size() * input_vectors.size() );
    }

    template<int dim, typename VectorType, typename DoFHandlerType>
    void
    SolutionTransfer<dim, VectorType, DoFHandlerType>::register_data_attach (const std::size_t size)
    {
      Assert(size > 0, ExcMessage("Please transfer at least one vector!"));

//TODO: casting away constness is bad
      parallel::distributed::Triangulation<dim,DoFHandlerType::space_dimension> *tria
        = (dynamic_cast<parallel::distributed::Triangulation<dim,DoFHandlerType::space_dimension>*>
           (const_cast<dealii::Triangulation<dim,DoFHandlerType::space_dimension>*>
            (&dof_handler->get_triangulation())));
      Assert (tria != nullptr, ExcInternalError());

      offset
        = tria->register_data_attach(size,
                                     std::bind(&SolutionTransfer<dim, VectorType,
                                               DoFHandlerType>::pack_callback,
                                               this,
                                               std::placeholders::_1,
                                               std::placeholders::_2,
                                               std::placeholders::_3));

    }

    template<int dim, typename VectorType, typename DoFHandlerType>
    void
    SolutionTransfer<dim, VectorType, DoFHandlerType>::
    prepare_for_coarsening_and_refinement (const VectorType &in)
    {
      std::vector<const VectorType *> all_in(1, &in);
      prepare_for_coarsening_and_refinement(all_in);
    }

    template<int dim, typename VectorType, typename DoFHandlerType>
    void
    SolutionTransfer<dim, VectorType, DoFHandlerType>::prepare_serialization (const VectorType &in)
    {
      std::vector<const VectorType *> all_in(1, &in);
      prepare_serialization(all_in);
    }

    template<int dim, typename VectorType, typename DoFHandlerType>
    void
    SolutionTransfer<dim, VectorType, DoFHandlerType>::prepare_serialization
    (const std::vector<const VectorType *> &all_in)
    {
      prepare_for_coarsening_and_refinement (all_in);
    }

    template<int dim, typename VectorType, typename DoFHandlerType>
    void
    SolutionTransfer<dim, VectorType, DoFHandlerType>::deserialize (VectorType &in)
    {
      std::vector<VectorType *> all_in(1, &in);
      deserialize(all_in);
    }

    template<int dim, typename VectorType, typename DoFHandlerType>
    void
    SolutionTransfer<dim, VectorType, DoFHandlerType>::deserialize (std::vector<VectorType *> &all_in)
    {
      register_data_attach( get_data_size() * all_in.size() );

      // this makes interpolate() happy
      input_vectors.resize(all_in.size());

      interpolate(all_in);
    }

    template<int dim, typename VectorType, typename DoFHandlerType>
    void
    SolutionTransfer<dim, VectorType, DoFHandlerType>::interpolate (std::vector<VectorType *> &all_out)
    {
      Assert(input_vectors.size()==all_out.size(),
             ExcDimensionMismatch(input_vectors.size(), all_out.size()) );

//TODO: casting away constness is bad
      parallel::distributed::Triangulation<dim,DoFHandlerType::space_dimension> *tria
        = (dynamic_cast<parallel::distributed::Triangulation<dim,DoFHandlerType::space_dimension>*>
           (const_cast<dealii::Triangulation<dim,DoFHandlerType::space_dimension>*>
            (&dof_handler->get_triangulation())));
      Assert (tria != nullptr, ExcInternalError());

      tria->notify_ready_to_unpack(offset,
                                   std::bind(&SolutionTransfer<dim, VectorType,
                                             DoFHandlerType>::unpack_callback,
                                             this,
                                             std::placeholders::_1,
                                             std::placeholders::_2,
                                             std::placeholders::_3,
                                             std::ref(all_out)));

      for (typename std::vector<VectorType *>::iterator it=all_out.begin();
           it !=all_out.end();
           ++it)
        (*it)->compress(::dealii::VectorOperation::insert);

      input_vectors.clear();
    }

    template<int dim, typename VectorType, typename DoFHandlerType>
    void
    SolutionTransfer<dim, VectorType, DoFHandlerType>::interpolate (VectorType &out)
    {
      std::vector<VectorType *> all_out(1, &out);
      interpolate(all_out);
    }

    template<int dim, typename VectorType, typename DoFHandlerType>
    unsigned int
    SolutionTransfer<dim, VectorType, DoFHandlerType>::get_data_size() const
    {
      return sizeof(typename VectorType::value_type)* DoFTools::max_dofs_per_cell(*dof_handler);
    }

    template<int dim, typename VectorType, typename DoFHandlerType>
    void
    SolutionTransfer<dim, VectorType, DoFHandlerType>::
    pack_callback(const typename Triangulation<dim,DoFHandlerType::space_dimension>::cell_iterator &cell_,
                  const typename Triangulation<dim,DoFHandlerType::space_dimension>::CellStatus /*status*/,
                  void *data)
    {
      typename VectorType::value_type *data_store = reinterpret_cast<typename VectorType::value_type *>(data);

      typename DoFHandlerType::cell_iterator cell(*cell_, dof_handler);

      const unsigned int dofs_per_cell=cell->get_fe().dofs_per_cell;
      ::dealii::Vector<typename VectorType::value_type> dofvalues(dofs_per_cell);
      for (typename std::vector<const VectorType *>::iterator it=input_vectors.begin();
           it !=input_vectors.end();
           ++it)
        {
          cell->get_interpolated_dof_values(*(*it), dofvalues);
          std::memcpy(data_store, &dofvalues(0), sizeof(typename VectorType::value_type)*dofs_per_cell);
          data_store += dofs_per_cell;
        }
    }

    template<int dim, typename VectorType, typename DoFHandlerType>
    void
    SolutionTransfer<dim, VectorType, DoFHandlerType>::unpack_callback
    (const typename Triangulation<dim,DoFHandlerType::space_dimension>::cell_iterator &cell_,
     const typename Triangulation<dim,DoFHandlerType::space_dimension>::CellStatus    /*status*/,
     const void                                           *data,
     std::vector<VectorType *>                            &all_out)
    {
      typename DoFHandlerType::cell_iterator
      cell(*cell_, dof_handler);

      const unsigned int dofs_per_cell=cell->get_fe().dofs_per_cell;
      ::dealii::Vector<typename VectorType::value_type> dofvalues(dofs_per_cell);
      const typename VectorType::value_type *data_store = reinterpret_cast<const typename VectorType::value_type *>(data);

      for (typename std::vector<VectorType *>::iterator it = all_out.begin();
           it != all_out.end();
           ++it)
        {
          std::memcpy(&dofvalues(0), data_store, sizeof(typename VectorType::value_type)*dofs_per_cell);
          cell->set_dof_values_by_interpolation(dofvalues, *(*it));
          data_store += dofs_per_cell;
        }
    }

  }
}

// explicit instantiations
#include "solution_transfer.inst"

DEAL_II_NAMESPACE_CLOSE

#endif
<commit_msg>added missing spacedim template<commit_after>// ---------------------------------------------------------------------
//
// Copyright (C) 2009 - 2016 by the deal.II authors
//
// This file is part of the deal.II library.
//
// The deal.II library is free software; you can use it, 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.
// The full text of the license can be found in the file LICENSE at
// the top level of the deal.II distribution.
//
// ---------------------------------------------------------------------

#include <deal.II/base/config.h>

#ifdef DEAL_II_WITH_P4EST

#include <deal.II/lac/vector.h>
#include <deal.II/lac/block_vector.h>
#include <deal.II/lac/la_parallel_vector.h>
#include <deal.II/lac/la_parallel_block_vector.h>
#include <deal.II/lac/petsc_parallel_vector.h>
#include <deal.II/lac/petsc_parallel_block_vector.h>
#include <deal.II/lac/trilinos_vector.h>
#include <deal.II/lac/trilinos_parallel_block_vector.h>

#include <deal.II/distributed/solution_transfer.h>
#include <deal.II/distributed/tria.h>
#include <deal.II/dofs/dof_tools.h>
#include <deal.II/dofs/dof_accessor.h>
#include <deal.II/grid/tria_accessor.h>
#include <deal.II/grid/tria_iterator.h>

#include <functional>

DEAL_II_NAMESPACE_OPEN

namespace parallel
{
  namespace distributed
  {

    template<int dim, typename VectorType, typename DoFHandlerType>
    SolutionTransfer<dim, VectorType, DoFHandlerType>::SolutionTransfer (const DoFHandlerType &dof)
      :
      dof_handler(&dof, typeid(*this).name()),
      offset (numbers::invalid_unsigned_int)
    {
      Assert ((dynamic_cast<const parallel::distributed::Triangulation<dim,DoFHandlerType::space_dimension>*>
               (&dof_handler->get_triangulation()) != nullptr),
              ExcMessage("parallel::distributed::SolutionTransfer requires a parallel::distributed::Triangulation object."));
    }

    template<int dim, typename VectorType, typename DoFHandlerType>
    SolutionTransfer<dim, VectorType, DoFHandlerType>::~SolutionTransfer ()
    {}

    template<int dim, typename VectorType, typename DoFHandlerType>
    void
    SolutionTransfer<dim, VectorType, DoFHandlerType>::
    prepare_for_coarsening_and_refinement (const std::vector<const VectorType *> &all_in)
    {
      input_vectors = all_in;
      register_data_attach( get_data_size() * input_vectors.size() );
    }

    template<int dim, typename VectorType, typename DoFHandlerType>
    void
    SolutionTransfer<dim, VectorType, DoFHandlerType>::register_data_attach (const std::size_t size)
    {
      Assert(size > 0, ExcMessage("Please transfer at least one vector!"));

//TODO: casting away constness is bad
      parallel::distributed::Triangulation<dim,DoFHandlerType::space_dimension> *tria
        = (dynamic_cast<parallel::distributed::Triangulation<dim,DoFHandlerType::space_dimension>*>
           (const_cast<dealii::Triangulation<dim,DoFHandlerType::space_dimension>*>
            (&dof_handler->get_triangulation())));
      Assert (tria != nullptr, ExcInternalError());

      offset
        = tria->register_data_attach(size,
                                     std::bind(&SolutionTransfer<dim, VectorType,
                                               DoFHandlerType>::pack_callback,
                                               this,
                                               std::placeholders::_1,
                                               std::placeholders::_2,
                                               std::placeholders::_3));

    }

    template<int dim, typename VectorType, typename DoFHandlerType>
    void
    SolutionTransfer<dim, VectorType, DoFHandlerType>::
    prepare_for_coarsening_and_refinement (const VectorType &in)
    {
      std::vector<const VectorType *> all_in(1, &in);
      prepare_for_coarsening_and_refinement(all_in);
    }

    template<int dim, typename VectorType, typename DoFHandlerType>
    void
    SolutionTransfer<dim, VectorType, DoFHandlerType>::prepare_serialization (const VectorType &in)
    {
      std::vector<const VectorType *> all_in(1, &in);
      prepare_serialization(all_in);
    }

    template<int dim, typename VectorType, typename DoFHandlerType>
    void
    SolutionTransfer<dim, VectorType, DoFHandlerType>::prepare_serialization
    (const std::vector<const VectorType *> &all_in)
    {
      prepare_for_coarsening_and_refinement (all_in);
    }

    template<int dim, typename VectorType, typename DoFHandlerType>
    void
    SolutionTransfer<dim, VectorType, DoFHandlerType>::deserialize (VectorType &in)
    {
      std::vector<VectorType *> all_in(1, &in);
      deserialize(all_in);
    }

    template<int dim, typename VectorType, typename DoFHandlerType>
    void
    SolutionTransfer<dim, VectorType, DoFHandlerType>::deserialize (std::vector<VectorType *> &all_in)
    {
      register_data_attach( get_data_size() * all_in.size() );

      // this makes interpolate() happy
      input_vectors.resize(all_in.size());

      interpolate(all_in);
    }

    template<int dim, typename VectorType, typename DoFHandlerType>
    void
    SolutionTransfer<dim, VectorType, DoFHandlerType>::interpolate (std::vector<VectorType *> &all_out)
    {
      Assert(input_vectors.size()==all_out.size(),
             ExcDimensionMismatch(input_vectors.size(), all_out.size()) );

//TODO: casting away constness is bad
      parallel::distributed::Triangulation<dim,DoFHandlerType::space_dimension> *tria
        = (dynamic_cast<parallel::distributed::Triangulation<dim,DoFHandlerType::space_dimension>*>
           (const_cast<dealii::Triangulation<dim,DoFHandlerType::space_dimension>*>
            (&dof_handler->get_triangulation())));
      Assert (tria != nullptr, ExcInternalError());

      tria->notify_ready_to_unpack(offset,
                                   std::bind(&SolutionTransfer<dim, VectorType,
                                             DoFHandlerType>::unpack_callback,
                                             this,
                                             std::placeholders::_1,
                                             std::placeholders::_2,
                                             std::placeholders::_3,
                                             std::ref(all_out)));

      for (typename std::vector<VectorType *>::iterator it=all_out.begin();
           it !=all_out.end();
           ++it)
        (*it)->compress(::dealii::VectorOperation::insert);

      input_vectors.clear();
    }

    template<int dim, typename VectorType, typename DoFHandlerType>
    void
    SolutionTransfer<dim, VectorType, DoFHandlerType>::interpolate (VectorType &out)
    {
      std::vector<VectorType *> all_out(1, &out);
      interpolate(all_out);
    }

    template<int dim, typename VectorType, typename DoFHandlerType>
    unsigned int
    SolutionTransfer<dim, VectorType, DoFHandlerType>::get_data_size() const
    {
      return sizeof(typename VectorType::value_type)* DoFTools::max_dofs_per_cell(*dof_handler);
    }

    template<int dim, typename VectorType, typename DoFHandlerType>
    void
    SolutionTransfer<dim, VectorType, DoFHandlerType>::
    pack_callback(const typename Triangulation<dim,DoFHandlerType::space_dimension>::cell_iterator &cell_,
                  const typename Triangulation<dim,DoFHandlerType::space_dimension>::CellStatus /*status*/,
                  void *data)
    {
      typename VectorType::value_type *data_store = reinterpret_cast<typename VectorType::value_type *>(data);

      typename DoFHandlerType::cell_iterator cell(*cell_, dof_handler);

      const unsigned int dofs_per_cell=cell->get_fe().dofs_per_cell;
      ::dealii::Vector<typename VectorType::value_type> dofvalues(dofs_per_cell);
      for (typename std::vector<const VectorType *>::iterator it=input_vectors.begin();
           it !=input_vectors.end();
           ++it)
        {
          cell->get_interpolated_dof_values(*(*it), dofvalues);
          std::memcpy(data_store, &dofvalues(0), sizeof(typename VectorType::value_type)*dofs_per_cell);
          data_store += dofs_per_cell;
        }
    }

    template<int dim, typename VectorType, typename DoFHandlerType>
    void
    SolutionTransfer<dim, VectorType, DoFHandlerType>::unpack_callback
    (const typename Triangulation<dim,DoFHandlerType::space_dimension>::cell_iterator &cell_,
     const typename Triangulation<dim,DoFHandlerType::space_dimension>::CellStatus    /*status*/,
     const void                                           *data,
     std::vector<VectorType *>                            &all_out)
    {
      typename DoFHandlerType::cell_iterator
      cell(*cell_, dof_handler);

      const unsigned int dofs_per_cell=cell->get_fe().dofs_per_cell;
      ::dealii::Vector<typename VectorType::value_type> dofvalues(dofs_per_cell);
      const typename VectorType::value_type *data_store = reinterpret_cast<const typename VectorType::value_type *>(data);

      for (typename std::vector<VectorType *>::iterator it = all_out.begin();
           it != all_out.end();
           ++it)
        {
          std::memcpy(&dofvalues(0), data_store, sizeof(typename VectorType::value_type)*dofs_per_cell);
          cell->set_dof_values_by_interpolation(dofvalues, *(*it));
          data_store += dofs_per_cell;
        }
    }

  }
}

// explicit instantiations
#include "solution_transfer.inst"

DEAL_II_NAMESPACE_CLOSE

#endif
<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2015, Nagoya University

 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  * Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 *
 *  * Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 *  * Neither the name of Autoware nor the names of its
 *    contributors may be used to endorse or promote products derived from
 *    this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 *  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 *  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 *  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 *  FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 *  DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 *  SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 *  OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 *  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include "hermite_curve.h"

namespace lane_planner
{
void createVectorFromPose(const geometry_msgs::Pose &p, tf::Vector3 *v)
{
  tf::Transform pose;
  tf::poseMsgToTF(p, pose);
  tf::Vector3 x_axis(1, 0, 0);
  *v = pose.getBasis() * x_axis;
}

void getPointAndVectorFromPose(const geometry_msgs::Pose &pose, Element2D *point, Element2D *vector)
{
  point->set(pose.position.x, pose.position.y);

  tf::Vector3 tmp_tf_vevtor;
  createVectorFromPose(pose, &tmp_tf_vevtor);
  vector->set(tmp_tf_vevtor.getX(), tmp_tf_vevtor.getY());
}

std::vector<waypoint_follower::waypoint> generateHermiteCurveForROS(const geometry_msgs::Pose &start,
                                                                    const geometry_msgs::Pose &end,
                                                                    const double velocity_mps, const double vlength)
{
  std::vector<waypoint_follower::waypoint> wps;
  Element2D p0(0, 0), v0(0, 0), p1(0, 0), v1(0, 0);
  getPointAndVectorFromPose(start, &p0, &v0);
  getPointAndVectorFromPose(end, &p1, &v1);

  std::vector<Element2D> result = generateHermiteCurve(p0, v0, p1, v1, vlength);

  double height_d = fabs(start.position.z - end.position.z);
  for (uint32_t i = 0; i < result.size(); i++)
  {
    waypoint_follower::waypoint wp;
    wp.pose.pose.position.x = result.at(i).x;
    wp.pose.pose.position.y = result.at(i).y;
    wp.twist.twist.linear.x = velocity_mps;

    // height
    wp.pose.pose.position.z = (i == 0) ? start.position.z
                                       : (i == result.size() - 1) ? end.position.z
                                       : start.position.z < end.position.z ?start.position.z + height_d * i / result.size()
                                       : start.position.z - height_d * i / result.size();

    // orientation
    if (i != result.size() - 1)
    {
      double radian = atan2(result.at(i + 1).y - result.at(i).y, result.at(i + 1).x - result.at(i).x);
      wp.pose.pose.orientation = tf::createQuaternionMsgFromYaw(radian);
    }
    else
    {
      wp.pose.pose.orientation = wps.at(wps.size() - 1).pose.pose.orientation;
    }

    wps.push_back(wp);
  }
  return wps;
}

std::vector<Element2D> generateHermiteCurve(const Element2D &p0, const Element2D &v0, const Element2D &p1, const Element2D &v1, const double vlength)
{
  std::vector<Element2D> result;
  const double interval = 1.0;
  const double error = 1e-3;
  int32_t divide = 2;
  while (divide < 100)
  {
    result.reserve(divide);
    for (int32_t i = 0; i < divide; i++)
    {
      double u = i * 1.0 / (divide - 1);
      double u_square = pow(u, 2);
      double u_cube = pow(u, 3);
      double coeff_p0 = 2 * u_cube - 3 * u_square + 1;
      double coeff_v0 = u_cube - 2 * u_square + u;
      double coeff_p1 = (-1) * 2 * u_cube + 3 * u_square;
      double coeff_v1 = u_cube - u_square;
      //printf("u: %lf, u^2: %lf, u^3: %lf, coeff_p0: %lf, coeff_v0: %lf, coeff_p1: %lf, coeff_v1: %lf\n", u, u_square, u_cube, coeff_p0, coeff_p1, coeff_v0, coeff_v1);
      result.push_back(
          Element2D((p0.x * coeff_p0 + vlength * v0.x * coeff_v0 + p1.x * coeff_p1 + vlength * v1.x * coeff_v1),
                    (p0.y * coeff_p0 + vlength * v0.y * coeff_v0 + p1.y * coeff_p1 + vlength * v1.y * coeff_v1)));
    }
    ROS_INFO_STREAM(sqrt(pow((result.at(0).x - result.at(1).x), 2) + pow((result.at(0).y - result.at(1).y), 2)));
    if (fabs(interval < sqrt(pow((result.at(0).x - result.at(1).x), 2) + pow((result.at(0).y - result.at(1).y), 2))) <
        error)
      return result;
    else
    {
      result.clear();
      result.shrink_to_fit();
      divide++;
    }
  }
  return result;
}
}  // namespace
<commit_msg>Fix hermite curve<commit_after>/*
 *  Copyright (c) 2015, Nagoya University

 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  * Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 *
 *  * Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 *  * Neither the name of Autoware nor the names of its
 *    contributors may be used to endorse or promote products derived from
 *    this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 *  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 *  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 *  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 *  FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 *  DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 *  SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 *  OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 *  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include "hermite_curve.h"

namespace lane_planner
{
void createVectorFromPose(const geometry_msgs::Pose &p, tf::Vector3 *v)
{
  tf::Transform pose;
  tf::poseMsgToTF(p, pose);
  tf::Vector3 x_axis(1, 0, 0);
  *v = pose.getBasis() * x_axis;
}

void getPointAndVectorFromPose(const geometry_msgs::Pose &pose, Element2D *point, Element2D *vector)
{
  point->set(pose.position.x, pose.position.y);

  tf::Vector3 tmp_tf_vevtor;
  createVectorFromPose(pose, &tmp_tf_vevtor);
  vector->set(tmp_tf_vevtor.getX(), tmp_tf_vevtor.getY());
}

std::vector<waypoint_follower::waypoint> generateHermiteCurveForROS(const geometry_msgs::Pose &start,
                                                                    const geometry_msgs::Pose &end,
                                                                    const double velocity_mps, const double vlength)
{
  std::vector<waypoint_follower::waypoint> wps;
  Element2D p0(0, 0), v0(0, 0), p1(0, 0), v1(0, 0);
  getPointAndVectorFromPose(start, &p0, &v0);
  getPointAndVectorFromPose(end, &p1, &v1);

  std::vector<Element2D> result = generateHermiteCurve(p0, v0, p1, v1, vlength);

  double height_d = fabs(start.position.z - end.position.z);
  for (uint32_t i = 0; i < result.size(); i++)
  {
    waypoint_follower::waypoint wp;
    wp.pose.pose.position.x = result.at(i).x;
    wp.pose.pose.position.y = result.at(i).y;
    wp.twist.twist.linear.x = velocity_mps;

    // height
    wp.pose.pose.position.z = (i == 0) ? start.position.z
                                       : (i == result.size() - 1) ? end.position.z
                                       : start.position.z < end.position.z ?start.position.z + height_d * i / result.size()
                                       : start.position.z - height_d * i / result.size();

    // orientation
    if (i != result.size() - 1)
    {
      double radian = atan2(result.at(i + 1).y - result.at(i).y, result.at(i + 1).x - result.at(i).x);
      wp.pose.pose.orientation = tf::createQuaternionMsgFromYaw(radian);
    }
    else
    {
      wp.pose.pose.orientation = wps.at(wps.size() - 1).pose.pose.orientation;
    }

    wps.push_back(wp);
  }
  return wps;
}

std::vector<Element2D> generateHermiteCurve(const Element2D &p0, const Element2D &v0, const Element2D &p1, const Element2D &v1, const double vlength)
{
  std::vector<Element2D> result;
  const double interval = 1.0;
  int32_t divide = 2;
  const int32_t loop = 100;
  while (divide < loop)
  {
    result.reserve(divide);
    for (int32_t i = 0; i < divide; i++)
    {
      double u = i * 1.0 / (divide - 1);
      double u_square = pow(u, 2);
      double u_cube = pow(u, 3);
      double coeff_p0 = 2 * u_cube - 3 * u_square + 1;
      double coeff_v0 = u_cube - 2 * u_square + u;
      double coeff_p1 = (-1) * 2 * u_cube + 3 * u_square;
      double coeff_v1 = u_cube - u_square;
      //printf("u: %lf, u^2: %lf, u^3: %lf, coeff_p0: %lf, coeff_v0: %lf, coeff_p1: %lf, coeff_v1: %lf\n", u, u_square, u_cube, coeff_p0, coeff_p1, coeff_v0, coeff_v1);
      result.push_back(
          Element2D((p0.x * coeff_p0 + vlength * v0.x * coeff_v0 + p1.x * coeff_p1 + vlength * v1.x * coeff_v1),
                    (p0.y * coeff_p0 + vlength * v0.y * coeff_v0 + p1.y * coeff_p1 + vlength * v1.y * coeff_v1)));
    }

    double dt = sqrt(pow((result.at(divide/2 - 1).x - result.at(divide/2).x), 2) + pow((result.at(divide/2 - 1).y - result.at(divide/2).y), 2));
    std::cout << "interval : " << dt << std::endl;
    if (interval > dt || divide == loop -1)
      return result;
    else
    {
      result.clear();
      result.shrink_to_fit();
      divide++;
    }
  }
  return result;
}
}  // namespace
<|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    vtkOpenGLPolyDataMapper2D.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

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

=========================================================================*/
#include "vtkOpenGLPolyDataMapper2D.h"

#include "vtkActor2D.h"
#include "vtkCellArray.h"
#include "vtkMath.h"
#include "vtkObjectFactory.h"
#include "vtkPlane.h"
#include "vtkPlaneCollection.h"
#include "vtkPointData.h"
#include "vtkPolyData.h"
#include "vtkProperty2D.h"
#include "vtkScalarsToColors.h"
#include "vtkUnsignedCharArray.h"
#include "vtkViewport.h"
#include "vtkWindow.h"
#include "vtkgluPickMatrix.h"
#include "vtkToolkits.h"  // for VTK_USE_GL2PS

#ifdef VTK_USE_GL2PS
#include "gl2ps.h"
#include "vtkGL2PSExporter.h"
#endif // VTK_USE_GL2PS

#include <math.h>

#ifndef VTK_IMPLEMENT_MESA_CXX
vtkCxxRevisionMacro(vtkOpenGLPolyDataMapper2D, "1.55");
vtkStandardNewMacro(vtkOpenGLPolyDataMapper2D);
#endif

void vtkOpenGLPolyDataMapper2D::RenderOverlay(vtkViewport* viewport,
                                              vtkActor2D* actor)
{
  int            numPts;
  vtkPolyData    *input= (vtkPolyData *)this->GetInput();
  int            j;
  vtkPoints      *p, *displayPts;
  vtkCellArray   *aPrim;
  vtkUnsignedCharArray *c=NULL;
  unsigned char  *rgba;
  unsigned char  color[4];
  vtkIdType      *pts = 0;
  vtkIdType      npts = 0;
  int            cellScalars = 0;
  int            cellNum = 0;
  vtkPlaneCollection *clipPlanes;
  vtkPlane           *plane;
  int                 i,numClipPlanes;
  double              planeEquation[4];

  vtkDebugMacro (<< "vtkOpenGLPolyDataMapper2D::Render");

  if ( input == NULL )
    {
    vtkErrorMacro(<< "No input!");
    return;
    }
  else
    {
    input->Update();
    numPts = input->GetNumberOfPoints();
    }

  if (numPts == 0)
    {
    vtkDebugMacro(<< "No points!");
    return;
    }

  if ( this->LookupTable == NULL )
    {
    this->CreateDefaultLookupTable();
    }

  // if something has changed regenrate colors and display lists
  // if required
  //
  if ( this->GetMTime() > this->BuildTime ||
       input->GetMTime() > this->BuildTime ||
       this->LookupTable->GetMTime() > this->BuildTime ||
       actor->GetProperty()->GetMTime() > this->BuildTime)
    {
    // sets this->Colors as side effect
    this->MapScalars(actor->GetProperty()->GetOpacity());
    this->BuildTime.Modified();
    }

  // Get the position of the actor
  int size[2];
  size[0] = viewport->GetSize()[0];
  size[1] = viewport->GetSize()[1];
  double *vport = viewport->GetViewport();
  int* actorPos =
    actor->GetPositionCoordinate()->GetComputedViewportValue(viewport);

  // get window info
  double *tileViewPort = viewport->GetVTKWindow()->GetTileViewport();
  double visVP[4];
  visVP[0] = (vport[0] >= tileViewPort[0]) ? vport[0] : tileViewPort[0];
  visVP[1] = (vport[1] >= tileViewPort[1]) ? vport[1] : tileViewPort[1];
  visVP[2] = (vport[2] <= tileViewPort[2]) ? vport[2] : tileViewPort[2];
  visVP[3] = (vport[3] <= tileViewPort[3]) ? vport[3] : tileViewPort[3];
  if (visVP[0] >= visVP[2])
    {
    return;
    }
  if (visVP[1] >= visVP[3])
    {
    return;
    }
  size[0] =
    vtkMath::Round(size[0]*(visVP[2] - visVP[0])/(vport[2] - vport[0]));
  size[1] =
    vtkMath::Round(size[1]*(visVP[3] - visVP[1])/(vport[3] - vport[1]));

  // Set up the font color from the text actor
  double*  actorColor = actor->GetProperty()->GetColor();
  color[0] = (unsigned char) (actorColor[0] * 255.0);
  color[1] = (unsigned char) (actorColor[1] * 255.0);
  color[2] = (unsigned char) (actorColor[2] * 255.0);
  color[3] = (unsigned char) (255.0*actor->GetProperty()->GetOpacity());

  // Transform the points, if necessary
  p = input->GetPoints();
  if ( this->TransformCoordinate )
    {
    int *itmp;
    numPts = p->GetNumberOfPoints();
    displayPts = vtkPoints::New();
    displayPts->SetNumberOfPoints(numPts);
    for ( j=0; j < numPts; j++ )
      {
      this->TransformCoordinate->SetValue(p->GetPoint(j));
      itmp = this->TransformCoordinate->GetComputedViewportValue(viewport);
      displayPts->SetPoint(j,itmp[0], itmp[1], 0.0);
      }
    p = displayPts;
    }

  // Set up the coloring
  if ( this->Colors )
    {
    c = this->Colors;
    if (!input->GetPointData()->GetScalars())
      {
      cellScalars = 1;
      }
    }
  vtkDebugMacro(<< c);
  vtkDebugMacro(<< cellScalars);

  // set the colors for the foreground
  glColor4ubv(color);

  // push a 2D matrix on the stack
  glMatrixMode( GL_PROJECTION );
  glPushMatrix();
  glLoadIdentity();
  if(viewport->GetIsPicking())
    {
    vtkgluPickMatrix(viewport->GetPickX(), viewport->GetPickY(),
                     1, 1, viewport->GetOrigin(), viewport->GetSize());
    }

  glMatrixMode( GL_MODELVIEW );
  glPushMatrix();
  glLoadIdentity();

  glDisable( GL_TEXTURE_2D );
  glDisable( GL_LIGHTING );

  // Assume we want to do Zbuffering for now.
  // we may turn this off later
  glDepthMask(GL_TRUE);

  int *winSize = viewport->GetVTKWindow()->GetSize();

  int xoff = static_cast<int>(actorPos[0] - (visVP[0] - vport[0])*
                              winSize[0]);
  int yoff = static_cast<int>(actorPos[1] - (visVP[1] - vport[1])*
                              winSize[1]);

  if ( actor->GetProperty()->GetDisplayLocation() ==
       VTK_FOREGROUND_LOCATION )
    {
    glOrtho(-xoff,-xoff + size[0],
            -yoff, -yoff +size[1], 0, 1);
    }
  else
    {
    glOrtho(-xoff,-xoff + size[0],
            -yoff, -yoff + size[1], -1, 0);
    }

  // Clipping plane stuff
  clipPlanes = this->ClippingPlanes;

  if (clipPlanes == NULL)
    {
    numClipPlanes = 0;
    }
  else
    {
    numClipPlanes = clipPlanes->GetNumberOfItems();
    if (numClipPlanes > 4)
      {
      vtkErrorMacro(<< "Only 4 clipping planes are used with 2D mappers");
      }
    }

  for (i = 0; i < numClipPlanes; i++)
    {
    glEnable((GLenum)(GL_CLIP_PLANE0+i));
    }

  for (i = 0; i < numClipPlanes; i++)
    {
    plane = (vtkPlane *)clipPlanes->GetItemAsObject(i);

    planeEquation[0] = plane->GetNormal()[0];
    planeEquation[1] = plane->GetNormal()[1];
    planeEquation[2] = plane->GetNormal()[2];
    planeEquation[3] = -(planeEquation[0]*plane->GetOrigin()[0]+
                         planeEquation[1]*plane->GetOrigin()[1]+
                         planeEquation[2]*plane->GetOrigin()[2]);
    glClipPlane((GLenum)(GL_CLIP_PLANE0+i),planeEquation);
    }

  // Set the PointSize
  glPointSize(actor->GetProperty()->GetPointSize());

  double *dptr;
  aPrim = input->GetVerts();
  glBegin(GL_POINTS);
  for (aPrim->InitTraversal(); aPrim->GetNextCell(npts,pts); cellNum++)
    {
    for (j = 0; j < npts; j++)
      {
      if (c)
        {
        if (cellScalars)
          {
          rgba = c->GetPointer(4*cellNum);
          }
        else
          {
          rgba = c->GetPointer(4*pts[j]);
          }
        glColor4ubv(rgba);
        }
      // this is done to work around an OpenGL bug, otherwise we could just
      // call glVertex2dv
      dptr = p->GetPoint(pts[j]);
      glVertex3d(dptr[0],dptr[1],0);
      }
    }
  glEnd();

  // Set pointsize and linewidth for GL2PS output.
#ifdef VTK_USE_GL2PS
  gl2psPointSize(actor->GetProperty()->GetPointSize()*
                 vtkGL2PSExporter::GetGlobalPointSizeFactor());
  gl2psLineWidth(actor->GetProperty()->GetLineWidth()*
                 vtkGL2PSExporter::GetGlobalLineWidthFactor());
#endif // VTK_USE_GL2PS

  // Set the LineWidth
  glLineWidth(actor->GetProperty()->GetLineWidth());

  // Set the LineStipple
  if (actor->GetProperty()->GetLineStipplePattern() != 0xFFFF)
    {
    glEnable (GL_LINE_STIPPLE);
#ifdef VTK_USE_GL2PS
    gl2psEnable(GL2PS_LINE_STIPPLE);
#endif // VTK_USE_GL2PS
    glLineStipple (actor->GetProperty()->GetLineStippleRepeatFactor(),
                   actor->GetProperty()->GetLineStipplePattern());
    }
  else
    {
    glDisable (GL_LINE_STIPPLE);
#ifdef VTK_USE_GL2PS
    gl2psDisable(GL2PS_LINE_STIPPLE);
#endif // VTK_USE_GL2PS
    }

  aPrim = input->GetLines();
  for (aPrim->InitTraversal(); aPrim->GetNextCell(npts,pts); cellNum++)
    {
    glBegin(GL_LINE_STRIP);
    for (j = 0; j < npts; j++)
      {
      if (c)
        {
        if (cellScalars)
          {
          rgba = c->GetPointer(4*cellNum);
          }
        else
          {
          rgba = c->GetPointer(4*pts[j]);
          }
        glColor4ubv(rgba);
        }
      // this is done to work around an OpenGL bug, otherwise we could just
      // call glVertex2dv
      dptr = p->GetPoint(pts[j]);
      glVertex3d(dptr[0],dptr[1],0);
      }
    glEnd();
    }

  aPrim = input->GetPolys();
  for (aPrim->InitTraversal(); aPrim->GetNextCell(npts,pts); cellNum++)
    {
    glBegin(GL_POLYGON);
    for (j = 0; j < npts; j++)
      {
      if (c)
        {
        if (cellScalars)
          {
          rgba = c->GetPointer(4*cellNum);
          }
        else
          {
          rgba = c->GetPointer(4*pts[j]);
          }
        glColor4ubv(rgba);
        }
      // this is done to work around an OpenGL bug, otherwise we could just
      // call glVertex2dv
      dptr = p->GetPoint(pts[j]);
      glVertex3d(dptr[0],dptr[1],0);
      }
    glEnd();
    }

  if ( this->TransformCoordinate )
    {
    p->Delete();
    }

  for (i = 0; i < numClipPlanes; i++)
    {
    glDisable((GLenum)(GL_CLIP_PLANE0+i));
    }

  // push a 2D matrix on the stack
  glMatrixMode( GL_PROJECTION);
  glPopMatrix();
  glMatrixMode( GL_MODELVIEW);
  glPopMatrix();
  glEnable( GL_LIGHTING);

  // Turn it back on in case we've turned it off
  glDepthMask( GL_TRUE );
}

//----------------------------------------------------------------------------
void vtkOpenGLPolyDataMapper2D::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);
}
<commit_msg>ENH: Add texture coordinates for showing text.<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkOpenGLPolyDataMapper2D.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

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

=========================================================================*/
#include "vtkOpenGLPolyDataMapper2D.h"

#include "vtkActor2D.h"
#include "vtkCellArray.h"
#include "vtkMath.h"
#include "vtkObjectFactory.h"
#include "vtkPlane.h"
#include "vtkPlaneCollection.h"
#include "vtkPointData.h"
#include "vtkPolyData.h"
#include "vtkProperty2D.h"
#include "vtkScalarsToColors.h"
#include "vtkUnsignedCharArray.h"
#include "vtkViewport.h"
#include "vtkWindow.h"
#include "vtkgluPickMatrix.h"
#include "vtkToolkits.h"  // for VTK_USE_GL2PS

#ifdef VTK_USE_GL2PS
#include "gl2ps.h"
#include "vtkGL2PSExporter.h"
#endif // VTK_USE_GL2PS

#include <math.h>

#ifndef VTK_IMPLEMENT_MESA_CXX
vtkCxxRevisionMacro(vtkOpenGLPolyDataMapper2D, "1.56");
vtkStandardNewMacro(vtkOpenGLPolyDataMapper2D);
#endif

void vtkOpenGLPolyDataMapper2D::RenderOverlay(vtkViewport* viewport,
                                              vtkActor2D* actor)
{
  int            numPts;
  vtkPolyData    *input= (vtkPolyData *)this->GetInput();
  int            j;
  vtkPoints      *p, *displayPts;
  vtkCellArray   *aPrim;
  vtkUnsignedCharArray *c=NULL;
  unsigned char  *rgba;
  unsigned char  color[4];
  vtkIdType      *pts = 0;
  vtkIdType      npts = 0;
  int            cellScalars = 0;
  int            cellNum = 0;
  vtkPlaneCollection *clipPlanes;
  vtkPlane           *plane;
  int                 i,numClipPlanes;
  double              planeEquation[4];
  vtkDataArray*  t = 0;

  vtkDebugMacro (<< "vtkOpenGLPolyDataMapper2D::Render");

  if ( input == NULL )
    {
    vtkErrorMacro(<< "No input!");
    return;
    }
  else
    {
    input->Update();
    numPts = input->GetNumberOfPoints();
    }

  if (numPts == 0)
    {
    vtkDebugMacro(<< "No points!");
    return;
    }

  if ( this->LookupTable == NULL )
    {
    this->CreateDefaultLookupTable();
    }

  // Texture and color by texture
  t = input->GetPointData()->GetTCoords();
  if ( t )
    {
    int tDim = t->GetNumberOfComponents();
    if (tDim != 2)
      {
      vtkDebugMacro(<< "Currently only 2d textures are supported.\n");
      t = 0;
      }
    }

  // if something has changed regenrate colors and display lists
  // if required
  //
  if ( this->GetMTime() > this->BuildTime ||
       input->GetMTime() > this->BuildTime ||
       this->LookupTable->GetMTime() > this->BuildTime ||
       actor->GetProperty()->GetMTime() > this->BuildTime)
    {
    // sets this->Colors as side effect
    this->MapScalars(actor->GetProperty()->GetOpacity());
    this->BuildTime.Modified();
    }

  // Get the position of the actor
  int size[2];
  size[0] = viewport->GetSize()[0];
  size[1] = viewport->GetSize()[1];
  double *vport = viewport->GetViewport();
  int* actorPos =
    actor->GetPositionCoordinate()->GetComputedViewportValue(viewport);

  // get window info
  double *tileViewPort = viewport->GetVTKWindow()->GetTileViewport();
  double visVP[4];
  visVP[0] = (vport[0] >= tileViewPort[0]) ? vport[0] : tileViewPort[0];
  visVP[1] = (vport[1] >= tileViewPort[1]) ? vport[1] : tileViewPort[1];
  visVP[2] = (vport[2] <= tileViewPort[2]) ? vport[2] : tileViewPort[2];
  visVP[3] = (vport[3] <= tileViewPort[3]) ? vport[3] : tileViewPort[3];
  if (visVP[0] >= visVP[2])
    {
    return;
    }
  if (visVP[1] >= visVP[3])
    {
    return;
    }
  size[0] =
    vtkMath::Round(size[0]*(visVP[2] - visVP[0])/(vport[2] - vport[0]));
  size[1] =
    vtkMath::Round(size[1]*(visVP[3] - visVP[1])/(vport[3] - vport[1]));

  // Set up the font color from the text actor
  double*  actorColor = actor->GetProperty()->GetColor();
  color[0] = (unsigned char) (actorColor[0] * 255.0);
  color[1] = (unsigned char) (actorColor[1] * 255.0);
  color[2] = (unsigned char) (actorColor[2] * 255.0);
  color[3] = (unsigned char) (255.0*actor->GetProperty()->GetOpacity());

  // Transform the points, if necessary
  p = input->GetPoints();
  if ( this->TransformCoordinate )
    {
    int *itmp;
    numPts = p->GetNumberOfPoints();
    displayPts = vtkPoints::New();
    displayPts->SetNumberOfPoints(numPts);
    for ( j=0; j < numPts; j++ )
      {
      this->TransformCoordinate->SetValue(p->GetPoint(j));
      itmp = this->TransformCoordinate->GetComputedViewportValue(viewport);
      displayPts->SetPoint(j,itmp[0], itmp[1], 0.0);
      }
    p = displayPts;
    }

  // Set up the coloring
  if ( this->Colors )
    {
    c = this->Colors;
    if (!input->GetPointData()->GetScalars())
      {
      cellScalars = 1;
      }
    }
  vtkDebugMacro(<< c);
  vtkDebugMacro(<< cellScalars);

  // set the colors for the foreground
  glColor4ubv(color);

  // push a 2D matrix on the stack
  glMatrixMode( GL_PROJECTION );
  glPushMatrix();
  glLoadIdentity();
  if(viewport->GetIsPicking())
    {
    vtkgluPickMatrix(viewport->GetPickX(), viewport->GetPickY(),
                     1, 1, viewport->GetOrigin(), viewport->GetSize());
    }

  glMatrixMode( GL_MODELVIEW );
  glPushMatrix();
  glLoadIdentity();

  if ( ! t)
    {
    glDisable( GL_TEXTURE_2D );
    }
  glDisable( GL_LIGHTING );

  // Assume we want to do Zbuffering for now.
  // we may turn this off later
  glDepthMask(GL_TRUE);

  int *winSize = viewport->GetVTKWindow()->GetSize();

  int xoff = static_cast<int>(actorPos[0] - (visVP[0] - vport[0])*
                              winSize[0]);
  int yoff = static_cast<int>(actorPos[1] - (visVP[1] - vport[1])*
                              winSize[1]);

  if ( actor->GetProperty()->GetDisplayLocation() ==
       VTK_FOREGROUND_LOCATION )
    {
    glOrtho(-xoff,-xoff + size[0],
            -yoff, -yoff +size[1], 0, 1);
    }
  else
    {
    glOrtho(-xoff,-xoff + size[0],
            -yoff, -yoff + size[1], -1, 0);
    }

  // Clipping plane stuff
  clipPlanes = this->ClippingPlanes;

  if (clipPlanes == NULL)
    {
    numClipPlanes = 0;
    }
  else
    {
    numClipPlanes = clipPlanes->GetNumberOfItems();
    if (numClipPlanes > 4)
      {
      vtkErrorMacro(<< "Only 4 clipping planes are used with 2D mappers");
      }
    }

  for (i = 0; i < numClipPlanes; i++)
    {
    glEnable((GLenum)(GL_CLIP_PLANE0+i));
    }

  for (i = 0; i < numClipPlanes; i++)
    {
    plane = (vtkPlane *)clipPlanes->GetItemAsObject(i);

    planeEquation[0] = plane->GetNormal()[0];
    planeEquation[1] = plane->GetNormal()[1];
    planeEquation[2] = plane->GetNormal()[2];
    planeEquation[3] = -(planeEquation[0]*plane->GetOrigin()[0]+
                         planeEquation[1]*plane->GetOrigin()[1]+
                         planeEquation[2]*plane->GetOrigin()[2]);
    glClipPlane((GLenum)(GL_CLIP_PLANE0+i),planeEquation);
    }

  // Set the PointSize
  glPointSize(actor->GetProperty()->GetPointSize());

  double *dptr;
  aPrim = input->GetVerts();
  glBegin(GL_POINTS);
  for (aPrim->InitTraversal(); aPrim->GetNextCell(npts,pts); cellNum++)
    {
    for (j = 0; j < npts; j++)
      {
      if (c)
        {
        if (cellScalars)
          {
          rgba = c->GetPointer(4*cellNum);
          }
        else
          {
          rgba = c->GetPointer(4*pts[j]);
          }
        glColor4ubv(rgba);
        }
      if (t)
        {
        glTexCoord2dv(t->GetTuple(pts[j]));
        }
      // this is done to work around an OpenGL bug, otherwise we could just
      // call glVertex2dv
      dptr = p->GetPoint(pts[j]);
      glVertex3d(dptr[0],dptr[1],0);
      }
    }
  glEnd();

  // Set pointsize and linewidth for GL2PS output.
#ifdef VTK_USE_GL2PS
  gl2psPointSize(actor->GetProperty()->GetPointSize()*
                 vtkGL2PSExporter::GetGlobalPointSizeFactor());
  gl2psLineWidth(actor->GetProperty()->GetLineWidth()*
                 vtkGL2PSExporter::GetGlobalLineWidthFactor());
#endif // VTK_USE_GL2PS

  // Set the LineWidth
  glLineWidth(actor->GetProperty()->GetLineWidth());

  // Set the LineStipple
  if (actor->GetProperty()->GetLineStipplePattern() != 0xFFFF)
    {
    glEnable (GL_LINE_STIPPLE);
#ifdef VTK_USE_GL2PS
    gl2psEnable(GL2PS_LINE_STIPPLE);
#endif // VTK_USE_GL2PS
    glLineStipple (actor->GetProperty()->GetLineStippleRepeatFactor(),
                   actor->GetProperty()->GetLineStipplePattern());
    }
  else
    {
    glDisable (GL_LINE_STIPPLE);
#ifdef VTK_USE_GL2PS
    gl2psDisable(GL2PS_LINE_STIPPLE);
#endif // VTK_USE_GL2PS
    }

  aPrim = input->GetLines();
  for (aPrim->InitTraversal(); aPrim->GetNextCell(npts,pts); cellNum++)
    {
    glBegin(GL_LINE_STRIP);
    for (j = 0; j < npts; j++)
      {
      if (c)
        {
        if (cellScalars)
          {
          rgba = c->GetPointer(4*cellNum);
          }
        else
          {
          rgba = c->GetPointer(4*pts[j]);
          }
        glColor4ubv(rgba);
        }
      if (t)
        {
        glTexCoord2dv(t->GetTuple(pts[j]));
        }
      // this is done to work around an OpenGL bug, otherwise we could just
      // call glVertex2dv
      dptr = p->GetPoint(pts[j]);
      glVertex3d(dptr[0],dptr[1],0);
      }
    glEnd();
    }

  aPrim = input->GetPolys();
  for (aPrim->InitTraversal(); aPrim->GetNextCell(npts,pts); cellNum++)
    {
    glBegin(GL_POLYGON);
    for (j = 0; j < npts; j++)
      {
      if (c)
        {
        if (cellScalars)
          {
          rgba = c->GetPointer(4*cellNum);
          }
        else
          {
          rgba = c->GetPointer(4*pts[j]);
          }
        glColor4ubv(rgba);
        }
      if (t)
        {
        glTexCoord2dv(t->GetTuple(pts[j]));
        }
      // this is done to work around an OpenGL bug, otherwise we could just
      // call glVertex2dv
      dptr = p->GetPoint(pts[j]);
      glVertex3d(dptr[0],dptr[1],0);
      }
    glEnd();
    }

  if ( this->TransformCoordinate )
    {
    p->Delete();
    }

  for (i = 0; i < numClipPlanes; i++)
    {
    glDisable((GLenum)(GL_CLIP_PLANE0+i));
    }

  // push a 2D matrix on the stack
  glMatrixMode( GL_PROJECTION);
  glPopMatrix();
  glMatrixMode( GL_MODELVIEW);
  glPopMatrix();
  glEnable( GL_LIGHTING);

  // Turn it back on in case we've turned it off
  glDepthMask( GL_TRUE );
}

//----------------------------------------------------------------------------
void vtkOpenGLPolyDataMapper2D::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);
}
<|endoftext|>


<commit_before>#include "..\header\Exit.h"

Exit::Exit(game_state* GameState){
	LogManager& l = LogManager::getInstance();
	WorldManager& w = WorldManager::getInstance();
	setType(TYPE_EXIT);
	setTransparency();
	setSolidness(Solidness::HARD);

	GameState->Stage1.exit.x += GameState->Bounds.minX;
	GameState->Stage1.exit.y += GameState->Bounds.minY;
	Position pos(GameState->Stage1.exit.x, GameState->Stage1.exit.y);
	setPosition(pos);
	l.writeLog("[Exit] New position: %d %d", pos.getX(), pos.getY());

	registerInterest(DF_STEP_EVENT);

	setVisible(true);

	this->GameState = GameState;
	l.writeLog("[Exit] Successfully loaded Exit.");
}

Exit::~Exit(){
	unregisterInterest(DF_STEP_EVENT);
}

int Exit::eventHandler(Event* e){
	LogManager& l = LogManager::getInstance();
	if (e->getType().compare(DF_STEP_EVENT) == 0){
		block_state* Blocks = this->GameState->Stage1.blocks;
		this->GameState->Stage1.exit.isBlocked = false;
		for (int i = 0; i<this->GameState->Stage1.blockStateSize; i++){
			if (Blocks[i].x == this->GameState->Stage1.exit.x && Blocks[i].y == this->GameState->Stage1.exit.y){
				this->GameState->Stage1.exit.isBlocked = true;
			}
		}
		return 1;
	}
	return 0;
}

void Exit::draw(){
	if (this->GameState->Board.isRotating){
		return;
	}
	if (this->GameState->Stage1.exit.isBlocked){
		return;
	}

	LogManager& l = LogManager::getInstance();
	GraphicsManager& g = GraphicsManager::getInstance();
	switch (this->GameState->Board.arrayOrder){
		case 0:{
			Position pos(this->getPosition().getX()+1, this->getPosition().getY()+1);
			g.drawCh(pos, '%', 5);
			break;
		}
		case 1:{
			int x = this->GameState->Stage1.exit.x;
			int y = this->GameState->Stage1.exit.y;
			int newY = this->GameState->Bounds.minY + (x - this->GameState->Bounds.minX);
			int newX = this->GameState->Bounds.minX + ((this->GameState->Bounds.maxY-1) - y);
			Position newPos(newX + 1, newY + 1);
			g.drawCh(newPos, '%', 5);
			break;
		}
		case 2:{
			int x = this->GameState->Stage1.exit.x;
			int y = this->GameState->Stage1.exit.y;
			int newX = (this->GameState->Bounds.maxX-1) - (x - this->GameState->Bounds.minX);
			int newY = this->GameState->Bounds.minY + ((this->GameState->Bounds.maxY-1) - y);
			Position newPos(newX+1, newY+1);
			g.drawCh(newPos, '%', 5);
			break;
		}
		case 3:{
			int x = this->GameState->Stage1.exit.x;
			int y = this->GameState->Stage1.exit.y;
			int newX = (this->GameState->Bounds.maxX-1) - ((this->GameState->Bounds.maxY-1) - y);
			int newY = (this->GameState->Bounds.maxY-1) - (x - this->GameState->Bounds.minX);
			Position newPos(newX+1, newY+1);
			g.drawCh(newPos, '%', 5);
			break;
		}
		default:{
			l.writeLog("[Exit] Wrong array order: %d", (int) (this->GameState->Board.arrayOrder));
			break;
		}
	}
	return;
}<commit_msg>Removed a log message. It is no longer needed.<commit_after>#include "..\header\Exit.h"

Exit::Exit(game_state* GameState){
	LogManager& l = LogManager::getInstance();
	WorldManager& w = WorldManager::getInstance();
	setType(TYPE_EXIT);
	setTransparency();
	setSolidness(Solidness::HARD);

	GameState->Stage1.exit.x += GameState->Bounds.minX;
	GameState->Stage1.exit.y += GameState->Bounds.minY;
	Position pos(GameState->Stage1.exit.x, GameState->Stage1.exit.y);
	setPosition(pos);

	registerInterest(DF_STEP_EVENT);

	setVisible(true);

	this->GameState = GameState;
	l.writeLog("[Exit] Successfully loaded Exit.");
}

Exit::~Exit(){
	unregisterInterest(DF_STEP_EVENT);
}

int Exit::eventHandler(Event* e){
	LogManager& l = LogManager::getInstance();
	if (e->getType().compare(DF_STEP_EVENT) == 0){
		block_state* Blocks = this->GameState->Stage1.blocks;
		this->GameState->Stage1.exit.isBlocked = false;
		for (int i = 0; i<this->GameState->Stage1.blockStateSize; i++){
			if (Blocks[i].x == this->GameState->Stage1.exit.x && Blocks[i].y == this->GameState->Stage1.exit.y){
				this->GameState->Stage1.exit.isBlocked = true;
			}
		}
		return 1;
	}
	return 0;
}

void Exit::draw(){
	if (this->GameState->Board.isRotating){
		return;
	}
	if (this->GameState->Stage1.exit.isBlocked){
		return;
	}

	LogManager& l = LogManager::getInstance();
	GraphicsManager& g = GraphicsManager::getInstance();
	switch (this->GameState->Board.arrayOrder){
		case 0:{
			Position pos(this->getPosition().getX()+1, this->getPosition().getY()+1);
			g.drawCh(pos, '%', 5);
			break;
		}
		case 1:{
			int x = this->GameState->Stage1.exit.x;
			int y = this->GameState->Stage1.exit.y;
			int newY = this->GameState->Bounds.minY + (x - this->GameState->Bounds.minX);
			int newX = this->GameState->Bounds.minX + ((this->GameState->Bounds.maxY-1) - y);
			Position newPos(newX + 1, newY + 1);
			g.drawCh(newPos, '%', 5);
			break;
		}
		case 2:{
			int x = this->GameState->Stage1.exit.x;
			int y = this->GameState->Stage1.exit.y;
			int newX = (this->GameState->Bounds.maxX-1) - (x - this->GameState->Bounds.minX);
			int newY = this->GameState->Bounds.minY + ((this->GameState->Bounds.maxY-1) - y);
			Position newPos(newX+1, newY+1);
			g.drawCh(newPos, '%', 5);
			break;
		}
		case 3:{
			int x = this->GameState->Stage1.exit.x;
			int y = this->GameState->Stage1.exit.y;
			int newX = (this->GameState->Bounds.maxX-1) - ((this->GameState->Bounds.maxY-1) - y);
			int newY = (this->GameState->Bounds.maxY-1) - (x - this->GameState->Bounds.minX);
			Position newPos(newX+1, newY+1);
			g.drawCh(newPos, '%', 5);
			break;
		}
		default:{
			l.writeLog("[Exit] Wrong array order: %d", (int) (this->GameState->Board.arrayOrder));
			break;
		}
	}
	return;
}<|endoftext|>