<commit_before>// $Id$
//***************************************************************************
// File:
//	Sparc.cpp
//
// Purpose:
//
// History:
//	7/15/01	 -  Vikram Adve  -  Created
//**************************************************************************/

#include "llvm/Method.h"
#include "llvm/Instruction.h"

#include "llvm/CodeGen/LiveRange.h"
#include "llvm/CodeGen/LiveRangeInfo.h"
#include "llvm/CodeGen/Sparc.h"
#include "llvm/CodeGen/SparcRegInfo.h"

//************************ Class Implementations **************************/

//---------------------------------------------------------------------------
// UltraSparcRegInfo
// Purpose:
//   This method will color incoming args to a method. If there are more
//   args than that can fit in regs, code will be inserted to pop them from
//   stack
//---------------------------------------------------------------------------

void UltraSparcRegInfo::colorArgs(const Method *const Meth,
				  LiveRangeInfo& LRI) const
{

                                                 // get the argument list
  const Method::ArgumentListType& ArgList = Meth->getArgumentList();
                                                 // get an iterator to arg list
  Method::ArgumentListType::const_iterator ArgIt = ArgList.begin();
  unsigned intArgNo=0;

  // to keep track of which float regs are allocated for argument passing
  bool FloatArgUsedArr[NumOfFloatArgRegs];

  // init float arg used array
  for(unsigned i=0; i < NumOfFloatArgRegs; ++i)
    FloatArgUsedArr[i] = false;

  // for each argument
  for( ; ArgIt != ArgList.end() ; ++ArgIt) {

    // get the LR of arg
    LiveRange *const LR = LRI.getLiveRangeForValue((const Value *) *ArgIt);
    unsigned RegClassID = (LR->getRegClass())->getID();

    // if the arg is in int class - allocate a reg for an int arg
    if( RegClassID == IntRegClassID ) {

      if( intArgNo < NumOfIntArgRegs) {
	LR->setColor( SparcIntRegOrder::i0 + intArgNo );

	if( DEBUG_RA) printReg( LR );
      }

      else {
	// TODO: Insert push code here
	assert( 0 && "Insert push code here!");
      }
      ++intArgNo;
    }

    // if the arg is float/double
    else if ( RegClassID == FloatRegClassID) {

      if( LR->getTypeID() == Type::DoubleTyID ) {

	// find the first reg # we can pass a double arg
	for(unsigned i=0; i < NumOfFloatArgRegs; i+= 2) {
	  if ( !FloatArgUsedArr[i] && !FloatArgUsedArr[i+1] ) {
	    LR->setColor( SparcFloatRegOrder::f0 + i );
	    FloatArgUsedArr[i] = true;
	    FloatArgUsedArr[i+1] = true;
	    if( DEBUG_RA) printReg( LR );
	    break;
	  }
	}
	if( ! LR->hasColor() ) { // if LR was not colored above

	  assert(0 && "insert push code here for a double");

	}

      }
      else if( LR->getTypeID() == Type::FloatTyID ) {

	// find the first reg # we can pass a float arg
	for(unsigned i=0; i < NumOfFloatArgRegs; ++i) {
	  if ( !FloatArgUsedArr[i] ) {
	    LR->setColor( SparcFloatRegOrder::f0 + i );
	    FloatArgUsedArr[i] = true;
	    if( DEBUG_RA) printReg( LR );
	    break;
	  }
	}
	if( ! LR->hasColor() ) { // if LR was not colored above
	  assert(0 && "insert push code here for a float");
	}

      }
      else
	assert(0 && "unknown float type in method arg");

    } // float register class

    else
      assert(0 && "Unknown RegClassID");
  }

}

void UltraSparcRegInfo::printReg(const LiveRange *const LR) {

  unsigned RegClassID = (LR->getRegClass())->getID();

  cout << " *Node " << (LR->getUserIGNode())->getIndex();

  if( ! LR->hasColor() ) {
    cout << " - could not find a color" << endl;
    return;
  }

  // if a color is found

  cout << " colored with color "<< LR->getColor();

  if( RegClassID == IntRegClassID ) {

    cout<< " [" << SparcIntRegOrder::getRegName(LR->getColor()) ;
    cout << "]" << endl;
  }
  else if ( RegClassID == FloatRegClassID) {
    cout << "[" << SparcFloatRegOrder::getRegName(LR->getColor());
    if( LR->getTypeID() == Type::DoubleTyID )
      cout << "+" << SparcFloatRegOrder::getRegName(LR->getColor()+1);
    cout << "]" << endl;
  }

}

void UltraSparcRegInfo::colorCallArgs(vector<const Instruction *> &
				      CallInstrList, LiveRangeInfo& LRI ) const
{

  vector<const Instruction *>::const_iterator InstIt = CallInstrList.begin();

  for( ; InstIt != CallInstrList.end(); ++InstIt) {

    // Inst = LLVM call instruction
    const Instruction *const CallI = *InstIt;

    MachineCodeForVMInstr &  MInstVec = CallI->getMachineInstrVec();
    MachineCodeForVMInstr::const_iterator MIIt = MInstVec.begin();

    // find the CALL/JMMPL machine instruction
    for( ; MIIt != MInstVec.end() &&
	   ! getUltraSparcInfo().getInstrInfo().isCall((*MIIt)->getOpCode());
	 ++MIIt );

    assert( (MIIt != MInstVec.end())  && "CALL/JMPL not found");

    // CallMI = CALL/JMPL machine isntruction
    const MachineInstr *const CallMI = *MIIt;

    Instruction::op_const_iterator OpIt = CallI->op_begin();

    unsigned intArgNo=0;
    //unsigned NumOfCallInterfs = LR->getNumOfCallInterferences();

    // to keep track of which float regs are allocated for argument passing
    bool FloatArgUsedArr[NumOfFloatArgRegs];

    // init float arg used array
    for(unsigned i=0; i < NumOfFloatArgRegs; ++i)
      FloatArgUsedArr[i] = false;

    // go thru all the operands of LLVM instruction
    for( ; OpIt != CallI->op_end(); ++OpIt ) {

      // get the LR of call operand (parameter)
      LiveRange *const LR = LRI.getLiveRangeForValue((const Value *) *OpIt);

      if ( !LR ) {
	cout << " Warning: In call instr, no LR for arg: " ;
	printValue(*OpIt);
	cout << endl;
	continue;
      }

      unsigned RegClassID = (LR->getRegClass())->getID();

      // if the arg is in int class - allocate a reg for an int arg
      if( RegClassID == IntRegClassID ) {

	if( intArgNo < NumOfIntArgRegs) {
	  setCallArgColor( LR, SparcIntRegOrder::o0 + intArgNo );
	}

	else {
	  // TODO: Insert push code here
	  assert( 0 && "Insert push code here!");
	}
	++intArgNo;
      }

      // if the arg is float/double
      else if ( RegClassID == FloatRegClassID) {

	if( LR->getTypeID() == Type::DoubleTyID ) {

	  // find the first reg # we can pass a double arg
	  for(unsigned i=0; i < NumOfFloatArgRegs; i+= 2) {
	    if ( !FloatArgUsedArr[i] && !FloatArgUsedArr[i+1] ) {
	      setCallArgColor(LR, SparcFloatRegOrder::f0 + i );
	      FloatArgUsedArr[i] = true;
	      FloatArgUsedArr[i+1] = true;
	      //if( DEBUG_RA) printReg( LR );
	      break;
	    }
	  }
	  if( ! LR->hasColor() ) { // if LR was not colored above

	    assert(0 && "insert push code here for a double");

	  }

	}
	else if( LR->getTypeID() == Type::FloatTyID ) {

	  // find the first reg # we can pass a float arg
	  for(unsigned i=0; i < NumOfFloatArgRegs; ++i) {
	    if ( !FloatArgUsedArr[i] ) {
	      setCallArgColor(LR, SparcFloatRegOrder::f0 + i );
	      FloatArgUsedArr[i] = true;
	      // LR->setColor( SparcFloatRegOrder::f0 + i );
	      // if( DEBUG_RA) printReg( LR );
	      break;
	    }
	  }
	  if( ! LR->hasColor() ) { // if LR was not colored above
	    assert(0 && "insert push code here for a float");
	  }

	}
	else
	  assert(0 && "unknown float type in method arg");

      } // float register class

      else
	assert(0 && "Unknown RegClassID");

    } // for each operand in a call instruction

  } // for all call instrctions in CallInstrList

}

void UltraSparcRegInfo::setCallArgColor(LiveRange *const LR,
					const unsigned RegNo) const {

  // if no call interference and LR is NOT previously colored (e.g., as an
  // incoming arg)
  if( ! LR->getNumOfCallInterferences() && ! LR->hasColor() ) {
    // we can directly allocate a %o register
    LR->setColor( RegNo);
    if( DEBUG_RA) printReg( LR );
  }
  else {                        // there are call interferences

    /*
    // insert a copy machine instr to copy from LR to %o(reg)
    PreMInstrMap[ CallMI ] =
    getNewCopyMInstr( LR->,  SparcIntRegOrder::o0 + intArgNo );
    */
    cout << " $$$ TODO: Insert a copy for call argument!: " << endl;

    // We don't color LR here. It's colored as any other normal LR
  }

}

//---------------------------------------------------------------------------
// class UltraSparcInstrInfo
//
// Purpose:
//   Information about individual instructions.
//   Most information is stored in the SparcMachineInstrDesc array above.
//   Other information is computed on demand, and most such functions
//   default to member functions in base class MachineInstrInfo.
//---------------------------------------------------------------------------

/*ctor*/
UltraSparcInstrInfo::UltraSparcInstrInfo()
  : MachineInstrInfo(SparcMachineInstrDesc,
		     /*descSize = */ NUM_TOTAL_OPCODES,
		     /*numRealOpCodes = */ NUM_REAL_OPCODES)
{
}

//---------------------------------------------------------------------------
// class UltraSparcSchedInfo
//
// Purpose:
//   Scheduling information for the UltraSPARC.
//   Primarily just initializes machine-dependent parameters in
//   class MachineSchedInfo.
//---------------------------------------------------------------------------

/*ctor*/
UltraSparcSchedInfo::UltraSparcSchedInfo(const MachineInstrInfo* mii)
  : MachineSchedInfo((unsigned int) SPARC_NUM_SCHED_CLASSES,
		     mii,
		     SparcRUsageDesc,
		     SparcInstrUsageDeltas,
		     SparcInstrIssueDeltas,
		     sizeof(SparcInstrUsageDeltas)/sizeof(InstrRUsageDelta),
		     sizeof(SparcInstrIssueDeltas)/sizeof(InstrIssueDelta))
{
  maxNumIssueTotal = 4;
  longestIssueConflict = 0;		// computed from issuesGaps[]

  branchMispredictPenalty = 4;		// 4 for SPARC IIi
  branchTargetUnknownPenalty = 2;	// 2 for SPARC IIi
  l1DCacheMissPenalty = 8;		// 7 or 9 for SPARC IIi
  l1ICacheMissPenalty = 8;		// ? for SPARC IIi

  inOrderLoads = true;			// true for SPARC IIi
  inOrderIssue = true;			// true for SPARC IIi
  inOrderExec  = false;			// false for most architectures
  inOrderRetire= true;			// true for most architectures

  // must be called after above parameters are initialized.
  this->initializeResources();
}

void
UltraSparcSchedInfo::initializeResources()
{
  // Compute MachineSchedInfo::instrRUsages and MachineSchedInfo::issueGaps
  MachineSchedInfo::initializeResources();

  // Machine-dependent fixups go here.  None for now.
}

//---------------------------------------------------------------------------
// class UltraSparcMachine
//
// Purpose:
//   Primary interface to machine description for the UltraSPARC.
//   Primarily just initializes machine-dependent parameters in
//   class TargetMachine, and creates machine-dependent subclasses
//   for classes such as MachineInstrInfo.
//
//---------------------------------------------------------------------------

UltraSparc::UltraSparc()

  : TargetMachine("UltraSparc-Native")
{
  machineInstrInfo = new UltraSparcInstrInfo;
  machineSchedInfo = new UltraSparcSchedInfo(machineInstrInfo);
  machineRegInfo = new UltraSparcRegInfo(this);

  optSizeForSubWordData = 4;
  minMemOpWordSize = 8;
  maxAtomicMemOpWordSize = 8;
  zeroRegNum = 0;			// %g0 always gives 0 on Sparc
}

UltraSparc::~UltraSparc()
{
  delete (UltraSparcInstrInfo*) machineInstrInfo;
  delete (UltraSparcRegInfo*) machineRegInfo;
  delete (UltraSparcSchedInfo*) machineSchedInfo;
}

//**************************************************************************/
<commit_msg>Updates to use local header files.<commit_after>//***************************************************************************
// File:
//	Sparc.cpp
//
// Purpose:
//
// History:
//	7/15/01	 -  Vikram Adve  -  Created
//**************************************************************************/

#include "SparcInternals.h"
#include "llvm/Method.h"
#include "llvm/CodeGen/InstrScheduling.h"
#include "llvm/CodeGen/InstrSelection.h"

//---------------------------------------------------------------------------
// class UltraSparcInstrInfo
//
// Purpose:
//   Information about individual instructions.
//   Most information is stored in the SparcMachineInstrDesc array above.
//   Other information is computed on demand, and most such functions
//   default to member functions in base class MachineInstrInfo.
//---------------------------------------------------------------------------

/*ctor*/
UltraSparcInstrInfo::UltraSparcInstrInfo()
  : MachineInstrInfo(SparcMachineInstrDesc,
		     /*descSize = */ NUM_TOTAL_OPCODES,
		     /*numRealOpCodes = */ NUM_REAL_OPCODES)
{
}

//---------------------------------------------------------------------------
// class UltraSparcSchedInfo
//
// Purpose:
//   Scheduling information for the UltraSPARC.
//   Primarily just initializes machine-dependent parameters in
//   class MachineSchedInfo.
//---------------------------------------------------------------------------

/*ctor*/
UltraSparcSchedInfo::UltraSparcSchedInfo(const MachineInstrInfo* mii)
  : MachineSchedInfo((unsigned int) SPARC_NUM_SCHED_CLASSES,
		     mii,
		     SparcRUsageDesc,
		     SparcInstrUsageDeltas,
		     SparcInstrIssueDeltas,
		     sizeof(SparcInstrUsageDeltas)/sizeof(InstrRUsageDelta),
		     sizeof(SparcInstrIssueDeltas)/sizeof(InstrIssueDelta))
{
  maxNumIssueTotal = 4;
  longestIssueConflict = 0;		// computed from issuesGaps[]

  branchMispredictPenalty = 4;		// 4 for SPARC IIi
  branchTargetUnknownPenalty = 2;	// 2 for SPARC IIi
  l1DCacheMissPenalty = 8;		// 7 or 9 for SPARC IIi
  l1ICacheMissPenalty = 8;		// ? for SPARC IIi

  inOrderLoads = true;			// true for SPARC IIi
  inOrderIssue = true;			// true for SPARC IIi
  inOrderExec  = false;			// false for most architectures
  inOrderRetire= true;			// true for most architectures

  // must be called after above parameters are initialized.
  this->initializeResources();
}

void
UltraSparcSchedInfo::initializeResources()
{
  // Compute MachineSchedInfo::instrRUsages and MachineSchedInfo::issueGaps
  MachineSchedInfo::initializeResources();

  // Machine-dependent fixups go here.  None for now.
}

//---------------------------------------------------------------------------
// class UltraSparcMachine
//
// Purpose:
//   Primary interface to machine description for the UltraSPARC.
//   Primarily just initializes machine-dependent parameters in
//   class TargetMachine, and creates machine-dependent subclasses
//   for classes such as MachineInstrInfo.
//
//---------------------------------------------------------------------------

UltraSparc::UltraSparc()
  : TargetMachine("UltraSparc-Native")
{
  machineInstrInfo = new UltraSparcInstrInfo;
  machineSchedInfo = new UltraSparcSchedInfo(machineInstrInfo);

  optSizeForSubWordData = 4;
  minMemOpWordSize = 8;
  maxAtomicMemOpWordSize = 8;
  zeroRegNum = 0;			// %g0 always gives 0 on Sparc
}

UltraSparc::~UltraSparc()
{
  delete (UltraSparcInstrInfo*) machineInstrInfo;
  delete (UltraSparcSchedInfo*) machineSchedInfo;
}

bool UltraSparc::compileMethod(Method *M) {
  if (SelectInstructionsForMethod(M, *this)) {
    cerr << "Instruction selection failed for method " << M->getName()
       << "\n\n";
    return true;
  }

  if (ScheduleInstructionsWithSSA(M, *this)) {
    cerr << "Instruction scheduling before allocation failed for method "
       << M->getName() << "\n\n";
    return true;
  }
  return false;
}
<|endoftext|>


<commit_before>// Virvo - Virtual Reality Volume Rendering
// Copyright (C) 1999-2003 University of Stuttgart, 2004-2005 Brown University
// Contact: Jurgen P. Schulze, jschulze@ucsd.edu
//
// This file is part of Virvo.
//
// Virvo is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library (see license.txt); if not, write to the
// Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

#include "debug.h"

#ifdef HAVE_CUDA

#ifdef _MSC_VER
#include <Windows.h>
#endif
#include <stdio.h>
#include <stdlib.h>

namespace cu = virvo::cuda;

void cu::debug_report_error(cudaError_t err, char const* file, int line)
{
    fprintf(stderr, "%s(%d) : CUDA error: %s\n", file, line, cudaGetErrorString(err));

#ifdef _MSC_VER
    if (IsDebuggerPresent())
    {
        DebugBreak();
    }
#else
    //exit(EXIT_FAILURE);
#endif
}

void cu::debug_meminfo(char const* file, int line)
{
    size_t avail = 0;
    size_t total = 0;

    cudaError_t err = cudaMemGetInfo(&avail, &total);
    if (cudaSuccess != err)
    {
        fprintf(stderr, "%s(%d) : CUDA memory usage: cudaMemGetInfo failed: %s\n", file, line, cudaGetErrorString(err));
        return;
    }

    double davail = static_cast<double>(avail);
    double dtotal = static_cast<double>(total);

    fprintf(stdout, "%s(%d) : CUDA memory usage: %d%%\n", file, line, 100.0 * (davail / dtotal));
}

#endif // HAVE_CUDA
<commit_msg>Use printf format identifier '%e' for double<commit_after>// Virvo - Virtual Reality Volume Rendering
// Copyright (C) 1999-2003 University of Stuttgart, 2004-2005 Brown University
// Contact: Jurgen P. Schulze, jschulze@ucsd.edu
//
// This file is part of Virvo.
//
// Virvo is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library (see license.txt); if not, write to the
// Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

#include "debug.h"

#ifdef HAVE_CUDA

#ifdef _MSC_VER
#include <Windows.h>
#endif
#include <stdio.h>
#include <stdlib.h>

namespace cu = virvo::cuda;

void cu::debug_report_error(cudaError_t err, char const* file, int line)
{
    fprintf(stderr, "%s(%d) : CUDA error: %s\n", file, line, cudaGetErrorString(err));

#ifdef _MSC_VER
    if (IsDebuggerPresent())
    {
        DebugBreak();
    }
#else
    //exit(EXIT_FAILURE);
#endif
}

void cu::debug_meminfo(char const* file, int line)
{
    size_t avail = 0;
    size_t total = 0;

    cudaError_t err = cudaMemGetInfo(&avail, &total);
    if (cudaSuccess != err)
    {
        fprintf(stderr, "%s(%d) : CUDA memory usage: cudaMemGetInfo failed: %s\n", file, line, cudaGetErrorString(err));
        return;
    }

    double davail = static_cast<double>(avail);
    double dtotal = static_cast<double>(total);

    fprintf(stdout, "%s(%d) : CUDA memory usage: %e%%\n", file, line, 100.0 * (davail / dtotal));
}

#endif // HAVE_CUDA
<|endoftext|>


<commit_before>/* -*-  mode: c++; c-default-style: "google"; indent-tabs-mode: nil -*- */
/* -------------------------------------------------------------------------
ATS

License: see $ATS_DIR/COPYRIGHT
Author: Ethan Coon

Implementation for the Coordinator.  Coordinator is basically just a class to hold
the cycle driver, which runs the overall, top level timestep loop.  It
instantiates states, ensures they are initialized, and runs the timestep loop
including Vis and restart/checkpoint dumps.  It contains one and only one PK
-- most likely this PK is an MPC of some type -- to do the actual work.
------------------------------------------------------------------------- */

#include <iostream>
#include "errors.hh"

#include "coordinator.hh"

namespace Amanzi {

Coordinator::Coordinator(Teuchos::ParameterList parameter_list,
                         Teuchos::RCP<Amanzi::AmanziMesh::Mesh>& mesh,
                         Epetra_MpiComm* comm ) :
  parameter_list_(parameter_list),
  mesh_(mesh),
  comm_(comm) {
  coordinator_init();
};

void Coordinator::coordinator_init() {
  coordinator_plist_ = parameter_list_.sublist("Coordinator");
  read_parameter_list();

  // create the state object
  Teuchos::ParameterList state_plist = parameter_list_.sublist("State");
  S_ = Teuchos::rcp(new State(state_plist));
  S_->RegisterDomainMesh(mesh_);

  // checkpointing for the state
  Teuchos::ParameterList chkp_plist = parameter_list_.sublist("Checkpoint");
  checkpoint_ = Teuchos::rcp(new Checkpoint(chkp_plist, comm_));

  // create the top level PK
  Teuchos::ParameterList pks_list = parameter_list_.sublist("PKs");
  Teuchos::ParameterList::ConstIterator pk_item = pks_list.begin();

  const std::string &pk_name = pks_list.name(pk_item);
  const Teuchos::ParameterEntry &pk_value = pks_list.entry(pk_item);

  // -- create the solution
  soln_ = Teuchos::rcp(new TreeVector(pk_name));

  // -- create the pk
  PKFactory pk_factory;
  pk_ = pk_factory.CreatePK(pks_list.sublist(pk_name), S_, soln_);
  pk_->set_name(pk_name);

  // // create the observations
  // Teuchos::ParameterList observation_plist = parameter_list_.sublist("Observation");
  // observations_ = Teuchos::rcp(new UnstructuredObservations(observation_plist,
  //         output_observations_));
}

void Coordinator::initialize() {
  // Set up the state, creating all data structures.
  S_->Setup();

  // Initialize the process kernels (initializes all independent variables)
  pk_->initialize(S_);

  // Initialize the state (initializes all dependent variables).
  S_->Initialize();

  // vis for the state
  // HACK to vis with a surrogate surface mesh.  This needs serious re-design. --etc
  bool surface_done = false;
  if (S_->HasMesh("surface") && S_->HasMesh("surface_3d")) {
    Teuchos::RCP<const AmanziMesh::Mesh> surface_3d = S_->GetMesh("surface_3d");
    Teuchos::RCP<const AmanziMesh::Mesh> surface = S_->GetMesh("surface");

    std::string plist_name = "Visualization surface";
    Teuchos::ParameterList& vis_plist = parameter_list_.sublist(plist_name);
    Teuchos::RCP<Visualization> vis = Teuchos::rcp(new Visualization(vis_plist, comm_));
    vis->set_mesh(surface_3d);
    vis->CreateFiles();
    vis->set_mesh(surface);
    visualization_.push_back(vis);
    S_->RemoveMesh("surface_3d");
    surface_done = true;
  }
  for (State::mesh_iterator mesh=S_->mesh_begin();
       mesh!=S_->mesh_end(); ++mesh) {
    if (mesh->first == "surface_3d") {
      // pass
    } else if ((mesh->first == "surface") && surface_done) {
      // pass
    } else {
      std::string plist_name = "Visualization "+mesh->first;
      Teuchos::ParameterList& vis_plist = parameter_list_.sublist(plist_name);
      vis_plist.set<std::string>("File Name Base",mesh->first);
      Teuchos::RCP<Visualization> vis =
        Teuchos::rcp(new Visualization(vis_plist, comm_));
      vis->set_mesh(mesh->second);
      vis->CreateFiles();
      visualization_.push_back(vis);
    }
  }
}

void Coordinator::read_parameter_list() {
  t0_ = coordinator_plist_.get<double>("Start Time");
  t1_ = coordinator_plist_.get<double>("End Time");
  string t0_units = coordinator_plist_.get<string>("Start Time Units", "s");
  string t1_units = coordinator_plist_.get<string>("End Time Units", "s");

  if (t0_units == "s") {
    // internal units in s
  } else if (t0_units == "d") { // days
    t0_ = t0_ * 24.0*3600.0;
  } else if (t0_units == "yr") { // years
    t0_ = t0_ * 365.25*24.0*3600.0;
  } else {
    Errors::Message message("Coordinator: error, invalid start time units");
    Exceptions::amanzi_throw(message);
  }

  if (t1_units == "s") {
    // internal units in s
  } else if (t1_units == "d") { // days
    t1_ = t1_ * 24.0*3600.0;
  } else if (t1_units == "yr") { // years
    t1_ = t1_ * 365.25*24.0*3600.0;
  } else {
    Errors::Message message("Coordinator: error, invalid end time units");
    Exceptions::amanzi_throw(message);
  }

  max_dt_ = coordinator_plist_.get<double>("Max Time Step Size", 1.0e99);
  min_dt_ = coordinator_plist_.get<double>("Min Time Step Size", 1.0e-12);
  end_cycle_ = coordinator_plist_.get<int>("End Cycle",-1);
}

// -----------------------------------------------------------------------------
// timestep loop
// -----------------------------------------------------------------------------
void Coordinator::cycle_driver() {
  // start at time t = t0 and initialize the state.  In a flow steady-state
  // problem, this should include advancing flow to steady state (which should
  // be done by flow_pk->initialize_state(S)
  S_->set_time(t0_);
  S_->set_cycle(0);
  initialize();
  S_->set_time(t0_); // in case steady state solve changed this
  S_->set_cycle(0);

  // the time step manager coordinates all non-physical timesteps
  Teuchos::Ptr<TimeStepManager> tsm = Teuchos::ptr(new TimeStepManager());

  // register times with the tsm
  // -- register visualization times
  for (std::vector<Teuchos::RCP<Visualization> >::iterator vis=visualization_.begin();
       vis!=visualization_.end(); ++vis) {
    (*vis)->RegisterWithTimeStepManager(tsm);
  }

  // -- register observation times
  //if (observations_) observations_->register_with_time_step_manager(TSM);
  // -- register the final time
  tsm->RegisterTimeEvent(t1_);

  // make observations
  //  observations_->MakeObservations(*S_);

  // write visualization if requested at IC
  pk_->calculate_diagnostics(S_);
  for (std::vector<Teuchos::RCP<Visualization> >::iterator vis=visualization_.begin();
       vis!=visualization_.end(); ++vis) {
    WriteVis((*vis).ptr(), S_.ptr());
  }

  // we need to create an intermediate state that will store the updated
  // solution until we know it has succeeded
  S_next_ = Teuchos::rcp(new State(*S_));
  *S_next_ = *S_;

  // set the states in the PKs
  Teuchos::RCP<const State> cS = S_; // ensure PKs get const reference state
  pk_->set_states(cS, S_, S_next_); // note this does not allow subcycling

  // iterate process kernels
  double dt;
  bool fail = false;
  while ((S_->time() < t1_) && ((end_cycle_ == -1) || (S_->cycle() <= end_cycle_))) {
    // get the physical step size
    dt = pk_->get_dt();

    // check if the step size has gotten too small
    if (dt < min_dt_) {
      Errors::Message message("Coordinator: error, timestep too small");
      Exceptions::amanzi_throw(message);
    }

    // cap the max step size
    if (dt > max_dt_) {
      dt = max_dt_;
    }

    // ask the step manager if this step is ok
    dt = tsm->TimeStep(S_->time(), dt);

    if (comm_->MyPID() == 0) {
      std::cout << "Cycle = " << S_->cycle();
      std::cout << ",  Time [days] = "<< S_->time() / (60*60*24);
      std::cout << ",  dt [days] = " << dt / (60*60*24)  << std::endl;
    }

    // advance
    S_next_->advance_time(dt);
    fail = pk_->advance(dt);

    // advance the iteration count
    S_next_->advance_cycle();

    if (!fail) {
      // make observations
      //      observations_->MakeObservations(*S_next_);

      // write visualization if requested
      // this needs to be fixed...
      bool dump = false;
      for (std::vector<Teuchos::RCP<Visualization> >::iterator vis=visualization_.begin();
           vis!=visualization_.end(); ++vis) {
        if ((*vis)->DumpRequested(S_next_->cycle(), S_next_->time())) {
          dump = true;
        }
      }
      if (dump) {
        pk_->calculate_diagnostics(S_next_);
      }

      for (std::vector<Teuchos::RCP<Visualization> >::iterator vis=visualization_.begin();
           vis!=visualization_.end(); ++vis) {
        if ((*vis)->DumpRequested(S_next_->cycle(), S_next_->time())) {
          WriteVis((*vis).ptr(), S_next_.ptr());
        }
      }

      WriteCheckpoint(checkpoint_.ptr(), S_next_.ptr());

      // write restart dump if requested
      // restart->dump_state(*S_next_);

      // we're done with this time step, copy the state
      *S_ = *S_next_;
    } else {
      // Failed the timestep.  The timestep sizes have been updated, so we can
      // try again.
      *S_next_ = *S_;
    }
  } // while not finished

  // force visualization and checkpoint at the end of simulation
  // this needs to be fixed -- should not force, but ask if we want to checkpoint/vis at end
  S_next_->advance_cycle(); // hackery to make the vis stop whining
  pk_->calculate_diagnostics(S_next_);

  for (std::vector<Teuchos::RCP<Visualization> >::iterator vis=visualization_.begin();
       vis!=visualization_.end(); ++vis) {
    WriteVis((*vis).ptr(), S_next_.ptr());
  }

  WriteCheckpoint(checkpoint_.ptr(), S_next_.ptr());

  // dump observations
  //  output_observations_.print(std::cout);
} // cycle driver

} // close namespace Amanzi
<commit_msg>bug fix to get darcy flux again<commit_after>/* -*-  mode: c++; c-default-style: "google"; indent-tabs-mode: nil -*- */
/* -------------------------------------------------------------------------
ATS

License: see $ATS_DIR/COPYRIGHT
Author: Ethan Coon

Implementation for the Coordinator.  Coordinator is basically just a class to hold
the cycle driver, which runs the overall, top level timestep loop.  It
instantiates states, ensures they are initialized, and runs the timestep loop
including Vis and restart/checkpoint dumps.  It contains one and only one PK
-- most likely this PK is an MPC of some type -- to do the actual work.
------------------------------------------------------------------------- */

#include <iostream>
#include "errors.hh"

#include "coordinator.hh"

namespace Amanzi {

Coordinator::Coordinator(Teuchos::ParameterList parameter_list,
                         Teuchos::RCP<Amanzi::AmanziMesh::Mesh>& mesh,
                         Epetra_MpiComm* comm ) :
  parameter_list_(parameter_list),
  mesh_(mesh),
  comm_(comm) {
  coordinator_init();
};

void Coordinator::coordinator_init() {
  coordinator_plist_ = parameter_list_.sublist("Coordinator");
  read_parameter_list();

  // create the state object
  Teuchos::ParameterList state_plist = parameter_list_.sublist("State");
  S_ = Teuchos::rcp(new State(state_plist));
  S_->RegisterDomainMesh(mesh_);

  // checkpointing for the state
  Teuchos::ParameterList chkp_plist = parameter_list_.sublist("Checkpoint");
  checkpoint_ = Teuchos::rcp(new Checkpoint(chkp_plist, comm_));

  // create the top level PK
  Teuchos::ParameterList pks_list = parameter_list_.sublist("PKs");
  Teuchos::ParameterList::ConstIterator pk_item = pks_list.begin();

  const std::string &pk_name = pks_list.name(pk_item);
  const Teuchos::ParameterEntry &pk_value = pks_list.entry(pk_item);

  // -- create the solution
  soln_ = Teuchos::rcp(new TreeVector(pk_name));

  // -- create the pk
  PKFactory pk_factory;
  pk_ = pk_factory.CreatePK(pks_list.sublist(pk_name), S_, soln_);
  pk_->set_name(pk_name);

  // // create the observations
  // Teuchos::ParameterList observation_plist = parameter_list_.sublist("Observation");
  // observations_ = Teuchos::rcp(new UnstructuredObservations(observation_plist,
  //         output_observations_));
}

void Coordinator::initialize() {
  // Set up the state, creating all data structures.
  S_->Setup();

  // Initialize the process kernels (initializes all independent variables)
  pk_->initialize(S_);

  // Initialize the state (initializes all dependent variables).
  S_->Initialize();

  // commit the initial conditions.
  pk_->commit_state(0., S_);

  // vis for the state
  // HACK to vis with a surrogate surface mesh.  This needs serious re-design. --etc
  bool surface_done = false;
  if (S_->HasMesh("surface") && S_->HasMesh("surface_3d")) {
    Teuchos::RCP<const AmanziMesh::Mesh> surface_3d = S_->GetMesh("surface_3d");
    Teuchos::RCP<const AmanziMesh::Mesh> surface = S_->GetMesh("surface");

    std::string plist_name = "Visualization surface";
    Teuchos::ParameterList& vis_plist = parameter_list_.sublist(plist_name);
    Teuchos::RCP<Visualization> vis = Teuchos::rcp(new Visualization(vis_plist, comm_));
    vis->set_mesh(surface_3d);
    vis->CreateFiles();
    vis->set_mesh(surface);
    visualization_.push_back(vis);
    S_->RemoveMesh("surface_3d");
    surface_done = true;
  }
  for (State::mesh_iterator mesh=S_->mesh_begin();
       mesh!=S_->mesh_end(); ++mesh) {
    if (mesh->first == "surface_3d") {
      // pass
    } else if ((mesh->first == "surface") && surface_done) {
      // pass
    } else {
      std::string plist_name = "Visualization "+mesh->first;
      Teuchos::ParameterList& vis_plist = parameter_list_.sublist(plist_name);
      vis_plist.set<std::string>("File Name Base",mesh->first);
      Teuchos::RCP<Visualization> vis =
        Teuchos::rcp(new Visualization(vis_plist, comm_));
      vis->set_mesh(mesh->second);
      vis->CreateFiles();
      visualization_.push_back(vis);
    }
  }
}

void Coordinator::read_parameter_list() {
  t0_ = coordinator_plist_.get<double>("Start Time");
  t1_ = coordinator_plist_.get<double>("End Time");
  string t0_units = coordinator_plist_.get<string>("Start Time Units", "s");
  string t1_units = coordinator_plist_.get<string>("End Time Units", "s");

  if (t0_units == "s") {
    // internal units in s
  } else if (t0_units == "d") { // days
    t0_ = t0_ * 24.0*3600.0;
  } else if (t0_units == "yr") { // years
    t0_ = t0_ * 365.25*24.0*3600.0;
  } else {
    Errors::Message message("Coordinator: error, invalid start time units");
    Exceptions::amanzi_throw(message);
  }

  if (t1_units == "s") {
    // internal units in s
  } else if (t1_units == "d") { // days
    t1_ = t1_ * 24.0*3600.0;
  } else if (t1_units == "yr") { // years
    t1_ = t1_ * 365.25*24.0*3600.0;
  } else {
    Errors::Message message("Coordinator: error, invalid end time units");
    Exceptions::amanzi_throw(message);
  }

  max_dt_ = coordinator_plist_.get<double>("Max Time Step Size", 1.0e99);
  min_dt_ = coordinator_plist_.get<double>("Min Time Step Size", 1.0e-12);
  end_cycle_ = coordinator_plist_.get<int>("End Cycle",-1);
}

// -----------------------------------------------------------------------------
// timestep loop
// -----------------------------------------------------------------------------
void Coordinator::cycle_driver() {
  // start at time t = t0 and initialize the state.  In a flow steady-state
  // problem, this should include advancing flow to steady state (which should
  // be done by flow_pk->initialize_state(S)
  S_->set_time(t0_);
  S_->set_cycle(0);
  initialize();
  S_->set_time(t0_); // in case steady state solve changed this
  S_->set_cycle(0);

  // the time step manager coordinates all non-physical timesteps
  Teuchos::Ptr<TimeStepManager> tsm = Teuchos::ptr(new TimeStepManager());

  // register times with the tsm
  // -- register visualization times
  for (std::vector<Teuchos::RCP<Visualization> >::iterator vis=visualization_.begin();
       vis!=visualization_.end(); ++vis) {
    (*vis)->RegisterWithTimeStepManager(tsm);
  }

  // -- register observation times
  //if (observations_) observations_->register_with_time_step_manager(TSM);
  // -- register the final time
  tsm->RegisterTimeEvent(t1_);

  // make observations
  //  observations_->MakeObservations(*S_);

  // write visualization if requested at IC
  pk_->calculate_diagnostics(S_);
  for (std::vector<Teuchos::RCP<Visualization> >::iterator vis=visualization_.begin();
       vis!=visualization_.end(); ++vis) {
    WriteVis((*vis).ptr(), S_.ptr());
  }

  // we need to create an intermediate state that will store the updated
  // solution until we know it has succeeded
  S_next_ = Teuchos::rcp(new State(*S_));
  *S_next_ = *S_;

  // set the states in the PKs
  Teuchos::RCP<const State> cS = S_; // ensure PKs get const reference state
  pk_->set_states(cS, S_, S_next_); // note this does not allow subcycling

  // iterate process kernels
  double dt;
  bool fail = false;
  while ((S_->time() < t1_) && ((end_cycle_ == -1) || (S_->cycle() <= end_cycle_))) {
    // get the physical step size
    dt = pk_->get_dt();

    // check if the step size has gotten too small
    if (dt < min_dt_) {
      Errors::Message message("Coordinator: error, timestep too small");
      Exceptions::amanzi_throw(message);
    }

    // cap the max step size
    if (dt > max_dt_) {
      dt = max_dt_;
    }

    // ask the step manager if this step is ok
    dt = tsm->TimeStep(S_->time(), dt);

    if (comm_->MyPID() == 0) {
      std::cout << "Cycle = " << S_->cycle();
      std::cout << ",  Time [days] = "<< S_->time() / (60*60*24);
      std::cout << ",  dt [days] = " << dt / (60*60*24)  << std::endl;
    }

    // advance
    S_next_->advance_time(dt);
    fail = pk_->advance(dt);

    // advance the iteration count
    S_next_->advance_cycle();

    if (!fail) {
      // make observations
      //      observations_->MakeObservations(*S_next_);

      // write visualization if requested
      // this needs to be fixed...
      bool dump = false;
      for (std::vector<Teuchos::RCP<Visualization> >::iterator vis=visualization_.begin();
           vis!=visualization_.end(); ++vis) {
        if ((*vis)->DumpRequested(S_next_->cycle(), S_next_->time())) {
          dump = true;
        }
      }
      if (dump) {
        pk_->calculate_diagnostics(S_next_);
      }

      for (std::vector<Teuchos::RCP<Visualization> >::iterator vis=visualization_.begin();
           vis!=visualization_.end(); ++vis) {
        if ((*vis)->DumpRequested(S_next_->cycle(), S_next_->time())) {
          WriteVis((*vis).ptr(), S_next_.ptr());
        }
      }

      WriteCheckpoint(checkpoint_.ptr(), S_next_.ptr());

      // write restart dump if requested
      // restart->dump_state(*S_next_);

      // we're done with this time step, copy the state
      *S_ = *S_next_;
    } else {
      // Failed the timestep.  The timestep sizes have been updated, so we can
      // try again.
      *S_next_ = *S_;
    }
  } // while not finished

  // force visualization and checkpoint at the end of simulation
  // this needs to be fixed -- should not force, but ask if we want to checkpoint/vis at end
  S_next_->advance_cycle(); // hackery to make the vis stop whining
  pk_->calculate_diagnostics(S_next_);

  for (std::vector<Teuchos::RCP<Visualization> >::iterator vis=visualization_.begin();
       vis!=visualization_.end(); ++vis) {
    WriteVis((*vis).ptr(), S_next_.ptr());
  }

  WriteCheckpoint(checkpoint_.ptr(), S_next_.ptr());

  // dump observations
  //  output_observations_.print(std::cout);
} // cycle driver

} // close namespace Amanzi
<|endoftext|>


<commit_before>#include "vm/vm.hpp"
#include "arguments.hpp"
#include "dispatch.hpp"
#include "configuration.hpp"

#include "instruments/rbxti-internal.hpp"
#include "instruments/tooling.hpp"

#include "builtin/compiledmethod.hpp"
#include "builtin/block_environment.hpp"
#include "builtin/variable_scope.hpp"
#include "builtin/system.hpp"

namespace rubinius {
namespace tooling {

  ToolBroker::ToolBroker()
    : tool_ids_(0)
    , global_tool_data_(0)
    , results_func_(0)
    , enable_func_(0)
    , enter_method_func_(0)
    , leave_method_func_(0)
    , enter_block_func_(0)
    , leave_block_func_(0)
    , enter_gc_func_(0)
    , leave_gc_func_(0)
    , enter_script_func_(0)
    , leave_script_func_(0)
    , thread_start_func_(0)
    , thread_stop_func_(0)
    , shutdown_func_(0)
  {}

  void ToolBroker::enable(STATE) {
    if(!enable_func_) return;

    state->shared.config.jit_disabled.set("true");
    System::vm_deoptimize_all(state, Qtrue);

    enable_func_(state->tooling_env());
  }

  bool ToolBroker::available(STATE) {
    if(enable_func_) return true;
    return false;
  }

  Object* ToolBroker::results(STATE) {
    if(!results_func_) return Qnil;

    state->shared.config.jit_disabled.set("false");

    // This finds all the methods again and this time makes them available
    // for JIT.
    System::vm_deoptimize_all(state, Qfalse);

    return rbxti::s(results_func_(state->tooling_env()));
  }

  void* ToolBroker::enter_method(STATE, Executable* exec, Module* o_mod,
                                 Arguments& args, CompiledMethod* cm)
  {
    if(!enter_method_func_) return 0;

    rbxti::robject recv = rbxti::s(args.recv());
    rbxti::rsymbol name = rbxti::o(args.name());
    rbxti::rmodule mod =  rbxti::o(o_mod);
    rbxti::rmethod meth = rbxti::o(cm);

    return enter_method_func_(state->tooling_env(), recv, name, mod, meth);
  }

  void ToolBroker::leave_method(STATE, void* tag)
  {
    if(!leave_method_func_) return;

    leave_method_func_(state->tooling_env(), tag);
  }

  void* ToolBroker::enter_block(STATE, BlockEnvironment* env, Module* i_mod)
  {
    if(!enter_block_func_) return 0;

    rbxti::rsymbol name = rbxti::o(env->top_scope()->method()->name());
    rbxti::rmodule mod =  rbxti::o(i_mod);
    rbxti::rmethod meth = rbxti::o(env->code());

    return enter_block_func_(state->tooling_env(), name, mod, meth);
  }

  void ToolBroker::leave_block(STATE, void* tag)
  {
    if(!leave_block_func_) return;
    leave_block_func_(state->tooling_env(), tag);
  }

  void* ToolBroker::enter_gc(STATE, int level)
  {
    if(!enter_gc_func_) return 0;
    return enter_gc_func_(state->tooling_env(), level);
  }

  void ToolBroker::leave_gc(STATE, void* tag)
  {
    if(!leave_gc_func_) return;
    leave_gc_func_(state->tooling_env(), tag);
  }

  void* ToolBroker::enter_script(STATE, CompiledMethod* cm)
  {
    if(!enter_script_func_) return 0;

    rbxti::rmethod meth = rbxti::o(cm);

    return enter_script_func_(state->tooling_env(), meth);
  }

  void  ToolBroker::leave_script(STATE, void* tag)
  {
    if(!leave_script_func_) return;
    leave_script_func_(state->tooling_env(), tag);
  }

  void ToolBroker::shutdown(STATE) {
    if(!shutdown_func_) return;
    shutdown_func_(state->tooling_env());
  }

  void ToolBroker::thread_start(STATE) {
    if(!thread_start_func_) return;
    thread_start_func_(state->tooling_env());
  }

  void ToolBroker::thread_stop(STATE) {
    if(!thread_stop_func_) return;
    thread_stop_func_(state->tooling_env());
  }

  void ToolBroker::set_tool_results(rbxti::results_func func) {
    results_func_ = func;
  }

  void ToolBroker::set_tool_enable(rbxti::enable_func func) {
    enable_func_ = func;
  }

  void ToolBroker::set_tool_enter_method(rbxti::enter_method func) {
    enter_method_func_ = func;
  }

  void ToolBroker::set_tool_leave_method(rbxti::leave_func func) {
    leave_method_func_ = func;
  }

  void ToolBroker::set_tool_enter_block(rbxti::enter_block func)
  {
    enter_block_func_ = func;
  }

  void ToolBroker::set_tool_leave_block(rbxti::leave_func func)
  {
    leave_block_func_ = func;
  }

  void ToolBroker::set_tool_enter_gc(rbxti::enter_gc func)
  {
    enter_gc_func_ = func;
  }

  void ToolBroker::set_tool_leave_gc(rbxti::leave_func func)
  {
    leave_gc_func_ = func;
  }

  void ToolBroker::set_tool_enter_script(rbxti::enter_script func)
  {
    enter_script_func_ = func;
  }

  void ToolBroker::set_tool_leave_script(rbxti::leave_func func)
  {
    leave_script_func_ = func;
  }

  void ToolBroker::set_tool_shutdown(rbxti::shutdown_func func) {
    shutdown_func_ = func;
  }

  void ToolBroker::set_tool_thread_start(rbxti::thread_start_func func) {
    thread_start_func_ = func;
  }

  void ToolBroker::set_tool_thread_stop(rbxti::thread_stop_func func) {
    thread_stop_func_ = func;
  }

}
}
<commit_msg>Fix profiling shutdown timing<commit_after>#include "vm/vm.hpp"
#include "arguments.hpp"
#include "dispatch.hpp"
#include "configuration.hpp"

#include "instruments/rbxti-internal.hpp"
#include "instruments/tooling.hpp"

#include "builtin/compiledmethod.hpp"
#include "builtin/block_environment.hpp"
#include "builtin/variable_scope.hpp"
#include "builtin/system.hpp"

namespace rubinius {
namespace tooling {

  ToolBroker::ToolBroker()
    : tool_ids_(0)
    , global_tool_data_(0)
    , results_func_(0)
    , enable_func_(0)
    , enter_method_func_(0)
    , leave_method_func_(0)
    , enter_block_func_(0)
    , leave_block_func_(0)
    , enter_gc_func_(0)
    , leave_gc_func_(0)
    , enter_script_func_(0)
    , leave_script_func_(0)
    , thread_start_func_(0)
    , thread_stop_func_(0)
    , shutdown_func_(0)
  {}

  void ToolBroker::enable(STATE) {
    if(!enable_func_) return;

    state->shared.config.jit_disabled.set("true");
    System::vm_deoptimize_all(state, Qtrue);

    enable_func_(state->tooling_env());
  }

  bool ToolBroker::available(STATE) {
    if(enable_func_) return true;
    return false;
  }

  Object* ToolBroker::results(STATE) {
    if(!results_func_) return Qnil;

    state->shared.config.jit_disabled.set("false");

    Object* res = rbxti::s(results_func_(state->tooling_env()));

    // This finds all the methods again and this time makes them available
    // for JIT.
    System::vm_deoptimize_all(state, Qfalse);

    return res;
  }

  void* ToolBroker::enter_method(STATE, Executable* exec, Module* o_mod,
                                 Arguments& args, CompiledMethod* cm)
  {
    if(!enter_method_func_) return 0;

    rbxti::robject recv = rbxti::s(args.recv());
    rbxti::rsymbol name = rbxti::o(args.name());
    rbxti::rmodule mod =  rbxti::o(o_mod);
    rbxti::rmethod meth = rbxti::o(cm);

    return enter_method_func_(state->tooling_env(), recv, name, mod, meth);
  }

  void ToolBroker::leave_method(STATE, void* tag)
  {
    if(!leave_method_func_) return;

    leave_method_func_(state->tooling_env(), tag);
  }

  void* ToolBroker::enter_block(STATE, BlockEnvironment* env, Module* i_mod)
  {
    if(!enter_block_func_) return 0;

    rbxti::rsymbol name = rbxti::o(env->top_scope()->method()->name());
    rbxti::rmodule mod =  rbxti::o(i_mod);
    rbxti::rmethod meth = rbxti::o(env->code());

    return enter_block_func_(state->tooling_env(), name, mod, meth);
  }

  void ToolBroker::leave_block(STATE, void* tag)
  {
    if(!leave_block_func_) return;
    leave_block_func_(state->tooling_env(), tag);
  }

  void* ToolBroker::enter_gc(STATE, int level)
  {
    if(!enter_gc_func_) return 0;
    return enter_gc_func_(state->tooling_env(), level);
  }

  void ToolBroker::leave_gc(STATE, void* tag)
  {
    if(!leave_gc_func_) return;
    leave_gc_func_(state->tooling_env(), tag);
  }

  void* ToolBroker::enter_script(STATE, CompiledMethod* cm)
  {
    if(!enter_script_func_) return 0;

    rbxti::rmethod meth = rbxti::o(cm);

    return enter_script_func_(state->tooling_env(), meth);
  }

  void  ToolBroker::leave_script(STATE, void* tag)
  {
    if(!leave_script_func_) return;
    leave_script_func_(state->tooling_env(), tag);
  }

  void ToolBroker::shutdown(STATE) {
    if(!shutdown_func_) return;
    shutdown_func_(state->tooling_env());
  }

  void ToolBroker::thread_start(STATE) {
    if(!thread_start_func_) return;
    thread_start_func_(state->tooling_env());
  }

  void ToolBroker::thread_stop(STATE) {
    if(!thread_stop_func_) return;
    thread_stop_func_(state->tooling_env());
  }

  void ToolBroker::set_tool_results(rbxti::results_func func) {
    results_func_ = func;
  }

  void ToolBroker::set_tool_enable(rbxti::enable_func func) {
    enable_func_ = func;
  }

  void ToolBroker::set_tool_enter_method(rbxti::enter_method func) {
    enter_method_func_ = func;
  }

  void ToolBroker::set_tool_leave_method(rbxti::leave_func func) {
    leave_method_func_ = func;
  }

  void ToolBroker::set_tool_enter_block(rbxti::enter_block func)
  {
    enter_block_func_ = func;
  }

  void ToolBroker::set_tool_leave_block(rbxti::leave_func func)
  {
    leave_block_func_ = func;
  }

  void ToolBroker::set_tool_enter_gc(rbxti::enter_gc func)
  {
    enter_gc_func_ = func;
  }

  void ToolBroker::set_tool_leave_gc(rbxti::leave_func func)
  {
    leave_gc_func_ = func;
  }

  void ToolBroker::set_tool_enter_script(rbxti::enter_script func)
  {
    enter_script_func_ = func;
  }

  void ToolBroker::set_tool_leave_script(rbxti::leave_func func)
  {
    leave_script_func_ = func;
  }

  void ToolBroker::set_tool_shutdown(rbxti::shutdown_func func) {
    shutdown_func_ = func;
  }

  void ToolBroker::set_tool_thread_start(rbxti::thread_start_func func) {
    thread_start_func_ = func;
  }

  void ToolBroker::set_tool_thread_stop(rbxti::thread_stop_func func) {
    thread_stop_func_ = func;
  }

}
}
<|endoftext|>


<commit_before>/*
 * Connection pooling for the translation server.
 *
 * author: Max Kellermann <mk@cm4all.com>
 */

#include "tstock.hxx"
#include "TranslateHandler.hxx"
#include "translate_client.hxx"
#include "stock/Stock.hxx"
#include "stock/Class.hxx"
#include "stock/Item.hxx"
#include "stock/GetHandler.hxx"
#include "lease.hxx"
#include "pool.hxx"
#include "gerrno.h"
#include "net/AllocatedSocketAddress.hxx"
#include "net/SocketDescriptor.hxx"
#include "event/Event.hxx"
#include "event/Callback.hxx"

#include <daemon/log.h>

#include <string.h>
#include <errno.h>

class TranslateConnection final : public PoolStockItem {
    SocketDescriptor s;

    Event event;

public:
    explicit TranslateConnection(struct pool &_pool, CreateStockItem c)
        :PoolStockItem(_pool, c) {}

    ~TranslateConnection() override {
        if (s.IsDefined())
            event.Delete();
    }

private:
    bool CreateAndConnect(SocketAddress address) {
        assert(!s.IsDefined());

        return s.Create(AF_LOCAL, SOCK_STREAM, 0) &&
            s.Connect(address);
    }

public:
    void CreateAndConnectAndFinish(SocketAddress address) {
        if (CreateAndConnect(address)) {
            event.Set(s.Get(), EV_READ,
                      MakeSimpleEventCallback(TranslateConnection,
                                              EventCallback), this);
            InvokeCreateSuccess();
        } else {
            auto error = new_error_errno();

            if (s.IsDefined())
                s.Close();

            InvokeCreateError(error);
        }
    }

    int GetSocket() {
        return s.Get();
    }

private:
    void EventCallback() {
        char buffer;
        ssize_t nbytes = recv(s.Get(), &buffer, sizeof(buffer), MSG_DONTWAIT);
        if (nbytes < 0)
            daemon_log(2, "error on idle translation server connection: %s\n",
                       strerror(errno));
        else if (nbytes > 0)
            daemon_log(2, "unexpected data in idle translation server connection\n");

        InvokeIdleDisconnect();
        pool_commit();
    }

public:
    /* virtual methods from class StockItem */
    bool Borrow(gcc_unused void *ctx) override {
        event.Delete();
        return true;
    }

    bool Release(gcc_unused void *ctx) override {
        event.Add();
        return true;
    }
};

static void
tstock_create(gcc_unused void *ctx,
              struct pool &parent_pool, CreateStockItem c,
              gcc_unused const char *uri, void *info,
              gcc_unused struct pool &caller_pool,
              gcc_unused struct async_operation_ref &async_ref)
{
    const auto &address = *(const AllocatedSocketAddress *)info;

    auto &pool = *pool_new_linear(&parent_pool, "tstock", 512);
    auto *connection = NewFromPool<TranslateConnection>(pool, pool, c);
    connection->CreateAndConnectAndFinish(address);
}

static constexpr StockClass tstock_class = {
    .create = tstock_create,
};

class TranslateStock {
    Stock *const stock;

    AllocatedSocketAddress address;

public:
    TranslateStock(struct pool &p, const char *path, unsigned limit)
        :stock(new Stock(p, tstock_class, nullptr, nullptr, limit, 8)) {
        address.SetLocal(path);
    }

    ~TranslateStock() {
        delete stock;
    }

    void Get(struct pool &pool, StockGetHandler &handler,
             struct async_operation_ref &async_ref) {
        stock->Get(pool, &address, handler, async_ref);
    }

    void Put(StockItem &item, bool destroy) {
        stock->Put(item, destroy);
    }
};

class TranslateStockRequest final : public StockGetHandler, Lease {
    struct pool &pool;

    TranslateStock &stock;
    TranslateConnection *item;

    const TranslateRequest &request;

    const TranslateHandler &handler;
    void *handler_ctx;

    struct async_operation_ref &async_ref;

public:
    TranslateStockRequest(TranslateStock &_stock, struct pool &_pool,
                          const TranslateRequest &_request,
                          const TranslateHandler &_handler, void *_ctx,
                          struct async_operation_ref &_async_ref)
        :pool(_pool), stock(_stock),
         request(_request),
         handler(_handler), handler_ctx(_ctx),
         async_ref(_async_ref) {}

    /* virtual methods from class StockGetHandler */
    void OnStockItemReady(StockItem &item) override;
    void OnStockItemError(GError *error) override;

    /* virtual methods from class Lease */
    void ReleaseLease(bool reuse) override {
        stock.Put(*item, !reuse);
    }
};

/*
 * stock callback
 *
 */

void
TranslateStockRequest::OnStockItemReady(StockItem &_item)
{
    item = &(TranslateConnection &)_item;
    translate(pool, item->GetSocket(),
              *this,
              request, handler, handler_ctx,
              async_ref);
}

void
TranslateStockRequest::OnStockItemError(GError *error)
{
    handler.error(error, handler_ctx);
}

/*
 * constructor
 *
 */

TranslateStock *
tstock_new(struct pool &pool, const char *socket_path, unsigned limit)
{
    return NewFromPool<TranslateStock>(pool, pool, socket_path, limit);
}

void
tstock_free(struct pool &pool, TranslateStock *stock)
{
    DeleteFromPool(pool, stock);
}

void
tstock_translate(TranslateStock &stock, struct pool &pool,
                 const TranslateRequest &request,
                 const TranslateHandler &handler, void *ctx,
                 struct async_operation_ref &async_ref)
{
    auto r = NewFromPool<TranslateStockRequest>(pool, stock, pool, request,
                                                handler, ctx, async_ref);
    stock.Get(pool, *r, async_ref);
}
<commit_msg>tstock: use HeapStockItem<commit_after>/*
 * Connection pooling for the translation server.
 *
 * author: Max Kellermann <mk@cm4all.com>
 */

#include "tstock.hxx"
#include "TranslateHandler.hxx"
#include "translate_client.hxx"
#include "stock/Stock.hxx"
#include "stock/Class.hxx"
#include "stock/Item.hxx"
#include "stock/GetHandler.hxx"
#include "lease.hxx"
#include "pool.hxx"
#include "gerrno.h"
#include "net/AllocatedSocketAddress.hxx"
#include "net/SocketDescriptor.hxx"
#include "event/Event.hxx"
#include "event/Callback.hxx"

#include <daemon/log.h>

#include <string.h>
#include <errno.h>

class TranslateConnection final : public HeapStockItem {
    SocketDescriptor s;

    Event event;

public:
    explicit TranslateConnection(CreateStockItem c)
        :HeapStockItem(c) {}

    ~TranslateConnection() override {
        if (s.IsDefined())
            event.Delete();
    }

private:
    bool CreateAndConnect(SocketAddress address) {
        assert(!s.IsDefined());

        return s.Create(AF_LOCAL, SOCK_STREAM, 0) &&
            s.Connect(address);
    }

public:
    void CreateAndConnectAndFinish(SocketAddress address) {
        if (CreateAndConnect(address)) {
            event.Set(s.Get(), EV_READ,
                      MakeSimpleEventCallback(TranslateConnection,
                                              EventCallback), this);
            InvokeCreateSuccess();
        } else {
            auto error = new_error_errno();

            if (s.IsDefined())
                s.Close();

            InvokeCreateError(error);
        }
    }

    int GetSocket() {
        return s.Get();
    }

private:
    void EventCallback() {
        char buffer;
        ssize_t nbytes = recv(s.Get(), &buffer, sizeof(buffer), MSG_DONTWAIT);
        if (nbytes < 0)
            daemon_log(2, "error on idle translation server connection: %s\n",
                       strerror(errno));
        else if (nbytes > 0)
            daemon_log(2, "unexpected data in idle translation server connection\n");

        InvokeIdleDisconnect();
        pool_commit();
    }

public:
    /* virtual methods from class StockItem */
    bool Borrow(gcc_unused void *ctx) override {
        event.Delete();
        return true;
    }

    bool Release(gcc_unused void *ctx) override {
        event.Add();
        return true;
    }
};

static void
tstock_create(gcc_unused void *ctx,
              gcc_unused struct pool &parent_pool, CreateStockItem c,
              gcc_unused const char *uri, void *info,
              gcc_unused struct pool &caller_pool,
              gcc_unused struct async_operation_ref &async_ref)
{
    const auto &address = *(const AllocatedSocketAddress *)info;

    auto *connection = new TranslateConnection(c);
    connection->CreateAndConnectAndFinish(address);
}

static constexpr StockClass tstock_class = {
    .create = tstock_create,
};

class TranslateStock {
    Stock *const stock;

    AllocatedSocketAddress address;

public:
    TranslateStock(struct pool &p, const char *path, unsigned limit)
        :stock(new Stock(p, tstock_class, nullptr, nullptr, limit, 8)) {
        address.SetLocal(path);
    }

    ~TranslateStock() {
        delete stock;
    }

    void Get(struct pool &pool, StockGetHandler &handler,
             struct async_operation_ref &async_ref) {
        stock->Get(pool, &address, handler, async_ref);
    }

    void Put(StockItem &item, bool destroy) {
        stock->Put(item, destroy);
    }
};

class TranslateStockRequest final : public StockGetHandler, Lease {
    struct pool &pool;

    TranslateStock &stock;
    TranslateConnection *item;

    const TranslateRequest &request;

    const TranslateHandler &handler;
    void *handler_ctx;

    struct async_operation_ref &async_ref;

public:
    TranslateStockRequest(TranslateStock &_stock, struct pool &_pool,
                          const TranslateRequest &_request,
                          const TranslateHandler &_handler, void *_ctx,
                          struct async_operation_ref &_async_ref)
        :pool(_pool), stock(_stock),
         request(_request),
         handler(_handler), handler_ctx(_ctx),
         async_ref(_async_ref) {}

    /* virtual methods from class StockGetHandler */
    void OnStockItemReady(StockItem &item) override;
    void OnStockItemError(GError *error) override;

    /* virtual methods from class Lease */
    void ReleaseLease(bool reuse) override {
        stock.Put(*item, !reuse);
    }
};

/*
 * stock callback
 *
 */

void
TranslateStockRequest::OnStockItemReady(StockItem &_item)
{
    item = &(TranslateConnection &)_item;
    translate(pool, item->GetSocket(),
              *this,
              request, handler, handler_ctx,
              async_ref);
}

void
TranslateStockRequest::OnStockItemError(GError *error)
{
    handler.error(error, handler_ctx);
}

/*
 * constructor
 *
 */

TranslateStock *
tstock_new(struct pool &pool, const char *socket_path, unsigned limit)
{
    return NewFromPool<TranslateStock>(pool, pool, socket_path, limit);
}

void
tstock_free(struct pool &pool, TranslateStock *stock)
{
    DeleteFromPool(pool, stock);
}

void
tstock_translate(TranslateStock &stock, struct pool &pool,
                 const TranslateRequest &request,
                 const TranslateHandler &handler, void *ctx,
                 struct async_operation_ref &async_ref)
{
    auto r = NewFromPool<TranslateStockRequest>(pool, stock, pool, request,
                                                handler, ctx, async_ref);
    stock.Get(pool, *r, async_ref);
}
<|endoftext|>


<commit_before>// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "vulkan_interface.h"

namespace vulkan {

std::string VulkanResultToString(VkResult result) {
  switch (result) {
    case VK_SUCCESS:
      return "VK_SUCCESS";
    case VK_NOT_READY:
      return "VK_NOT_READY";
    case VK_TIMEOUT:
      return "VK_TIMEOUT";
    case VK_EVENT_SET:
      return "VK_EVENT_SET";
    case VK_EVENT_RESET:
      return "VK_EVENT_RESET";
    case VK_INCOMPLETE:
      return "VK_INCOMPLETE";
    case VK_ERROR_OUT_OF_HOST_MEMORY:
      return "VK_ERROR_OUT_OF_HOST_MEMORY";
    case VK_ERROR_OUT_OF_DEVICE_MEMORY:
      return "VK_ERROR_OUT_OF_DEVICE_MEMORY";
    case VK_ERROR_INITIALIZATION_FAILED:
      return "VK_ERROR_INITIALIZATION_FAILED";
    case VK_ERROR_DEVICE_LOST:
      return "VK_ERROR_DEVICE_LOST";
    case VK_ERROR_MEMORY_MAP_FAILED:
      return "VK_ERROR_MEMORY_MAP_FAILED";
    case VK_ERROR_LAYER_NOT_PRESENT:
      return "VK_ERROR_LAYER_NOT_PRESENT";
    case VK_ERROR_EXTENSION_NOT_PRESENT:
      return "VK_ERROR_EXTENSION_NOT_PRESENT";
    case VK_ERROR_FEATURE_NOT_PRESENT:
      return "VK_ERROR_FEATURE_NOT_PRESENT";
    case VK_ERROR_INCOMPATIBLE_DRIVER:
      return "VK_ERROR_INCOMPATIBLE_DRIVER";
    case VK_ERROR_TOO_MANY_OBJECTS:
      return "VK_ERROR_TOO_MANY_OBJECTS";
    case VK_ERROR_FORMAT_NOT_SUPPORTED:
      return "VK_ERROR_FORMAT_NOT_SUPPORTED";
    case VK_ERROR_FRAGMENTED_POOL:
      return "VK_ERROR_FRAGMENTED_POOL";
    case VK_ERROR_SURFACE_LOST_KHR:
      return "VK_ERROR_SURFACE_LOST_KHR";
    case VK_ERROR_NATIVE_WINDOW_IN_USE_KHR:
      return "VK_ERROR_NATIVE_WINDOW_IN_USE_KHR";
    case VK_SUBOPTIMAL_KHR:
      return "VK_SUBOPTIMAL_KHR";
    case VK_ERROR_OUT_OF_DATE_KHR:
      return "VK_ERROR_OUT_OF_DATE_KHR";
    case VK_ERROR_INCOMPATIBLE_DISPLAY_KHR:
      return "VK_ERROR_INCOMPATIBLE_DISPLAY_KHR";
    case VK_ERROR_VALIDATION_FAILED_EXT:
      return "VK_ERROR_VALIDATION_FAILED_EXT";
    case VK_ERROR_INVALID_SHADER_NV:
      return "VK_ERROR_INVALID_SHADER_NV";
    case VK_RESULT_RANGE_SIZE:
      return "VK_RESULT_RANGE_SIZE";
    case VK_RESULT_MAX_ENUM:
      return "VK_RESULT_MAX_ENUM";
    case VK_ERROR_INVALID_EXTERNAL_HANDLE:
      return "VK_ERROR_INVALID_EXTERNAL_HANDLE";
    case VK_ERROR_OUT_OF_POOL_MEMORY:
      return "VK_ERROR_OUT_OF_POOL_MEMORY";
    default:
      return "Unknown Error";
  }
  return "";
}

}  // namespace vulkan
<commit_msg>vulkan: Fix build issue due to missing VK_RESULT_RANGE_SIZE (#24829)<commit_after>// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "vulkan_interface.h"

namespace vulkan {

std::string VulkanResultToString(VkResult result) {
  switch (result) {
    case VK_SUCCESS:
      return "VK_SUCCESS";
    case VK_NOT_READY:
      return "VK_NOT_READY";
    case VK_TIMEOUT:
      return "VK_TIMEOUT";
    case VK_EVENT_SET:
      return "VK_EVENT_SET";
    case VK_EVENT_RESET:
      return "VK_EVENT_RESET";
    case VK_INCOMPLETE:
      return "VK_INCOMPLETE";
    case VK_ERROR_OUT_OF_HOST_MEMORY:
      return "VK_ERROR_OUT_OF_HOST_MEMORY";
    case VK_ERROR_OUT_OF_DEVICE_MEMORY:
      return "VK_ERROR_OUT_OF_DEVICE_MEMORY";
    case VK_ERROR_INITIALIZATION_FAILED:
      return "VK_ERROR_INITIALIZATION_FAILED";
    case VK_ERROR_DEVICE_LOST:
      return "VK_ERROR_DEVICE_LOST";
    case VK_ERROR_MEMORY_MAP_FAILED:
      return "VK_ERROR_MEMORY_MAP_FAILED";
    case VK_ERROR_LAYER_NOT_PRESENT:
      return "VK_ERROR_LAYER_NOT_PRESENT";
    case VK_ERROR_EXTENSION_NOT_PRESENT:
      return "VK_ERROR_EXTENSION_NOT_PRESENT";
    case VK_ERROR_FEATURE_NOT_PRESENT:
      return "VK_ERROR_FEATURE_NOT_PRESENT";
    case VK_ERROR_INCOMPATIBLE_DRIVER:
      return "VK_ERROR_INCOMPATIBLE_DRIVER";
    case VK_ERROR_TOO_MANY_OBJECTS:
      return "VK_ERROR_TOO_MANY_OBJECTS";
    case VK_ERROR_FORMAT_NOT_SUPPORTED:
      return "VK_ERROR_FORMAT_NOT_SUPPORTED";
    case VK_ERROR_FRAGMENTED_POOL:
      return "VK_ERROR_FRAGMENTED_POOL";
    case VK_ERROR_SURFACE_LOST_KHR:
      return "VK_ERROR_SURFACE_LOST_KHR";
    case VK_ERROR_NATIVE_WINDOW_IN_USE_KHR:
      return "VK_ERROR_NATIVE_WINDOW_IN_USE_KHR";
    case VK_SUBOPTIMAL_KHR:
      return "VK_SUBOPTIMAL_KHR";
    case VK_ERROR_OUT_OF_DATE_KHR:
      return "VK_ERROR_OUT_OF_DATE_KHR";
    case VK_ERROR_INCOMPATIBLE_DISPLAY_KHR:
      return "VK_ERROR_INCOMPATIBLE_DISPLAY_KHR";
    case VK_ERROR_VALIDATION_FAILED_EXT:
      return "VK_ERROR_VALIDATION_FAILED_EXT";
    case VK_ERROR_INVALID_SHADER_NV:
      return "VK_ERROR_INVALID_SHADER_NV";
#if VK_HEADER_VERSION < 140
    case VK_RESULT_RANGE_SIZE:
      return "VK_RESULT_RANGE_SIZE";
#endif
    case VK_RESULT_MAX_ENUM:
      return "VK_RESULT_MAX_ENUM";
    case VK_ERROR_INVALID_EXTERNAL_HANDLE:
      return "VK_ERROR_INVALID_EXTERNAL_HANDLE";
    case VK_ERROR_OUT_OF_POOL_MEMORY:
      return "VK_ERROR_OUT_OF_POOL_MEMORY";
    default:
      return "Unknown Error";
  }
  return "";
}

}  // namespace vulkan
<|endoftext|>


<commit_before>#include <shell.hpp>

#include <kdb>

#include <iostream>
#include <sstream>

using namespace std;
using namespace kdb;

ShellCommand::ShellCommand()
{}

int ShellCommand::execute(int, char**)
{
	KeySet current;
	Key currentKey;

	string commandline;
	string prompt = "> ";

	cout << prompt;
	while (getline(cin, commandline))
	{
		istringstream is (commandline);
		string command;

		is >> command;
		if (command == "kdbGet")
		{
			string parent;
			is >> parent;
			Key parentKey (parent, KEY_END);
			cout << "return value: " << kdb.get(current, parentKey) << endl;
		}
		else if (command == "kdbSet")
		{
			string parent;
			is >> parent;
			Key parentKey (parent, KEY_END);
			cout << "return value: " << kdb.set(current, parentKey) << endl;
		}
		else if (command == "keySetName")
		{
			string name;
			is >> name;
			currentKey.setName(name);
		}
		else if (command == "keySetMeta")
		{
			string name;
			is >> name;
			string value;
			is >> value;
			std::string tmp;
			getline (is, tmp);
			value += tmp;
			currentKey.setMeta(name, value);
			cout << "Set meta " << name << " to " << value << endl;
		}
		else if (command == "keySetString")
		{
			string value;
			is >> value;
			std::string tmp;
			getline (is, tmp);
			value += tmp;
			currentKey.setString(value);
		}
		else if (command == "ksAppendKey")
		{
			current.append(currentKey);
		}
		else if (command == "ksCut")
		{
			string parent;
			is >> parent;
			Key parentKey (parent, KEY_END);

			current.cut (parentKey);
		}
		else if (command == "ksOutput")
		{
			current.rewind();
			while (current.next())
			{
				cout << current.current().getName() << " value: " << current.current().getString() << endl;
			}
		} else {
			cout << "unknown command" << endl;
		}

		cout << prompt;
	}

	return 0;
}

ShellCommand::~ShellCommand()
{}
<commit_msg>dup key to allow multiple appending<commit_after>#include <shell.hpp>

#include <kdb>

#include <iostream>
#include <sstream>

using namespace std;
using namespace kdb;

ShellCommand::ShellCommand()
{}

int ShellCommand::execute(int, char**)
{
	KeySet current;
	Key currentKey;

	string commandline;
	string prompt = "> ";

	cout << prompt;
	while (getline(cin, commandline))
	{
		istringstream is (commandline);
		string command;

		is >> command;
		if (command == "kdbGet")
		{
			string parent;
			is >> parent;
			Key parentKey (parent, KEY_END);
			cout << "return value: " << kdb.get(current, parentKey) << endl;
		}
		else if (command == "kdbSet")
		{
			string parent;
			is >> parent;
			Key parentKey (parent, KEY_END);
			cout << "return value: " << kdb.set(current, parentKey) << endl;
		}
		else if (command == "keySetName")
		{
			string name;
			is >> name;
			currentKey.setName(name);
		}
		else if (command == "keySetMeta")
		{
			string name;
			is >> name;
			string value;
			is >> value;
			std::string tmp;
			getline (is, tmp);
			value += tmp;
			currentKey.setMeta(name, value);
			cout << "Set meta " << name << " to " << value << endl;
		}
		else if (command == "keySetString")
		{
			string value;
			is >> value;
			std::string tmp;
			getline (is, tmp);
			value += tmp;
			currentKey.setString(value);
		}
		else if (command == "ksAppendKey")
		{
			current.append(currentKey.dup());
		}
		else if (command == "ksCut")
		{
			string parent;
			is >> parent;
			Key parentKey (parent, KEY_END);

			current.cut (parentKey);
		}
		else if (command == "ksOutput")
		{
			current.rewind();
			while (current.next())
			{
				cout << current.current().getName() << " value: " << current.current().getString() << endl;
			}
		} else {
			cout << "unknown command" << endl;
		}

		cout << prompt;
	}

	return 0;
}

ShellCommand::~ShellCommand()
{}
<|endoftext|>


<commit_before>#include "../test.h"
#include <thrust/host_vector.h>
#include "../cuda_array_mapper.h"
#include "../../src/placement/summed_area_table.h"

TEST(Test_SummedAreaTable, SATWithoutClass)
{
  std::vector<float> input = { 1, 2, 3, 4 };
  thrust::host_vector<float> result = algSAT(input.data(), 2, 2);

  ASSERT_LE(4, result.size());

  EXPECT_EQ(1, result[0]);
  EXPECT_EQ(3, result[1]);
  EXPECT_EQ(4, result[2]);
  EXPECT_EQ(10, result[3]);
}

TEST(Test_SummedAreaTable, SAT)
{
  std::vector<float> input = { 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8 };
  cudaChannelFormatDesc channelDesc =
      cudaCreateChannelDesc(32, 0, 0, 0, cudaChannelFormatKindFloat);
  auto inputImageProvider =
      std::make_shared<CudaArrayMapper<float>>(4, 4, input, channelDesc);

  SummedAreaTable table(inputImageProvider);
  table.runKernel();
  thrust::host_vector<float> result = table.getResults();

  ASSERT_LE(16, result.size());

  EXPECT_EQ(1, result[0]);
  EXPECT_EQ(3, result[1]);
  EXPECT_EQ(6, result[2]);
  EXPECT_EQ(10, result[3]);
  EXPECT_EQ(6, result[4]);
  EXPECT_EQ(14, result[5]);
  EXPECT_EQ(24, result[6]);
  EXPECT_EQ(36, result[7]);
}
<commit_msg>Add test for larger summed area table 32 x 32 which seems to work.<commit_after>#include "../test.h"
#include <thrust/host_vector.h>
#include "../cuda_array_mapper.h"
#include "../../src/placement/summed_area_table.h"

TEST(Test_SummedAreaTable, SATWithoutClass)
{
  std::vector<float> input = { 1, 2, 3, 4 };
  thrust::host_vector<float> result = algSAT(input.data(), 2, 2);

  ASSERT_LE(4, result.size());

  EXPECT_EQ(1, result[0]);
  EXPECT_EQ(3, result[1]);
  EXPECT_EQ(4, result[2]);
  EXPECT_EQ(10, result[3]);
}

TEST(Test_SummedAreaTable, SAT)
{
  std::vector<float> input = { 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8 };
  cudaChannelFormatDesc channelDesc =
      cudaCreateChannelDesc(32, 0, 0, 0, cudaChannelFormatKindFloat);
  auto inputImageProvider =
      std::make_shared<CudaArrayMapper<float>>(4, 4, input, channelDesc);

  SummedAreaTable table(inputImageProvider);
  table.runKernel();
  thrust::host_vector<float> result = table.getResults();

  ASSERT_LE(16, result.size());

  EXPECT_EQ(1, result[0]);
  EXPECT_EQ(3, result[1]);
  EXPECT_EQ(6, result[2]);
  EXPECT_EQ(10, result[3]);
  EXPECT_EQ(6, result[4]);
  EXPECT_EQ(14, result[5]);
  EXPECT_EQ(24, result[6]);
  EXPECT_EQ(36, result[7]);
}

TEST(Test_SummedAreaTable, SATLarger)
{
  std::vector<float> input(32 * 32, 0);
  for (int i = 0; i < 4; ++i)
  {
    input[i] = i + 1;
    input[i + 32] = i + 5;
    input[i + 64] = i + 1;
    input[i + 96] = i + 5;
  }
  cudaChannelFormatDesc channelDesc =
      cudaCreateChannelDesc(32, 0, 0, 0, cudaChannelFormatKindFloat);
  auto inputImageProvider =
      std::make_shared<CudaArrayMapper<float>>(32, 32, input, channelDesc);

  SummedAreaTable table(inputImageProvider);
  table.runKernel();
  thrust::host_vector<float> result = table.getResults();

  ASSERT_LE(32 * 32, result.size());

  EXPECT_EQ(1, result[0]);
  EXPECT_EQ(3, result[1]);
  EXPECT_EQ(6, result[2]);
  EXPECT_EQ(10, result[3]);
  EXPECT_EQ(10, result[4]);
  EXPECT_EQ(10, result[31]);
  EXPECT_EQ(6, result[32]);
  EXPECT_EQ(14, result[33]);
  EXPECT_EQ(24, result[34]);
  EXPECT_EQ(36, result[35]);
}
<|endoftext|>


<commit_before>#include "twsgen.h"
#include "tws_xml.h"
#include "tws_meta.h"
#include "config.h"

#include <popt.h>
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <libxml/tree.h>

static poptContext opt_ctx;
static const char *filep = NULL;
static int skipdefp = 0;
static int histjobp = 0;
static const char *endDateTimep = "";

#define VERSION_MSG \
PACKAGE_NAME " " PACKAGE_VERSION "\n\
Copyright (C) 2010-2011 Ruediger Meier <sweet_f_a@gmx.de>\n\
License: BSD 3-Clause\n"

static void displayArgs( poptContext con, poptCallbackReason /*foo*/,
	poptOption *key, const char */*arg*/, void */*data*/ )
{
	if (key->shortName == 'h') {
		poptPrintHelp(con, stdout, 0);
	} else if (key->shortName == 'V') {
		fprintf(stdout, VERSION_MSG);
	} else {
		poptPrintUsage(con, stdout, 0);
	}

	exit(0);
}

static struct poptOption flow_opts[] = {
	{"verbose-xml", 'x', POPT_ARG_NONE, &skipdefp, 0,
		"Never skip xml default values.", NULL},
	{"histjob", 'H', POPT_ARG_NONE, &histjobp, 0,
		"generate hist job", "FILE"},
	{"endDateTime", 'e', POPT_ARG_STRING, &endDateTimep, 0,
		"Query end date time, default is \"\" which means now.", "DATETIME"},
	POPT_TABLEEND
};

static struct poptOption help_opts[] = {
	{NULL, '\0', POPT_ARG_CALLBACK, (void*)displayArgs, 0, NULL, NULL},
	{"help", 'h', POPT_ARG_NONE, NULL, 0, "Show this help message.", NULL},
	{"version", 'V', POPT_ARG_NONE, NULL, 0, "Print version string and exit.",
		NULL},
	{"usage", '\0', POPT_ARG_NONE, NULL, 0, "Display brief usage message."
		, NULL},
	POPT_TABLEEND
};

static const struct poptOption twsDL_opts[] = {
	{NULL, '\0', POPT_ARG_INCLUDE_TABLE, flow_opts, 0,
	 "Program advice:", NULL},
	{NULL, '\0', POPT_ARG_INCLUDE_TABLE, help_opts, 0,
	 "Help options:", NULL},
	POPT_TABLEEND
};

void clear_popt()
{
	poptFreeContext(opt_ctx);
}

void twsgen_parse_cl(size_t argc, const char *argv[])
{
	opt_ctx = poptGetContext(NULL, argc, argv, twsDL_opts, 0);
	atexit(clear_popt);

	poptSetOtherOptionHelp( opt_ctx, "[OPTION]... FILE");

	int rc;
	while( (rc = poptGetNextOpt(opt_ctx)) > 0 ) {
		// handle options when we have returning ones
		assert(false);
	}

	if( rc != -1 ) {
		fprintf( stderr, "error: %s '%s'\n",
			poptStrerror(rc), poptBadOption(opt_ctx, 0) );
		exit(2);
	}

	const char** rest = poptGetArgs(opt_ctx);
	if( rest != NULL && *rest != NULL ) {
		filep = *rest;
		rest++;

		if( *rest != NULL ) {
			fprintf( stderr, "error: bad usage\n" );
			exit(2);
		}
	} else {
			fprintf( stderr, "error: bad usage\n" );
			exit(2);
	}
}

int main(int argc, char *argv[])
{
	twsgen_parse_cl(argc, (const char **) argv);

	TwsXml::setSkipDefaults( !skipdefp );

	if( !histjobp ) {
		fprintf( stderr, "error, only -H is implemented\n" );
		return 1;
	}

	TwsXml file;
	if( ! file.openFile(filep) ) {
		return 1;
	}

	xmlNodePtr xn;
	int count_docs = 0;
	HistTodo histTodo;
	while( (xn = file.nextXmlNode()) != NULL ) {
		count_docs++;
		PacketContractDetails *pcd = PacketContractDetails::fromXml( xn );

		bool myProp_includeExpired = true;
		int myProp_reqMaxContractsPerSpec = -1;
		QList<std::string> myProp_whatToShow = QList<std::string>() << "BID";
		std::string myProp_durationStr = "1 W";
		std::string myProp_barSizeSetting = "30 mins";
		int myProp_useRTH = 1;
		int myProp_formatDate = 1;
		for( int i = 0; i<pcd->constList().size(); i++ ) {

			const IB::ContractDetails &cd = pcd->constList().at(i);
			IB::Contract c = cd.summary;
			c.includeExpired = myProp_includeExpired;

			if( myProp_reqMaxContractsPerSpec > 0 && myProp_reqMaxContractsPerSpec <= i ) {
				break;
			}

			foreach( std::string wts, myProp_whatToShow ) {
				HistRequest hR;
				hR.initialize( c, endDateTimep, myProp_durationStr,
				               myProp_barSizeSetting, wts, myProp_useRTH, myProp_formatDate );
				histTodo.add( hR );

				PacketHistData phd;
				phd.record( 0, hR );
				phd.dumpXml();
			}
		}
		delete pcd;
	}
	// TODO this should be xml dump
	histTodo.dumpLeft( stderr );
	fprintf( stderr, "notice, %d xml docs parsed from file '%s'\n",
		count_docs, filep );

	return 0;
}
<commit_msg>twsgen cmd, add option [-b|--barSizeSetting=STRING]<commit_after>#include "twsgen.h"
#include "tws_xml.h"
#include "tws_meta.h"
#include "config.h"

#include <popt.h>
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <libxml/tree.h>

static poptContext opt_ctx;
static const char *filep = NULL;
static int skipdefp = 0;
static int histjobp = 0;
static const char *endDateTimep = "";
static const char *barSizeSettingp = "1 hour";

#define VERSION_MSG \
PACKAGE_NAME " " PACKAGE_VERSION "\n\
Copyright (C) 2010-2011 Ruediger Meier <sweet_f_a@gmx.de>\n\
License: BSD 3-Clause\n"

static void displayArgs( poptContext con, poptCallbackReason /*foo*/,
	poptOption *key, const char */*arg*/, void */*data*/ )
{
	if (key->shortName == 'h') {
		poptPrintHelp(con, stdout, 0);
	} else if (key->shortName == 'V') {
		fprintf(stdout, VERSION_MSG);
	} else {
		poptPrintUsage(con, stdout, 0);
	}

	exit(0);
}

static struct poptOption flow_opts[] = {
	{"verbose-xml", 'x', POPT_ARG_NONE, &skipdefp, 0,
		"Never skip xml default values.", NULL},
	{"histjob", 'H', POPT_ARG_NONE, &histjobp, 0,
		"generate hist job", "FILE"},
	{"endDateTime", 'e', POPT_ARG_STRING, &endDateTimep, 0,
		"Query end date time, default is \"\" which means now.", "DATETIME"},
	{"barSizeSetting", 'b', POPT_ARG_STRING, &barSizeSettingp, 0,
		"Size of the bars, default is \"1 hour\".", NULL},
	POPT_TABLEEND
};

static struct poptOption help_opts[] = {
	{NULL, '\0', POPT_ARG_CALLBACK, (void*)displayArgs, 0, NULL, NULL},
	{"help", 'h', POPT_ARG_NONE, NULL, 0, "Show this help message.", NULL},
	{"version", 'V', POPT_ARG_NONE, NULL, 0, "Print version string and exit.",
		NULL},
	{"usage", '\0', POPT_ARG_NONE, NULL, 0, "Display brief usage message."
		, NULL},
	POPT_TABLEEND
};

static const struct poptOption twsDL_opts[] = {
	{NULL, '\0', POPT_ARG_INCLUDE_TABLE, flow_opts, 0,
	 "Program advice:", NULL},
	{NULL, '\0', POPT_ARG_INCLUDE_TABLE, help_opts, 0,
	 "Help options:", NULL},
	POPT_TABLEEND
};

void clear_popt()
{
	poptFreeContext(opt_ctx);
}

void twsgen_parse_cl(size_t argc, const char *argv[])
{
	opt_ctx = poptGetContext(NULL, argc, argv, twsDL_opts, 0);
	atexit(clear_popt);

	poptSetOtherOptionHelp( opt_ctx, "[OPTION]... FILE");

	int rc;
	while( (rc = poptGetNextOpt(opt_ctx)) > 0 ) {
		// handle options when we have returning ones
		assert(false);
	}

	if( rc != -1 ) {
		fprintf( stderr, "error: %s '%s'\n",
			poptStrerror(rc), poptBadOption(opt_ctx, 0) );
		exit(2);
	}

	const char** rest = poptGetArgs(opt_ctx);
	if( rest != NULL && *rest != NULL ) {
		filep = *rest;
		rest++;

		if( *rest != NULL ) {
			fprintf( stderr, "error: bad usage\n" );
			exit(2);
		}
	} else {
			fprintf( stderr, "error: bad usage\n" );
			exit(2);
	}
}

int main(int argc, char *argv[])
{
	twsgen_parse_cl(argc, (const char **) argv);

	TwsXml::setSkipDefaults( !skipdefp );

	if( !histjobp ) {
		fprintf( stderr, "error, only -H is implemented\n" );
		return 1;
	}

	TwsXml file;
	if( ! file.openFile(filep) ) {
		return 1;
	}

	xmlNodePtr xn;
	int count_docs = 0;
	HistTodo histTodo;
	while( (xn = file.nextXmlNode()) != NULL ) {
		count_docs++;
		PacketContractDetails *pcd = PacketContractDetails::fromXml( xn );

		bool myProp_includeExpired = true;
		int myProp_reqMaxContractsPerSpec = -1;
		QList<std::string> myProp_whatToShow = QList<std::string>() << "BID";
		std::string myProp_durationStr = "1 W";
		int myProp_useRTH = 1;
		int myProp_formatDate = 1;
		for( int i = 0; i<pcd->constList().size(); i++ ) {

			const IB::ContractDetails &cd = pcd->constList().at(i);
			IB::Contract c = cd.summary;
			c.includeExpired = myProp_includeExpired;

			if( myProp_reqMaxContractsPerSpec > 0 && myProp_reqMaxContractsPerSpec <= i ) {
				break;
			}

			foreach( std::string wts, myProp_whatToShow ) {
				HistRequest hR;
				hR.initialize( c, endDateTimep, myProp_durationStr,
				               barSizeSettingp, wts, myProp_useRTH, myProp_formatDate );
				histTodo.add( hR );

				PacketHistData phd;
				phd.record( 0, hR );
				phd.dumpXml();
			}
		}
		delete pcd;
	}
	// TODO this should be xml dump
	histTodo.dumpLeft( stderr );
	fprintf( stderr, "notice, %d xml docs parsed from file '%s'\n",
		count_docs, filep );

	return 0;
}
<|endoftext|>


<commit_before>#include "include/Angel.h"
#include "cube.h"

#include <iostream>
#include <time.h>
#include <sys/time.h>
#include <unistd.h>
#include <algorithm>

using namespace std;
using namespace Angel;

GLfloat screen_width = 600;
GLfloat screen_height = 600;

GLuint program;
GLuint vao;

GLuint P_loc, M_loc, V_loc, W_loc; // locations pointers of P, M, V, W matrices in shader

mat4 I_mat = mat4(1.0); // Identity matrix
mat4 M_mat = mat4(1.0); // Model matrix
mat4 V_mat = mat4(1.0); // View matrix
mat4 W_mat = mat4(1.0); // World matrix (rotation of cube by mouse)
mat4 P_mat = mat4(1.0); // projection matrix

vec3 eye(5,5,-10);

// test cube for EPIC RADO :D :D
cube *test_cube;

//==================
//openGL functions
//==================

inline void create_buffer(GLuint* vbo, size_t pts_size, const GLvoid * pts, size_t color_size, const GLvoid * color){
	// example code to be replaced with project customized code
	glGenBuffers(2, vbo); // generate buffers position, color
	glBindBuffer(GL_ARRAY_BUFFER, vbo[0]);
	glBufferData(GL_ARRAY_BUFFER, pts_size, pts, GL_STATIC_DRAW);
	glEnableVertexAttribArray(0);
	glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0) );

	//color
	glBindBuffer(GL_ARRAY_BUFFER, vbo[1]);
	glBufferData(GL_ARRAY_BUFFER, color_size, color, GL_STATIC_DRAW);
	glEnableVertexAttribArray(1);
	glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0) );
}

void init_buffers() {
	// Initializing  VAOs and VBOs
	glGenVertexArrays(1, &vao);
	glBindVertexArray(vao);
	test_cube = new cube(program, 0 );
}

void init(void) {

	// Load shaders and use the resulting shader program
	program = InitShader("vshader.glsl", "fshader.glsl");
	glUseProgram(program);

	init_buffers();

	V_mat = LookAt(eye, vec3(0,0,0), vec3(0,1,0));
	P_mat = Perspective(45.0f, 1.0f*screen_width/screen_height, 1.0f, 100.0f);

	// matrices location in shader
	P_loc = glGetUniformLocation(program, "P");
	V_loc = glGetUniformLocation(program, "V");
	M_loc = glGetUniformLocation(program, "M");
	W_loc = glGetUniformLocation(program, "W");

	glUniformMatrix4fv(P_loc, 1, true, P_mat);
	glUniformMatrix4fv(V_loc, 1, true, V_mat);
	glUniformMatrix4fv(M_loc, 1, true, M_mat);
	glUniformMatrix4fv(W_loc, 1, true, W_mat);

	glClearColor(0.9, 0.9, 0.9, 1.0); // grey background :/ not sure about the color

	glEnable(GL_DEPTH_TEST);// Enable depth test
	glDepthFunc(GL_LESS);// Accept fragment if it closer to the camera than the former one
}

void display(void) {
	glClear(GL_COLOR_BUFFER_BIT);     // clear the window//

	glEnableVertexAttribArray(vao);
	glBindVertexArray(vao);

	// update rotation and translation matrices of each object before uploading to shader
	glUniformMatrix4fv(M_loc, 1, true, M_mat);
	test_cube->draw();

	glDisableVertexAttribArray(vao);
	glutSwapBuffers(); // Double buffering
}

void keyboard(unsigned char key, int x, int y) {
	switch (key) {
	case 033:
		cout << "exit" << endl;
		exit(EXIT_SUCCESS);
		break;
	}
}

void keyboard_special(int key, int x, int y) {
	switch (key) {
	case GLUT_KEY_RIGHT:
		break;
	case GLUT_KEY_LEFT:
		break;
	case GLUT_KEY_DOWN:
		break;
	case GLUT_KEY_UP:
		break;
	}
}

void onMouse(int button, int state, int x, int y) {
}

void onPassiveMotion(int x, int y) {
}

void onReshape(int width, int height) {
	screen_width = width;
	screen_height = height;
	glViewport(0, 0, screen_width, screen_height);
	P_mat = Perspective(45.0f, 1.0f*screen_width/screen_height, 1.0f, 100.0f);
	glUniformMatrix4fv(P_loc, 1, false, P_mat);
}

//=========
//main loop
//=========

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

	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_RGBA | GLUT_MULTISAMPLE);
	glutInitWindowSize(screen_width, screen_height);

	//----------------------------------------
	// If you are using freeglut, the next two lines will check if
	// the code is truly 3.2. Otherwise, comment them out

	//glutInitContextVersion( 3, 2 );
	//glutInitContextProfile( GLUT_CORE_PROFILE );
	//----------------------------------------

	glutCreateWindow("Labyrinth :D");
	glewInit();
	init();

	glutDisplayFunc(display);
	glutKeyboardFunc(keyboard);
	glutSpecialFunc(keyboard_special);
	glutMouseFunc(onMouse);
	glutPassiveMotionFunc(onPassiveMotion);
	glutReshapeFunc(onReshape);

	glutMainLoop();
	return 0;
}

<commit_msg>Adds :D in Labyrinth.cpp<commit_after>#include "include/Angel.h"
#include "cube.h"

#include <iostream>
#include <time.h>
#include <sys/time.h>
#include <unistd.h>
#include <algorithm>

using namespace std;
using namespace Angel;

GLfloat screen_width = 600;
GLfloat screen_height = 600;

GLuint program;
GLuint vao;

GLuint P_loc, M_loc, V_loc, W_loc; // locations pointers of P, M, V, W matrices in shader

mat4 I_mat = mat4(1.0); // Identity matrix
mat4 M_mat = mat4(1.0); // Model matrix
mat4 V_mat = mat4(1.0); // View matrix
mat4 W_mat = mat4(1.0); // World matrix (rotation of cube by mouse)
mat4 P_mat = mat4(1.0); // projection matrix

vec3 eye(5,5,-10);

// test cube for EPIC RADO :D :D :D
cube *test_cube;

//==================
//openGL functions
//==================

inline void create_buffer(GLuint* vbo, size_t pts_size, const GLvoid * pts, size_t color_size, const GLvoid * color){
	// example code to be replaced with project customized code
	glGenBuffers(2, vbo); // generate buffers position, color
	glBindBuffer(GL_ARRAY_BUFFER, vbo[0]);
	glBufferData(GL_ARRAY_BUFFER, pts_size, pts, GL_STATIC_DRAW);
	glEnableVertexAttribArray(0);
	glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0) );

	//color
	glBindBuffer(GL_ARRAY_BUFFER, vbo[1]);
	glBufferData(GL_ARRAY_BUFFER, color_size, color, GL_STATIC_DRAW);
	glEnableVertexAttribArray(1);
	glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0) );
}

void init_buffers() {
	// Initializing  VAOs and VBOs
	glGenVertexArrays(1, &vao);
	glBindVertexArray(vao);
	test_cube = new cube(program, 0 );
}

void init(void) {

	// Load shaders and use the resulting shader program
	program = InitShader("vshader.glsl", "fshader.glsl");
	glUseProgram(program);

	init_buffers();

	V_mat = LookAt(eye, vec3(0,0,0), vec3(0,1,0));
	P_mat = Perspective(45.0f, 1.0f*screen_width/screen_height, 1.0f, 100.0f);

	// matrices location in shader
	P_loc = glGetUniformLocation(program, "P");
	V_loc = glGetUniformLocation(program, "V");
	M_loc = glGetUniformLocation(program, "M");
	W_loc = glGetUniformLocation(program, "W");

	glUniformMatrix4fv(P_loc, 1, true, P_mat);
	glUniformMatrix4fv(V_loc, 1, true, V_mat);
	glUniformMatrix4fv(M_loc, 1, true, M_mat);
	glUniformMatrix4fv(W_loc, 1, true, W_mat);

	glClearColor(0.9, 0.9, 0.9, 1.0); // grey background :/ not sure about the color

	glEnable(GL_DEPTH_TEST);// Enable depth test
	glDepthFunc(GL_LESS);// Accept fragment if it closer to the camera than the former one
}

void display(void) {
	glClear(GL_COLOR_BUFFER_BIT);     // clear the window//

	glEnableVertexAttribArray(vao);
	glBindVertexArray(vao);

	// update rotation and translation matrices of each object before uploading to shader
	glUniformMatrix4fv(M_loc, 1, true, M_mat);
	test_cube->draw();

	glDisableVertexAttribArray(vao);
	glutSwapBuffers(); // Double buffering
}

void keyboard(unsigned char key, int x, int y) {
	switch (key) {
	case 033:
		cout << "exit" << endl;
		exit(EXIT_SUCCESS);
		break;
	}
}

void keyboard_special(int key, int x, int y) {
	switch (key) {
	case GLUT_KEY_RIGHT:
		break;
	case GLUT_KEY_LEFT:
		break;
	case GLUT_KEY_DOWN:
		break;
	case GLUT_KEY_UP:
		break;
	}
}

void onMouse(int button, int state, int x, int y) {
}

void onPassiveMotion(int x, int y) {
}

void onReshape(int width, int height) {
	screen_width = width;
	screen_height = height;
	glViewport(0, 0, screen_width, screen_height);
	P_mat = Perspective(45.0f, 1.0f*screen_width/screen_height, 1.0f, 100.0f);
	glUniformMatrix4fv(P_loc, 1, false, P_mat);
}

//=========
//main loop
//=========

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

	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_RGBA | GLUT_MULTISAMPLE);
	glutInitWindowSize(screen_width, screen_height);

	//----------------------------------------
	// If you are using freeglut, the next two lines will check if
	// the code is truly 3.2. Otherwise, comment them out

	//glutInitContextVersion( 3, 2 );
	//glutInitContextProfile( GLUT_CORE_PROFILE );
	//----------------------------------------

	glutCreateWindow("Labyrinth :D");
	glewInit();
	init();

	glutDisplayFunc(display);
	glutKeyboardFunc(keyboard);
	glutSpecialFunc(keyboard_special);
	glutMouseFunc(onMouse);
	glutPassiveMotionFunc(onPassiveMotion);
	glutReshapeFunc(onReshape);

	glutMainLoop();
	return 0;
}

<|endoftext|>


<commit_before>/**
 * @file   dummy_camera.cpp
 * @author Gabriel Naves da Silva
 * @author Matheus Vieira Portela
 * @date   21/03/2014
 *
 * @attention Copyright (C) 2014 UnBall Robot Soccer Team
 *
 * @brief  Dummy camera node
 *
 * Loads the rgb video file and publishes it on the "/camera/rgb/image_raw" topic,
 * and loads the depth images in sequence and publishes them on the
 * "/camera/depth/image_raw" topic.
 */

#include <ros/ros.h>
#include <image_transport/image_transport.h>
#include <cv_bridge/cv_bridge.h>
#include <sensor_msgs/image_encodings.h>
#include <opencv2/highgui/highgui.hpp>

#include <string>

/**
 * Converts an integer to a string.
 *
 * @param num the integer to be converted.
 */
std::string to_string(int num)
{
    std::string result;
    char tmp[100];
    sprintf(tmp, "%d\0", num);
    result = tmp;
    return result;
}

int main(int argc, char **argv)
{
    ros::init(argc, argv, "dummy_camera");
    ros::NodeHandle nh;
    image_transport::ImageTransport it(nh); // Used to publish and subscribe to images.
    image_transport::Publisher rgb_pub = it.advertise("/camera/rgb/image_raw", 1);
    image_transport::Publisher depth_pub = it.advertise("/camera/depth/image_raw", 1);
    cv_bridge::CvImage rgb_frame, depth_frame;
    int frame_counter; // Used to count the number of frames published on the topic.
    int num_frames;

    // Check if enough arguments where given
    if( argc != 3)
    {
        ROS_ERROR("Not enough arguments. Usage: dummy_camera <rgb video file> <depth image folder>");
        return -1;
    }

    // Load rgb video and check for errors
    cv::VideoCapture rgb_cap(argv[1]);
    if (!rgb_cap.isOpened())
    {
        ROS_ERROR("Could not open of find the rgb video file");
        return -1;
    }

    // Opens depth image and check for errors
    std::string depth_image_file, folder(argv[2]);
    if (depth_image_file[depth_image_file.size()-1] == '/') depth_image_file.erase(depth_image_file.end());
    depth_image_file = folder + "/depth";
    int depth_counter = 0;

    // Set the loop rate, defined by the framerate of the video
    ros::Rate loop_rate(rgb_cap.get(CV_CAP_PROP_FPS));
    ROS_DEBUG("Loop rate: %lf", rgb_cap.get(CV_CAP_PROP_FPS));

    // Set rgb and depth frame encoding
    rgb_frame.encoding = sensor_msgs::image_encodings::BGR8;
    depth_frame.encoding = sensor_msgs::image_encodings::TYPE_16UC1;

    // Retrieve amount of frames on the video
    num_frames = rgb_cap.get(CV_CAP_PROP_FRAME_COUNT);
    ROS_DEBUG("Frame number: %d", num_frames);

    // Publish the video
    ROS_INFO("Sending video");
    for (frame_counter = 0; ros::ok() && (frame_counter < num_frames); frame_counter++)
    {
        ROS_DEBUG("Frame counter: %d", frame_counter);
        // Publish the rgb frame
        ROS_DEBUG("Publishing the rgb frame");
        rgb_cap >> rgb_frame.image; // Get a new frame from the rgb video capture
        rgb_pub.publish(rgb_frame.toImageMsg());

        // Publish the depth frame
        ROS_DEBUG("Publishing the depth frame");
        depth_counter++;
        depth_frame.image = cv::imread(depth_image_file+to_string(depth_counter)+".png", CV_LOAD_IMAGE_ANYDEPTH);
        depth_pub.publish(depth_frame.toImageMsg());

        ros::spinOnce();
        loop_rate.sleep();
    }
    ROS_INFO("Finished sending video");

    return 0;
}
<commit_msg>Fixed the bug with the dummy rgb video and dummy_camera. This fix is not final. More info on issue #42.<commit_after>/**
 * @file   dummy_camera.cpp
 * @author Gabriel Naves da Silva
 * @author Matheus Vieira Portela
 * @date   21/03/2014
 *
 * @attention Copyright (C) 2014 UnBall Robot Soccer Team
 *
 * @brief  Dummy camera node
 *
 * Loads the rgb video file and publishes it on the "/camera/rgb/image_raw" topic,
 * and loads the depth images in sequence and publishes them on the
 * "/camera/depth/image_raw" topic.
 */

#include <ros/ros.h>
#include <image_transport/image_transport.h>
#include <cv_bridge/cv_bridge.h>
#include <sensor_msgs/image_encodings.h>
#include <opencv2/highgui/highgui.hpp>

#include <string>

/**
 * Converts an integer to a string.
 *
 * @param num the integer to be converted.
 */
std::string to_string(int num)
{
    std::string result;
    char tmp[100];
    sprintf(tmp, "%d", num);
    result = tmp;
    return result;
}

int main(int argc, char **argv)
{
    ros::init(argc, argv, "dummy_camera");
    ros::NodeHandle nh;
    image_transport::ImageTransport it(nh); // Used to publish and subscribe to images.
    image_transport::Publisher rgb_pub = it.advertise("/camera/rgb/image_raw", 1);
    image_transport::Publisher depth_pub = it.advertise("/camera/depth/image_raw", 1);
    cv_bridge::CvImage rgb_frame, depth_frame;
    int frame_counter; // Used to count the number of frames published on the topic.
    int num_frames;

    // Check if enough arguments where given
    if( argc != 3)
    {
        ROS_ERROR("Not enough arguments. Usage: dummy_camera <rgb video file> <depth image folder>");
        return -1;
    }

    // Load rgb video and check for errors
    cv::VideoCapture rgb_cap(argv[1]);
    if (!rgb_cap.isOpened())
    {
        ROS_ERROR("Could not open of find the rgb video file");
        return -1;
    }

    // Opens depth image and check for errors
    std::string depth_image_file, folder(argv[2]);
    if (depth_image_file[depth_image_file.size()-1] == '/') depth_image_file.erase(depth_image_file.end());
    depth_image_file = folder + "/depth";
    int depth_counter = 0;

    // Set the loop rate, defined by the framerate of the video
    ros::Rate loop_rate(25);
    ROS_ERROR("Loop rate: %lf", rgb_cap.get(CV_CAP_PROP_FPS));

    // Set rgb and depth frame encoding
    rgb_frame.encoding = sensor_msgs::image_encodings::BGR8;
    depth_frame.encoding = sensor_msgs::image_encodings::TYPE_16UC1;

    // Retrieve amount of frames on the video
    num_frames = rgb_cap.get(CV_CAP_PROP_FRAME_COUNT);
    ROS_ERROR("Frame number: %d", num_frames);

    // Publish the video
    ROS_INFO("Sending video");
    for (frame_counter = 0; ros::ok() && (frame_counter < num_frames); frame_counter++)
    {
        ROS_DEBUG("Frame counter: %d", frame_counter);
        // Publish the rgb frame
        ROS_DEBUG("Publishing the rgb frame");
        rgb_cap >> rgb_frame.image; // Get a new frame from the rgb video capture
        rgb_pub.publish(rgb_frame.toImageMsg());

        // Publish the depth frame
        ROS_DEBUG("Publishing the depth frame");
        depth_counter++;
        depth_frame.image = cv::imread(depth_image_file+to_string(depth_counter)+".png", CV_LOAD_IMAGE_ANYDEPTH);
        depth_pub.publish(depth_frame.toImageMsg());

        ros::spinOnce();
        loop_rate.sleep();
    }
    ROS_INFO("Finished sending video");

    return 0;
}
<|endoftext|>