<commit_before>/***************************************************************************
              fbellini@cern.ch - last modified on 28/11/2013
//
//Lauches KStar analysis with rsn mini package
//Allows basic configuration of pile-up check and event cuts
//
****************************************************************************/
enum pairYCutSet { kPairDefault=0,
		   kCentral //=1
                 };

enum eventCutSet { kEvtDefault=0,
		   kNoPileUpCut, //=1
		   kDefaultVtx12,//=2
		   kDefaultVtx8, //=3
		   kDefaultVtx5, //=4
		   kMCEvtDefault, //=5
		   kSpecial1, //=6
		   kSpecial2, //=7
		   kNoEvtSel, //=8
		   kSpecial3//=9
                 };

enum eventMixConfig { kDisabled = -1,
		      kMixDefault,//=0 //10 events, Dvz = 1cm, DC = 10
		      k5Evts, //=1 //5 events, Dvz = 1cm, DC = 10
		      k5Cent,  //=2 //10 events, Dvz = 1cm, DC = 5
		      k5Evts5Cent
                    };

AliRsnMiniAnalysisTask * AddTaskKStarPP8TeV_PID
(
 Bool_t      isMC = kFALSE,
 Bool_t      isPP = kTRUE,
 TString     outNameSuffix = "tpc2stof3sveto",
 Int_t       evtCutSetID = 0,
 Int_t       pairCutSetID = 0,
 Int_t       mixingConfigID = 0,
 Int_t       aodFilterBit = 5,
 Int_t       customQualityCutsID = -1,
 AliRsnCutSetDaughterParticle::ERsnDaughterCutSet cutPiCandidate = AliRsnCutSetDaughterParticle::kTPCpidTOFveto3s,
 AliRsnCutSetDaughterParticle::ERsnDaughterCutSet cutKaCandidate = AliRsnCutSetDaughterParticle::kTPCpidTOFveto3s,
 Float_t     nsigmaPi = 2.0,
 Float_t     nsigmaKa = 2.0,
 Bool_t      enableMonitor = kTRUE,
 Bool_t      IsMcTrueOnly = kFALSE,
 TString     monitorOpt = "NoSIGN",
 Bool_t      useMixLS = 0,
 Bool_t      checkReflex = 0,
 AliRsnMiniValue::EType yaxisvar = AliRsnMiniValue::kPt
)
{

  //-------------------------------------------
  // event cuts
  //-------------------------------------------
  UInt_t      triggerMask = AliVEvent::kINT7;//A Khuntia
  // if(isMC && (evtCutSetID==eventCutSet::kNoEvtSel || evtCutSetID==eventCutSet::kSpecial3)) triggerMask=AliVEvent::kAny;
  Bool_t      rejectPileUp = kTRUE; //
  Double_t    vtxZcut = 10.0; //cm, default cut on vtx z

  if (evtCutSetID==eventCutSet::kDefaultVtx12){vtxZcut = 12.0;} //cm

  if (evtCutSetID==eventCutSet::kDefaultVtx8){vtxZcut = 8.0;} //cm

  if (evtCutSetID==eventCutSet::kDefaultVtx5){vtxZcut = 5.0;}//cm

  if (evtCutSetID==eventCutSet::kNoPileUpCut){rejectPileUp=kFALSE;}//cm

  if(evtCutSetID==eventCutSet::kSpecial2) vtxZcut=1.e6;//off

  //-------------------------------------------
  //pair cuts
  //-------------------------------------------
  Double_t    minYlab =  -0.5;
  Double_t    maxYlab =  0.5;

  if (pairCutSetID==pairYCutSet::kCentral) { //|y_cm|<0.3
    minYlab = -0.3;    maxYlab = 0.3;
  }

  //-------------------------------------------
  //mixing settings
  //-------------------------------------------
  Int_t       nmix = 0;
  Float_t     maxDiffVzMix = 1.0;
  Float_t     maxDiffMultMix = 10.0;

  if (mixingConfigID == eventMixConfig::kMixDefault) { nmix = 10;}

  if (mixingConfigID == eventMixConfig::k5Evts) {nmix = 5;}

  if (mixingConfigID == eventMixConfig::k5Cent) {maxDiffMultMix = 5;}

  if(mixingConfigID==eventMixConfig::k5Evts5Cent){nmix=5; maxDiffMultMix=5;}

  //
  // -- INITIALIZATION ----------------------------------------------------------------------------
  // retrieve analysis manager
  //
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
   if (!mgr) {
      ::Error("AddAnalysisTaskTOFKStar", "No analysis manager to connect to.");
      return NULL;
   }

   // create the task and configure
   TString taskName = Form("TOFKStar%s%s_%i%i", (isPP? "pp" : "PbPb"), (isMC ? "MC" : "Data"), (Int_t)cutPiCandidate,(Int_t)cutKaCandidate );
   AliRsnMiniAnalysisTask *task = new AliRsnMiniAnalysisTask(taskName.Data(), isMC);
   //task->UseESDTriggerMask(triggerMask); //ESD
   //task->SelectCollisionCandidates(triggerMask); //AOD
   if(evtCutSetID!=eventCutSet::kNoEvtSel && evtCutSetID!=eventCutSet::kSpecial3) task->SelectCollisionCandidates(triggerMask); //AOD

   if (isPP)
     task->UseMultiplicity("QUALITY");
   else
     task->UseCentrality("V0M");
   // set event mixing options
   task->UseContinuousMix();
   //task->UseBinnedMix();
   task->SetNMix(nmix);
   task->SetMaxDiffVz(maxDiffVzMix);
   task->SetMaxDiffMult(maxDiffMultMix);
   ::Info("AddAnalysisTaskTOFKStar", Form("Event mixing configuration: \n events to mix = %i \n max diff. vtxZ = cm %5.3f \n max diff multi = %5.3f", nmix, maxDiffVzMix, maxDiffMultMix));

   mgr->AddTask(task);

   //
   // cut on primary vertex:
   // - 2nd argument --> |Vz| range
   // - 3rd argument --> minimum required number of contributors to vtx
   // - 4th argument --> tells if TPC stand-alone vertexes must be accepted
   AliRsnCutPrimaryVertex *cutVertex=0;
    if (evtCutSetID!=eventCutSet::kSpecial1 && evtCutSetID!=eventCutSet::kNoEvtSel){
    cutVertex = new AliRsnCutPrimaryVertex("cutVertex", vtxZcut, 0, kFALSE);
    if (evtCutSetID==eventCutSet::kSpecial3) cutVertex->SetCheckGeneratedVertexZ();

     }//vertex loop

   if (isPP && (!isMC)) {
     cutVertex->SetCheckPileUp(rejectPileUp);   // set the check for pileup
     ::Info("AddAnalysisTaskTOFKStar", Form(":::::::::::::::::: Pile-up rejection mode: %s", (rejectPileUp)?"ON":"OFF"));
     //cutVertex->SetCheckZResolutionSPD();//A Khuntia
     //cutVertex->SetCheckDispersionSPD();//A Khuntia
     //cutVertex->SetCheckZDifferenceSPDTrack();//A Khuntia
   }

   ///////----------AKhuntia----------//////
   /*AliRsnCutEventUtils* cutEventUtils=0;
   cutEventUtils=new AliRsnCutEventUtils("cutEventUtils",kTRUE,rejectPileUp);
   cutEventUtils->SetCheckIncompleteDAQ();
   cutEventUtils->SetCheckSPDClusterVsTrackletBG();*/
   //------------------------------------
   // define and fill cut set for event cut
   AliRsnCutSet *eventCuts = new AliRsnCutSet("eventCuts", AliRsnTarget::kEvent);
   eventCuts->AddCut(cutVertex);
   eventCuts->SetCutScheme(Form("%s", cutVertex->GetName()));
   task->SetEventCuts(eventCuts);

   //
   // -- EVENT-ONLY COMPUTATIONS -------------------------------------------------------------------
   //
   //vertex
   Int_t vtxID = task->CreateValue(AliRsnMiniValue::kVz, kFALSE);
   AliRsnMiniOutput *outVtx = task->CreateOutput("eventVtx", "HIST", "EVENT");
   outVtx->AddAxis(vtxID, 240, -12.0, 12.0);

   //multiplicity or centrality
   Int_t multID = task->CreateValue(AliRsnMiniValue::kMult, kFALSE);
   AliRsnMiniOutput *outMult = task->CreateOutput("eventMult", "HIST", "EVENT");
   if (isPP)
     outMult->AddAxis(multID, 400, 0.0, 400.0);
   else
     outMult->AddAxis(multID, 100, 0.0, 100.0);

   TH2F* hvz=new TH2F("hVzVsCent","", 100, 0., 100., 240, -12.0, 12.0);
   task->SetEventQAHist("vz",hvz);//plugs this histogram into the fHAEventVz data member

   TH2F* hmc=new TH2F("MultiVsCent","", 100, 0., 100., 400, 0., 400.);
   hmc->GetYaxis()->SetTitle("QUALITY");
   task->SetEventQAHist("multicent",hmc);//plugs this histogram into the fHAEventMultiCent data member

   //
   // -- PAIR CUTS (common to all resonances) ------------------------------------------------------
   //

   AliRsnCutMiniPair *cutY = new AliRsnCutMiniPair("cutRapidity", AliRsnCutMiniPair::kRapidityRange);
   cutY->SetRangeD(minYlab, maxYlab);

   AliRsnCutSet *cutsPair = new AliRsnCutSet("pairCuts", AliRsnTarget::kMother);
   cutsPair->AddCut(cutY);
   cutsPair->SetCutScheme(cutY->GetName());

   //
   // -- CONFIG ANALYSIS --------------------------------------------------------------------------
   //
     gROOT->LoadMacro("$ALICE_PHYSICS/PWGLF/RESONANCES/macros/mini/ConfigKStarPP8TeV_PID.C");
   //gROOT->LoadMacro("ConfigKStarPP8TeV_PID.C");
   if (!ConfigKStarPP8TeV_PID(task, isMC, isPP, "", cutsPair, aodFilterBit, customQualityCutsID, cutPiCandidate, cutKaCandidate, nsigmaPi, nsigmaKa, enableMonitor, isMC&IsMcTrueOnly,  monitorOpt.Data(), useMixLS, isMC&checkReflex, yaxisvar)) return 0x0;

   //
   // -- CONTAINERS --------------------------------------------------------------------------------
   //
   TString outputFileName = AliAnalysisManager::GetCommonFileName();
   //  outputFileName += ":Rsn";
   Printf("AddAnalysisTaskTOFKStar - Set OutputFileName : \n %s\n", outputFileName.Data() );

   AliAnalysisDataContainer *output = mgr->CreateContainer(Form("RsnOut_%s",outNameSuffix.Data()),
							   TList::Class(),
							   AliAnalysisManager::kOutputContainer,
							   outputFileName);
   mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
   mgr->ConnectOutput(task, 1, output);

   return task;
}
<commit_msg>bug found in the macro and solved it for KStar analysis in pp at 8 TeV<commit_after>/***************************************************************************
              fbellini@cern.ch - last modified on 28/11/2013
//
//Lauches KStar analysis with rsn mini package
//Allows basic configuration of pile-up check and event cuts
//
****************************************************************************/
enum pairYCutSet { kPairDefault=0,
		   kCentral //=1
                 };

enum eventCutSet { kEvtDefault=0,
		   kNoPileUpCut, //=1
		   kDefaultVtx12,//=2
		   kDefaultVtx8, //=3
		   kDefaultVtx5, //=4
		   kMCEvtDefault, //=5
		   kSpecial1, //=6
		   kSpecial2, //=7
		   kNoEvtSel, //=8
		   kSpecial3//=9
                 };

enum eventMixConfig { kDisabled = -1,
		      kMixDefault,//=0 //10 events, Dvz = 1cm, DC = 10
		      k5Evts, //=1 //5 events, Dvz = 1cm, DC = 10
		      k5Cent,  //=2 //10 events, Dvz = 1cm, DC = 5
		      k5Evts5Cent
                    };

AliRsnMiniAnalysisTask * AddTaskKStarPP8TeV_PID
(
 Bool_t      isMC = kFALSE,
 Bool_t      isPP = kTRUE,
 TString     outNameSuffix = "tpc2stof3sveto",
 Int_t       evtCutSetID = 0,
 Int_t       pairCutSetID = 0,
 Int_t       mixingConfigID = 0,
 Int_t       aodFilterBit = 5,
 Int_t       customQualityCutsID = -1,
 AliRsnCutSetDaughterParticle::ERsnDaughterCutSet cutPiCandidate = AliRsnCutSetDaughterParticle::kTPCpidTOFveto3s,
 AliRsnCutSetDaughterParticle::ERsnDaughterCutSet cutKaCandidate = AliRsnCutSetDaughterParticle::kTPCpidTOFveto3s,
 Float_t     nsigmaPi = 2.0,
 Float_t     nsigmaKa = 2.0,
 Bool_t      enableMonitor = kTRUE,
 Bool_t      IsMcTrueOnly = kFALSE,
 TString     monitorOpt = "NoSIGN",
 Bool_t      useMixLS = 0,
 Bool_t      checkReflex = 0,
 AliRsnMiniValue::EType yaxisvar = AliRsnMiniValue::kPt
)
{

  //-------------------------------------------
  // event cuts
  //-------------------------------------------
  UInt_t      triggerMask = AliVEvent::kINT7;//A Khuntia
  // if(isMC && (evtCutSetID==eventCutSet::kNoEvtSel || evtCutSetID==eventCutSet::kSpecial3)) triggerMask=AliVEvent::kAny;
  Bool_t      rejectPileUp = kTRUE; //
  Double_t    vtxZcut = 10.0; //cm, default cut on vtx z

  if (evtCutSetID==eventCutSet::kDefaultVtx12){vtxZcut = 12.0;} //cm

  if (evtCutSetID==eventCutSet::kDefaultVtx8){vtxZcut = 8.0;} //cm

  if (evtCutSetID==eventCutSet::kDefaultVtx5){vtxZcut = 5.0;}//cm

  if (evtCutSetID==eventCutSet::kNoPileUpCut){rejectPileUp=kFALSE;}//cm

  if(evtCutSetID==eventCutSet::kSpecial2) vtxZcut=1.e6;//off

  //-------------------------------------------
  //pair cuts
  //-------------------------------------------
  Double_t    minYlab =  -0.5;
  Double_t    maxYlab =  0.5;

  if (pairCutSetID==pairYCutSet::kCentral) { //|y_cm|<0.3
    minYlab = -0.3;    maxYlab = 0.3;
  }

  //-------------------------------------------
  //mixing settings
  //-------------------------------------------
  Int_t       nmix = 0;
  Float_t     maxDiffVzMix = 1.0;
  Float_t     maxDiffMultMix = 10.0;

  if (mixingConfigID == eventMixConfig::kMixDefault) { nmix = 10;}

  if (mixingConfigID == eventMixConfig::k5Evts) {nmix = 5;}

  if (mixingConfigID == eventMixConfig::k5Cent) {maxDiffMultMix = 5;}

  if(mixingConfigID==eventMixConfig::k5Evts5Cent){nmix=5; maxDiffMultMix=5;}

  //
  // -- INITIALIZATION ----------------------------------------------------------------------------
  // retrieve analysis manager
  //
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
   if (!mgr) {
      ::Error("AddAnalysisTaskTOFKStar", "No analysis manager to connect to.");
      return NULL;
   }

   // create the task and configure
   TString taskName = Form("TOFKStar%s%s_%i%i", (isPP? "pp" : "PbPb"), (isMC ? "MC" : "Data"), (Int_t)cutPiCandidate,(Int_t)cutKaCandidate );
   AliRsnMiniAnalysisTask *task = new AliRsnMiniAnalysisTask(taskName.Data(), isMC);
   //task->UseESDTriggerMask(triggerMask); //ESD
   //task->SelectCollisionCandidates(triggerMask); //AOD
   if(evtCutSetID!=eventCutSet::kNoEvtSel && evtCutSetID!=eventCutSet::kSpecial3) task->SelectCollisionCandidates(triggerMask); //AOD

   if (isPP)
     task->UseMultiplicity("QUALITY");
   else
     task->UseCentrality("V0M");
   // set event mixing options
   task->UseContinuousMix();
   //task->UseBinnedMix();
   task->SetNMix(nmix);
   task->SetMaxDiffVz(maxDiffVzMix);
   task->SetMaxDiffMult(maxDiffMultMix);
   ::Info("AddAnalysisTaskTOFKStar", Form("Event mixing configuration: \n events to mix = %i \n max diff. vtxZ = cm %5.3f \n max diff multi = %5.3f", nmix, maxDiffVzMix, maxDiffMultMix));

   mgr->AddTask(task);

   //
   // cut on primary vertex:
   // - 2nd argument --> |Vz| range
   // - 3rd argument --> minimum required number of contributors to vtx
   // - 4th argument --> tells if TPC stand-alone vertexes must be accepted
   AliRsnCutPrimaryVertex *cutVertex=0;
    if (evtCutSetID!=eventCutSet::kSpecial1 && evtCutSetID!=eventCutSet::kNoEvtSel){
    cutVertex = new AliRsnCutPrimaryVertex("cutVertex", vtxZcut, 0, kFALSE);
    if (evtCutSetID==eventCutSet::kSpecial3) cutVertex->SetCheckGeneratedVertexZ();

     }//vertex loop

   if (isPP && (!isMC)&&cutVertex) {
     cutVertex->SetCheckPileUp(rejectPileUp);   // set the check for pileup
     ::Info("AddAnalysisTaskTOFKStar", Form(":::::::::::::::::: Pile-up rejection mode: %s", (rejectPileUp)?"ON":"OFF"));
     //cutVertex->SetCheckZResolutionSPD();//A Khuntia
     //cutVertex->SetCheckDispersionSPD();//A Khuntia
     //cutVertex->SetCheckZDifferenceSPDTrack();//A Khuntia
   }

   ///////----------AKhuntia----------//////
   /*AliRsnCutEventUtils* cutEventUtils=0;
   cutEventUtils=new AliRsnCutEventUtils("cutEventUtils",kTRUE,rejectPileUp);
   cutEventUtils->SetCheckIncompleteDAQ();
   cutEventUtils->SetCheckSPDClusterVsTrackletBG();*/
   //------------------------------------
   // define and fill cut set for event cut

   AliRsnCutSet* eventCuts=0;
   if(cutVertex){
   eventCuts = new AliRsnCutSet("eventCuts", AliRsnTarget::kEvent);
   eventCuts->AddCut(cutVertex);
   eventCuts->SetCutScheme(Form("%s", cutVertex->GetName()));
   task->SetEventCuts(eventCuts);
   }
   //
   // -- EVENT-ONLY COMPUTATIONS -------------------------------------------------------------------
   //
   //vertex
   Int_t vtxID = task->CreateValue(AliRsnMiniValue::kVz, kFALSE);
   AliRsnMiniOutput *outVtx = task->CreateOutput("eventVtx", "HIST", "EVENT");
   outVtx->AddAxis(vtxID, 240, -12.0, 12.0);

   //multiplicity or centrality
   Int_t multID = task->CreateValue(AliRsnMiniValue::kMult, kFALSE);
   AliRsnMiniOutput *outMult = task->CreateOutput("eventMult", "HIST", "EVENT");
   if (isPP)
     outMult->AddAxis(multID, 400, 0.0, 400.0);
   else
     outMult->AddAxis(multID, 100, 0.0, 100.0);

   TH2F* hvz=new TH2F("hVzVsCent","", 100, 0., 100., 240, -12.0, 12.0);
   task->SetEventQAHist("vz",hvz);//plugs this histogram into the fHAEventVz data member

   TH2F* hmc=new TH2F("MultiVsCent","", 100, 0., 100., 400, 0., 400.);
   hmc->GetYaxis()->SetTitle("QUALITY");
   task->SetEventQAHist("multicent",hmc);//plugs this histogram into the fHAEventMultiCent data member

   //
   // -- PAIR CUTS (common to all resonances) ------------------------------------------------------
   //

   AliRsnCutMiniPair *cutY = new AliRsnCutMiniPair("cutRapidity", AliRsnCutMiniPair::kRapidityRange);
   cutY->SetRangeD(minYlab, maxYlab);

   AliRsnCutSet *cutsPair = new AliRsnCutSet("pairCuts", AliRsnTarget::kMother);
   cutsPair->AddCut(cutY);
   cutsPair->SetCutScheme(cutY->GetName());

   //
   // -- CONFIG ANALYSIS --------------------------------------------------------------------------
   //
     gROOT->LoadMacro("$ALICE_PHYSICS/PWGLF/RESONANCES/macros/mini/ConfigKStarPP8TeV_PID.C");
   //gROOT->LoadMacro("ConfigKStarPP8TeV_PID.C");
   if (!ConfigKStarPP8TeV_PID(task, isMC, isPP, "", cutsPair, aodFilterBit, customQualityCutsID, cutPiCandidate, cutKaCandidate, nsigmaPi, nsigmaKa, enableMonitor, isMC&IsMcTrueOnly,  monitorOpt.Data(), useMixLS, isMC&checkReflex, yaxisvar)) return 0x0;

   //
   // -- CONTAINERS --------------------------------------------------------------------------------
   //
   TString outputFileName = AliAnalysisManager::GetCommonFileName();
   //  outputFileName += ":Rsn";
   Printf("AddAnalysisTaskTOFKStar - Set OutputFileName : \n %s\n", outputFileName.Data() );

   AliAnalysisDataContainer *output = mgr->CreateContainer(Form("RsnOut_%s",outNameSuffix.Data()),
							   TList::Class(),
							   AliAnalysisManager::kOutputContainer,
							   outputFileName);
   mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
   mgr->ConnectOutput(task, 1, output);

   return task;
}
<|endoftext|>


<commit_before><commit_msg>Handle missing SIZE_MAX<commit_after><|endoftext|>


<commit_before>/*
 * DensifyPointCloud.cpp
 *
 * Copyright (c) 2014-2015 SEACAVE
 *
 * Author(s):
 *
 *      cDc <cdc.seacave@gmail.com>
 *
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *
 * Additional Terms:
 *
 *      You are required to preserve legal notices and author attributions in
 *      that material or in the Appropriate Legal Notices displayed by works
 *      containing it.
 */

#include "../../libs/MVS/Common.h"
#include "../../libs/MVS/Scene.h"
#include <boost/program_options.hpp>

using namespace MVS;

// D E F I N E S ///////////////////////////////////////////////////

#define APPNAME _T("DensifyPointCloud")

// S T R U C T S ///////////////////////////////////////////////////

namespace OPT {
String strInputFileName;
String strOutputFileName;
String strMeshFileName;
String strDenseConfigFileName;
float fSampleMesh;
int thFilterPointCloud;
int nArchiveType;
int nProcessPriority;
unsigned nMaxThreads;
String strConfigFileName;
boost::program_options::variables_map vm;
} // namespace OPT

// initialize and parse the command line parameters
bool Initialize(size_t argc, LPCTSTR* argv)
{
	// initialize log and console
	OPEN_LOG();
	OPEN_LOGCONSOLE();

	// group of options allowed only on command line
	boost::program_options::options_description generic("Generic options");
	generic.add_options()
		("help,h", "produce this help message")
		("working-folder,w", boost::program_options::value<std::string>(&WORKING_FOLDER), "working directory (default current directory)")
		("config-file,c", boost::program_options::value<std::string>(&OPT::strConfigFileName)->default_value(APPNAME _T(".cfg")), "file name containing program options")
		("archive-type", boost::program_options::value(&OPT::nArchiveType)->default_value(2), "project archive type: 0-text, 1-binary, 2-compressed binary")
		("process-priority", boost::program_options::value(&OPT::nProcessPriority)->default_value(-1), "process priority (below normal by default)")
		("max-threads", boost::program_options::value(&OPT::nMaxThreads)->default_value(0), "maximum number of threads (0 for using all available cores)")
		#if TD_VERBOSE != TD_VERBOSE_OFF
		("verbosity,v", boost::program_options::value(&g_nVerbosityLevel)->default_value(
			#if TD_VERBOSE == TD_VERBOSE_DEBUG
			3
			#else
			2
			#endif
			), "verbosity level")
		#endif
		;

	// group of options allowed both on command line and in config file
	unsigned nResolutionLevel;
	unsigned nMaxResolution;
	unsigned nMinResolution;
	unsigned nNumViews;
	unsigned nMinViewsFuse;
	unsigned nOptimize;
	unsigned nEstimateColors;
	unsigned nEstimateNormals;
	boost::program_options::options_description config("Densify options");
	config.add_options()
		("input-file,i", boost::program_options::value<std::string>(&OPT::strInputFileName), "input filename containing camera poses and image list")
		("output-file,o", boost::program_options::value<std::string>(&OPT::strOutputFileName), "output filename for storing the dense point-cloud")
		("resolution-level", boost::program_options::value(&nResolutionLevel)->default_value(1), "how many times to scale down the images before point cloud computation")
		("max-resolution", boost::program_options::value(&nMaxResolution)->default_value(3200), "do not scale images higher than this resolution")
		("min-resolution", boost::program_options::value(&nMinResolution)->default_value(640), "do not scale images lower than this resolution")
		("number-views", boost::program_options::value(&nNumViews)->default_value(5), "number of views used for depth-map estimation (0 - all neighbor views available)")
		("number-views-fuse", boost::program_options::value(&nMinViewsFuse)->default_value(3), "minimum number of images that agrees with an estimate during fusion in order to consider it inlier")
		("optimize", boost::program_options::value(&nOptimize)->default_value(7), "filter used after depth-map estimation (0 - disabled, 1 - remove speckles, 2 - fill gaps, 4 - cross-adjust)")
		("estimate-colors", boost::program_options::value(&nEstimateColors)->default_value(2), "estimate the colors for the dense point-cloud")
		("estimate-normals", boost::program_options::value(&nEstimateNormals)->default_value(0), "estimate the normals for the dense point-cloud")
		("sample-mesh", boost::program_options::value(&OPT::fSampleMesh)->default_value(0.f), "uniformly samples points on a mesh (0 - disabled, <0 - number of points, >0 - sample density per square unit)")
		("filter-point-cloud", boost::program_options::value(&OPT::thFilterPointCloud)->default_value(0), "filter dense point-cloud based on visibility (0 - disabled)")
		;

	// hidden options, allowed both on command line and
	// in config file, but will not be shown to the user
	boost::program_options::options_description hidden("Hidden options");
	hidden.add_options()
		("dense-config-file", boost::program_options::value<std::string>(&OPT::strDenseConfigFileName), "optional configuration file for the densifier (overwritten by the command line options)")
		;

	boost::program_options::options_description cmdline_options;
	cmdline_options.add(generic).add(config).add(hidden);

	boost::program_options::options_description config_file_options;
	config_file_options.add(config).add(hidden);

	boost::program_options::positional_options_description p;
	p.add("input-file", -1);

	try {
		// parse command line options
		boost::program_options::store(boost::program_options::command_line_parser((int)argc, argv).options(cmdline_options).positional(p).run(), OPT::vm);
		boost::program_options::notify(OPT::vm);
		INIT_WORKING_FOLDER;
		// parse configuration file
		std::ifstream ifs(MAKE_PATH_SAFE(OPT::strConfigFileName));
		if (ifs) {
			boost::program_options::store(parse_config_file(ifs, config_file_options), OPT::vm);
			boost::program_options::notify(OPT::vm);
		}
	}
	catch (const std::exception& e) {
		LOG(e.what());
		return false;
	}

	// initialize the log file
	OPEN_LOGFILE(MAKE_PATH(APPNAME _T("-")+Util::getUniqueName(0)+_T(".log")).c_str());

	// print application details: version and command line
	Util::LogBuild();
	LOG(_T("Command line:%s"), Util::CommandLineToString(argc, argv).c_str());

	// validate input
	Util::ensureValidPath(OPT::strInputFileName);
	Util::ensureUnifySlash(OPT::strInputFileName);
	if (OPT::vm.count("help") || OPT::strInputFileName.IsEmpty()) {
		boost::program_options::options_description visible("Available options");
		visible.add(generic).add(config);
		GET_LOG() << visible;
	}
	if (OPT::strInputFileName.IsEmpty())
		return false;

	// initialize optional options
	Util::ensureValidPath(OPT::strOutputFileName);
	Util::ensureUnifySlash(OPT::strOutputFileName);
	if (OPT::strOutputFileName.IsEmpty())
		OPT::strOutputFileName = Util::getFileFullName(OPT::strInputFileName) + _T("_dense.mvs");

	// init dense options
	if (!Util::isFullPath(OPT::strDenseConfigFileName))
		OPT::strDenseConfigFileName = MAKE_PATH(OPT::strDenseConfigFileName);
	OPTDENSE::init();
	const bool bValidConfig(OPTDENSE::oConfig.Load(OPT::strDenseConfigFileName));
	OPTDENSE::update();
	OPTDENSE::nResolutionLevel = nResolutionLevel;
	OPTDENSE::nMaxResolution = nMaxResolution;
	OPTDENSE::nMinResolution = nMinResolution;
	OPTDENSE::nNumViews = nNumViews;
	OPTDENSE::nMinViewsFuse = nMinViewsFuse;
	OPTDENSE::nOptimize = nOptimize;
	OPTDENSE::nEstimateColors = nEstimateColors;
	OPTDENSE::nEstimateNormals = nEstimateNormals;
	if (!bValidConfig)
		OPTDENSE::oConfig.Save(OPT::strDenseConfigFileName);

	// initialize global options
	Process::setCurrentProcessPriority((Process::Priority)OPT::nProcessPriority);
	#ifdef _USE_OPENMP
	if (OPT::nMaxThreads != 0)
		omp_set_num_threads(OPT::nMaxThreads);
	#endif

	#ifdef _USE_BREAKPAD
	// start memory dumper
	MiniDumper::Create(APPNAME, WORKING_FOLDER);
	#endif

	Util::Init();
	return true;
}

// finalize application instance
void Finalize()
{
	#if TD_VERBOSE != TD_VERBOSE_OFF
	// print memory statistics
	Util::LogMemoryInfo();
	#endif

	CLOSE_LOGFILE();
	CLOSE_LOGCONSOLE();
	CLOSE_LOG();
}

int main(int argc, LPCTSTR* argv)
{
	#ifdef _DEBUGINFO
	// set _crtBreakAlloc index to stop in <dbgheap.c> at allocation
	_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);// | _CRTDBG_CHECK_ALWAYS_DF);
	#endif

	if (!Initialize(argc, argv))
		return EXIT_FAILURE;

	Scene scene(OPT::nMaxThreads);
	if (OPT::fSampleMesh != 0) {
		// sample input mesh and export the obtained point-cloud
		if (!scene.mesh.Load(MAKE_PATH_SAFE(OPT::strInputFileName)))
			return EXIT_FAILURE;
		TD_TIMER_START();
		PointCloud pointcloud;
		if (OPT::fSampleMesh > 0)
			scene.mesh.SamplePoints(OPT::fSampleMesh, 0, pointcloud);
		else
			scene.mesh.SamplePoints((unsigned)ROUND2INT(-OPT::fSampleMesh), pointcloud);
		VERBOSE("Sample mesh completed: %u points (%s)", pointcloud.GetSize(), TD_TIMER_GET_FMT().c_str());
		pointcloud.Save(MAKE_PATH_SAFE(Util::getFileFullName(OPT::strOutputFileName))+_T(".ply"));
		Finalize();
		return EXIT_SUCCESS;
	}
	// load and estimate a dense point-cloud
	if (!scene.Load(MAKE_PATH_SAFE(OPT::strInputFileName)))
		return EXIT_FAILURE;
	if (scene.pointcloud.IsEmpty()) {
		VERBOSE("error: empty initial point-cloud");
		return EXIT_FAILURE;
	}
	if (OPT::thFilterPointCloud < 0) {
		// filter point-cloud based on camera-point visibility intersections
		scene.PointCloudFilter(OPT::thFilterPointCloud);
		const String baseFileName(MAKE_PATH_SAFE(Util::getFileFullName(OPT::strOutputFileName))+_T("_filtered"));
		scene.Save(baseFileName+_T(".mvs"), (ARCHIVE_TYPE)OPT::nArchiveType);
		scene.pointcloud.Save(baseFileName+_T(".ply"));
		Finalize();
		return EXIT_SUCCESS;
	}
	if ((ARCHIVE_TYPE)OPT::nArchiveType != ARCHIVE_MVS) {
		TD_TIMER_START();
		if (!scene.DenseReconstruction())
			return EXIT_FAILURE;
		VERBOSE("Densifying point-cloud completed: %u points (%s)", scene.pointcloud.GetSize(), TD_TIMER_GET_FMT().c_str());
	}

	// save the final mesh
	const String baseFileName(MAKE_PATH_SAFE(Util::getFileFullName(OPT::strOutputFileName)));
	scene.Save(baseFileName+_T(".mvs"), (ARCHIVE_TYPE)OPT::nArchiveType);
	scene.pointcloud.Save(baseFileName+_T(".ply"));
	#if TD_VERBOSE != TD_VERBOSE_OFF
	if (VERBOSITY_LEVEL > 2)
		scene.ExportCamerasMLP(baseFileName+_T(".mlp"), baseFileName+_T(".ply"));
	#endif

	Finalize();
	return EXIT_SUCCESS;
}
/*----------------------------------------------------------------*/
<commit_msg>dense: fix crash when working directory is provided (#460)<commit_after>/*
 * DensifyPointCloud.cpp
 *
 * Copyright (c) 2014-2015 SEACAVE
 *
 * Author(s):
 *
 *      cDc <cdc.seacave@gmail.com>
 *
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *
 * Additional Terms:
 *
 *      You are required to preserve legal notices and author attributions in
 *      that material or in the Appropriate Legal Notices displayed by works
 *      containing it.
 */

#include "../../libs/MVS/Common.h"
#include "../../libs/MVS/Scene.h"
#include <boost/program_options.hpp>

using namespace MVS;

// D E F I N E S ///////////////////////////////////////////////////

#define APPNAME _T("DensifyPointCloud")

// S T R U C T S ///////////////////////////////////////////////////

namespace OPT {
String strInputFileName;
String strOutputFileName;
String strMeshFileName;
String strDenseConfigFileName;
float fSampleMesh;
int thFilterPointCloud;
int nArchiveType;
int nProcessPriority;
unsigned nMaxThreads;
String strConfigFileName;
boost::program_options::variables_map vm;
} // namespace OPT

// initialize and parse the command line parameters
bool Initialize(size_t argc, LPCTSTR* argv)
{
	// initialize log and console
	OPEN_LOG();
	OPEN_LOGCONSOLE();

	// group of options allowed only on command line
	boost::program_options::options_description generic("Generic options");
	generic.add_options()
		("help,h", "produce this help message")
		("working-folder,w", boost::program_options::value<std::string>(&WORKING_FOLDER), "working directory (default current directory)")
		("config-file,c", boost::program_options::value<std::string>(&OPT::strConfigFileName)->default_value(APPNAME _T(".cfg")), "file name containing program options")
		("archive-type", boost::program_options::value(&OPT::nArchiveType)->default_value(2), "project archive type: 0-text, 1-binary, 2-compressed binary")
		("process-priority", boost::program_options::value(&OPT::nProcessPriority)->default_value(-1), "process priority (below normal by default)")
		("max-threads", boost::program_options::value(&OPT::nMaxThreads)->default_value(0), "maximum number of threads (0 for using all available cores)")
		#if TD_VERBOSE != TD_VERBOSE_OFF
		("verbosity,v", boost::program_options::value(&g_nVerbosityLevel)->default_value(
			#if TD_VERBOSE == TD_VERBOSE_DEBUG
			3
			#else
			2
			#endif
			), "verbosity level")
		#endif
		;

	// group of options allowed both on command line and in config file
	unsigned nResolutionLevel;
	unsigned nMaxResolution;
	unsigned nMinResolution;
	unsigned nNumViews;
	unsigned nMinViewsFuse;
	unsigned nOptimize;
	unsigned nEstimateColors;
	unsigned nEstimateNormals;
	boost::program_options::options_description config("Densify options");
	config.add_options()
		("input-file,i", boost::program_options::value<std::string>(&OPT::strInputFileName), "input filename containing camera poses and image list")
		("output-file,o", boost::program_options::value<std::string>(&OPT::strOutputFileName), "output filename for storing the dense point-cloud")
		("resolution-level", boost::program_options::value(&nResolutionLevel)->default_value(1), "how many times to scale down the images before point cloud computation")
		("max-resolution", boost::program_options::value(&nMaxResolution)->default_value(3200), "do not scale images higher than this resolution")
		("min-resolution", boost::program_options::value(&nMinResolution)->default_value(640), "do not scale images lower than this resolution")
		("number-views", boost::program_options::value(&nNumViews)->default_value(5), "number of views used for depth-map estimation (0 - all neighbor views available)")
		("number-views-fuse", boost::program_options::value(&nMinViewsFuse)->default_value(3), "minimum number of images that agrees with an estimate during fusion in order to consider it inlier")
		("optimize", boost::program_options::value(&nOptimize)->default_value(7), "filter used after depth-map estimation (0 - disabled, 1 - remove speckles, 2 - fill gaps, 4 - cross-adjust)")
		("estimate-colors", boost::program_options::value(&nEstimateColors)->default_value(2), "estimate the colors for the dense point-cloud")
		("estimate-normals", boost::program_options::value(&nEstimateNormals)->default_value(0), "estimate the normals for the dense point-cloud")
		("sample-mesh", boost::program_options::value(&OPT::fSampleMesh)->default_value(0.f), "uniformly samples points on a mesh (0 - disabled, <0 - number of points, >0 - sample density per square unit)")
		("filter-point-cloud", boost::program_options::value(&OPT::thFilterPointCloud)->default_value(0), "filter dense point-cloud based on visibility (0 - disabled)")
		;

	// hidden options, allowed both on command line and
	// in config file, but will not be shown to the user
	boost::program_options::options_description hidden("Hidden options");
	hidden.add_options()
		("dense-config-file", boost::program_options::value<std::string>(&OPT::strDenseConfigFileName), "optional configuration file for the densifier (overwritten by the command line options)")
		;

	boost::program_options::options_description cmdline_options;
	cmdline_options.add(generic).add(config).add(hidden);

	boost::program_options::options_description config_file_options;
	config_file_options.add(config).add(hidden);

	boost::program_options::positional_options_description p;
	p.add("input-file", -1);

	try {
		// parse command line options
		boost::program_options::store(boost::program_options::command_line_parser((int)argc, argv).options(cmdline_options).positional(p).run(), OPT::vm);
		boost::program_options::notify(OPT::vm);
		INIT_WORKING_FOLDER;
		// parse configuration file
		std::ifstream ifs(MAKE_PATH_SAFE(OPT::strConfigFileName));
		if (ifs) {
			boost::program_options::store(parse_config_file(ifs, config_file_options), OPT::vm);
			boost::program_options::notify(OPT::vm);
		}
	}
	catch (const std::exception& e) {
		LOG(e.what());
		return false;
	}

	// initialize the log file
	OPEN_LOGFILE(MAKE_PATH(APPNAME _T("-")+Util::getUniqueName(0)+_T(".log")).c_str());

	// print application details: version and command line
	Util::LogBuild();
	LOG(_T("Command line:%s"), Util::CommandLineToString(argc, argv).c_str());

	// validate input
	Util::ensureValidPath(OPT::strInputFileName);
	Util::ensureUnifySlash(OPT::strInputFileName);
	if (OPT::vm.count("help") || OPT::strInputFileName.IsEmpty()) {
		boost::program_options::options_description visible("Available options");
		visible.add(generic).add(config);
		GET_LOG() << visible;
	}
	if (OPT::strInputFileName.IsEmpty())
		return false;

	// initialize optional options
	Util::ensureValidPath(OPT::strOutputFileName);
	Util::ensureUnifySlash(OPT::strOutputFileName);
	if (OPT::strOutputFileName.IsEmpty())
		OPT::strOutputFileName = Util::getFileFullName(OPT::strInputFileName) + _T("_dense.mvs");

	// init dense options
	if (!OPT::strDenseConfigFileName.IsEmpty())
		OPT::strDenseConfigFileName = MAKE_PATH_SAFE(OPT::strDenseConfigFileName);
	OPTDENSE::init();
	const bool bValidConfig(OPTDENSE::oConfig.Load(OPT::strDenseConfigFileName));
	OPTDENSE::update();
	OPTDENSE::nResolutionLevel = nResolutionLevel;
	OPTDENSE::nMaxResolution = nMaxResolution;
	OPTDENSE::nMinResolution = nMinResolution;
	OPTDENSE::nNumViews = nNumViews;
	OPTDENSE::nMinViewsFuse = nMinViewsFuse;
	OPTDENSE::nOptimize = nOptimize;
	OPTDENSE::nEstimateColors = nEstimateColors;
	OPTDENSE::nEstimateNormals = nEstimateNormals;
	if (!bValidConfig && !OPT::strDenseConfigFileName.IsEmpty())
		OPTDENSE::oConfig.Save(OPT::strDenseConfigFileName);

	// initialize global options
	Process::setCurrentProcessPriority((Process::Priority)OPT::nProcessPriority);
	#ifdef _USE_OPENMP
	if (OPT::nMaxThreads != 0)
		omp_set_num_threads(OPT::nMaxThreads);
	#endif

	#ifdef _USE_BREAKPAD
	// start memory dumper
	MiniDumper::Create(APPNAME, WORKING_FOLDER);
	#endif

	Util::Init();
	return true;
}

// finalize application instance
void Finalize()
{
	#if TD_VERBOSE != TD_VERBOSE_OFF
	// print memory statistics
	Util::LogMemoryInfo();
	#endif

	CLOSE_LOGFILE();
	CLOSE_LOGCONSOLE();
	CLOSE_LOG();
}

int main(int argc, LPCTSTR* argv)
{
	#ifdef _DEBUGINFO
	// set _crtBreakAlloc index to stop in <dbgheap.c> at allocation
	_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);// | _CRTDBG_CHECK_ALWAYS_DF);
	#endif

	if (!Initialize(argc, argv))
		return EXIT_FAILURE;

	Scene scene(OPT::nMaxThreads);
	if (OPT::fSampleMesh != 0) {
		// sample input mesh and export the obtained point-cloud
		if (!scene.mesh.Load(MAKE_PATH_SAFE(OPT::strInputFileName)))
			return EXIT_FAILURE;
		TD_TIMER_START();
		PointCloud pointcloud;
		if (OPT::fSampleMesh > 0)
			scene.mesh.SamplePoints(OPT::fSampleMesh, 0, pointcloud);
		else
			scene.mesh.SamplePoints((unsigned)ROUND2INT(-OPT::fSampleMesh), pointcloud);
		VERBOSE("Sample mesh completed: %u points (%s)", pointcloud.GetSize(), TD_TIMER_GET_FMT().c_str());
		pointcloud.Save(MAKE_PATH_SAFE(Util::getFileFullName(OPT::strOutputFileName))+_T(".ply"));
		Finalize();
		return EXIT_SUCCESS;
	}
	// load and estimate a dense point-cloud
	if (!scene.Load(MAKE_PATH_SAFE(OPT::strInputFileName)))
		return EXIT_FAILURE;
	if (scene.pointcloud.IsEmpty()) {
		VERBOSE("error: empty initial point-cloud");
		return EXIT_FAILURE;
	}
	if (OPT::thFilterPointCloud < 0) {
		// filter point-cloud based on camera-point visibility intersections
		scene.PointCloudFilter(OPT::thFilterPointCloud);
		const String baseFileName(MAKE_PATH_SAFE(Util::getFileFullName(OPT::strOutputFileName))+_T("_filtered"));
		scene.Save(baseFileName+_T(".mvs"), (ARCHIVE_TYPE)OPT::nArchiveType);
		scene.pointcloud.Save(baseFileName+_T(".ply"));
		Finalize();
		return EXIT_SUCCESS;
	}
	if ((ARCHIVE_TYPE)OPT::nArchiveType != ARCHIVE_MVS) {
		TD_TIMER_START();
		if (!scene.DenseReconstruction())
			return EXIT_FAILURE;
		VERBOSE("Densifying point-cloud completed: %u points (%s)", scene.pointcloud.GetSize(), TD_TIMER_GET_FMT().c_str());
	}

	// save the final mesh
	const String baseFileName(MAKE_PATH_SAFE(Util::getFileFullName(OPT::strOutputFileName)));
	scene.Save(baseFileName+_T(".mvs"), (ARCHIVE_TYPE)OPT::nArchiveType);
	scene.pointcloud.Save(baseFileName+_T(".ply"));
	#if TD_VERBOSE != TD_VERBOSE_OFF
	if (VERBOSITY_LEVEL > 2)
		scene.ExportCamerasMLP(baseFileName+_T(".mlp"), baseFileName+_T(".ply"));
	#endif

	Finalize();
	return EXIT_SUCCESS;
}
/*----------------------------------------------------------------*/
<|endoftext|>


<commit_before>#include "bct.h"
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>

bool bct::safe_mode = false;

/* M
 * Returns a vector of indices of the elements in m that satisfy a condition
 * given by a comparison with cmprVal. Presently, the comparsion operators are
 * coded in the cmprFlag parameter, as follows:
 * 0 -> 'greater than operator, >'
 */
gsl_matrix* bct::find(const gsl_matrix* m, int cmprFlag, double cmprVal) {
	gsl_matrix* indices = gsl_matrix_alloc(2, m->size1 * m->size1);
	int size = 0;
	if(cmprFlag==0) { //means, perform a '>'
		for(int i = 0;i < m->size1;i++) {
			for(int j = 0;j < m->size2;j++) {
				double matrixVal = gsl_matrix_get(m, i, j);
				if(matrixVal > cmprVal) {
					gsl_matrix_set(indices, 0, size++, i);
					gsl_matrix_set(indices, 1, size++, j);
				}
			}
		}
		gsl_matrix* trimIndices = gsl_matrix_alloc(2, size * size);
		gsl_matrix_view trim = gsl_matrix_submatrix((gsl_matrix*)m, 0, 0, size-1, size-1);
		gsl_matrix_memcpy(trimIndices, &trim.matrix);
		gsl_matrix_free(indices);
		return trimIndices;
	}
}

/* M
 * Strip a vector by picking only those cells where there is a corresponding
 * number 1 in the 'pick vector'.
 */
gsl_vector* bct::pick_cells(const gsl_vector* srcV, const gsl_vector* pickV) {
		int stripVindex = 0;
		int nnzV = nnz(pickV);
		gsl_vector* stripV = gsl_vector_alloc(nnzV);
		for(int i = 0;i < srcV->size;i++) {
			//1 or 1.0, does it make a difference?
			//Nevertheless, pickV is created by logical_not method and it sets integer values
			if(gsl_vector_get(pickV, i) == 1)
				gsl_vector_set(stripV, stripVindex++, gsl_vector_get(srcV, i));
		}
		return stripV;
}

/*
 * Turns safe mode on or off.
 */
void bct::set_safe_mode(bool safe_mode) {
	bct::safe_mode = safe_mode;
}

/* M
 * Splice two vectors into one
 */
gsl_vector* bct::splice(const gsl_vector* v1, const gsl_vector* v2) {
	int spliceVindex = 0;
	gsl_vector* spliceV = gsl_vector_alloc(v1->size + v2->size);
	for(int i = 0;i < v1->size;i++)
		gsl_vector_set(spliceV, spliceVindex++, gsl_vector_get(v1, i));
	for(int i = 0;i < v2->size;i++)
		gsl_vector_set(spliceV, spliceVindex++, gsl_vector_get(v2, i));
	return spliceV;
}
<commit_msg>modified pick_cells method to return an "empty" vector if nnz returns  nothing<commit_after>#include "bct.h"
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include <cassert>

bool bct::safe_mode = false;

/* M
 * Returns a vector of indices of the elements in m that satisfy a condition
 * given by a comparison with cmprVal. Presently, the comparsion operators are
 * coded in the cmprFlag parameter, as follows:
 * 0 -> 'greater than operator, >'
 */
gsl_matrix* bct::find(const gsl_matrix* m, int cmprFlag, double cmprVal) {
	gsl_matrix* indices = gsl_matrix_alloc(2, m->size1 * m->size1);
	int size = 0;
	if(cmprFlag==0) { //means, perform a '>'
		for(int i = 0;i < m->size1;i++) {
			for(int j = 0;j < m->size2;j++) {
				double matrixVal = gsl_matrix_get(m, i, j);
				if(matrixVal > cmprVal) {
					gsl_matrix_set(indices, 0, size++, i);
					gsl_matrix_set(indices, 1, size++, j);
				}
			}
		}
		gsl_matrix* trimIndices = gsl_matrix_alloc(2, size * size);
		gsl_matrix_view trim = gsl_matrix_submatrix((gsl_matrix*)m, 0, 0, size-1, size-1);
		gsl_matrix_memcpy(trimIndices, &trim.matrix);
		gsl_matrix_free(indices);
		return trimIndices;
	}
}

/* M
 * Strip a vector by picking only those cells where there is a corresponding
 * number 1 in the 'pick vector'.
 */
gsl_vector* bct::pick_cells(const gsl_vector* srcV, const gsl_vector* pickV) {
		int stripVindex = 0;
		int nnzV = nnz(pickV);
		if(!(nnzV > 0)) { //Matlab returns an empty matrix in this case, here it needs to be handled differently
			gsl_vector* stripV = gsl_vector_alloc(1);
			gsl_vector_set(stripV, 0, 0);
			return stripV;
		}
		else {
			gsl_vector* stripV = gsl_vector_alloc(nnzV);
			for(int i = 0;i < srcV->size;i++) {
				//1 or 1.0, does it make a difference?
				//Nevertheless, pickV is created by logical_not method and it sets integer values
				if(gsl_vector_get(pickV, i) == 1)
					gsl_vector_set(stripV, stripVindex++, gsl_vector_get(srcV, i));
			}
			return stripV;
		}
}

/*
 * Turns safe mode on or off.
 */
void bct::set_safe_mode(bool safe_mode) {
	bct::safe_mode = safe_mode;
}

/* M
 * Splice two vectors into one
 */
gsl_vector* bct::splice(const gsl_vector* v1, const gsl_vector* v2) {
	int spliceVindex = 0;
	gsl_vector* spliceV = gsl_vector_alloc(v1->size + v2->size);
	for(int i = 0;i < v1->size;i++)
		gsl_vector_set(spliceV, spliceVindex++, gsl_vector_get(v1, i));
	for(int i = 0;i < v2->size;i++)
		gsl_vector_set(spliceV, spliceVindex++, gsl_vector_get(v2, i));
	return spliceV;
}
<|endoftext|>


<commit_before>#ifndef UTILITY_HPP
# define UTILITY_HPP

#include <cstddef>

#include <type_traits>

namespace generic
{

template <::std::size_t...> struct indices { };

namespace detail
{

// indices
template<class A, class B> struct catenate_indices;

template <::std::size_t ...Is, ::std::size_t ...Js>
struct catenate_indices<indices<Is...>, indices<Js...> >
{
  using indices_type = indices<Is..., Js...>;
};

template <::std::size_t, ::std::size_t, typename = void> struct expand_indices;

template <::std::size_t A, ::std::size_t B>
struct expand_indices<A, B, typename ::std::enable_if::type>
{
  using indices_type = indices;
};

template <::std::size_t A, ::std::size_t B>
struct expand_indices<A, B, typename ::std::enable_if::type>
{
  static_assert(A = B");
  using indices_type = typename catenate_indices<
    typename expand_indices::indices_type,
    typename expand_indices<(A + B) / 2 + 1, B>::indices_type
  >::indices_type;
};

}

template <::std::size_t A>
struct make_indices : detail::expand_indices<0, A>::indices_type
{
};

template <::std::size_t A, ::std::size_t B>
struct make_indices_range : detail::expand_indices::indices_type
{
};

// sequences
template <::std::size_t I, typename A, typename ...B>
struct type_at : type_at
{
};

template <typename A, typename ...B>
struct type_at<0, A, B...>
{
  using type = A;
};

template <typename A, typename ...B>
struct front
{
  using type = A;
};

template <typename A, typename ...B>
struct back : back
{
};

template <typename A>
struct back
{
  using type = A;
};

template <bool B>
using bool_ = ::std::integral_constant<bool, B>;

template <class A, class ...B>
struct all_of : bool_<A::value && all_of::value> { };

template <class A>
struct all_of : bool_ { };

}

#endif // UTILITY_HPP
<commit_msg>some fixes<commit_after>#ifndef UTILITY_HPP
# define UTILITY_HPP

#include <cstddef>

#include <type_traits>

namespace generic
{

template <::std::size_t...> struct indices { };

namespace detail
{

// indices
template<class A, class B> struct catenate_indices;

template <::std::size_t ...Is, ::std::size_t ...Js>
struct catenate_indices<indices<Is...>, indices<Js...> >
{
  using indices_type = indices<Is..., Js...>;
};

template <::std::size_t, ::std::size_t, typename = void> struct expand_indices;

template <::std::size_t A, ::std::size_t B>
struct expand_indices<A, B, typename ::std::enable_if::type>
{
  using indices_type = indices;
};

template <::std::size_t A, ::std::size_t B>
struct expand_indices<A, B, typename ::std::enable_if::type>
{
  static_assert(A  B");
  using indices_type = typename catenate_indices<
    typename expand_indices::indices_type,
    typename expand_indices<(A + B) / 2 + 1, B>::indices_type
  >::indices_type;
};

}

template <::std::size_t A>
struct make_indices : detail::expand_indices<0, A>::indices_type
{
};

template <::std::size_t A, ::std::size_t B>
struct make_indices_range : detail::expand_indices::indices_type
{
};

// sequences
template <::std::size_t I, typename A, typename ...B>
struct type_at : type_at
{
};

template <typename A, typename ...B>
struct type_at<0, A, B...>
{
  using type = A;
};

template <typename A, typename ...B>
struct front
{
  using type = A;
};

template <typename A, typename ...B>
struct back : back
{
};

template <typename A>
struct back
{
  using type = A;
};

template <bool B>
using bool_ = ::std::integral_constant<bool, B>;

template <class A, class ...B>
struct all_of : bool_<A::value && all_of::value> { };

template <class A>
struct all_of : bool_ { };

}

#endif // UTILITY_HPP
<|endoftext|>


<commit_before>#ifndef UTILITY_HPP
# define UTILITY_HPP

#include <cstddef>

#include <type_traits>

namespace generic
{

template<typename T> constexpr inline T const& as_const(T& t) { return t; }

template <::std::size_t...> struct indices { };

namespace detail
{

// indices
template<class, class> struct catenate_indices;

template <::std::size_t ...Is, ::std::size_t ...Js>
struct catenate_indices<indices<Is...>, indices<Js...> >
{
  using indices_type = indices<Is..., Js...>;
};

template <::std::size_t, ::std::size_t, typename = void>
struct expand_indices;

template <::std::size_t A, ::std::size_t B>
struct expand_indices<A, B, typename ::std::enable_if::type>
{
  using indices_type = indices;
};

template <::std::size_t A, ::std::size_t B>
struct expand_indices<A, B, typename ::std::enable_if::type>
{
  static_assert(A  B");
  using indices_type = typename catenate_indices<
    typename expand_indices::indices_type,
    typename expand_indices<(A + B) / 2 + 1, B>::indices_type
  >::indices_type;
};

}

template <::std::size_t A>
struct make_indices : detail::expand_indices<0, A - 1>::indices_type;

template <>
struct make_indices<0> : indices<>
{
};

template <::std::size_t A, ::std::size_t B>
struct make_indices_range : detail::expand_indices::indices_type
{
};

template <::std::size_t A>
struct make_indices_range : indices<>
{
};

// sequences
template <::std::size_t I, typename A, typename ...B>
struct type_at : type_at
{
};

template <typename A, typename ...B>
struct type_at<0, A, B...>
{
  using type = A;
};

template <typename A, typename ...B>
struct front
{
  using type = A;
};

template <typename A, typename ...B>
struct back : back
{
};

template <typename A>
struct back
{
  using type = A;
};

template <bool B>
using bool_ = ::std::integral_constant<bool, B>;

template <class A, class ...B>
struct all_of : bool_<A::value && all_of::value> { };

template <class A>
struct all_of : bool_ { };

}

#endif // UTILITY_HPP
<commit_msg>some fixes<commit_after>#ifndef UTILITY_HPP
# define UTILITY_HPP

#include <cstddef>

#include <type_traits>

namespace generic
{

template<typename T> constexpr inline T const& as_const(T& t) { return t; }

template <::std::size_t...> struct indices { };

namespace detail
{

// indices
template<class, class> struct catenate_indices;

template <::std::size_t ...Is, ::std::size_t ...Js>
struct catenate_indices<indices<Is...>, indices<Js...> >
{
  using indices_type = indices<Is..., Js...>;
};

template <::std::size_t, ::std::size_t, typename = void>
struct expand_indices;

template <::std::size_t A, ::std::size_t B>
struct expand_indices<A, B, typename ::std::enable_if::type>
{
  using indices_type = indices;
};

template <::std::size_t A, ::std::size_t B>
struct expand_indices<A, B, typename ::std::enable_if::type>
{
  static_assert(A  B");
  using indices_type = typename catenate_indices<
    typename expand_indices::indices_type,
    typename expand_indices<(A + B) / 2 + 1, B>::indices_type
  >::indices_type;
};

}

template <::std::size_t A>
struct make_indices : detail::expand_indices<0, A - 1>::indices_type
{
};

template <>
struct make_indices<0> : indices<>
{
};

template <::std::size_t A, ::std::size_t B>
struct make_indices_range : detail::expand_indices::indices_type
{
};

template <::std::size_t A>
struct make_indices_range : indices<>
{
};

// sequences
template <::std::size_t I, typename A, typename ...B>
struct type_at : type_at
{
};

template <typename A, typename ...B>
struct type_at<0, A, B...>
{
  using type = A;
};

template <typename A, typename ...B>
struct front
{
  using type = A;
};

template <typename A, typename ...B>
struct back : back
{
};

template <typename A>
struct back
{
  using type = A;
};

template <bool B>
using bool_ = ::std::integral_constant<bool, B>;

template <class A, class ...B>
struct all_of : bool_<A::value && all_of::value> { };

template <class A>
struct all_of : bool_ { };

}

#endif // UTILITY_HPP
<|endoftext|>


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

  Program:   Insight Segmentation & Registration Toolkit
  Module:    wrap_IOBase.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2002 Insight Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

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

=========================================================================*/
#include "itkRawImageIO.h"
#include "itkPNGImageIO.h"
#include "itkMetaImageIO.h"
#include "itkPNGImageIOFactory.h"
#include "itkMetaImageIOFactory.h"
#include "itkDicomImageIOFactory.h"

#ifdef CABLE_CONFIGURATION
#include "wrap_ITKIO.h"

ITK_WRAP_CONFIG_GROUP(IOBase);
ITK_WRAP_OBJECT(PNGImageIO);
ITK_WRAP_OBJECT(MetaImageIO);
ITK_WRAP_OBJECT(PNGImageIOFactory);
ITK_WRAP_OBJECT(MetaImageIOFactory);
ITK_WRAP_OBJECT(DicomImageIOFactory);
ITK_WRAP_OBJECT_TEMPLATE_2(RawImageIOF2, RawImageIO<float, 2>);
ITK_WRAP_OBJECT_TEMPLATE_2(RawImageIOF3, RawImageIO<float, 3>);

#endif
<commit_msg>ENH: Added wrapper for ImageIOBase.<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    wrap_IOBase.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2002 Insight Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

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

=========================================================================*/
#include "itkRawImageIO.h"
#include "itkImageIOBase.h"
#include "itkPNGImageIO.h"
#include "itkMetaImageIO.h"
#include "itkPNGImageIOFactory.h"
#include "itkMetaImageIOFactory.h"
#include "itkDicomImageIOFactory.h"

#ifdef CABLE_CONFIGURATION
#include "wrap_ITKIO.h"

ITK_WRAP_CONFIG_GROUP(IOBase);
ITK_WRAP_OBJECT(ImageIOBase);
ITK_WRAP_OBJECT(PNGImageIO);
ITK_WRAP_OBJECT(MetaImageIO);
ITK_WRAP_OBJECT(PNGImageIOFactory);
ITK_WRAP_OBJECT(MetaImageIOFactory);
ITK_WRAP_OBJECT(DicomImageIOFactory);
ITK_WRAP_OBJECT_TEMPLATE_2(RawImageIOF2, RawImageIO<float, 2>);
ITK_WRAP_OBJECT_TEMPLATE_2(RawImageIOF3, RawImageIO<float, 3>);

#endif
<|endoftext|>


<commit_before>#include <string>
#include "stdafx.h"
#include "MainScene.h"
#include "MCScene.h"

Scene* MCScene::createScene()
{
	auto scene = Scene::create();

	auto layer = MCScene::create();

	scene->addChild(layer);

	return scene;
}

bool MCScene::init()
{
	if (!CCLayerColor::initWithColor(Color4B(0, 0, 0, 255)))
	{
		return false;
	}

	this->schedule(schedule_selector(MCScene::ChangeBackGroundColor), DELTA_TIME);

	auto backgroundGirl0 = Sprite::create("res/mc.jpg");
	backgroundGirl0->setAnchorPoint(Point::ZERO);
	backgroundGirl0->setPosition(Point::ZERO);

	auto backgroundGirl1 = Sprite::create("res/mc.jpg");
	backgroundGirl1->setAnchorPoint(Point::ZERO);
	backgroundGirl1->setPosition(Point(backgroundGirl0->getContentSize().width, 0));

	backgroundGirl0->addChild(backgroundGirl1);
	backgroundGirl0->setScale(0.1);
	this->addChild(backgroundGirl0);

	auto GotoMainScene = MenuItemFont::create("Go to MainScene", CC_CALLBACK_1(MCScene::ChangeToMainScene, this));
	auto GotoMainSceneMenu = Menu::create(GotoMainScene, NULL);
	GotoMainSceneMenu->setPosition(200, 300);
	this->addChild(GotoMainSceneMenu);

	auto taewooMission1 = Label::createWithTTF("JUMP!!!", "fonts/arial.ttf", 50);
	taewooMission1->setPosition(Point(200, 150));
	taewooMission1->setName("twMissionLabel");
	taewooMission1->setVisible(false);
	this->addChild(taewooMission1);

	auto dir = Director::getInstance();
	auto screen = dir->getVisibleSize();

	auto jinwookMission = Sprite::create("boy 31x40.png");
	auto boysize = jinwookMission->getContentSize();
	jinwookMission->setPosition(0 + boysize.width / 2, 0 + boysize.height / 2);
	jinwookMission->setName("boy");
	this->addChild(jinwookMission);

	auto moveToRL = MoveBy::create(1, Point(screen.width - boysize.width, 0));
	auto moveToRU = MoveBy::create(1, Point(0 , screen.height - boysize.height));
	auto moveToLU = MoveBy::create(1, Point( -screen.width + boysize.width, 0));
	auto moveToLL = MoveBy::create(1, Point(0, -screen.height + boysize.height));

	auto moveArround = Sequence::create(moveToRL, moveToRU, moveToLU, moveToLL, NULL);
	auto repeat_action = RepeatForever::create(moveArround);

	jinwookMission->runAction(repeat_action);

	auto _mouseListener = EventListenerMouse::create();
	_mouseListener->onMouseUp = CC_CALLBACK_1(MCScene::onMouseUp, this);
	_mouseListener->onMouseDown = CC_CALLBACK_1(MCScene::onMouseDown, this);
	_eventDispatcher->addEventListenerWithSceneGraphPriority(_mouseListener, this);

	auto aniSprite = Sprite::create();
	aniSprite->setPosition(100, 100);
	this->addChild(aniSprite);

	//ִϸ̼  ߰
	Vector<SpriteFrame*> animFrames;
	const int frameCut = 3;//
	const int AniCharheight = 70;
	const int AniCharWidth = 32;

	animFrames.reserve(frameCut);
	for (int i = 0; i < frameCut; i++)
		animFrames.pushBack(SpriteFrame::create("res/animSprite2.png", Rect(AniCharWidth * i*3, AniCharheight, AniCharWidth, AniCharheight)));

	// create the animation out of the frame
	Animation* animation = Animation::createWithSpriteFrames(animFrames, 0.1f);
	Animate* animate = Animate::create(animation);

	// run it and repeat it forever
	RepeatForever *aniAction = RepeatForever::create(animate); //׼ 
	auto jump = JumpBy::create(0.5, Point(0, 0), 20, 1);
	RepeatForever *jumpForever = RepeatForever::create(jump);
	aniSprite->runAction(aniAction); //Ʈ(spr)
	aniSprite->runAction(jumpForever);

	return true;
}

void MCScene::ChangeToMainScene(Ref* pSender)
{
	Director::getInstance()->replaceScene(MainScene::createScene());
}

void MCScene::onMouseUp(Event *event)
{
	auto label = this->getChildByName("twMissionLabel");
	label->setVisible(false);
}

void MCScene::onMouseDown(Event *event)
{
	auto e = (EventMouse*)event;
	auto blinkLabel = this->getChildByName("twMissionLabel");
	blinkLabel->setVisible(true);
	auto runningBoy = this->getChildByName("boy");
	auto moveToMouse = JumpBy::create(0.3, Point(0, 0), 50, 1);
	runningBoy->runAction(moveToMouse);
}

void MCScene::ChangeBackGroundColor(const float intervalTime)
{
	this->setColor(Color3B((random() % 255), (random() % 255), (random() % 255)));
}<commit_msg>내꺼 왜 스크롤이 제대로 안돼지<commit_after>#include <string>
#include "stdafx.h"
#include "MainScene.h"
#include "MCScene.h"

Scene* MCScene::createScene()
{
	auto scene = Scene::create();

	auto layer = MCScene::create();

	scene->addChild(layer);

	return scene;
}

bool MCScene::init()
{
	if (!CCLayerColor::initWithColor(Color4B(0, 0, 0, 255)))
	{
		return false;
	}
	this->schedule(schedule_selector(MCScene::ChangeBackGroundColor), DELTA_TIME);

	auto dir = Director::getInstance();
	auto screen = dir->getVisibleSize();

	auto backgroundGirl0 = Sprite::create("res/mc.jpg");
	backgroundGirl0->setAnchorPoint(Point::ZERO);
	backgroundGirl0->setPosition(Point::ZERO);
	int width = backgroundGirl0->getContentSize().width;
	int height = backgroundGirl0->getContentSize().height;
	float scrollVelocity = 100;
	float scaleRatio = screen.height / height;
	backgroundGirl0->setScale(scaleRatio);

	auto backgroundGirl1 = Sprite::create("res/mc.jpg");
	backgroundGirl1->setAnchorPoint(Point::ZERO);
	backgroundGirl1->setPosition(Point(width, 0));

	auto moveRight = MoveTo::create(screen.width / (scrollVelocity * scaleRatio), Point(-width, 0));
	auto moveBack = MoveTo::create(0, Point::ZERO);
	auto scrollBG = RepeatForever::create(Sequence::create(moveRight, moveBack, NULL));
	backgroundGirl0->runAction(scrollBG);
	backgroundGirl0->addChild(backgroundGirl1);
	this->addChild(backgroundGirl0);

	auto GotoMainScene = MenuItemFont::create("Go to MainScene", CC_CALLBACK_1(MCScene::ChangeToMainScene, this));
	auto GotoMainSceneMenu = Menu::create(GotoMainScene, NULL);
	GotoMainSceneMenu->setPosition(200, 300);
	this->addChild(GotoMainSceneMenu);

	auto taewooMission1 = Label::createWithTTF("JUMP!!!", "fonts/arial.ttf", 50);
	taewooMission1->setPosition(Point(200, 150));
	taewooMission1->setName("twMissionLabel");
	taewooMission1->setVisible(false);
	this->addChild(taewooMission1);

	auto jinwookMission = Sprite::create("boy 31x40.png");
	auto boysize = jinwookMission->getContentSize();
	jinwookMission->setPosition(0 + boysize.width / 2, 0 + boysize.height / 2);
	jinwookMission->setName("boy");
	this->addChild(jinwookMission);

	auto moveToRL = MoveBy::create(1, Point(screen.width - boysize.width, 0));
	auto moveToRU = MoveBy::create(1, Point(0 , screen.height - boysize.height));
	auto moveToLU = MoveBy::create(1, Point( -screen.width + boysize.width, 0));
	auto moveToLL = MoveBy::create(1, Point(0, -screen.height + boysize.height));

	auto moveArround = Sequence::create(moveToRL, moveToRU, moveToLU, moveToLL, NULL);
	auto repeat_action = RepeatForever::create(moveArround);

	jinwookMission->runAction(repeat_action);

	auto _mouseListener = EventListenerMouse::create();
	_mouseListener->onMouseUp = CC_CALLBACK_1(MCScene::onMouseUp, this);
	_mouseListener->onMouseDown = CC_CALLBACK_1(MCScene::onMouseDown, this);
	_eventDispatcher->addEventListenerWithSceneGraphPriority(_mouseListener, this);

	auto aniSprite = Sprite::create();
	aniSprite->setPosition(100, 100);
	this->addChild(aniSprite);

	//ִϸ̼  ߰
	Vector<SpriteFrame*> animFrames;
	const int frameCut = 3;//
	const int AniCharheight = 70;
	const int AniCharWidth = 32;

	animFrames.reserve(frameCut);
	for (int i = 0; i < frameCut; i++)
		animFrames.pushBack(SpriteFrame::create("res/animSprite2.png", Rect(AniCharWidth * i*3, AniCharheight, AniCharWidth, AniCharheight)));

	// create the animation out of the frame
	Animation* animation = Animation::createWithSpriteFrames(animFrames, 0.1f);
	Animate* animate = Animate::create(animation);

	// run it and repeat it forever
	RepeatForever *aniAction = RepeatForever::create(animate); //׼ 
	auto jump = JumpBy::create(0.5, Point(0, 0), 20, 1);
	RepeatForever *jumpForever = RepeatForever::create(jump);
	aniSprite->runAction(aniAction); //Ʈ(spr)
	aniSprite->runAction(jumpForever);

	return true;
}

void MCScene::ChangeToMainScene(Ref* pSender)
{
	Director::getInstance()->replaceScene(MainScene::createScene());
}

void MCScene::onMouseUp(Event *event)
{
	auto label = this->getChildByName("twMissionLabel");
	label->setVisible(false);
}

void MCScene::onMouseDown(Event *event)
{
	auto e = (EventMouse*)event;
	auto blinkLabel = this->getChildByName("twMissionLabel");
	blinkLabel->setVisible(true);
	auto runningBoy = this->getChildByName("boy");
	auto moveToMouse = JumpBy::create(0.3, Point(0, 0), 50, 1);
	runningBoy->runAction(moveToMouse);
}

void MCScene::ChangeBackGroundColor(const float intervalTime)
{
	this->setColor(Color3B((random() % 255), (random() % 255), (random() % 255)));
}<|endoftext|>


<commit_before>/**
 * @file prereqs.hpp
 *
 * The core includes that mlpack expects; standard C++ includes and Armadillo.
 */
#ifndef __MLPACK_PREREQS_HPP
#define __MLPACK_PREREQS_HPP

// First, check if Armadillo was included before, warning if so.
#ifdef ARMA_INCLUDES
#pragma message "Armadillo was included before mlpack; this can sometimes cause\
 problems.  It should only be necessary to include <mlpack/core.hpp> and not \
<armadillo>."
#endif

// Next, standard includes.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <limits.h>
#include <float.h>
#include <stdint.h>
#include <iostream>
#include <stdexcept>

// Defining _USE_MATH_DEFINES should set M_PI.
#define _USE_MATH_DEFINES
#include <math.h>

// For tgamma().
#include <boost/math/special_functions/gamma.hpp>

// But if it's not defined, we'll do it.
#ifndef M_PI
  #define M_PI 3.141592653589793238462643383279
#endif

// Give ourselves a nice way to force functions to be inline if we need.
#define force_inline
#if defined(__GNUG__) && !defined(DEBUG)
  #undef force_inline
  #define force_inline __attribute__((always_inline))
#elif defined(_MSC_VER) && !defined(DEBUG)
  #undef force_inline
  #define force_inline __forceinline
#endif

// We'll need the necessary boost::serialization features, as well as what we
// use with mlpack.  In Boost 1.59 and newer, the BOOST_PFTO code is no longer
// defined, but we still need to define it (as nothing) so that the mlpack
// serialization shim compiles.
#include <boost/serialization/serialization.hpp>
#ifndef BOOST_PFTO
  #define BOOST_PFTO
#endif
#include <mlpack/core/data/serialization_shim.hpp>

// Now include Armadillo through the special mlpack extensions.
#include <mlpack/core/arma_extend/arma_extend.hpp>

// Ensure that the user isn't doing something stupid with their Armadillo
// defines.
#include <mlpack/core/util/arma_config_check.hpp>

// On Visual Studio, disable C4519 (default arguments for function templates)
// since it's by default an error, which doesn't even make any sense because
// it's part of the C++11 standard.
#ifdef _MSC_VER
  #pragma warning(disable : 4519)
#endif

#endif
<commit_msg>Add serialization prerequisites.<commit_after>/**
 * @file prereqs.hpp
 *
 * The core includes that mlpack expects; standard C++ includes and Armadillo.
 */
#ifndef __MLPACK_PREREQS_HPP
#define __MLPACK_PREREQS_HPP

// First, check if Armadillo was included before, warning if so.
#ifdef ARMA_INCLUDES
#pragma message "Armadillo was included before mlpack; this can sometimes cause\
 problems.  It should only be necessary to include <mlpack/core.hpp> and not \
<armadillo>."
#endif

// Next, standard includes.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <limits.h>
#include <float.h>
#include <stdint.h>
#include <iostream>
#include <stdexcept>

// Defining _USE_MATH_DEFINES should set M_PI.
#define _USE_MATH_DEFINES
#include <math.h>

// For tgamma().
#include <boost/math/special_functions/gamma.hpp>

// But if it's not defined, we'll do it.
#ifndef M_PI
  #define M_PI 3.141592653589793238462643383279
#endif

// Give ourselves a nice way to force functions to be inline if we need.
#define force_inline
#if defined(__GNUG__) && !defined(DEBUG)
  #undef force_inline
  #define force_inline __attribute__((always_inline))
#elif defined(_MSC_VER) && !defined(DEBUG)
  #undef force_inline
  #define force_inline __forceinline
#endif

// We'll need the necessary boost::serialization features, as well as what we
// use with mlpack.  In Boost 1.59 and newer, the BOOST_PFTO code is no longer
// defined, but we still need to define it (as nothing) so that the mlpack
// serialization shim compiles.
#include <boost/serialization/serialization.hpp>
#include <boost/serialization/vector.hpp>
#include <boost/serialization/map.hpp>
#include <boost/serialization/unordered_map.hpp>
#ifndef BOOST_PFTO
  #define BOOST_PFTO
#endif
#include <mlpack/core/data/serialization_shim.hpp>

// Now include Armadillo through the special mlpack extensions.
#include <mlpack/core/arma_extend/arma_extend.hpp>

// Ensure that the user isn't doing something stupid with their Armadillo
// defines.
#include <mlpack/core/util/arma_config_check.hpp>

// On Visual Studio, disable C4519 (default arguments for function templates)
// since it's by default an error, which doesn't even make any sense because
// it's part of the C++11 standard.
#ifdef _MSC_VER
  #pragma warning(disable : 4519)
#endif

#endif
<|endoftext|>


<commit_before>/*
Copyright (c) 2014, Nicolas Brown
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.

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

* Neither the name of dragonscript nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/

#pragma once

#include "loris\loris.hpp"

using namespace loris;

template<> Value::operator double() {
	return AsNumber();
}

template<> Value::operator long() {
	return AsNumber();
}

template<> Value::operator std::string() {
	return AsString();
}

Value box(int value)
{
	return Value::CreateNumber(value);
}

Value box(long value)
{
	return Value::CreateNumber(value);
}

Value box(float value)
{
	return Value::CreateNumber(value);
}

Value box(double value)
{
	return Value::CreateNumber(value);
}

Value box(const std::string& value)
{
	return Value::CreateString(value.c_str());
}

Value box(bool value)
{
	return Value::CreateBool(value);
}

template<typename T>
Value box(T value)
{
	auto obj = new Object();
	obj->managed = false;
	obj->data = (void*)value;
	return Value::CreateObject(obj);
}

template<typename Ret, typename ... Params, size_t ... I>
Ret call_func(Ret(*sig)(Params...),
	std::index_sequence<I...>, VirtualMachine* vm)
{
	return sig(vm->GetArg(I)...);
}

template<typename Ret, typename ... Params>
std::function<Value(VirtualMachine* vm, Object* self)> Def(Ret(*sig)(Params...))
{
	if (std::is_same<Ret, void>::value) {
		return [=](VirtualMachine* vm, Object* self)
		{
			call_func(sig, std::index_sequence_for<Params...>{}, vm);
			return Value::CreateNull();
		};
	}
	else {
		return [=](VirtualMachine* vm, Object* self)
		{
			return box(call_func(sig, std::index_sequence_for<Params...>{}, vm));
		};
	}
}<commit_msg>Added class for building loris classes<commit_after>/*
Copyright (c) 2014, Nicolas Brown
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.

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

* Neither the name of dragonscript nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/

#pragma once

#include "loris\loris.hpp"

namespace loris {

template<> Value::operator double() {
	return AsNumber();
}

template<> Value::operator long() {
	return AsNumber();
}

template<> Value::operator std::string() {
	return AsString();
}

Value box(int value)
{
	return Value::CreateNumber(value);
}

Value box(long value)
{
	return Value::CreateNumber(value);
}

Value box(float value)
{
	return Value::CreateNumber(value);
}

Value box(double value)
{
	return Value::CreateNumber(value);
}

Value box(const std::string& value)
{
	return Value::CreateString(value.c_str());
}

Value box(bool value)
{
	return Value::CreateBool(value);
}

template<typename T>
Value box(T value)
{
	auto obj = new Object();
	obj->managed = false;
	obj->data = (void*)value;
	return Value::CreateObject(obj);
}

template<typename Ret, typename ... Params, size_t ... I>
Ret call_func(Ret(*sig)(Params...),
	std::index_sequence<I...>, VirtualMachine* vm)
{
	return sig(vm->GetArg(I)...);
}

template<typename Ret, typename ... Params>
std::function<Value(VirtualMachine* vm, Object* self)> Def(Ret(*sig)(Params...))
{
	if (std::is_same<Ret, void>::value) {
		return [=](VirtualMachine* vm, Object* self)
		{
			call_func(sig, std::index_sequence_for<Params...>{}, vm);
			return Value::CreateNull();
		};
	}
	else {
		return [=](VirtualMachine* vm, Object* self)
		{
			return box(call_func(sig, std::index_sequence_for<Params...>{}, vm));
		};
	}
}

class ClassBuilder
{
public:
	Class * def;

	ClassBuilder()
	{
		def = NULL;
	}

	ClassBuilder Start(string className)
	{
		def = new Class();
		def->name = className;

		return *this;
	}

	ClassBuilder Attrib(string name)
	{
		assert(def != NULL);

		ClassAttrib attr;
		attr.name = name;
		attr.isStatic = false;
		attr.init = NULL;
		def->attribs.push_back(attr);

		return *this;
	}

	ClassBuilder StaticAttrib(string name)
	{
		assert(def != NULL);

		ClassAttrib attr;
		attr.name = name;
		attr.isStatic = true;
		attr.init = NULL;
		def->attribs.push_back(attr);

		return *this;
	}

	ClassBuilder Constructor(NativeFunction native)
	{
		Function* func = new Function;
		func->name = def->name;
		func->isStatic = false;
		func->isNative = true;
		func->nativeFunction = native;

		def->methods[def->name] = func;
		return *this;
	}

	ClassBuilder Destructor(NativeFunction native)
	{
		Function* func = new Function;
		func->name = def->name;
		func->isStatic = false;
		func->isNative = true;
		func->nativeFunction = native;

		def->destructor = func;
		return *this;
	}

	ClassBuilder Method(string name, NativeFunction native)
	{
		Function* func = new Function;
		func->name = def->name;
		func->isStatic = false;
		func->isNative = true;
		func->nativeFunction = native;

		def->methods[name] = func;
		return *this;
	}

	ClassBuilder StaticMethod(string name, NativeFunction native)
	{
		Function* func = new Function;
		func->name = def->name;
		func->isStatic = true;
		func->isNative = true;
		func->nativeFunction = native;

		def->methods[name] = func;
		return *this;
	}

	Class* Build()
	{
		Class* c = def;
		def = NULL;

		return c;
	}
};

ClassBuilder CreateClass(std::string name)
{
	ClassBuilder builder;
	return builder.Start(name);
}

}<|endoftext|>


<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2006 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/
//$Id: map.hpp 39 2005-04-10 20:39:53Z pavlenko $

#ifndef MAP_HPP
#define MAP_HPP

#ifdef HAVE_CONFIG_H
  #include <config.h>
#endif

#include <mapnik/feature_type_style.hpp>
#include <mapnik/datasource.hpp>
#include <mapnik/layer.hpp>
#include <boost/optional/optional.hpp>

namespace mapnik
{
    class MAPNIK_DECL Map
    {
    public:

        enum aspect_fix_mode
        {
            /* grow the width or height of the specified geo bbox to fill the map size. default behaviour. */
            GROW_BBOX,
            /* grow the width or height of the map to accomodate the specified geo bbox. */
            GROW_CANVAS,
            /* shrink the width or height of the specified geo bbox to fill the map size. */
            SHRINK_BBOX,
            /* shrink the width or height of the map to accomodate the specified geo bbox. */
            SHRINK_CANVAS,
            /* adjust the width of the specified geo bbox, leave height and map size unchanged */
            ADJUST_BBOX_WIDTH,
            /* adjust the height of the specified geo bbox, leave width and map size unchanged */
            ADJUST_BBOX_HEIGHT,
            /* adjust the width of the map, leave height and geo bbox unchanged */
            ADJUST_CANVAS_WIDTH,
            /* adjust the height of the map, leave width and geo bbox unchanged */
            ADJUST_CANVAS_HEIGHT
        };
    private:
        static const unsigned MIN_MAPSIZE=16;
        static const unsigned MAX_MAPSIZE=MIN_MAPSIZE<<10;
        unsigned width_;
        unsigned height_;
        std::string  srs_;
        boost::optional<Color> background_;
        std::map<std::string,feature_type_style> styles_;
        std::map<std::string,FontSet> fontsets_;
        std::vector<Layer> layers_;
        Envelope<double> currentExtent_;
        aspect_fix_mode aspectFixMode_;

    public:

        typedef std::map<std::string,feature_type_style>::const_iterator const_style_iterator;
        typedef std::map<std::string,feature_type_style>::iterator style_iterator;

        /*! \brief Default constructor.
         *
         *  Creates a map with these parameters:
         *  - width = 400
         *  - height = 400
         *  - projection = "+proj=latlong +datum=WGS84"
         */
        Map();

        /*! \brief Constructor
         *  @param width Initial map width.
         *  @param height Initial map height.
         *  @param srs Initial map projection.
         */
        Map(int width, int height, std::string const& srs="+proj=latlong +datum=WGS84");

        /*! \brief Copy Constructur.
         *
         *  @param rhs Map to copy from.
         */
        Map(const Map& rhs);

        /*! \brief Assignment operator
         *
         *  TODO: to be documented
         *
         */
        Map& operator=(const Map& rhs);

        /*! \brief Get all styles
         * @return Const reference to styles
         */
        std::map<std::string,feature_type_style> const& styles() const;

        /*! \brief Get all styles
         * @return Non-constant reference to styles
         */
        std::map<std::string,feature_type_style> & styles();

        /*! \brief Get first iterator in styles.
         *  @return Constant style iterator.
         */
        const_style_iterator begin_styles() const;

        /*! \brief Get last iterator in styles.
         *  @return Constant style iterator.
         */
        const_style_iterator end_styles() const;

        /*! \brief Get first iterator in styles.
         *  @return Non-constant style iterator.
         */
        style_iterator begin_styles();

        /*! \brief Get last iterator in styles.
         *  @return Non-constant style iterator.
         */
        style_iterator end_styles();

        /*! \brief Insert a style in the map.
         *  @param name The name of the style.
         *  @param style The style to insert.
         *  @return true If success.
         *  @return false If no success.
         */
        bool insert_style(std::string const& name,feature_type_style const& style);

        /*! \brief Remove a style from the map.
         *  @param name The name of the style.
         */
        void remove_style(const std::string& name);

        /*! \brief Find a style.
         *  @param name The name of the style.
         *  @return The style if found. If not found return the default map style.
         */
        feature_type_style const& find_style(std::string const& name) const;

        /*! \brief Insert a fontset into the map.
         *  @param name The name of the fontset.
         *  @param style The fontset to insert.
         *  @return true If success.
         *  @return false If failure.
         */
        bool insert_fontset(std::string const& name, FontSet const& fontset);

        /*! \brief Find a fontset.
         *  @param name The name of the fontset.
         *  @return The fontset if found. If not found return the default map fontset.
         */
        FontSet const& find_fontset(std::string const& name) const;

        /*! \brief Get number of all layers.
         */
        size_t layerCount() const;

        /*! \brief Add a layer to the map.
         *  @param l The layer to add.
         */
        void addLayer(const Layer& l);

        /*! \brief Get a layer.
         *  @param index Layer number.
         *  @return Constant layer.
         */
        const Layer& getLayer(size_t index) const;

        /*! \brief Get a layer.
         *  @param index Layer number.
         *  @return Non-constant layer.
         */
        Layer& getLayer(size_t index);

        /*! \brief Remove a layer.
         *  @param index Layer number.
         */
        void removeLayer(size_t index);

        /*! \brief Get all layers.
         *  @return Constant layers.
         */
        std::vector<Layer> const& layers() const;

        /*! \brief Get all layers.
         *  @return Non-constant layers.
         */
        std::vector<Layer> & layers();

        /*! \brief Remove all layers and styles from the map.
         */
        void remove_all();

        /*! \brief Get map width.
         */
        unsigned getWidth() const;

        /*! \brief Get map height.
         */
        unsigned getHeight() const;

        /*! \brief Set map width.
         */
        void setWidth(unsigned width);

        /*! \brief Set map height.
         */
        void setHeight(unsigned height);

        /*! \brief Resize the map.
         */
        void resize(unsigned width,unsigned height);

        /*! \brief Get the map projection.
         *  @return Map projection.
         */
        std::string const& srs() const;

        /*! \brief Set the map projection.
         *  @param srs Map projection.
         */
        void set_srs(std::string const& srs);

        /*! \brief Set the map background color.
         *  @param c Background color.
         */
        void set_background(const Color& c);

        /*! \brief Get the map background color
         *  @return Background color as boost::optional
         *  object
         */
        boost::optional<Color> const& background() const;

        /*! \brief Zoom the map at the current position.
         *  @param factor The factor how much the map is zoomed in or out.
         */
        void zoom(double factor);

        /*! \brief Zoom the map to a bounding box.
         *
         *  Aspect is handled automatic if not fitting to width/height.
         *  @param box The bounding box where to zoom.
         */
        void zoomToBox(const Envelope<double>& box);

        /*! \brief Zoom the map to show all data.
         */
        void zoom_all();

        void pan(int x,int y);

        void pan_and_zoom(int x,int y,double zoom);

        /*! \brief Get current bounding box.
         *  @return The current bounding box.
         */
        const Envelope<double>& getCurrentExtent() const;

        double scale() const;

        CoordTransform view_transform() const;

        featureset_ptr query_point(unsigned index, double x, double y) const;

        featureset_ptr query_map_point(unsigned index, double x, double y) const;
        ~Map();

        void setAspectFixMode(aspect_fix_mode afm) { aspectFixMode_ = afm; }
        bool getAspectFixMode() { return aspectFixMode_; }

    private:
        void fixAspectRatio();
    };
}

#endif //MAP_HPP
<commit_msg>+fixed init order<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2006 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/
//$Id: map.hpp 39 2005-04-10 20:39:53Z pavlenko $

#ifndef MAP_HPP
#define MAP_HPP

#ifdef HAVE_CONFIG_H
  #include <config.h>
#endif

#include <mapnik/feature_type_style.hpp>
#include <mapnik/datasource.hpp>
#include <mapnik/layer.hpp>
#include <boost/optional/optional.hpp>

namespace mapnik
{
    class MAPNIK_DECL Map
    {
    public:

        enum aspect_fix_mode
        {
            /* grow the width or height of the specified geo bbox to fill the map size. default behaviour. */
            GROW_BBOX,
            /* grow the width or height of the map to accomodate the specified geo bbox. */
            GROW_CANVAS,
            /* shrink the width or height of the specified geo bbox to fill the map size. */
            SHRINK_BBOX,
            /* shrink the width or height of the map to accomodate the specified geo bbox. */
            SHRINK_CANVAS,
            /* adjust the width of the specified geo bbox, leave height and map size unchanged */
            ADJUST_BBOX_WIDTH,
            /* adjust the height of the specified geo bbox, leave width and map size unchanged */
            ADJUST_BBOX_HEIGHT,
            /* adjust the width of the map, leave height and geo bbox unchanged */
            ADJUST_CANVAS_WIDTH,
            /* adjust the height of the map, leave width and geo bbox unchanged */
            ADJUST_CANVAS_HEIGHT
        };
    private:
        static const unsigned MIN_MAPSIZE=16;
        static const unsigned MAX_MAPSIZE=MIN_MAPSIZE<<10;
        unsigned width_;
        unsigned height_;
        std::string  srs_;
        boost::optional<Color> background_;
        std::map<std::string,feature_type_style> styles_;
        std::map<std::string,FontSet> fontsets_;
        std::vector<Layer> layers_;
        aspect_fix_mode aspectFixMode_;
        Envelope<double> currentExtent_;

    public:

        typedef std::map<std::string,feature_type_style>::const_iterator const_style_iterator;
        typedef std::map<std::string,feature_type_style>::iterator style_iterator;

        /*! \brief Default constructor.
         *
         *  Creates a map with these parameters:
         *  - width = 400
         *  - height = 400
         *  - projection = "+proj=latlong +datum=WGS84"
         */
        Map();

        /*! \brief Constructor
         *  @param width Initial map width.
         *  @param height Initial map height.
         *  @param srs Initial map projection.
         */
        Map(int width, int height, std::string const& srs="+proj=latlong +datum=WGS84");

        /*! \brief Copy Constructur.
         *
         *  @param rhs Map to copy from.
         */
        Map(const Map& rhs);

        /*! \brief Assignment operator
         *
         *  TODO: to be documented
         *
         */
        Map& operator=(const Map& rhs);

        /*! \brief Get all styles
         * @return Const reference to styles
         */
        std::map<std::string,feature_type_style> const& styles() const;

        /*! \brief Get all styles
         * @return Non-constant reference to styles
         */
        std::map<std::string,feature_type_style> & styles();

        /*! \brief Get first iterator in styles.
         *  @return Constant style iterator.
         */
        const_style_iterator begin_styles() const;

        /*! \brief Get last iterator in styles.
         *  @return Constant style iterator.
         */
        const_style_iterator end_styles() const;

        /*! \brief Get first iterator in styles.
         *  @return Non-constant style iterator.
         */
        style_iterator begin_styles();

        /*! \brief Get last iterator in styles.
         *  @return Non-constant style iterator.
         */
        style_iterator end_styles();

        /*! \brief Insert a style in the map.
         *  @param name The name of the style.
         *  @param style The style to insert.
         *  @return true If success.
         *  @return false If no success.
         */
        bool insert_style(std::string const& name,feature_type_style const& style);

        /*! \brief Remove a style from the map.
         *  @param name The name of the style.
         */
        void remove_style(const std::string& name);

        /*! \brief Find a style.
         *  @param name The name of the style.
         *  @return The style if found. If not found return the default map style.
         */
        feature_type_style const& find_style(std::string const& name) const;

        /*! \brief Insert a fontset into the map.
         *  @param name The name of the fontset.
         *  @param style The fontset to insert.
         *  @return true If success.
         *  @return false If failure.
         */
        bool insert_fontset(std::string const& name, FontSet const& fontset);

        /*! \brief Find a fontset.
         *  @param name The name of the fontset.
         *  @return The fontset if found. If not found return the default map fontset.
         */
        FontSet const& find_fontset(std::string const& name) const;

        /*! \brief Get number of all layers.
         */
        size_t layerCount() const;

        /*! \brief Add a layer to the map.
         *  @param l The layer to add.
         */
        void addLayer(const Layer& l);

        /*! \brief Get a layer.
         *  @param index Layer number.
         *  @return Constant layer.
         */
        const Layer& getLayer(size_t index) const;

        /*! \brief Get a layer.
         *  @param index Layer number.
         *  @return Non-constant layer.
         */
        Layer& getLayer(size_t index);

        /*! \brief Remove a layer.
         *  @param index Layer number.
         */
        void removeLayer(size_t index);

        /*! \brief Get all layers.
         *  @return Constant layers.
         */
        std::vector<Layer> const& layers() const;

        /*! \brief Get all layers.
         *  @return Non-constant layers.
         */
        std::vector<Layer> & layers();

        /*! \brief Remove all layers and styles from the map.
         */
        void remove_all();

        /*! \brief Get map width.
         */
        unsigned getWidth() const;

        /*! \brief Get map height.
         */
        unsigned getHeight() const;

        /*! \brief Set map width.
         */
        void setWidth(unsigned width);

        /*! \brief Set map height.
         */
        void setHeight(unsigned height);

        /*! \brief Resize the map.
         */
        void resize(unsigned width,unsigned height);

        /*! \brief Get the map projection.
         *  @return Map projection.
         */
        std::string const& srs() const;

        /*! \brief Set the map projection.
         *  @param srs Map projection.
         */
        void set_srs(std::string const& srs);

        /*! \brief Set the map background color.
         *  @param c Background color.
         */
        void set_background(const Color& c);

        /*! \brief Get the map background color
         *  @return Background color as boost::optional
         *  object
         */
        boost::optional<Color> const& background() const;

        /*! \brief Zoom the map at the current position.
         *  @param factor The factor how much the map is zoomed in or out.
         */
        void zoom(double factor);

        /*! \brief Zoom the map to a bounding box.
         *
         *  Aspect is handled automatic if not fitting to width/height.
         *  @param box The bounding box where to zoom.
         */
        void zoomToBox(const Envelope<double>& box);

        /*! \brief Zoom the map to show all data.
         */
        void zoom_all();

        void pan(int x,int y);

        void pan_and_zoom(int x,int y,double zoom);

        /*! \brief Get current bounding box.
         *  @return The current bounding box.
         */
        const Envelope<double>& getCurrentExtent() const;

        double scale() const;

        CoordTransform view_transform() const;

        featureset_ptr query_point(unsigned index, double x, double y) const;

        featureset_ptr query_map_point(unsigned index, double x, double y) const;
        ~Map();

        void setAspectFixMode(aspect_fix_mode afm) { aspectFixMode_ = afm; }
        bool getAspectFixMode() { return aspectFixMode_; }

    private:
        void fixAspectRatio();
    };
}

#endif //MAP_HPP
<|endoftext|>