<commit_before>// $Id$

//**************************************************************************
//* This file is property of and copyright by the ALICE HLT Project        *
//* ALICE Experiment at CERN, All rights reserved.                         *
//*                                                                        *
//* Primary Authors: Matthias Richter <Matthias.Richter@ift.uib.no>        *
//*                  for The ALICE HLT Project.                            *
//*                                                                        *
//* Permission to use, copy, modify and distribute this software and its   *
//* documentation strictly for non-commercial purposes is hereby granted   *
//* without fee, provided that the above copyright notice appears in all   *
//* copies and that both the copyright notice and this permission notice   *
//* appear in the supporting documentation. The authors make no claims     *
//* about the suitability of this software for any purpose. It is          *
//* provided "as is" without express or implied warranty.                  *
//**************************************************************************

//  @file   AliHLTITSAgent.cxx
//  @author Matthias Richter
//  @date   25.08.2008
//  @brief  Agent of the libAliHLTITS library
//  @note

#include <cassert>
#include "AliHLTITSAgent.h"
#include "AliHLTConfiguration.h"
#include "AliHLTOUT.h"
#include "AliHLTDAQ.h"

// header files of library components
#include "AliHLTITSCompressRawDataSDDComponent.h"
#include "AliHLTITSSSDQARecPointsComponent.h"
#include "AliHLTITSQAComponent.h"
#include "AliHLTITSClusterFinderComponent.h"
#include "AliHLTITSClusterHistoComponent.h"
#include "AliHLTITSTrackerComponent.h"
#include "AliHLTITSVertexerSPDComponent.h"
#include "AliHLTITSDigitPublisherComponent.h"

// header file of the module preprocessor
// none at the moment

/** global instance for agent registration */
AliHLTITSAgent gAliHLTITSAgent;

/** ROOT macro for the implementation of ROOT specific class methods */
ClassImp(AliHLTITSAgent)

AliHLTITSAgent::AliHLTITSAgent()
  :
  AliHLTModuleAgent("ITS"),
  fRawDataHandler(NULL)
{
  // see header file for class documentation
  // or
  // refer to README to build package
  // or
  // visit http://web.ift.uib.no/~kjeks/doc/alice-hlt
}

AliHLTITSAgent::~AliHLTITSAgent()
{
  // see header file for class documentation
}

int AliHLTITSAgent::CreateConfigurations(AliHLTConfigurationHandler* handler,
					 AliRawReader* rawReader,
					 AliRunLoader* runloader) const
{
  // see header file for class documentation
  int iResult=0;
  if (!handler) return -EINVAL;

  ///////////////////////////////////////////////////////////////////////////////////////////////////
  ///////////////////////////////////////////////////////////////////////////////////////////////////
  //
  // ITS tracking is currently only working on raw data
  // to run on digits, a digit publisher needs to be implemented

  TString trackerInput="";
  TString vertexerSPDInput="";
  if (rawReader || !runloader) {
    // AliSimulation: use the AliRawReaderPublisher if the raw reader is available
    // Alireconstruction: indicated by runloader==NULL, run always on raw data

    ///////////////////////////////////////////////////////////////////////////////////////////////////
    //
    // define the ITS cluster finder configurations
    //

    TString spdCF;
    TString ssdCF;
    TString sddCF;

    iResult=CreateCFConfigurations(handler, AliHLTDAQ::DetectorID("ITSSPD"), spdCF);
    handler->CreateConfiguration("ITS-SPD-CF","BlockFilter",spdCF.Data(),"");

    iResult=CreateCFConfigurations(handler, AliHLTDAQ::DetectorID("ITSSDD"), sddCF);
    handler->CreateConfiguration("ITS-SDD-CF","BlockFilter",sddCF.Data(),"");

    iResult=CreateCFConfigurations(handler, AliHLTDAQ::DetectorID("ITSSSD"), ssdCF);
    handler->CreateConfiguration("ITS-SSD-CF","BlockFilter",ssdCF.Data(),"");

    ///////////////////////////////////////////////////////////////////////////////////////////////////
    //
    // define the SPD vertexer Z input
    //
    vertexerSPDInput="ITS-SPD-CF";

    ///////////////////////////////////////////////////////////////////////////////////////////////////
    //
    // define the ITS tracker input
    //
    trackerInput="ITS-SPD-CF ITS-SDD-CF ITS-SSD-CF";
  }
  else if (runloader && !rawReader) {
    // indicates AliSimulation with no RawReader available -> run on digits

    ///////////////////////////////////////////////////////////////////////////////////////////////////
    //
    // define the Digit Publisher and ITS cluster finder configuration
    //
    handler->CreateConfiguration("DigitPublisher","AliLoaderPublisher",NULL,"-loader ITSLoader -datatype 'ALITREED' 'ITS '");
    handler->CreateConfiguration("DigitClusterFinder","ITSClusterFinderDigits","DigitPublisher","");

    ///////////////////////////////////////////////////////////////////////////////////////////////////
    //
    // define the SPD vertexer Z input.
    //
    // Can not run on Digit ClusterFinder. Wrong inputtype. And wrong input data.
    // If this is fixed in the VertexerSPD it needs to implement the data type
    // handling for the ITS digits and ignore the input from the SDD and SSD
    //vertexerSPDInput="DigitClusterFinder";

    ///////////////////////////////////////////////////////////////////////////////////////////////////
    //
    // define the ITS tracker input
    //
    // Currently there is a seg fault in the TTree access from the DigitClusterFinder
    // needs first to be investigated
    //trackerInput="DigitClusterFinder";
  }

  ///////////////////////////////////////////////////////////////////////////////////////////////////
  //
  // define the SPD vertexer Z configuration
  //
  if (!vertexerSPDInput.IsNull()) {
    handler->CreateConfiguration("ITS-SPD-vertexer","ITSVertexerSPD", vertexerSPDInput, "");
  }

  ///////////////////////////////////////////////////////////////////////////////////////////////////
  //
  // define the ITS tracker configuration
  //
  if (!trackerInput.IsNull()) {
    if (handler->FindConfiguration("TPC-globalmerger")) {
      // add the TPC tracking if available
      trackerInput+=" TPC-globalmerger";
    }
    handler->CreateConfiguration("ITS-tracker","ITSTracker",trackerInput.Data(),"");
  }

  return 0;
}

const char* AliHLTITSAgent::GetReconstructionChains(AliRawReader* /*rawReader*/,
						       AliRunLoader* runloader) const
{
  // see header file for class documentation
  if (runloader) {
    // reconstruction chains for AliRoot simulation
    // Note: run loader is only available while running embedded into
    // AliRoot simulation

    // the chain is just defined and can be used as input for subsequent
    // components
    //return "ITS-tracker";
  }

  return "";
}

const char* AliHLTITSAgent::GetRequiredComponentLibraries() const
{
  // see header file for class documentation
  return "libAliHLTUtil.so libAliHLTRCU.so libAliHLTTPC.so";
}

int AliHLTITSAgent::RegisterComponents(AliHLTComponentHandler* pHandler) const
{
  // see header file for class documentation
  assert(pHandler);
  if (!pHandler) return -EINVAL;
  pHandler->AddComponent(new AliHLTITSCompressRawDataSDDComponent);
  pHandler->AddComponent(new AliHLTITSSSDQARecPointsComponent);
  pHandler->AddComponent(new AliHLTITSQAComponent);
  pHandler->AddComponent(new AliHLTITSClusterFinderComponent(AliHLTITSClusterFinderComponent::kClusterFinderSPD));
  pHandler->AddComponent(new AliHLTITSClusterFinderComponent(AliHLTITSClusterFinderComponent::kClusterFinderSDD));
  pHandler->AddComponent(new AliHLTITSClusterFinderComponent(AliHLTITSClusterFinderComponent::kClusterFinderSSD));
  pHandler->AddComponent(new AliHLTITSClusterFinderComponent(AliHLTITSClusterFinderComponent::kClusterFinderDigits));
  pHandler->AddComponent(new AliHLTITSClusterHistoComponent);
  pHandler->AddComponent(new AliHLTITSTrackerComponent);
  pHandler->AddComponent(new AliHLTITSVertexerSPDComponent);
  pHandler->AddComponent(new AliHLTITSDigitPublisherComponent);

  return 0;
}

AliHLTModulePreprocessor* AliHLTITSAgent::GetPreprocessor()
{
  // see header file for class documentation
  return NULL;
}

int AliHLTITSAgent::GetHandlerDescription(AliHLTComponentDataType dt,
					     AliHLTUInt32_t spec,
					     AliHLTOUTHandlerDesc& desc) const
{
  // see header file for class documentation

  // Handlers for ITS raw data. Even though there are 3 detectors
  // everything is handled in one module library and one HLTOUT handler.
  // This assumes that the data blocks are sent with data type
  // {DDL_RAW :ISDD} and the bit set in the specification corresponding.
  // to detector DDL id.
  // An HLTOUT handler is implemented to extract the equipment id from
  // the specification.
  // Note: Future versions of the framework will provide a default handler
  // class with that functionality.
  if (dt==(kAliHLTDataTypeDDLRaw|kAliHLTDataOriginITSSDD)) {
      desc=AliHLTOUTHandlerDesc(kRawReader, dt, GetModuleId());
      HLTInfo("module %s handles data block type %s specification %d (0x%x)",
	      GetModuleId(), AliHLTComponent::DataType2Text(dt).c_str(), spec, spec);
      return 1;
  }
  return 0;
}

AliHLTOUTHandler* AliHLTITSAgent::GetOutputHandler(AliHLTComponentDataType dt,
						   AliHLTUInt32_t /*spec*/)
{
  // see header file for class documentation
  if (dt==(kAliHLTDataTypeDDLRaw|kAliHLTDataOriginITSSDD)) {
    // use the default handler
    if (!fRawDataHandler) {
      fRawDataHandler=new AliHLTOUTSDDRawDataHandler;
    }
    return fRawDataHandler;
  }
  return NULL;
}

int AliHLTITSAgent::DeleteOutputHandler(AliHLTOUTHandler* pInstance)
{
  // see header file for class documentation
  if (pInstance==NULL) return -EINVAL;

  if (pInstance==fRawDataHandler) {
    delete fRawDataHandler;
    fRawDataHandler=NULL;
    return 0;
  }

  delete pInstance;
  return 0;
}

int AliHLTITSAgent::AliHLTOUTSDDRawDataHandler::ProcessData(AliHLTOUT* pData)
{
  // see header file for class documentation
  if (!pData) return -EINVAL;
  static int errorCount=0;
  const int maxErrorCount=10;
  AliHLTComponentDataType dt=kAliHLTVoidDataType;
  AliHLTUInt32_t spec=kAliHLTVoidDataSpec;
  int iResult=pData->GetDataBlockDescription(dt, spec);
  if (iResult>=0) {
    if (dt==(kAliHLTDataTypeDDLRaw|kAliHLTDataOriginITSSDD)) {
      int ddlOffset=256;//AliDAQ::DdlIDOffset("ITSSDD");
      int numberOfDDLs=24;//AliDAQ::NumberOfDdls("ITSSDD");
      int ddlNo=0;
      for (;ddlNo<32 && ddlNo<numberOfDDLs; ddlNo++) {
	if (spec&(0x1<<ddlNo)) break;
      }
      if (ddlNo>=32 || ddlNo>=numberOfDDLs) {
	HLTError("invalid specification 0x%08x: can not extract DDL id for data block %s", spec, AliHLTComponent::DataType2Text(dt).c_str());
	iResult=-ENODEV;
      } else if (spec^(0x1<<ddlNo)) {
	iResult=-EEXIST;
	HLTError("multiple links set in specification 0x%08x: can not extract DDL id for data block %s", spec, AliHLTComponent::DataType2Text(dt).c_str());
      } else {
	iResult=ddlOffset+ddlNo;
      }
    } else {
      if (errorCount++<10) {
	HLTError("wrong data type: expecting %s, got %s; %s",
		 AliHLTComponent::DataType2Text(kAliHLTDataTypeDDLRaw|kAliHLTDataOriginITSSDD).c_str(),
		 AliHLTComponent::DataType2Text(dt).c_str(),
		   errorCount==maxErrorCount?"suppressing further error messages":"");
      }
      iResult=-EFAULT;
    }
  }
  return iResult;
}

int AliHLTITSAgent::CreateCFConfigurations(AliHLTConfigurationHandler* pHandler, int detectorId, TString& output) const
{
  // see header file for class documentation
  if (!pHandler) return -EINVAL;

  ///////////////////////////////////////////////////////////////////////////////////////////////////
  //
  // define the ITS cluster finder components
  //

  //The spec starts from 0x1 in SPD, SDD and SSD. So 0x1 is ddl 0 for SPD, 0x10 is ddl 1, and so on
  //in SDD 0x1 is ddl 256, 0x10 is ddl 257, and so on. This means that the spec has to be set to 0x1
  //before the loops over the clusterfinder

  TString idString=AliHLTDAQ::DetectorName(detectorId);
  if (idString.CompareTo("ITSSPD") &&
      idString.CompareTo("ITSSDD") &&
      idString.CompareTo("ITSSSD")) {
    HLTError("invalid detector id %d does not describe any ITS detector", detectorId);
    return -ENOENT;
  }

  int minddl=AliHLTDAQ::DdlIDOffset(detectorId);
  int maxddl=minddl+AliHLTDAQ::NumberOfDdls(detectorId)-1;
  int spec=0x1;
  int ddlno=0;

  bool bOneCFperDDL=false;
  TString origin=idString; origin.ReplaceAll("ITS", "I");
  TString cfBase=idString; cfBase+="_CF";
  TString componentId=idString; componentId.ReplaceAll("ITS", "ITSClusterFinder");
  TString cfinput, cf;
  for(ddlno=minddl;ddlno<=maxddl;ddlno++){
    TString arg, publisher;

    // the HLT origin defines are 4 chars: ISPD, ISSD, ISDD respectively
    arg.Form("-minid %d -datatype 'DDL_RAW ' '%s' -dataspec 0x%08x",ddlno, origin.Data(), spec);
    if (CheckFilter(kHLTLogDebug)) arg+=" -verbose";
    publisher.Form("ITS-DP_%d", ddlno);
    pHandler->CreateConfiguration(publisher.Data(), "AliRawReaderPublisher", NULL , arg.Data());

    if (cfinput.Length()>0) cfinput+=" ";
    cfinput+=publisher;

    if (bOneCFperDDL) {
    cf.Form("%s_%d",cfBase.Data(), ddlno);
    pHandler->CreateConfiguration(cf.Data(), componentId.Data(), publisher.Data(), "");

    if (output.Length()>0) output+=" ";
    output+=cf;
    }

    spec=spec<<1;
  }

  if (bOneCFperDDL) {
    cf.Form("%s",cfBase.Data());
    pHandler->CreateConfiguration(cf.Data(), componentId.Data(), cfinput.Data(), "");

    if (output.Length()>0) output+=" ";
    output+=cf;
  }

  return 0;
}
<commit_msg>bugfix: correct use of the condition variable<commit_after>// $Id$

//**************************************************************************
//* This file is property of and copyright by the ALICE HLT Project        *
//* ALICE Experiment at CERN, All rights reserved.                         *
//*                                                                        *
//* Primary Authors: Matthias Richter <Matthias.Richter@ift.uib.no>        *
//*                  for The ALICE HLT Project.                            *
//*                                                                        *
//* Permission to use, copy, modify and distribute this software and its   *
//* documentation strictly for non-commercial purposes is hereby granted   *
//* without fee, provided that the above copyright notice appears in all   *
//* copies and that both the copyright notice and this permission notice   *
//* appear in the supporting documentation. The authors make no claims     *
//* about the suitability of this software for any purpose. It is          *
//* provided "as is" without express or implied warranty.                  *
//**************************************************************************

//  @file   AliHLTITSAgent.cxx
//  @author Matthias Richter
//  @date   25.08.2008
//  @brief  Agent of the libAliHLTITS library
//  @note

#include <cassert>
#include "AliHLTITSAgent.h"
#include "AliHLTConfiguration.h"
#include "AliHLTOUT.h"
#include "AliHLTDAQ.h"

// header files of library components
#include "AliHLTITSCompressRawDataSDDComponent.h"
#include "AliHLTITSSSDQARecPointsComponent.h"
#include "AliHLTITSQAComponent.h"
#include "AliHLTITSClusterFinderComponent.h"
#include "AliHLTITSClusterHistoComponent.h"
#include "AliHLTITSTrackerComponent.h"
#include "AliHLTITSVertexerSPDComponent.h"
#include "AliHLTITSDigitPublisherComponent.h"

// header file of the module preprocessor
// none at the moment

/** global instance for agent registration */
AliHLTITSAgent gAliHLTITSAgent;

/** ROOT macro for the implementation of ROOT specific class methods */
ClassImp(AliHLTITSAgent)

AliHLTITSAgent::AliHLTITSAgent()
  :
  AliHLTModuleAgent("ITS"),
  fRawDataHandler(NULL)
{
  // see header file for class documentation
  // or
  // refer to README to build package
  // or
  // visit http://web.ift.uib.no/~kjeks/doc/alice-hlt
}

AliHLTITSAgent::~AliHLTITSAgent()
{
  // see header file for class documentation
}

int AliHLTITSAgent::CreateConfigurations(AliHLTConfigurationHandler* handler,
					 AliRawReader* rawReader,
					 AliRunLoader* runloader) const
{
  // see header file for class documentation
  int iResult=0;
  if (!handler) return -EINVAL;

  ///////////////////////////////////////////////////////////////////////////////////////////////////
  ///////////////////////////////////////////////////////////////////////////////////////////////////
  //
  // ITS tracking is currently only working on raw data
  // to run on digits, a digit publisher needs to be implemented

  TString trackerInput="";
  TString vertexerSPDInput="";
  if (rawReader || !runloader) {
    // AliSimulation: use the AliRawReaderPublisher if the raw reader is available
    // Alireconstruction: indicated by runloader==NULL, run always on raw data

    ///////////////////////////////////////////////////////////////////////////////////////////////////
    //
    // define the ITS cluster finder configurations
    //

    TString spdCF;
    TString ssdCF;
    TString sddCF;

    iResult=CreateCFConfigurations(handler, AliHLTDAQ::DetectorID("ITSSPD"), spdCF);
    handler->CreateConfiguration("ITS-SPD-CF","BlockFilter",spdCF.Data(),"");

    iResult=CreateCFConfigurations(handler, AliHLTDAQ::DetectorID("ITSSDD"), sddCF);
    handler->CreateConfiguration("ITS-SDD-CF","BlockFilter",sddCF.Data(),"");

    iResult=CreateCFConfigurations(handler, AliHLTDAQ::DetectorID("ITSSSD"), ssdCF);
    handler->CreateConfiguration("ITS-SSD-CF","BlockFilter",ssdCF.Data(),"");

    ///////////////////////////////////////////////////////////////////////////////////////////////////
    //
    // define the SPD vertexer Z input
    //
    vertexerSPDInput="ITS-SPD-CF";

    ///////////////////////////////////////////////////////////////////////////////////////////////////
    //
    // define the ITS tracker input
    //
    trackerInput="ITS-SPD-CF ITS-SDD-CF ITS-SSD-CF";
  }
  else if (runloader && !rawReader) {
    // indicates AliSimulation with no RawReader available -> run on digits

    ///////////////////////////////////////////////////////////////////////////////////////////////////
    //
    // define the Digit Publisher and ITS cluster finder configuration
    //
    handler->CreateConfiguration("DigitPublisher","AliLoaderPublisher",NULL,"-loader ITSLoader -datatype 'ALITREED' 'ITS '");
    handler->CreateConfiguration("DigitClusterFinder","ITSClusterFinderDigits","DigitPublisher","");

    ///////////////////////////////////////////////////////////////////////////////////////////////////
    //
    // define the SPD vertexer Z input.
    //
    // Can not run on Digit ClusterFinder. Wrong inputtype. And wrong input data.
    // If this is fixed in the VertexerSPD it needs to implement the data type
    // handling for the ITS digits and ignore the input from the SDD and SSD
    //vertexerSPDInput="DigitClusterFinder";

    ///////////////////////////////////////////////////////////////////////////////////////////////////
    //
    // define the ITS tracker input
    //
    // Currently there is a seg fault in the TTree access from the DigitClusterFinder
    // needs first to be investigated
    //trackerInput="DigitClusterFinder";
  }

  ///////////////////////////////////////////////////////////////////////////////////////////////////
  //
  // define the SPD vertexer Z configuration
  //
  if (!vertexerSPDInput.IsNull()) {
    handler->CreateConfiguration("ITS-SPD-vertexer","ITSVertexerSPD", vertexerSPDInput, "");
  }

  ///////////////////////////////////////////////////////////////////////////////////////////////////
  //
  // define the ITS tracker configuration
  //
  if (!trackerInput.IsNull()) {
    if (handler->FindConfiguration("TPC-globalmerger")) {
      // add the TPC tracking if available
      trackerInput+=" TPC-globalmerger";
    }
    handler->CreateConfiguration("ITS-tracker","ITSTracker",trackerInput.Data(),"");
  }

  return 0;
}

const char* AliHLTITSAgent::GetReconstructionChains(AliRawReader* /*rawReader*/,
						       AliRunLoader* runloader) const
{
  // see header file for class documentation
  if (runloader) {
    // reconstruction chains for AliRoot simulation
    // Note: run loader is only available while running embedded into
    // AliRoot simulation

    // the chain is just defined and can be used as input for subsequent
    // components
    //return "ITS-tracker";
  }

  return "";
}

const char* AliHLTITSAgent::GetRequiredComponentLibraries() const
{
  // see header file for class documentation
  return "libAliHLTUtil.so libAliHLTRCU.so libAliHLTTPC.so";
}

int AliHLTITSAgent::RegisterComponents(AliHLTComponentHandler* pHandler) const
{
  // see header file for class documentation
  assert(pHandler);
  if (!pHandler) return -EINVAL;
  pHandler->AddComponent(new AliHLTITSCompressRawDataSDDComponent);
  pHandler->AddComponent(new AliHLTITSSSDQARecPointsComponent);
  pHandler->AddComponent(new AliHLTITSQAComponent);
  pHandler->AddComponent(new AliHLTITSClusterFinderComponent(AliHLTITSClusterFinderComponent::kClusterFinderSPD));
  pHandler->AddComponent(new AliHLTITSClusterFinderComponent(AliHLTITSClusterFinderComponent::kClusterFinderSDD));
  pHandler->AddComponent(new AliHLTITSClusterFinderComponent(AliHLTITSClusterFinderComponent::kClusterFinderSSD));
  pHandler->AddComponent(new AliHLTITSClusterFinderComponent(AliHLTITSClusterFinderComponent::kClusterFinderDigits));
  pHandler->AddComponent(new AliHLTITSClusterHistoComponent);
  pHandler->AddComponent(new AliHLTITSTrackerComponent);
  pHandler->AddComponent(new AliHLTITSVertexerSPDComponent);
  pHandler->AddComponent(new AliHLTITSDigitPublisherComponent);

  return 0;
}

AliHLTModulePreprocessor* AliHLTITSAgent::GetPreprocessor()
{
  // see header file for class documentation
  return NULL;
}

int AliHLTITSAgent::GetHandlerDescription(AliHLTComponentDataType dt,
					     AliHLTUInt32_t spec,
					     AliHLTOUTHandlerDesc& desc) const
{
  // see header file for class documentation

  // Handlers for ITS raw data. Even though there are 3 detectors
  // everything is handled in one module library and one HLTOUT handler.
  // This assumes that the data blocks are sent with data type
  // {DDL_RAW :ISDD} and the bit set in the specification corresponding.
  // to detector DDL id.
  // An HLTOUT handler is implemented to extract the equipment id from
  // the specification.
  // Note: Future versions of the framework will provide a default handler
  // class with that functionality.
  if (dt==(kAliHLTDataTypeDDLRaw|kAliHLTDataOriginITSSDD)) {
      desc=AliHLTOUTHandlerDesc(kRawReader, dt, GetModuleId());
      HLTInfo("module %s handles data block type %s specification %d (0x%x)",
	      GetModuleId(), AliHLTComponent::DataType2Text(dt).c_str(), spec, spec);
      return 1;
  }
  return 0;
}

AliHLTOUTHandler* AliHLTITSAgent::GetOutputHandler(AliHLTComponentDataType dt,
						   AliHLTUInt32_t /*spec*/)
{
  // see header file for class documentation
  if (dt==(kAliHLTDataTypeDDLRaw|kAliHLTDataOriginITSSDD)) {
    // use the default handler
    if (!fRawDataHandler) {
      fRawDataHandler=new AliHLTOUTSDDRawDataHandler;
    }
    return fRawDataHandler;
  }
  return NULL;
}

int AliHLTITSAgent::DeleteOutputHandler(AliHLTOUTHandler* pInstance)
{
  // see header file for class documentation
  if (pInstance==NULL) return -EINVAL;

  if (pInstance==fRawDataHandler) {
    delete fRawDataHandler;
    fRawDataHandler=NULL;
    return 0;
  }

  delete pInstance;
  return 0;
}

int AliHLTITSAgent::AliHLTOUTSDDRawDataHandler::ProcessData(AliHLTOUT* pData)
{
  // see header file for class documentation
  if (!pData) return -EINVAL;
  static int errorCount=0;
  const int maxErrorCount=10;
  AliHLTComponentDataType dt=kAliHLTVoidDataType;
  AliHLTUInt32_t spec=kAliHLTVoidDataSpec;
  int iResult=pData->GetDataBlockDescription(dt, spec);
  if (iResult>=0) {
    if (dt==(kAliHLTDataTypeDDLRaw|kAliHLTDataOriginITSSDD)) {
      int ddlOffset=256;//AliDAQ::DdlIDOffset("ITSSDD");
      int numberOfDDLs=24;//AliDAQ::NumberOfDdls("ITSSDD");
      int ddlNo=0;
      for (;ddlNo<32 && ddlNo<numberOfDDLs; ddlNo++) {
	if (spec&(0x1<<ddlNo)) break;
      }
      if (ddlNo>=32 || ddlNo>=numberOfDDLs) {
	HLTError("invalid specification 0x%08x: can not extract DDL id for data block %s", spec, AliHLTComponent::DataType2Text(dt).c_str());
	iResult=-ENODEV;
      } else if (spec^(0x1<<ddlNo)) {
	iResult=-EEXIST;
	HLTError("multiple links set in specification 0x%08x: can not extract DDL id for data block %s", spec, AliHLTComponent::DataType2Text(dt).c_str());
      } else {
	iResult=ddlOffset+ddlNo;
      }
    } else {
      if (errorCount++<10) {
	HLTError("wrong data type: expecting %s, got %s; %s",
		 AliHLTComponent::DataType2Text(kAliHLTDataTypeDDLRaw|kAliHLTDataOriginITSSDD).c_str(),
		 AliHLTComponent::DataType2Text(dt).c_str(),
		   errorCount==maxErrorCount?"suppressing further error messages":"");
      }
      iResult=-EFAULT;
    }
  }
  return iResult;
}

int AliHLTITSAgent::CreateCFConfigurations(AliHLTConfigurationHandler* pHandler, int detectorId, TString& output) const
{
  // see header file for class documentation
  if (!pHandler) return -EINVAL;

  ///////////////////////////////////////////////////////////////////////////////////////////////////
  //
  // define the ITS cluster finder components
  //

  //The spec starts from 0x1 in SPD, SDD and SSD. So 0x1 is ddl 0 for SPD, 0x10 is ddl 1, and so on
  //in SDD 0x1 is ddl 256, 0x10 is ddl 257, and so on. This means that the spec has to be set to 0x1
  //before the loops over the clusterfinder

  TString idString=AliHLTDAQ::DetectorName(detectorId);
  if (idString.CompareTo("ITSSPD") &&
      idString.CompareTo("ITSSDD") &&
      idString.CompareTo("ITSSSD")) {
    HLTError("invalid detector id %d does not describe any ITS detector", detectorId);
    return -ENOENT;
  }

  int minddl=AliHLTDAQ::DdlIDOffset(detectorId);
  int maxddl=minddl+AliHLTDAQ::NumberOfDdls(detectorId)-1;
  int spec=0x1;
  int ddlno=0;

  bool bOneCFperDDL=false;
  TString origin=idString; origin.ReplaceAll("ITS", "I");
  TString cfBase=idString; cfBase+="_CF";
  TString componentId=idString; componentId.ReplaceAll("ITS", "ITSClusterFinder");
  TString cfinput, cf;
  for(ddlno=minddl;ddlno<=maxddl;ddlno++){
    TString arg, publisher;

    // the HLT origin defines are 4 chars: ISPD, ISSD, ISDD respectively
    arg.Form("-minid %d -datatype 'DDL_RAW ' '%s' -dataspec 0x%08x",ddlno, origin.Data(), spec);
    if (CheckFilter(kHLTLogDebug)) arg+=" -verbose";
    publisher.Form("ITS-DP_%d", ddlno);
    pHandler->CreateConfiguration(publisher.Data(), "AliRawReaderPublisher", NULL , arg.Data());

    if (cfinput.Length()>0) cfinput+=" ";
    cfinput+=publisher;

    if (bOneCFperDDL) {
    cf.Form("%s_%d",cfBase.Data(), ddlno);
    pHandler->CreateConfiguration(cf.Data(), componentId.Data(), publisher.Data(), "");

    if (output.Length()>0) output+=" ";
    output+=cf;
    }

    spec=spec<<1;
  }

  if (!bOneCFperDDL) {
    cf.Form("%s",cfBase.Data());
    pHandler->CreateConfiguration(cf.Data(), componentId.Data(), cfinput.Data(), "");

    if (output.Length()>0) output+=" ";
    output+=cf;
  }

  return 0;
}
<|endoftext|>


<commit_before>//#define CONSOLE_DEBUG

#include <iostream>
#include <thread>
#include <Windows.h>
#include "Core/Halite.h"

GLFWwindow * window;

void handleMouse(GLFWwindow * w, int button, int action, int mods);
void handleCursor(GLFWwindow * w, double x, double y);
void handleKeys(GLFWwindow * w, int button, int scancode, int action, int mods);
void handleChars(GLFWwindow * w, unsigned int code);
void handleDrop(GLFWwindow * w, int count, const char ** paths);
void handleErrors(int error, const char * description);
void handleResize(GLFWwindow * w, int width, int height);

void renderLaunch();

Halite * my_game; //Is a pointer to avoid problems with assignment, dynamic memory, and default constructors.
bool isPaused = false, leftPressed = false, rightPressed = false, upPressed = false, downPressed = false, shiftPressed = false, newGame = false, isLaunch = true, mousePressed = false;
float maxFps = 8, turnNumber = 0, graphZoom = 1.0, maxZoom, mouseX, mouseY;
short numTurns;

std::string filename;
std::fstream debug;

FTPixmapFont * t;

#ifdef CONSOLE_DEBUG
int main()
#else
INT WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR lpCmdLine, INT nCmdShow)
#endif
{
	//Open debug:
	std::string debugfilename = "logs/";
	time_t rawtime;
	tm timeinfo;
	time(&rawtime);
	localtime_s(&timeinfo, &rawtime);
	const int STRING_LEN = 30;  char timeC[STRING_LEN]; asctime_s(timeC, STRING_LEN, &timeinfo);
	std::string timeString(timeC);  timeString.pop_back();
	std::replace_if(timeString.begin(), timeString.end(), [](char c) -> bool { return c == ' '; }, '_');
	std::replace_if(timeString.begin(), timeString.end(), [](char c) -> bool { return c == ':'; }, '-');
	debugfilename += timeString.substr(4);
	debugfilename += ".log";
	debug.open(debugfilename, std::ios_base::out);
	if(!debug.is_open()) //If file couldn't be opened.
	{
		debug.open("DEBUG.log", std::ios_base::out);
		debug << "I couldn't find the folder \"logs\" and consequently can't create multiple logs. Please create that folder for me in the future.";
		debug.flush();
	}

	// start GL context and O/S window using the GLFW helper library
	if(!glfwInit())
	{
		debug << "Could not start GLFW3\n";
		return EXIT_FAILURE;
	}

	GLFWmonitor* primary = glfwGetPrimaryMonitor();
	const GLFWvidmode * mode = glfwGetVideoMode(primary);
	glfwWindowHint(GLFW_REFRESH_RATE, mode->refreshRate);

	window = glfwCreateWindow(mode->width * 2 / 3, mode->height * 2 / 3, "Halite", NULL, NULL);
	if(!window)
	{
		debug << "Could not open window with GLFW3\n";
		glfwTerminate();
		return EXIT_FAILURE;
	}

	glfwMakeContextCurrent(window);

	glewExperimental = GL_TRUE;
	if(glewInit() != GLEW_OK) return EXIT_FAILURE;

	util::initShaderHandler(&debug);
	t = new FTPixmapFont("fonts/FreeSans.ttf");
	t->FaceSize(48);

	//Set handlers:

	//Set leopard handler.
	glfwSetKeyCallback(window, handleKeys);
	//Set character handler.
	glfwSetCharCallback(window, handleChars);
	//Set mouse handler
	glfwSetMouseButtonCallback(window, handleMouse);
	//Set cursor handler.
	glfwSetCursorPosCallback(window, handleCursor);
	//Set error callback handler
	glfwSetErrorCallback(handleErrors);
	//Set file drop function
	glfwSetDropCallback(window, handleDrop);
	//Set window resize handler
	glfwSetWindowSizeCallback(window, handleResize);

	my_game = new Halite();
	while(isLaunch && !glfwWindowShouldClose(window)) renderLaunch();

	clock_t c = clock();
	while(!glfwWindowShouldClose(window))
	{
		//Limit render rate:
		float delta = float(clock() - c) / CLOCKS_PER_SEC;
		c = clock();

		short turnNumberS = turnNumber;
		my_game->render(window, turnNumberS, graphZoom, mouseX, mouseY, mousePressed);
		if(abs(turnNumber - float(turnNumberS) > 1)) turnNumber = turnNumberS; //Means it's gone past the right edge

		//Poll events
		glfwPollEvents();

		if(upPressed && maxFps <= 120) maxFps += maxFps * delta;
		else if(downPressed && maxFps != 4) maxFps -= maxFps * delta;

		if(leftPressed)
		{
			if(shiftPressed) turnNumber -= 5 * maxFps * delta;
			else turnNumber -= maxFps * delta;
		}
		else if(rightPressed)
		{
			if(shiftPressed) turnNumber += 5 * maxFps * delta;
			else turnNumber += maxFps * delta;
		}
		else if(!isPaused) turnNumber += maxFps * delta;
		if(turnNumber < 0) turnNumber = 0;
	}

	return EXIT_SUCCESS;
}

void handleMouse(GLFWwindow * w, int button, int action, int mods)
{
	if(button == GLFW_MOUSE_BUTTON_1)
	{
		mousePressed = action == GLFW_PRESS;
	}
}

void handleCursor(GLFWwindow * w, double x, double y)
{
	int sx, sy; glfwGetWindowSize(window, &sx, &sy);
	mouseX = (float(2 * x) / sx) - 1.0;
	mouseY = (float(-2 * y) / sy) + 1.0;
}

void handleKeys(GLFWwindow * w, int key, int scancode, int action, int mods)
{
	if(key == GLFW_KEY_LEFT && action == GLFW_PRESS)
	{
		leftPressed = true;
		isPaused = true;
	}
	else if(key == GLFW_KEY_RIGHT && action == GLFW_PRESS)
	{
		rightPressed = true;
		isPaused = true;
	}
	else if(key == GLFW_KEY_LEFT && action == GLFW_RELEASE)
	{
		leftPressed = false;
	}
	else if(key == GLFW_KEY_RIGHT && action == GLFW_RELEASE)
	{
		rightPressed = false;
	}
	else if(key == GLFW_KEY_UP && action == GLFW_PRESS)
	{
		upPressed = true;
	}
	else if(key == GLFW_KEY_DOWN && action == GLFW_PRESS)
	{
		downPressed = true;
	}
	else if(key == GLFW_KEY_UP && action == GLFW_RELEASE)
	{
		upPressed = false;
	}
	else if(key == GLFW_KEY_DOWN && action == GLFW_RELEASE)
	{
		downPressed = false;
	}
	else if((key == GLFW_KEY_LEFT_SHIFT || key == GLFW_KEY_RIGHT_SHIFT) && action == GLFW_PRESS)
	{
		shiftPressed = true;
	}
	else if((key == GLFW_KEY_LEFT_SHIFT || key == GLFW_KEY_RIGHT_SHIFT) && action == GLFW_RELEASE)
	{
		shiftPressed = false;
	}
	else if(key == GLFW_KEY_ESCAPE)
	{
		exit(0);
	}
}

void handleChars(GLFWwindow * w, unsigned int code)
{
	if(code == ' ') isPaused = !isPaused;
	else if(code == '+')
	{
		graphZoom *= 1.5;
		if(graphZoom > maxZoom) graphZoom = maxZoom;
	}
	else if(code == '-')
	{
		graphZoom /= 1.5;
		if(graphZoom < 1) graphZoom = 1;
	}
	else if(code == '>' || code == '.')
	{
		turnNumber++;
		isPaused = true;
	}
	else if(code == '<' || code == ',')
	{
		turnNumber--;
		isPaused = true;
	}
	else if(code == 'Z' || code == 'z')
	{
		turnNumber = 0;
	}
	else if(code == 'X' || code == 'x')
	{
		turnNumber = numTurns - 1;
	}
}

void handleDrop(GLFWwindow * w, int count, const char ** paths)
{
	unsigned short wi, he;
	try
	{
		numTurns = my_game->input(w, paths[0], wi, he);
	}
	catch(std::runtime_error e)
	{
		debug << e.what();
#ifdef CONSOLE_DEBUG
		std::cout << e.what();
#endif
		return;
	}
	const int MIN_POINTS_VISIBLE = 3;
	//Set new max_zoom. We allow zooming until only MIN_POINTS_VISIBLE points are visible.
	maxZoom = numTurns / float(MIN_POINTS_VISIBLE);
	isLaunch = false;
	isPaused = false;
	turnNumber = 0;
}

void handleErrors(int error, const char * description)
{
	debug << description;
}

void handleResize(GLFWwindow * w, int width, int height)
{
	glViewport(0, 0, width, height);
}

void renderLaunch()
{
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	util::renderText(t, window, -.85, 0.0, 36, "Drop a replay on-screen to watch it!");

	glfwSwapBuffers(window);
	glfwPollEvents();
}<commit_msg>Get GL Version<commit_after>//#define CONSOLE_DEBUG

#include <iostream>
#include <thread>
#include <Windows.h>
#include "Core/Halite.h"

GLFWwindow * window;

void handleMouse(GLFWwindow * w, int button, int action, int mods);
void handleCursor(GLFWwindow * w, double x, double y);
void handleKeys(GLFWwindow * w, int button, int scancode, int action, int mods);
void handleChars(GLFWwindow * w, unsigned int code);
void handleDrop(GLFWwindow * w, int count, const char ** paths);
void handleErrors(int error, const char * description);
void handleResize(GLFWwindow * w, int width, int height);

void renderLaunch();

Halite * my_game; //Is a pointer to avoid problems with assignment, dynamic memory, and default constructors.
bool isPaused = false, leftPressed = false, rightPressed = false, upPressed = false, downPressed = false, shiftPressed = false, newGame = false, isLaunch = true, mousePressed = false;
float maxFps = 8, turnNumber = 0, graphZoom = 1.0, maxZoom, mouseX, mouseY;
short numTurns;

std::string filename;
std::fstream debug;

FTPixmapFont * t;

#ifdef CONSOLE_DEBUG
int main()
#else
INT WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR lpCmdLine, INT nCmdShow)
#endif
{
	//Open debug:
	std::string debugfilename = "logs/";
	time_t rawtime;
	tm timeinfo;
	time(&rawtime);
	localtime_s(&timeinfo, &rawtime);
	const int STRING_LEN = 30;  char timeC[STRING_LEN]; asctime_s(timeC, STRING_LEN, &timeinfo);
	std::string timeString(timeC);  timeString.pop_back();
	std::replace_if(timeString.begin(), timeString.end(), [](char c) -> bool { return c == ' '; }, '_');
	std::replace_if(timeString.begin(), timeString.end(), [](char c) -> bool { return c == ':'; }, '-');
	debugfilename += timeString.substr(4);
	debugfilename += ".log";
	debug.open(debugfilename, std::ios_base::out);
	if(!debug.is_open()) //If file couldn't be opened.
	{
		debug.open("DEBUG.log", std::ios_base::out);
		debug << "I couldn't find the folder \"logs\" and consequently can't create multiple logs. Please create that folder for me in the future.";
		debug.flush();
	}

	// start GL context and O/S window using the GLFW helper library
	if(!glfwInit())
	{
		debug << "Could not start GLFW3\n";
		return EXIT_FAILURE;
	}

	glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4.3);
	glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 4);
	glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

	GLFWmonitor* primary = glfwGetPrimaryMonitor();
	const GLFWvidmode * mode = glfwGetVideoMode(primary);
	glfwWindowHint(GLFW_REFRESH_RATE, mode->refreshRate);

	window = glfwCreateWindow(mode->width * 2 / 3, mode->height * 2 / 3, "Halite", NULL, NULL);
	if(!window)
	{
		debug << "Could not open window with GLFW3\n";
		glfwTerminate();
		return EXIT_FAILURE;
	}

	glfwMakeContextCurrent(window);

	glewExperimental = GL_TRUE;
	if(glewInit() != GLEW_OK) return EXIT_FAILURE;

	const char * glVersion = (const char * )glGetString(GL_VERSION);
	debug << glVersion;
	debug.flush();

	util::initShaderHandler(&debug);
	t = new FTPixmapFont("fonts/FreeSans.ttf");
	t->FaceSize(48);

	//Set handlers:

	//Set leopard handler.
	glfwSetKeyCallback(window, handleKeys);
	//Set character handler.
	glfwSetCharCallback(window, handleChars);
	//Set mouse handler
	glfwSetMouseButtonCallback(window, handleMouse);
	//Set cursor handler.
	glfwSetCursorPosCallback(window, handleCursor);
	//Set error callback handler
	glfwSetErrorCallback(handleErrors);
	//Set file drop function
	glfwSetDropCallback(window, handleDrop);
	//Set window resize handler
	glfwSetWindowSizeCallback(window, handleResize);

	my_game = new Halite();
	while(isLaunch && !glfwWindowShouldClose(window)) renderLaunch();

	clock_t c = clock();
	while(!glfwWindowShouldClose(window))
	{
		//Limit render rate:
		float delta = float(clock() - c) / CLOCKS_PER_SEC;
		c = clock();

		short turnNumberS = turnNumber;
		my_game->render(window, turnNumberS, graphZoom, mouseX, mouseY, mousePressed);
		if(abs(turnNumber - float(turnNumberS) > 1)) turnNumber = turnNumberS; //Means it's gone past the right edge

		//Poll events
		glfwPollEvents();

		if(upPressed && maxFps <= 120) maxFps += maxFps * delta;
		else if(downPressed && maxFps != 4) maxFps -= maxFps * delta;

		if(leftPressed)
		{
			if(shiftPressed) turnNumber -= 5 * maxFps * delta;
			else turnNumber -= maxFps * delta;
		}
		else if(rightPressed)
		{
			if(shiftPressed) turnNumber += 5 * maxFps * delta;
			else turnNumber += maxFps * delta;
		}
		else if(!isPaused) turnNumber += maxFps * delta;
		if(turnNumber < 0) turnNumber = 0;
	}

	return EXIT_SUCCESS;
}

void handleMouse(GLFWwindow * w, int button, int action, int mods)
{
	if(button == GLFW_MOUSE_BUTTON_1)
	{
		mousePressed = action == GLFW_PRESS;
	}
}

void handleCursor(GLFWwindow * w, double x, double y)
{
	int sx, sy; glfwGetWindowSize(window, &sx, &sy);
	mouseX = (float(2 * x) / sx) - 1.0;
	mouseY = (float(-2 * y) / sy) + 1.0;
}

void handleKeys(GLFWwindow * w, int key, int scancode, int action, int mods)
{
	if(key == GLFW_KEY_LEFT && action == GLFW_PRESS)
	{
		leftPressed = true;
		isPaused = true;
	}
	else if(key == GLFW_KEY_RIGHT && action == GLFW_PRESS)
	{
		rightPressed = true;
		isPaused = true;
	}
	else if(key == GLFW_KEY_LEFT && action == GLFW_RELEASE)
	{
		leftPressed = false;
	}
	else if(key == GLFW_KEY_RIGHT && action == GLFW_RELEASE)
	{
		rightPressed = false;
	}
	else if(key == GLFW_KEY_UP && action == GLFW_PRESS)
	{
		upPressed = true;
	}
	else if(key == GLFW_KEY_DOWN && action == GLFW_PRESS)
	{
		downPressed = true;
	}
	else if(key == GLFW_KEY_UP && action == GLFW_RELEASE)
	{
		upPressed = false;
	}
	else if(key == GLFW_KEY_DOWN && action == GLFW_RELEASE)
	{
		downPressed = false;
	}
	else if((key == GLFW_KEY_LEFT_SHIFT || key == GLFW_KEY_RIGHT_SHIFT) && action == GLFW_PRESS)
	{
		shiftPressed = true;
	}
	else if((key == GLFW_KEY_LEFT_SHIFT || key == GLFW_KEY_RIGHT_SHIFT) && action == GLFW_RELEASE)
	{
		shiftPressed = false;
	}
	else if(key == GLFW_KEY_ESCAPE)
	{
		exit(0);
	}
}

void handleChars(GLFWwindow * w, unsigned int code)
{
	if(code == ' ') isPaused = !isPaused;
	else if(code == '+')
	{
		graphZoom *= 1.5;
		if(graphZoom > maxZoom) graphZoom = maxZoom;
	}
	else if(code == '-')
	{
		graphZoom /= 1.5;
		if(graphZoom < 1) graphZoom = 1;
	}
	else if(code == '>' || code == '.')
	{
		turnNumber++;
		isPaused = true;
	}
	else if(code == '<' || code == ',')
	{
		turnNumber--;
		isPaused = true;
	}
	else if(code == 'Z' || code == 'z')
	{
		turnNumber = 0;
	}
	else if(code == 'X' || code == 'x')
	{
		turnNumber = numTurns - 1;
	}
}

void handleDrop(GLFWwindow * w, int count, const char ** paths)
{
	unsigned short wi, he;
	try
	{
		numTurns = my_game->input(w, paths[0], wi, he);
	}
	catch(std::runtime_error e)
	{
		debug << e.what();
#ifdef CONSOLE_DEBUG
		std::cout << e.what();
#endif
		return;
	}
	const int MIN_POINTS_VISIBLE = 3;
	//Set new max_zoom. We allow zooming until only MIN_POINTS_VISIBLE points are visible.
	maxZoom = numTurns / float(MIN_POINTS_VISIBLE);
	isLaunch = false;
	isPaused = false;
	turnNumber = 0;
}

void handleErrors(int error, const char * description)
{
	debug << description;
}

void handleResize(GLFWwindow * w, int width, int height)
{
	glViewport(0, 0, width, height);
}

void renderLaunch()
{
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	util::renderText(t, window, -.85, 0.0, 36, "Drop a replay on-screen to watch it!");

	glfwSwapBuffers(window);
	glfwPollEvents();
}<|endoftext|>


<commit_before><commit_msg>2 Bug fixes:   - Set-Cookie delimiter was a comma, but should have been a NUL.   - Requests with query strings containing 'http://' caused request url paths     to be truncated.<commit_after><|endoftext|>


<commit_before><commit_msg>Mark HTTPSRequestTest.HTTPSErrorsNoClobberTSSTest flaky.<commit_after><|endoftext|>


<commit_before><commit_msg>The FTPDirectoryListing test has been failing in a couple of runs. Marking it as flaky<commit_after><|endoftext|>


<commit_before>// This program reads two ints from file and returns average
// filename: readFromFile
// Programmer: J. Guerra
// Last Modified: Nov 17, 2015

#include <iostream>
#include <string>
#include <fstream>
using namespace std;

void main() {
	string input;
	int a, b;
	ifstream file;

	// title block
	cout
		<< "\t This program asks the user for the name of a file \n"
		<< "\t             that contains two numbers,            \n"
		<< "\t      and prints on the monitor their average      \n"
		<< "\t                    by J. Guerra                   \n" << endl;

	// prompt for file
	cout << "What file contains your data? ";
	getline(cin, input);

	file.open(input);

	if (!file) {				// check if file is good
		system("color 98");		// background 9 = light blue, text 8 = gray
		cout << "\aFailed to open file: \"" << input << "\". Exiting the program.\n\n";

		system("pause");
		exit(0);
	}

	file >> a >> b;

	cout << "The average of " << a << " and " << b << " is: " << (a + b) / 2.0 << ".\n\n";

	file.close();

	system("pause");
}<commit_msg>moved the line up to protect file<commit_after>// This program reads two ints from file and returns average
// filename: readFromFile
// Programmer: J. Guerra
// Last Modified: Nov 17, 2015

#include <iostream>
#include <string>
#include <fstream>
using namespace std;

void main() {
	string input;
	int a, b;
	ifstream file;

	// title block
	cout
		<< "\t This program asks the user for the name of a file \n"
		<< "\t             that contains two numbers,            \n"
		<< "\t      and prints on the monitor their average      \n"
		<< "\t                    by J. Guerra                   \n" << endl;

	// prompt for file
	cout << "What file contains your data? ";
	getline(cin, input);

	file.open(input);

	if (!file) {				// check if file is good
		system("color 98");		// background 9 = light blue, text 8 = gray
		cout << "\aFailed to open file: \"" << input << "\". Exiting the program.\n\n";

		system("pause");
		exit(0);
	}

	file >> a >> b;
	file.close();

	cout << "The average of " << a << " and " << b << " is: " << (a + b) / 2.0 << ".\n\n";

	system("pause");
}<|endoftext|>


<commit_before>// STL
#include <iostream>
// Boost String
#include <boost/locale.hpp>

// ////////////// M A I N //////////////
int main (int argc, char* argv[]) {

  // Get the global localisation backend
  boost::locale::localization_backend_manager lLocBEMgr =
    boost::locale::localization_backend_manager::global();

  // Select ICU backend as default
  lLocBEMgr.select ("icu");

  // Set this backend globally
  boost::locale::localization_backend_manager::global (lLocBEMgr);

  // Create a generator that uses this backend.
  boost::locale::generator locGen (lLocBEMgr);

  // Create locale generator with the system default locale
  std::locale::global (locGen (""));

  // With STL locale feature
  std::string mucDE ("München");
  std::string mucRU ("Мюнхен");
  std::string pacaFR ("Provence Alpes Côtes d'Azur");
  std::string pvgZH ("上海浦东国际机场");

  // Test the Boost Locale string conversions
  std::cout << "Original: " << mucDE << std::endl
            <<"Upper " << boost::locale::to_upper (mucDE) << std::endl
            <<"Lower " << boost::locale::to_lower (mucDE) << std::endl
            <<"Title " << boost::locale::to_title (mucDE) << std::endl
            <<"Fold  " << boost::locale::fold_case (mucDE) << std::endl
            << "Normalise: "
            << boost::locale::normalize (mucDE, boost::locale::norm_nfkc)
            << std::endl;

  std::cout << "Original: " << mucRU << std::endl
            <<"Upper " << boost::locale::to_upper (mucRU) << std::endl
            <<"Lower " << boost::locale::to_lower (mucRU) << std::endl
            <<"Title " << boost::locale::to_title (mucRU) << std::endl
            <<"Fold  " << boost::locale::fold_case (mucRU) << std::endl
            << "Normalise: "
            << boost::locale::normalize (mucRU, boost::locale::norm_nfkc)
            << std::endl;

  std::cout << "Original: " << pacaFR << std::endl
            <<"Upper " << boost::locale::to_upper (pacaFR) << std::endl
            <<"Lower " << boost::locale::to_lower (pacaFR) << std::endl
            <<"Title " << boost::locale::to_title (pacaFR) << std::endl
            <<"Fold  " << boost::locale::fold_case (pacaFR) << std::endl
            << "Normalise: "
            << boost::locale::normalize (pacaFR, boost::locale::norm_nfkc)
            << std::endl;

  std::cout << "Original: " << pvgZH << std::endl
            <<"Upper " << boost::locale::to_upper (pvgZH) << std::endl
            <<"Lower " << boost::locale::to_lower (pvgZH) << std::endl
            <<"Title " << boost::locale::to_title (pvgZH) << std::endl
            <<"Fold  " << boost::locale::fold_case (pvgZH) << std::endl
            << "Normalise: "
            << boost::locale::normalize (pvgZH, boost::locale::norm_nfkc)
            << std::endl;

  return 0;
}
<commit_msg>[Test] Took a better string example for accentuated words (côté rather than Côte).<commit_after>// STL
#include <iostream>
// Boost Locale
#include <boost/locale.hpp>

// ////////////// M A I N //////////////
int main (int argc, char* argv[]) {

  // Get the global localisation backend
  boost::locale::localization_backend_manager lLocBEMgr =
    boost::locale::localization_backend_manager::global();

  // Select ICU backend as default
  lLocBEMgr.select ("icu");

  // Set this backend globally
  boost::locale::localization_backend_manager::global (lLocBEMgr);

  // Create a generator that uses this backend.
  boost::locale::generator locGen (lLocBEMgr);

  // Create locale generator with the system default locale
  std::locale::global (locGen (""));

  // A few instances of languages
  std::string mucDE ("München");
  std::string mucRU ("Мюнхен");
  std::string sideFR ("Côté");
  std::string pvgZH ("上海浦东国际机场");

  // Test the Boost Locale string conversions
  std::cout << "Original: " << mucDE << std::endl
            <<"Upper " << boost::locale::to_upper (mucDE) << std::endl
            <<"Lower " << boost::locale::to_lower (mucDE) << std::endl
            <<"Title " << boost::locale::to_title (mucDE) << std::endl
            <<"Fold  " << boost::locale::fold_case (mucDE) << std::endl
            << "Normalise: "
            << boost::locale::normalize (mucDE, boost::locale::norm_nfkc)
            << std::endl;

  std::cout << "Original: " << mucRU << std::endl
            <<"Upper " << boost::locale::to_upper (mucRU) << std::endl
            <<"Lower " << boost::locale::to_lower (mucRU) << std::endl
            <<"Title " << boost::locale::to_title (mucRU) << std::endl
            <<"Fold  " << boost::locale::fold_case (mucRU) << std::endl
            << "Normalise: "
            << boost::locale::normalize (mucRU, boost::locale::norm_nfkc)
            << std::endl;

  std::cout << "Original: " << sideFR << std::endl
            <<"Upper " << boost::locale::to_upper (sideFR) << std::endl
            <<"Lower " << boost::locale::to_lower (sideFR) << std::endl
            <<"Title " << boost::locale::to_title (sideFR) << std::endl
            <<"Fold  " << boost::locale::fold_case (sideFR) << std::endl
            << "Normalised - [NFD]: "
            << boost::locale::normalize (sideFR, boost::locale::norm_nfd)
            << "; [NFC]: "
            << boost::locale::normalize (sideFR, boost::locale::norm_nfc)
            << ";  [NFKD]: "
            << boost::locale::normalize (sideFR, boost::locale::norm_nfkd)
            << "; [NFKC]: "
            << boost::locale::normalize (sideFR, boost::locale::norm_nfkc)
            << std::endl;

  std::cout << "Original: " << pvgZH << std::endl
            <<"Upper " << boost::locale::to_upper (pvgZH) << std::endl
            <<"Lower " << boost::locale::to_lower (pvgZH) << std::endl
            <<"Title " << boost::locale::to_title (pvgZH) << std::endl
            <<"Fold  " << boost::locale::fold_case (pvgZH) << std::endl
            << "Normalise: "
            << boost::locale::normalize (pvgZH, boost::locale::norm_nfkc)
            << std::endl;

  return 0;
}
<|endoftext|>


<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// This file implements a X11 chromoting client.

#include <iostream>

#include "base/at_exit.h"
#include "base/message_loop.h"
#include "base/stl_util-inl.h"
#include "base/task.h"
#include "base/waitable_event.h"
#include "remoting/client/client_util.h"
#include "remoting/client/host_connection.h"
#include "remoting/client/jingle_host_connection.h"
#include "remoting/jingle_glue/jingle_thread.h"

// Include Xlib at the end because it clashes with ClientMessage defined in
// the protocol buffer.
// x11_view.h also includes Xlib.h so put it behind all other headers but
// before Xlib.h
#include "remoting/client/x11_view.h"
#include <X11/Xlib.h>

using remoting::JingleHostConnection;
using remoting::JingleThread;

namespace remoting {

class X11Client : public base::RefCountedThreadSafe<X11Client>,
                  public HostConnection::HostEventCallback {
 public:
  X11Client(MessageLoop* loop, base::WaitableEvent* client_done)
      : message_loop_(loop),
        client_done_(client_done),
        display_(NULL),
        window_(0),
        width_(0),
        height_(0) {
  }

  virtual ~X11Client() {
    DCHECK(!display_);
    DCHECK(!window_);
  }

  ////////////////////////////////////////////////////////////////////////////
  // HostConnection::EventHandler implementations.
  virtual void HandleMessages(HostConnection* conn,
                              remoting::HostMessageList* messages) {
    for (size_t i = 0; i < messages->size(); ++i) {
      HostMessage* msg = (*messages)[i];
      if (msg->has_init_client()) {
        message_loop_->PostTask(
            FROM_HERE, NewRunnableMethod(this, &X11Client::DoInitClient, msg));
      } else if (msg->has_begin_update_stream()) {
        message_loop_->PostTask(
            FROM_HERE,
            NewRunnableMethod(this, &X11Client::DoBeginUpdate, msg));
      } else if (msg->has_update_stream_packet()) {
        message_loop_->PostTask(
            FROM_HERE,
            NewRunnableMethod(this, &X11Client::DoHandleUpdate, msg));
      } else if (msg->has_end_update_stream()) {
        message_loop_->PostTask(
            FROM_HERE, NewRunnableMethod(this, &X11Client::DoEndUpdate, msg));
      } else {
        NOTREACHED() << "Unknown message received";
      }
    }
    // Assume we have processed all the messages.
    messages->clear();
  }

  virtual void OnConnectionOpened(HostConnection* conn) {
    std::cout << "Connection established." << std::endl;
  }

  virtual void OnConnectionClosed(HostConnection* conn) {
    std::cout << "Connection closed." << std::endl;
    client_done_->Signal();
  }

  virtual void OnConnectionFailed(HostConnection* conn) {
    std::cout << "Conection failed." << std::endl;
    client_done_->Signal();
  }

  void InitX11() {
    message_loop_->PostTask(FROM_HERE,
                         NewRunnableMethod(this, &X11Client::DoInitX11));
  }

  void DoInitX11() {
    display_ = XOpenDisplay(NULL);
    if (!display_) {
      std::cout << "Error - cannot open display" << std::endl;
      client_done_->Signal();
    }

    // Get properties of the screen.
    int screen = DefaultScreen(display_);
    int root_window = RootWindow(display_, screen);

    // Creates the window.
    window_ = XCreateSimpleWindow(display_, root_window, 1, 1, 640, 480, 0,
                                  BlackPixel(display_, screen),
                                  BlackPixel(display_, screen));
    DCHECK(window_);
    XStoreName(display_, window_, "X11 Remoting");

    // Specifies what kind of messages we want to receive.
    XSelectInput(display_, window_, ExposureMask | ButtonPressMask);
    XMapWindow(display_, window_);
  }

  void DestroyX11() {
    message_loop_->PostTask(FROM_HERE,
                         NewRunnableMethod(this, &X11Client::DoDestroyX11));
  }

  void DoDestroyX11() {
    if (display_ && window_) {
      // Shutdown the window system.
      XDestroyWindow(display_, window_);
      XCloseDisplay(display_);
      display_ = NULL;
      window_ = 0;
    }
  }

 private:
  // This method is executed on the main loop.
  void DoInitClient(HostMessage* msg) {
    DCHECK_EQ(message_loop_, MessageLoop::current());
    DCHECK(msg->has_init_client());
    scoped_ptr<HostMessage> deleter(msg);

    // Saves the dimension and resize the window.
    width_ = msg->init_client().width();
    height_ = msg->init_client().height();
    LOG(INFO) << "Init client receievd: " << width_ << "x" << height_;
    XResizeWindow(display_, window_, width_, height_);

    // Now construct the X11View that renders the remote desktop.
    view_ = new X11View(display_, window_, width_, height_);

    // Schedule the event handler to process the event queue of X11.
    ScheduleX11EventHandler();
  }

  // The following methods are executed on the same thread as libjingle.
  void DoBeginUpdate(HostMessage* msg) {
    DCHECK_EQ(message_loop_, MessageLoop::current());
    DCHECK(msg->has_begin_update_stream());

    view_->HandleBeginUpdateStream(msg);
  }

  void DoHandleUpdate(HostMessage* msg) {
    DCHECK_EQ(message_loop_, MessageLoop::current());
    DCHECK(msg->has_update_stream_packet());

    view_->HandleUpdateStreamPacket(msg);
  }

  void DoEndUpdate(HostMessage* msg) {
    DCHECK_EQ(message_loop_, MessageLoop::current());
    DCHECK(msg->has_end_update_stream());

    view_->HandleEndUpdateStream(msg);
  }

  void DoProcessX11Events() {
    DCHECK_EQ(message_loop_, MessageLoop::current());
    if (XPending(display_)) {
      XEvent e;
      XNextEvent(display_, &e);
      if (e.type == Expose) {
        // Tell the ChromotingView to paint again.
        view_->Paint();
      } else if (e.type == ButtonPress) {
        // TODO(hclam): Implement.
        NOTIMPLEMENTED();
      } else {
        // TODO(hclam): Implement.
        NOTIMPLEMENTED();
      }
    }

    // Schedule the next event handler.
    ScheduleX11EventHandler();
  }

  void ScheduleX11EventHandler() {
    // Schedule a delayed task to process X11 events in 10ms.
    static const int kProcessEventsInterval = 10;
    message_loop_->PostDelayedTask(
        FROM_HERE,
        NewRunnableMethod(this, &X11Client::DoProcessX11Events),
        kProcessEventsInterval);
  }

  MessageLoop* message_loop_;
  base::WaitableEvent* client_done_;

  // Members used for display.
  Display* display_;
  Window window_;

  // Dimension of the window. They are initialized when InitClient message is
  // received.
  int width_;
  int height_;

  scoped_refptr<ChromotingView> view_;

  DISALLOW_COPY_AND_ASSIGN(X11Client);
};

}  // namespace remoting

int main(int argc, char** argv) {
  base::AtExitManager at_exit;
  std::string host_jid;
  std::string username;
  std::string auth_token;

  if (!remoting::GetLoginInfo(argc, argv, &host_jid, &username, &auth_token)) {
    std::cout << "Cannot obtain login info" << std::endl;
    return 1;
  }

  JingleThread network_thread;
  network_thread.Start();

  base::WaitableEvent client_done(false, false);
  scoped_refptr<remoting::X11Client> client =
      new remoting::X11Client(network_thread.message_loop(), &client_done);
  scoped_refptr<JingleHostConnection> connection =
      new JingleHostConnection(&network_thread, client);
  connection->Connect(username, auth_token, host_jid);

  client->InitX11();

  // Wait until the main loop is done.
  client_done.Wait();

  connection->Disconnect();

  client->DestroyX11();

  // Quit the current message loop.
  network_thread.message_loop()->PostTask(FROM_HERE,
                                          new MessageLoop::QuitTask());
  network_thread.Stop();

  return 0;
}
<commit_msg>Coverity: Fix missing return in error check in remoting::X11Client::DoInitX11.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// This file implements a X11 chromoting client.

#include <iostream>

#include "base/at_exit.h"
#include "base/message_loop.h"
#include "base/stl_util-inl.h"
#include "base/task.h"
#include "base/waitable_event.h"
#include "remoting/client/client_util.h"
#include "remoting/client/host_connection.h"
#include "remoting/client/jingle_host_connection.h"
#include "remoting/jingle_glue/jingle_thread.h"

// Include Xlib at the end because it clashes with ClientMessage defined in
// the protocol buffer.
// x11_view.h also includes Xlib.h so put it behind all other headers but
// before Xlib.h
#include "remoting/client/x11_view.h"
#include <X11/Xlib.h>

using remoting::JingleHostConnection;
using remoting::JingleThread;

namespace remoting {

class X11Client : public base::RefCountedThreadSafe<X11Client>,
                  public HostConnection::HostEventCallback {
 public:
  X11Client(MessageLoop* loop, base::WaitableEvent* client_done)
      : message_loop_(loop),
        client_done_(client_done),
        display_(NULL),
        window_(0),
        width_(0),
        height_(0) {
  }

  virtual ~X11Client() {
    DCHECK(!display_);
    DCHECK(!window_);
  }

  ////////////////////////////////////////////////////////////////////////////
  // HostConnection::EventHandler implementations.
  virtual void HandleMessages(HostConnection* conn,
                              remoting::HostMessageList* messages) {
    for (size_t i = 0; i < messages->size(); ++i) {
      HostMessage* msg = (*messages)[i];
      if (msg->has_init_client()) {
        message_loop_->PostTask(
            FROM_HERE, NewRunnableMethod(this, &X11Client::DoInitClient, msg));
      } else if (msg->has_begin_update_stream()) {
        message_loop_->PostTask(
            FROM_HERE,
            NewRunnableMethod(this, &X11Client::DoBeginUpdate, msg));
      } else if (msg->has_update_stream_packet()) {
        message_loop_->PostTask(
            FROM_HERE,
            NewRunnableMethod(this, &X11Client::DoHandleUpdate, msg));
      } else if (msg->has_end_update_stream()) {
        message_loop_->PostTask(
            FROM_HERE, NewRunnableMethod(this, &X11Client::DoEndUpdate, msg));
      } else {
        NOTREACHED() << "Unknown message received";
      }
    }
    // Assume we have processed all the messages.
    messages->clear();
  }

  virtual void OnConnectionOpened(HostConnection* conn) {
    std::cout << "Connection established." << std::endl;
  }

  virtual void OnConnectionClosed(HostConnection* conn) {
    std::cout << "Connection closed." << std::endl;
    client_done_->Signal();
  }

  virtual void OnConnectionFailed(HostConnection* conn) {
    std::cout << "Conection failed." << std::endl;
    client_done_->Signal();
  }

  void InitX11() {
    message_loop_->PostTask(FROM_HERE,
                         NewRunnableMethod(this, &X11Client::DoInitX11));
  }

  void DoInitX11() {
    display_ = XOpenDisplay(NULL);
    if (!display_) {
      std::cout << "Error - cannot open display" << std::endl;
      client_done_->Signal();
      return;
    }

    // Get properties of the screen.
    int screen = DefaultScreen(display_);
    int root_window = RootWindow(display_, screen);

    // Creates the window.
    window_ = XCreateSimpleWindow(display_, root_window, 1, 1, 640, 480, 0,
                                  BlackPixel(display_, screen),
                                  BlackPixel(display_, screen));
    DCHECK(window_);
    XStoreName(display_, window_, "X11 Remoting");

    // Specifies what kind of messages we want to receive.
    XSelectInput(display_, window_, ExposureMask | ButtonPressMask);
    XMapWindow(display_, window_);
  }

  void DestroyX11() {
    message_loop_->PostTask(FROM_HERE,
                         NewRunnableMethod(this, &X11Client::DoDestroyX11));
  }

  void DoDestroyX11() {
    if (display_ && window_) {
      // Shutdown the window system.
      XDestroyWindow(display_, window_);
      XCloseDisplay(display_);
      display_ = NULL;
      window_ = 0;
    }
  }

 private:
  // This method is executed on the main loop.
  void DoInitClient(HostMessage* msg) {
    DCHECK_EQ(message_loop_, MessageLoop::current());
    DCHECK(msg->has_init_client());
    scoped_ptr<HostMessage> deleter(msg);

    // Saves the dimension and resize the window.
    width_ = msg->init_client().width();
    height_ = msg->init_client().height();
    LOG(INFO) << "Init client receievd: " << width_ << "x" << height_;
    XResizeWindow(display_, window_, width_, height_);

    // Now construct the X11View that renders the remote desktop.
    view_ = new X11View(display_, window_, width_, height_);

    // Schedule the event handler to process the event queue of X11.
    ScheduleX11EventHandler();
  }

  // The following methods are executed on the same thread as libjingle.
  void DoBeginUpdate(HostMessage* msg) {
    DCHECK_EQ(message_loop_, MessageLoop::current());
    DCHECK(msg->has_begin_update_stream());

    view_->HandleBeginUpdateStream(msg);
  }

  void DoHandleUpdate(HostMessage* msg) {
    DCHECK_EQ(message_loop_, MessageLoop::current());
    DCHECK(msg->has_update_stream_packet());

    view_->HandleUpdateStreamPacket(msg);
  }

  void DoEndUpdate(HostMessage* msg) {
    DCHECK_EQ(message_loop_, MessageLoop::current());
    DCHECK(msg->has_end_update_stream());

    view_->HandleEndUpdateStream(msg);
  }

  void DoProcessX11Events() {
    DCHECK_EQ(message_loop_, MessageLoop::current());
    if (XPending(display_)) {
      XEvent e;
      XNextEvent(display_, &e);
      if (e.type == Expose) {
        // Tell the ChromotingView to paint again.
        view_->Paint();
      } else if (e.type == ButtonPress) {
        // TODO(hclam): Implement.
        NOTIMPLEMENTED();
      } else {
        // TODO(hclam): Implement.
        NOTIMPLEMENTED();
      }
    }

    // Schedule the next event handler.
    ScheduleX11EventHandler();
  }

  void ScheduleX11EventHandler() {
    // Schedule a delayed task to process X11 events in 10ms.
    static const int kProcessEventsInterval = 10;
    message_loop_->PostDelayedTask(
        FROM_HERE,
        NewRunnableMethod(this, &X11Client::DoProcessX11Events),
        kProcessEventsInterval);
  }

  MessageLoop* message_loop_;
  base::WaitableEvent* client_done_;

  // Members used for display.
  Display* display_;
  Window window_;

  // Dimension of the window. They are initialized when InitClient message is
  // received.
  int width_;
  int height_;

  scoped_refptr<ChromotingView> view_;

  DISALLOW_COPY_AND_ASSIGN(X11Client);
};

}  // namespace remoting

int main(int argc, char** argv) {
  base::AtExitManager at_exit;
  std::string host_jid;
  std::string username;
  std::string auth_token;

  if (!remoting::GetLoginInfo(argc, argv, &host_jid, &username, &auth_token)) {
    std::cout << "Cannot obtain login info" << std::endl;
    return 1;
  }

  JingleThread network_thread;
  network_thread.Start();

  base::WaitableEvent client_done(false, false);
  scoped_refptr<remoting::X11Client> client =
      new remoting::X11Client(network_thread.message_loop(), &client_done);
  scoped_refptr<JingleHostConnection> connection =
      new JingleHostConnection(&network_thread, client);
  connection->Connect(username, auth_token, host_jid);

  client->InitX11();

  // Wait until the main loop is done.
  client_done.Wait();

  connection->Disconnect();

  client->DestroyX11();

  // Quit the current message loop.
  network_thread.message_loop()->PostTask(FROM_HERE,
                                          new MessageLoop::QuitTask());
  network_thread.Stop();

  return 0;
}
<|endoftext|>


<commit_before>/*
Highly Optimized Object-oriented Many-particle Dynamics -- Blue Edition
(HOOMD-blue) Open Source Software License Copyright 2008-2011 Ames Laboratory
Iowa State University and The Regents of the University of Michigan All rights
reserved.

HOOMD-blue may contain modifications ("Contributions") provided, and to which
copyright is held, by various Contributors who have granted The Regents of the
University of Michigan the right to modify and/or distribute such Contributions.

You may redistribute, use, and create derivate works of HOOMD-blue, in source
and binary forms, provided you abide by the following conditions:

* Redistributions of source code must retain the above copyright notice, this
list of conditions, and the following disclaimer both in the code and
prominently in any materials provided with the distribution.

* Redistributions in binary form must reproduce the above copyright notice, this
list of conditions, and the following disclaimer in the documentation and/or
other materials provided with the distribution.

* All publications and presentations based on HOOMD-blue, including any reports
or published results obtained, in whole or in part, with HOOMD-blue, will
acknowledge its use according to the terms posted at the time of submission on:
http://codeblue.umich.edu/hoomd-blue/citations.html

* Any electronic documents citing HOOMD-Blue will link to the HOOMD-Blue website:
http://codeblue.umich.edu/hoomd-blue/

* Apart from the above required attributions, neither the name of the copyright
holder nor the names of HOOMD-blue's contributors may be used to endorse or
promote products derived from this software without specific prior written
permission.

Disclaimer

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND/OR ANY
WARRANTIES THAT THIS SOFTWARE IS FREE OF INFRINGEMENT ARE DISCLAIMED.

IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

// Maintainer: joaander

/*! \file NeighborListGPUBinned.cc
    \brief Defines NeighborListGPUBinned
*/

#include "NeighborListGPUBinned.h"
#include "NeighborListGPUBinned.cuh"

#include <boost/python.hpp>
using namespace boost::python;

#ifdef ENABLE_MPI
#include "Communicator.h"
#endif

NeighborListGPUBinned::NeighborListGPUBinned(boost::shared_ptr<SystemDefinition> sysdef,
                                             Scalar r_cut,
                                             Scalar r_buff,
                                             boost::shared_ptr<CellList> cl)
    : NeighborListGPU(sysdef, r_cut, r_buff), m_cl(cl)
    {
    // create a default cell list if one was not specified
    if (!m_cl)
        m_cl = boost::shared_ptr<CellList>(new CellList(sysdef));

    m_cl->setNominalWidth(r_cut + r_buff + m_d_max - Scalar(1.0));
    m_cl->setRadius(1);
    m_cl->setComputeTDB(false);
    m_cl->setFlagIndex();

    gpu_setup_compute_nlist_binned();
    CHECK_CUDA_ERROR();

    // default to 0 last allocated quantities
    m_last_dim = make_uint3(0,0,0);
    m_last_cell_Nmax = 0;
    dca_cell_adj = NULL;
    dca_cell_xyzf = NULL;
    dca_cell_tdb = NULL;
    m_block_size = 64;

    // When running on compute 1.x, textures are allocated with the height equal to the number of cells
    // limit the number of cells to the maximum texture dimension
    if (exec_conf->getComputeCapability() < 200)
        {
        m_cl->setMaxCells(exec_conf->dev_prop.maxTexture2D[1]);
        }
    }

NeighborListGPUBinned::~NeighborListGPUBinned()
    {
    // free the old arrays
    if (dca_cell_adj != NULL)
        cudaFreeArray(dca_cell_adj);
    if (dca_cell_xyzf != NULL)
        cudaFreeArray(dca_cell_xyzf);
    if (dca_cell_tdb != NULL)
        cudaFreeArray(dca_cell_tdb);

    CHECK_CUDA_ERROR();
    }

void NeighborListGPUBinned::setRCut(Scalar r_cut, Scalar r_buff)
    {
    NeighborListGPU::setRCut(r_cut, r_buff);

    m_cl->setNominalWidth(r_cut + r_buff + m_d_max - Scalar(1.0));
    }

void NeighborListGPUBinned::setMaximumDiameter(Scalar d_max)
    {
    NeighborListGPU::setMaximumDiameter(d_max);

    // need to update the cell list settings appropriately
    m_cl->setNominalWidth(m_r_cut + m_r_buff + m_d_max - Scalar(1.0));
    }

void NeighborListGPUBinned::setFilterBody(bool filter_body)
    {
    NeighborListGPU::setFilterBody(filter_body);

    // need to update the cell list settings appropriately
    if (m_filter_body || m_filter_diameter)
        m_cl->setComputeTDB(true);
    else
        m_cl->setComputeTDB(false);
    }

void NeighborListGPUBinned::setFilterDiameter(bool filter_diameter)
    {
    NeighborListGPU::setFilterDiameter(filter_diameter);

    // need to update the cell list settings appropriately
    if (m_filter_body || m_filter_diameter)
        m_cl->setComputeTDB(true);
    else
        m_cl->setComputeTDB(false);
    }

void NeighborListGPUBinned::buildNlist(unsigned int timestep)
    {
    if (m_storage_mode != full)
        {
        m_exec_conf->msg->error() << "Only full mode nlists can be generated on the GPU" << endl;
        throw runtime_error("Error computing neighbor list");
        }

    if (m_inside_thread)
        m_cl->computeThread(timestep,m_thread_id);
    else
        m_cl->compute(timestep);

    // check that at least 3x3x3 cells are computed
    uint3 dim = m_cl->getDim();
    if (dim.x < 3 || dim.y < 3 || dim.z < 3)
        {
        m_exec_conf->msg->error() << "NeighborListGPUBinned doesn't work on boxes where r_cut+r_buff is greater than 1/3 any box dimension" << endl;
        throw runtime_error("Error computing neighbor list");
        }

    if (m_prof)
        m_prof->push(exec_conf, "compute");

    // acquire the particle data
    ArrayHandle<Scalar4> d_pos(m_pdata->getPositions(), access_location::device, access_mode::read);
    ArrayHandle<Scalar> d_diameter(m_pdata->getDiameters(), access_location::device, access_mode::read);
    ArrayHandle<unsigned int> d_body(m_pdata->getBodies(), access_location::device, access_mode::read);

    const BoxDim& box = m_pdata->getBox();

    // access the cell list data arrays
    ArrayHandle<unsigned int> d_cell_size(m_cl->getCellSizeArray(), access_location::device, access_mode::read);
    ArrayHandle<Scalar4> d_cell_xyzf(m_cl->getXYZFArray(), access_location::device, access_mode::read);
    ArrayHandle<Scalar4> d_cell_tdb(m_cl->getTDBArray(), access_location::device, access_mode::read);
    ArrayHandle<unsigned int> d_cell_adj(m_cl->getCellAdjArray(), access_location::device, access_mode::read);

    ArrayHandle<unsigned int> d_nlist(m_nlist, access_location::device, access_mode::overwrite);
    ArrayHandle<unsigned int> d_n_neigh(m_n_neigh, access_location::device, access_mode::overwrite);
    ArrayHandle<unsigned int> d_ghost_nlist(m_ghost_nlist, access_location::device, access_mode::overwrite);
    ArrayHandle<unsigned int> d_n_ghost_neigh(m_n_ghost_neigh, access_location::device, access_mode::overwrite);
    ArrayHandle<Scalar4> d_last_pos(m_last_pos, access_location::device, access_mode::overwrite);

    // start by creating a temporary copy of r_cut sqaured
    Scalar rmax = m_r_cut + m_r_buff;
    // add d_max - 1.0, if diameter filtering is not already taking care of it
    if (!m_filter_diameter)
        rmax += m_d_max - Scalar(1.0);
    Scalar rmaxsq = rmax*rmax;

    uint3 num_ghost_cells = m_cl->getNGhostCells();
    Scalar nominal_width  = m_r_cut + m_r_buff + m_d_max - Scalar(1.0);
    Scalar3 ghost_width = nominal_width*Scalar(1.0/2.0)*make_scalar3((Scalar)num_ghost_cells.x, (Scalar)num_ghost_cells.y, (Scalar)num_ghost_cells.z);

    bool compute_ghost_nlist = m_pdata->getDomainDecomposition();

    if (exec_conf->getComputeCapability() >= 200)
        {
        cudaStream_t stream = 0;
        if (m_inside_thread)
            stream = m_exec_conf->getThreadStream(m_thread_id);

        gpu_compute_nlist_binned(d_nlist.data,
                                 d_ghost_nlist.data,
                                 d_n_neigh.data,
                                 d_n_ghost_neigh.data,
                                 d_last_pos.data,
                                 m_conditions.getDeviceFlags(),
                                 m_nlist_indexer,
                                 d_pos.data,
                                 d_body.data,
                                 d_diameter.data,
                                 m_pdata->getN(),
                                 d_cell_size.data,
                                 d_cell_xyzf.data,
                                 d_cell_tdb.data,
                                 d_cell_adj.data,
                                 m_cl->getCellIndexer(),
                                 m_cl->getCellListIndexer(),
                                 m_cl->getCellAdjIndexer(),
                                 box,
                                 rmaxsq,
                                 m_block_size,
                                 m_filter_body,
                                 m_filter_diameter,
                                 ghost_width,
                                 compute_ghost_nlist,
                                 stream);
        }
    else
        {
        unsigned int ncell = m_cl->getDim().x * m_cl->getDim().y * m_cl->getDim().z;

        // upate the cuda array allocations (note, this is smart enough to not reallocate when there has been no change)
        if (needReallocateCudaArrays())
            {
            allocateCudaArrays();
            cudaMemcpyToArray(dca_cell_adj, 0, 0, d_cell_adj.data, sizeof(unsigned int)*ncell*27, cudaMemcpyDeviceToDevice);
            }

        // update the values in those arrays
        if (m_prof) m_prof->push(exec_conf, "copy");
        cudaMemcpyToArray(dca_cell_xyzf, 0, 0, d_cell_xyzf.data, sizeof(float4)*ncell*m_last_cell_Nmax, cudaMemcpyDeviceToDevice);
        if (m_filter_body || m_filter_diameter)
            cudaMemcpyToArray(dca_cell_tdb, 0, 0, d_cell_tdb.data, sizeof(float4)*ncell*m_last_cell_Nmax, cudaMemcpyDeviceToDevice);

        if (m_prof) m_prof->pop(exec_conf);

        if (exec_conf->isCUDAErrorCheckingEnabled())
            CHECK_CUDA_ERROR();

        gpu_compute_nlist_binned_1x(d_nlist.data,
                                    d_n_neigh.data,
                                    d_last_pos.data,
                                    m_conditions.getDeviceFlags(),
                                    m_nlist_indexer,
                                    d_pos.data,
                                    d_body.data,
                                    d_diameter.data,
                                    m_pdata->getN(),
                                    d_cell_size.data,
                                    dca_cell_xyzf,
                                    dca_cell_tdb,
                                    dca_cell_adj,
                                    m_cl->getCellIndexer(),
                                    box,
                                    rmaxsq,
                                    m_block_size,
                                    m_filter_body,
                                    m_filter_diameter,
                                    ghost_width);
        }

    if (exec_conf->isCUDAErrorCheckingEnabled())
        CHECK_CUDA_ERROR();

    if (m_prof)
        m_prof->pop(exec_conf);
    }

bool NeighborListGPUBinned::needReallocateCudaArrays()
    {
    // quit now if the dimensions are the same as the last allocation
    uint3 cur_dim = m_cl->getDim();
    unsigned int cur_cell_Nmax = m_cl->getNmax();

    if (cur_dim.x == m_last_dim.x &&
        cur_dim.y == m_last_dim.y &&
        cur_dim.z == m_last_dim.z &&
        cur_cell_Nmax == m_last_cell_Nmax &&
        dca_cell_adj != NULL &&
        dca_cell_xyzf != NULL &&
        dca_cell_tdb != NULL)
        {
        return false;
        }
    else
        {
        return true;
        }
    }

void NeighborListGPUBinned::allocateCudaArrays()
    {
    // quit now if the dimensions are the same as the last allocation
    uint3 cur_dim = m_cl->getDim();
    unsigned int cur_cell_Nmax = m_cl->getNmax();

    m_last_dim = cur_dim;
    m_last_cell_Nmax = cur_cell_Nmax;

    // free the old arrays
    if (dca_cell_adj != NULL)
        cudaFreeArray(dca_cell_adj);
    if (dca_cell_xyzf != NULL)
        cudaFreeArray(dca_cell_xyzf);
    if (dca_cell_tdb != NULL)
        cudaFreeArray(dca_cell_tdb);

    CHECK_CUDA_ERROR();

    // allocate the new ones
    unsigned int ncell = cur_dim.x * cur_dim.y * cur_dim.z;

    cudaChannelFormatDesc xyzf_desc = cudaCreateChannelDesc< float4 >();
    cudaMallocArray(&dca_cell_xyzf, &xyzf_desc, cur_cell_Nmax, ncell);
    cudaMallocArray(&dca_cell_tdb, &xyzf_desc, cur_cell_Nmax, ncell);
    cudaChannelFormatDesc adj_desc = cudaCreateChannelDesc< unsigned int >();
    cudaMallocArray(&dca_cell_adj, &adj_desc, 27, ncell);

    CHECK_CUDA_ERROR();
    }

void export_NeighborListGPUBinned()
    {
    class_<NeighborListGPUBinned, boost::shared_ptr<NeighborListGPUBinned>, bases<NeighborListGPU>, boost::noncopyable >
                     ("NeighborListGPUBinned", init< boost::shared_ptr<SystemDefinition>, Scalar, Scalar, boost::shared_ptr<CellList> >())
                    .def("setBlockSize", &NeighborListGPUBinned::setBlockSize)
                     ;
    }

<commit_msg>Inserted appropriate #ifdef<commit_after>/*
Highly Optimized Object-oriented Many-particle Dynamics -- Blue Edition
(HOOMD-blue) Open Source Software License Copyright 2008-2011 Ames Laboratory
Iowa State University and The Regents of the University of Michigan All rights
reserved.

HOOMD-blue may contain modifications ("Contributions") provided, and to which
copyright is held, by various Contributors who have granted The Regents of the
University of Michigan the right to modify and/or distribute such Contributions.

You may redistribute, use, and create derivate works of HOOMD-blue, in source
and binary forms, provided you abide by the following conditions:

* Redistributions of source code must retain the above copyright notice, this
list of conditions, and the following disclaimer both in the code and
prominently in any materials provided with the distribution.

* Redistributions in binary form must reproduce the above copyright notice, this
list of conditions, and the following disclaimer in the documentation and/or
other materials provided with the distribution.

* All publications and presentations based on HOOMD-blue, including any reports
or published results obtained, in whole or in part, with HOOMD-blue, will
acknowledge its use according to the terms posted at the time of submission on:
http://codeblue.umich.edu/hoomd-blue/citations.html

* Any electronic documents citing HOOMD-Blue will link to the HOOMD-Blue website:
http://codeblue.umich.edu/hoomd-blue/

* Apart from the above required attributions, neither the name of the copyright
holder nor the names of HOOMD-blue's contributors may be used to endorse or
promote products derived from this software without specific prior written
permission.

Disclaimer

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND/OR ANY
WARRANTIES THAT THIS SOFTWARE IS FREE OF INFRINGEMENT ARE DISCLAIMED.

IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

// Maintainer: joaander

/*! \file NeighborListGPUBinned.cc
    \brief Defines NeighborListGPUBinned
*/

#include "NeighborListGPUBinned.h"
#include "NeighborListGPUBinned.cuh"

#include <boost/python.hpp>
using namespace boost::python;

#ifdef ENABLE_MPI
#include "Communicator.h"
#endif

NeighborListGPUBinned::NeighborListGPUBinned(boost::shared_ptr<SystemDefinition> sysdef,
                                             Scalar r_cut,
                                             Scalar r_buff,
                                             boost::shared_ptr<CellList> cl)
    : NeighborListGPU(sysdef, r_cut, r_buff), m_cl(cl)
    {
    // create a default cell list if one was not specified
    if (!m_cl)
        m_cl = boost::shared_ptr<CellList>(new CellList(sysdef));

    m_cl->setNominalWidth(r_cut + r_buff + m_d_max - Scalar(1.0));
    m_cl->setRadius(1);
    m_cl->setComputeTDB(false);
    m_cl->setFlagIndex();

    gpu_setup_compute_nlist_binned();
    CHECK_CUDA_ERROR();

    // default to 0 last allocated quantities
    m_last_dim = make_uint3(0,0,0);
    m_last_cell_Nmax = 0;
    dca_cell_adj = NULL;
    dca_cell_xyzf = NULL;
    dca_cell_tdb = NULL;
    m_block_size = 64;

    // When running on compute 1.x, textures are allocated with the height equal to the number of cells
    // limit the number of cells to the maximum texture dimension
    if (exec_conf->getComputeCapability() < 200)
        {
        m_cl->setMaxCells(exec_conf->dev_prop.maxTexture2D[1]);
        }
    }

NeighborListGPUBinned::~NeighborListGPUBinned()
    {
    // free the old arrays
    if (dca_cell_adj != NULL)
        cudaFreeArray(dca_cell_adj);
    if (dca_cell_xyzf != NULL)
        cudaFreeArray(dca_cell_xyzf);
    if (dca_cell_tdb != NULL)
        cudaFreeArray(dca_cell_tdb);

    CHECK_CUDA_ERROR();
    }

void NeighborListGPUBinned::setRCut(Scalar r_cut, Scalar r_buff)
    {
    NeighborListGPU::setRCut(r_cut, r_buff);

    m_cl->setNominalWidth(r_cut + r_buff + m_d_max - Scalar(1.0));
    }

void NeighborListGPUBinned::setMaximumDiameter(Scalar d_max)
    {
    NeighborListGPU::setMaximumDiameter(d_max);

    // need to update the cell list settings appropriately
    m_cl->setNominalWidth(m_r_cut + m_r_buff + m_d_max - Scalar(1.0));
    }

void NeighborListGPUBinned::setFilterBody(bool filter_body)
    {
    NeighborListGPU::setFilterBody(filter_body);

    // need to update the cell list settings appropriately
    if (m_filter_body || m_filter_diameter)
        m_cl->setComputeTDB(true);
    else
        m_cl->setComputeTDB(false);
    }

void NeighborListGPUBinned::setFilterDiameter(bool filter_diameter)
    {
    NeighborListGPU::setFilterDiameter(filter_diameter);

    // need to update the cell list settings appropriately
    if (m_filter_body || m_filter_diameter)
        m_cl->setComputeTDB(true);
    else
        m_cl->setComputeTDB(false);
    }

void NeighborListGPUBinned::buildNlist(unsigned int timestep)
    {
    if (m_storage_mode != full)
        {
        m_exec_conf->msg->error() << "Only full mode nlists can be generated on the GPU" << endl;
        throw runtime_error("Error computing neighbor list");
        }

    if (m_inside_thread)
        m_cl->computeThread(timestep,m_thread_id);
    else
        m_cl->compute(timestep);

    // check that at least 3x3x3 cells are computed
    uint3 dim = m_cl->getDim();
    if (dim.x < 3 || dim.y < 3 || dim.z < 3)
        {
        m_exec_conf->msg->error() << "NeighborListGPUBinned doesn't work on boxes where r_cut+r_buff is greater than 1/3 any box dimension" << endl;
        throw runtime_error("Error computing neighbor list");
        }

    if (m_prof)
        m_prof->push(exec_conf, "compute");

    // acquire the particle data
    ArrayHandle<Scalar4> d_pos(m_pdata->getPositions(), access_location::device, access_mode::read);
    ArrayHandle<Scalar> d_diameter(m_pdata->getDiameters(), access_location::device, access_mode::read);
    ArrayHandle<unsigned int> d_body(m_pdata->getBodies(), access_location::device, access_mode::read);

    const BoxDim& box = m_pdata->getBox();

    // access the cell list data arrays
    ArrayHandle<unsigned int> d_cell_size(m_cl->getCellSizeArray(), access_location::device, access_mode::read);
    ArrayHandle<Scalar4> d_cell_xyzf(m_cl->getXYZFArray(), access_location::device, access_mode::read);
    ArrayHandle<Scalar4> d_cell_tdb(m_cl->getTDBArray(), access_location::device, access_mode::read);
    ArrayHandle<unsigned int> d_cell_adj(m_cl->getCellAdjArray(), access_location::device, access_mode::read);

    ArrayHandle<unsigned int> d_nlist(m_nlist, access_location::device, access_mode::overwrite);
    ArrayHandle<unsigned int> d_n_neigh(m_n_neigh, access_location::device, access_mode::overwrite);
    ArrayHandle<unsigned int> d_ghost_nlist(m_ghost_nlist, access_location::device, access_mode::overwrite);
    ArrayHandle<unsigned int> d_n_ghost_neigh(m_n_ghost_neigh, access_location::device, access_mode::overwrite);
    ArrayHandle<Scalar4> d_last_pos(m_last_pos, access_location::device, access_mode::overwrite);

    // start by creating a temporary copy of r_cut sqaured
    Scalar rmax = m_r_cut + m_r_buff;
    // add d_max - 1.0, if diameter filtering is not already taking care of it
    if (!m_filter_diameter)
        rmax += m_d_max - Scalar(1.0);
    Scalar rmaxsq = rmax*rmax;

    uint3 num_ghost_cells = m_cl->getNGhostCells();
    Scalar nominal_width  = m_r_cut + m_r_buff + m_d_max - Scalar(1.0);
    Scalar3 ghost_width = nominal_width*Scalar(1.0/2.0)*make_scalar3((Scalar)num_ghost_cells.x, (Scalar)num_ghost_cells.y, (Scalar)num_ghost_cells.z);

    bool compute_ghost_nlist = false;
#ifdef ENABLE_MPI
    if (m_pdata->getDomainDecomposition())
        compute_ghost_nlist = true;
#endif

    if (exec_conf->getComputeCapability() >= 200)
        {
        cudaStream_t stream = 0;
        if (m_inside_thread)
            stream = m_exec_conf->getThreadStream(m_thread_id);

        gpu_compute_nlist_binned(d_nlist.data,
                                 d_ghost_nlist.data,
                                 d_n_neigh.data,
                                 d_n_ghost_neigh.data,
                                 d_last_pos.data,
                                 m_conditions.getDeviceFlags(),
                                 m_nlist_indexer,
                                 d_pos.data,
                                 d_body.data,
                                 d_diameter.data,
                                 m_pdata->getN(),
                                 d_cell_size.data,
                                 d_cell_xyzf.data,
                                 d_cell_tdb.data,
                                 d_cell_adj.data,
                                 m_cl->getCellIndexer(),
                                 m_cl->getCellListIndexer(),
                                 m_cl->getCellAdjIndexer(),
                                 box,
                                 rmaxsq,
                                 m_block_size,
                                 m_filter_body,
                                 m_filter_diameter,
                                 ghost_width,
                                 compute_ghost_nlist,
                                 stream);
        }
    else
        {
        unsigned int ncell = m_cl->getDim().x * m_cl->getDim().y * m_cl->getDim().z;

        // upate the cuda array allocations (note, this is smart enough to not reallocate when there has been no change)
        if (needReallocateCudaArrays())
            {
            allocateCudaArrays();
            cudaMemcpyToArray(dca_cell_adj, 0, 0, d_cell_adj.data, sizeof(unsigned int)*ncell*27, cudaMemcpyDeviceToDevice);
            }

        // update the values in those arrays
        if (m_prof) m_prof->push(exec_conf, "copy");
        cudaMemcpyToArray(dca_cell_xyzf, 0, 0, d_cell_xyzf.data, sizeof(float4)*ncell*m_last_cell_Nmax, cudaMemcpyDeviceToDevice);
        if (m_filter_body || m_filter_diameter)
            cudaMemcpyToArray(dca_cell_tdb, 0, 0, d_cell_tdb.data, sizeof(float4)*ncell*m_last_cell_Nmax, cudaMemcpyDeviceToDevice);

        if (m_prof) m_prof->pop(exec_conf);

        if (exec_conf->isCUDAErrorCheckingEnabled())
            CHECK_CUDA_ERROR();

        gpu_compute_nlist_binned_1x(d_nlist.data,
                                    d_n_neigh.data,
                                    d_last_pos.data,
                                    m_conditions.getDeviceFlags(),
                                    m_nlist_indexer,
                                    d_pos.data,
                                    d_body.data,
                                    d_diameter.data,
                                    m_pdata->getN(),
                                    d_cell_size.data,
                                    dca_cell_xyzf,
                                    dca_cell_tdb,
                                    dca_cell_adj,
                                    m_cl->getCellIndexer(),
                                    box,
                                    rmaxsq,
                                    m_block_size,
                                    m_filter_body,
                                    m_filter_diameter,
                                    ghost_width);
        }

    if (exec_conf->isCUDAErrorCheckingEnabled())
        CHECK_CUDA_ERROR();

    if (m_prof)
        m_prof->pop(exec_conf);
    }

bool NeighborListGPUBinned::needReallocateCudaArrays()
    {
    // quit now if the dimensions are the same as the last allocation
    uint3 cur_dim = m_cl->getDim();
    unsigned int cur_cell_Nmax = m_cl->getNmax();

    if (cur_dim.x == m_last_dim.x &&
        cur_dim.y == m_last_dim.y &&
        cur_dim.z == m_last_dim.z &&
        cur_cell_Nmax == m_last_cell_Nmax &&
        dca_cell_adj != NULL &&
        dca_cell_xyzf != NULL &&
        dca_cell_tdb != NULL)
        {
        return false;
        }
    else
        {
        return true;
        }
    }

void NeighborListGPUBinned::allocateCudaArrays()
    {
    // quit now if the dimensions are the same as the last allocation
    uint3 cur_dim = m_cl->getDim();
    unsigned int cur_cell_Nmax = m_cl->getNmax();

    m_last_dim = cur_dim;
    m_last_cell_Nmax = cur_cell_Nmax;

    // free the old arrays
    if (dca_cell_adj != NULL)
        cudaFreeArray(dca_cell_adj);
    if (dca_cell_xyzf != NULL)
        cudaFreeArray(dca_cell_xyzf);
    if (dca_cell_tdb != NULL)
        cudaFreeArray(dca_cell_tdb);

    CHECK_CUDA_ERROR();

    // allocate the new ones
    unsigned int ncell = cur_dim.x * cur_dim.y * cur_dim.z;

    cudaChannelFormatDesc xyzf_desc = cudaCreateChannelDesc< float4 >();
    cudaMallocArray(&dca_cell_xyzf, &xyzf_desc, cur_cell_Nmax, ncell);
    cudaMallocArray(&dca_cell_tdb, &xyzf_desc, cur_cell_Nmax, ncell);
    cudaChannelFormatDesc adj_desc = cudaCreateChannelDesc< unsigned int >();
    cudaMallocArray(&dca_cell_adj, &adj_desc, 27, ncell);

    CHECK_CUDA_ERROR();
    }

void export_NeighborListGPUBinned()
    {
    class_<NeighborListGPUBinned, boost::shared_ptr<NeighborListGPUBinned>, bases<NeighborListGPU>, boost::noncopyable >
                     ("NeighborListGPUBinned", init< boost::shared_ptr<SystemDefinition>, Scalar, Scalar, boost::shared_ptr<CellList> >())
                    .def("setBlockSize", &NeighborListGPUBinned::setBlockSize)
                     ;
    }

<|endoftext|>